FFmpeg
Loading...
Searching...
No Matches
http.c
Go to the documentation of this file.
1/*
2 * HTTP protocol for ffmpeg client
3 * Copyright (c) 2000, 2001 Fabrice Bellard
4 *
5 * This file is part of FFmpeg.
6 *
7 * FFmpeg is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU Lesser General Public
9 * License as published by the Free Software Foundation; either
10 * version 2.1 of the License, or (at your option) any later version.
11 *
12 * FFmpeg is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 * Lesser General Public License for more details.
16 *
17 * You should have received a copy of the GNU Lesser General Public
18 * License along with FFmpeg; if not, write to the Free Software
19 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20 */
21
22#include <stdbool.h>
23
24#include "config.h"
25#include "config_components.h"
26
27#include <string.h>
28#include <time.h>
29#if CONFIG_ZLIB
30#include <zlib.h>
31#endif /* CONFIG_ZLIB */
32
33#include "libavutil/avassert.h"
34#include "libavutil/avstring.h"
35#include "libavutil/bprint.h"
37#include "libavutil/macros.h"
38#include "libavutil/mem.h"
39#include "libavutil/opt.h"
40#include "libavutil/time.h"
42
43#include "avformat.h"
44#include "http.h"
45#include "httpauth.h"
46#include "internal.h"
47#include "network.h"
48#include "os_support.h"
49#include "url.h"
50#include "version.h"
51
52/* XXX: POST protocol is not completely implemented because ffmpeg uses
53 * only a subset of it. */
54
55/* The IO buffer size is unrelated to the max URL size in itself, but needs
56 * to be large enough to fit the full request headers (including long
57 * path names). */
58#define BUFFER_SIZE (MAX_URL_SIZE + HTTP_HEADERS_SIZE)
59#define MAX_REDIRECTS 8
60#define MAX_CACHED_REDIRECTS 32
61#define HTTP_SINGLE 1
62#define HTTP_MUTLI 2
63#define MAX_DATE_LEN 19
64#define WHITESPACES " \n\t\r"
71
72typedef struct HTTPContext {
73 const AVClass *class;
74 unsigned char buffer[BUFFER_SIZE], *buf_ptr, *buf_end;
75
76 /*************************
77 * Configuration options *
78 *************************/
79 uint64_t off, end_off; /* `off` is also mutated by seeking / reading */
80 char *location;
82 char *headers;
83 char *mime_type;
86 char *referer;
88 int seekable; /**< Control seekability, 0 = disable, 1 = enable, -1 = probe. */
90 int multiple_requests; /**< A flag which indicates if we use persistent connections. */
91 uint8_t *post_data;
93 char *cookies; ///< holds newline (\n) delimited Set-Cookie header field values (without the "Set-Cookie: " field name)
94 int icy;
98 /* -1 = try to send if applicable, 0 = always disabled, 1 = always enabled */
100 char *method;
110 char *resource;
115 uint64_t request_size;
117
118 /**********************
119 * Context-wide state *
120 **********************/
121 HTTPAuthState auth_state; /* auth_state.auth_type is also a config option */
123 uint64_t filesize;
126 /* A dictionary containing cookies keyed by cookie name */
130
131 /* Connection statistics */
137 int64_t sum_latency; /* divide by nb_requests */
139
140 /************************
141 * Per-connection state *
142 ************************/
144 char *uri;
148 /* Used if "Transfer-Encoding: chunked" otherwise -1. */
149 uint64_t chunksize;
151 uint64_t range_end;
152 /* Set if the server correctly handles Connection: close and will close
153 * the connection after feeding us the content. */
155 /* A flag which indicates if the end of chunked encoding has been sent. */
157 /* A flag which indicates we have finished to read POST reply. */
159 /* how much data was read since the last ICY metadata packet */
161 /* after how many bytes of read data a new metadata packet will be found */
162 uint64_t icy_metaint;
163#if CONFIG_ZLIB
164 int compressed;
165 z_stream inflate_stream;
166 uint8_t *inflate_buffer;
167#endif /* CONFIG_ZLIB */
168 unsigned int retry_after;
169 int initial_requests; /* whether or not to limit requests to initial_request_size */
170
171 /* Temporary during header parsing */
174
175 /******************
176 * Listener state *
177 ******************/
178 /* URLContext *hd; */
183
184#define OFFSET(x) offsetof(HTTPContext, x)
185#define D AV_OPT_FLAG_DECODING_PARAM
186#define E AV_OPT_FLAG_ENCODING_PARAM
187#define DEFAULT_USER_AGENT "Lavf/" AV_STRINGIFY(LIBAVFORMAT_VERSION)
188
189static const AVOption http_options[] = {
190 { "seekable", "control seekability of connection", OFFSET(seekable), AV_OPT_TYPE_BOOL, { .i64 = -1 }, -1, 1, D },
191 { "chunked_post", "use chunked transfer-encoding for posts", OFFSET(chunked_post), AV_OPT_TYPE_BOOL, { .i64 = 1 }, 0, 1, E },
192 { "http_proxy", "set HTTP proxy to tunnel through", OFFSET(http_proxy), AV_OPT_TYPE_STRING, { .str = NULL }, 0, 0, D | E },
193 { "headers", "set custom HTTP headers, can override built in default headers", OFFSET(headers), AV_OPT_TYPE_STRING, { .str = NULL }, 0, 0, D | E },
194 { "content_type", "set a specific content type for the POST messages", OFFSET(content_type), AV_OPT_TYPE_STRING, { .str = NULL }, 0, 0, D | E },
195 { "user_agent", "override User-Agent header", OFFSET(user_agent), AV_OPT_TYPE_STRING, { .str = DEFAULT_USER_AGENT }, 0, 0, D },
196 { "referer", "override referer header", OFFSET(referer), AV_OPT_TYPE_STRING, { .str = NULL }, 0, 0, D },
197 { "multiple_requests", "use persistent connections", OFFSET(multiple_requests), AV_OPT_TYPE_BOOL, { .i64 = -1 }, -1, 1, D | E },
198 { "request_size", "size (in bytes) of requests to make", OFFSET(request_size), AV_OPT_TYPE_INT64, { .i64 = 0 }, 0, INT64_MAX, D },
199 { "initial_request_size", "size (in bytes) of initial requests made during probing / header parsing", OFFSET(initial_request_size), AV_OPT_TYPE_INT64, { .i64 = 0 }, 0, INT64_MAX, D },
200 { "post_data", "set custom HTTP post data", OFFSET(post_data), AV_OPT_TYPE_BINARY, .flags = D | E },
201 { "mime_type", "export the MIME type", OFFSET(mime_type), AV_OPT_TYPE_STRING, { .str = NULL }, 0, 0, AV_OPT_FLAG_EXPORT | AV_OPT_FLAG_READONLY },
202 { "http_version", "export the http response version", OFFSET(http_version), AV_OPT_TYPE_STRING, { .str = NULL }, 0, 0, AV_OPT_FLAG_EXPORT | AV_OPT_FLAG_READONLY },
203 { "cookies", "set cookies to be sent in applicable future requests, use newline delimited Set-Cookie HTTP field value syntax", OFFSET(cookies), AV_OPT_TYPE_STRING, { .str = NULL }, 0, 0, D },
204 { "icy", "request ICY metadata", OFFSET(icy), AV_OPT_TYPE_BOOL, { .i64 = 1 }, 0, 1, D },
205 { "icy_metadata_headers", "return ICY metadata headers", OFFSET(icy_metadata_headers), AV_OPT_TYPE_STRING, { .str = NULL }, 0, 0, AV_OPT_FLAG_EXPORT },
206 { "icy_metadata_packet", "return current ICY metadata packet", OFFSET(icy_metadata_packet), AV_OPT_TYPE_STRING, { .str = NULL }, 0, 0, AV_OPT_FLAG_EXPORT },
207 { "metadata", "metadata read from the bitstream", OFFSET(metadata), AV_OPT_TYPE_DICT, {0}, 0, 0, AV_OPT_FLAG_EXPORT },
208 { "auth_type", "HTTP authentication type", OFFSET(auth_state.auth_type), AV_OPT_TYPE_INT, { .i64 = HTTP_AUTH_NONE }, HTTP_AUTH_NONE, HTTP_AUTH_BASIC, D | E, .unit = "auth_type"},
209 { "none", "No auth method set, autodetect", 0, AV_OPT_TYPE_CONST, { .i64 = HTTP_AUTH_NONE }, 0, 0, D | E, .unit = "auth_type"},
210 { "basic", "HTTP basic authentication", 0, AV_OPT_TYPE_CONST, { .i64 = HTTP_AUTH_BASIC }, 0, 0, D | E, .unit = "auth_type"},
211 { "send_expect_100", "Force sending an Expect: 100-continue header for POST", OFFSET(send_expect_100), AV_OPT_TYPE_BOOL, { .i64 = -1 }, -1, 1, E },
212 { "location", "The actual location of the data received", OFFSET(location), AV_OPT_TYPE_STRING, { .str = NULL }, 0, 0, D | E },
213 { "offset", "initial byte offset", OFFSET(off), AV_OPT_TYPE_INT64, { .i64 = 0 }, 0, INT64_MAX, D },
214 { "end_offset", "try to limit the request to bytes preceding this offset", OFFSET(end_off), AV_OPT_TYPE_INT64, { .i64 = 0 }, 0, INT64_MAX, D },
215 { "method", "Override the HTTP method or set the expected HTTP method from a client", OFFSET(method), AV_OPT_TYPE_STRING, { .str = NULL }, 0, 0, D | E },
216 { "reconnect", "auto reconnect after disconnect before EOF", OFFSET(reconnect), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, D },
217 { "reconnect_at_eof", "auto reconnect at EOF", OFFSET(reconnect_at_eof), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, D },
218 { "reconnect_on_network_error", "auto reconnect in case of tcp/tls error during connect", OFFSET(reconnect_on_network_error), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, D },
219 { "reconnect_on_http_error", "list of http status codes to reconnect on", OFFSET(reconnect_on_http_error), AV_OPT_TYPE_STRING, { .str = NULL }, 0, 0, D },
220 { "reconnect_streamed", "auto reconnect streamed / non seekable streams", OFFSET(reconnect_streamed), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, D },
221 { "reconnect_delay_max", "max reconnect delay in seconds after which to give up", OFFSET(reconnect_delay_max), AV_OPT_TYPE_INT, { .i64 = 120 }, 0, UINT_MAX/1000/1000, D },
222 { "reconnect_max_retries", "the max number of times to retry a connection", OFFSET(reconnect_max_retries), AV_OPT_TYPE_INT, { .i64 = -1 }, -1, INT_MAX, D },
223 { "reconnect_delay_total_max", "max total reconnect delay in seconds after which to give up", OFFSET(reconnect_delay_total_max), AV_OPT_TYPE_INT, { .i64 = 256 }, 0, UINT_MAX/1000/1000, D },
224 { "respect_retry_after", "respect the Retry-After header when retrying connections", OFFSET(respect_retry_after), AV_OPT_TYPE_BOOL, { .i64 = 1 }, 0, 1, D },
225 { "listen", "listen on HTTP", OFFSET(listen), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 2, D | E },
226 { "resource", "The resource requested by a client", OFFSET(resource), AV_OPT_TYPE_STRING, { .str = NULL }, 0, 0, E },
227 { "reply_code", "The http status code to return to a client", OFFSET(reply_code), AV_OPT_TYPE_INT, { .i64 = 200}, INT_MIN, 599, E},
228 { "short_seek_size", "Threshold to favor readahead over seek.", OFFSET(short_seek_size), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, INT_MAX, D },
229 { "max_redirects", "Maximum number of redirects", OFFSET(max_redirects), AV_OPT_TYPE_INT, { .i64 = MAX_REDIRECTS }, 0, INT_MAX, D },
230 { NULL }
231};
232
233static int http_connect(URLContext *h, const char *path, const char *local_path,
234 const char *hoststr, const char *auth,
235 const char *proxyauth);
236static int http_read_header(URLContext *h);
237static int http_shutdown(URLContext *h, int flags);
238
240{
241 memcpy(&((HTTPContext *)dest->priv_data)->auth_state,
242 &((HTTPContext *)src->priv_data)->auth_state,
243 sizeof(HTTPAuthState));
244 memcpy(&((HTTPContext *)dest->priv_data)->proxy_auth_state,
245 &((HTTPContext *)src->priv_data)->proxy_auth_state,
246 sizeof(HTTPAuthState));
247}
248
250{
251 const char *path, *proxy_path, *lower_proto = "tcp", *local_path;
252 char *env_http_proxy, *env_no_proxy;
253 char *hashmark;
254 char hostname[1024], hoststr[1024], proto[10], tmp_host[1024];
255 char auth[1024], proxyauth[1024] = "";
256 char path1[MAX_URL_SIZE], sanitized_path[MAX_URL_SIZE + 1];
257 char buf[1024], urlbuf[MAX_URL_SIZE];
258 int port, use_proxy, err = 0;
259 HTTPContext *s = h->priv_data;
260
261 av_url_split(proto, sizeof(proto), auth, sizeof(auth),
262 hostname, sizeof(hostname), &port,
263 path1, sizeof(path1), s->location);
264
265 av_strlcpy(tmp_host, hostname, sizeof(tmp_host));
266 // In case of an IPv6 address, we need to strip the Zone ID,
267 // if any. We do it at the first % sign, as percent encoding
268 // can be used in the Zone ID itself.
269 if (strchr(tmp_host, ':'))
270 tmp_host[strcspn(tmp_host, "%")] = '\0';
271 ff_url_join(hoststr, sizeof(hoststr), NULL, NULL, tmp_host, port, NULL);
272
273 env_http_proxy = getenv_utf8("http_proxy");
274 proxy_path = s->http_proxy ? s->http_proxy : env_http_proxy;
275
276 env_no_proxy = getenv_utf8("no_proxy");
277 use_proxy = !ff_http_match_no_proxy(env_no_proxy, hostname) &&
278 proxy_path && av_strstart(proxy_path, "http://", NULL);
279 freeenv_utf8(env_no_proxy);
280
281 if (h->protocol_whitelist && av_match_list(proto, h->protocol_whitelist, ',') <= 0) {
282 av_log(h, AV_LOG_ERROR, "Protocol '%s' not on whitelist '%s'!\n", proto, h->protocol_whitelist);
283 return AVERROR(EINVAL);
284 }
285
286 if (h->protocol_blacklist && av_match_list(proto, h->protocol_blacklist, ',') > 0) {
287 av_log(h, AV_LOG_ERROR, "Protocol '%s' on blacklist '%s'!\n", proto, h->protocol_blacklist);
288 return AVERROR(EINVAL);
289 }
290
291 if (!strcmp(proto, "https")) {
292 lower_proto = "tls";
293 use_proxy = 0;
294 if (port < 0)
295 port = 443;
296 /* pass http_proxy to underlying protocol */
297 if (s->http_proxy) {
298 err = av_dict_set(options, "http_proxy", s->http_proxy, 0);
299 if (err < 0)
300 goto end;
301 }
302 } else if (strcmp(proto, "http")) {
303 err = AVERROR(EINVAL);
304 goto end;
305 }
306
307 if (port < 0)
308 port = 80;
309
310 hashmark = strchr(path1, '#');
311 if (hashmark)
312 *hashmark = '\0';
313
314 if (path1[0] == '\0') {
315 path = "/";
316 } else if (path1[0] == '?') {
317 snprintf(sanitized_path, sizeof(sanitized_path), "/%s", path1);
318 path = sanitized_path;
319 } else {
320 path = path1;
321 }
322 local_path = path;
323 if (use_proxy) {
324 /* Reassemble the request URL without auth string - we don't
325 * want to leak the auth to the proxy. */
326 ff_url_join(urlbuf, sizeof(urlbuf), proto, NULL, hostname, port, "%s",
327 path1);
328 path = urlbuf;
329 av_url_split(NULL, 0, proxyauth, sizeof(proxyauth),
330 hostname, sizeof(hostname), &port, NULL, 0, proxy_path);
331 }
332
333 ff_url_join(buf, sizeof(buf), lower_proto, NULL, hostname, port, NULL);
334
335 if (!s->hd) {
336 s->nb_connections++;
338 &h->interrupt_callback, options,
339 h->protocol_whitelist, h->protocol_blacklist, h);
340 }
341
342end:
343 freeenv_utf8(env_http_proxy);
344 return err < 0 ? err : http_connect(
345 h, path, local_path, hoststr, auth, proxyauth);
346}
347
349{
350 const char *status_group;
351 char http_code[4];
352
353 switch (err) {
360 status_group = "4xx";
361 break;
362
364 status_group = "5xx";
365 break;
366
367 default:
368 return s->reconnect_on_network_error;
369 }
370
371 if (!s->reconnect_on_http_error)
372 return 0;
373
374 if (av_match_list(status_group, s->reconnect_on_http_error, ',') > 0)
375 return 1;
376
377 snprintf(http_code, sizeof(http_code), "%d", s->http_code);
378
379 return av_match_list(http_code, s->reconnect_on_http_error, ',') > 0;
380}
381
383{
385 int64_t expiry;
386 char *delim;
387
388 re = av_dict_get(s->redirect_cache, s->location, NULL, AV_DICT_MATCH_CASE);
389 if (!re) {
390 return NULL;
391 }
392
393 delim = strchr(re->value, ';');
394 if (!delim) {
395 return NULL;
396 }
397
398 expiry = strtoll(re->value, NULL, 10);
399 if (time(NULL) > expiry) {
400 return NULL;
401 }
402
403 return delim + 1;
404}
405
406static int redirect_cache_set(HTTPContext *s, const char *source, const char *dest, int64_t expiry)
407{
408 char *value;
409 int ret;
410
411 value = av_asprintf("%"PRIi64";%s", expiry, dest);
412 if (!value) {
413 return AVERROR(ENOMEM);
414 }
415
416 ret = av_dict_set(&s->redirect_cache, source, value, AV_DICT_MATCH_CASE | AV_DICT_DONT_STRDUP_VAL);
417 if (ret < 0)
418 return ret;
419
420 return 0;
421}
422
423/* return non zero if error */
425{
426 HTTPAuthType cur_auth_type, cur_proxy_auth_type;
427 HTTPContext *s = h->priv_data;
428 int ret, conn_attempts = 1, auth_attempts = 0, redirects = 0;
429 int reconnect_delay = 0;
430 int reconnect_delay_total = 0;
431 uint64_t off;
432 char *cached;
433
434redo:
435
436 cached = redirect_cache_get(s);
437 if (cached) {
438 if (redirects++ >= s->max_redirects)
439 return AVERROR(EIO);
440
441 av_free(s->location);
442 s->location = av_strdup(cached);
443 if (!s->location) {
444 ret = AVERROR(ENOMEM);
445 goto fail;
446 }
447 goto redo;
448 }
449
450 av_dict_copy(options, s->chained_options, 0);
451
452 cur_auth_type = s->auth_state.auth_type;
453 cur_proxy_auth_type = s->auth_state.auth_type;
454
455 off = s->off;
457 if (ret < 0) {
458 if (!http_should_reconnect(s, ret) ||
459 reconnect_delay > s->reconnect_delay_max ||
460 (s->reconnect_max_retries >= 0 && conn_attempts > s->reconnect_max_retries) ||
461 reconnect_delay_total > s->reconnect_delay_total_max)
462 goto fail;
463
464 /* Both fields here are in seconds. */
465 if (s->respect_retry_after && s->retry_after > 0) {
466 reconnect_delay = s->retry_after;
467 if (reconnect_delay > s->reconnect_delay_max)
468 goto fail;
469 s->retry_after = 0;
470 s->nb_retries++;
471 }
472
473 av_log(h, AV_LOG_WARNING, "Will %s at %"PRIu64" in %d second(s).\n",
474 s->willclose ? "reconnect" : "retry", off, reconnect_delay);
475 ret = ff_network_sleep_interruptible(1000U * 1000 * reconnect_delay, &h->interrupt_callback);
476 if (ret != AVERROR(ETIMEDOUT))
477 goto fail;
478 reconnect_delay_total += reconnect_delay;
479 reconnect_delay = 1 + 2 * reconnect_delay;
480 s->nb_reconnects++;
481 conn_attempts++;
482
483 /* restore the offset (http_connect resets it) */
484 s->off = off;
485
486 ffurl_closep(&s->hd);
487 goto redo;
488 }
489
490 auth_attempts++;
491 if (s->http_code == 401) {
492 if ((cur_auth_type == HTTP_AUTH_NONE || s->auth_state.stale) &&
493 s->auth_state.auth_type != HTTP_AUTH_NONE && auth_attempts < 4) {
494 ffurl_closep(&s->hd);
495 goto redo;
496 } else
497 goto fail;
498 }
499 if (s->http_code == 407) {
500 if ((cur_proxy_auth_type == HTTP_AUTH_NONE || s->proxy_auth_state.stale) &&
501 s->proxy_auth_state.auth_type != HTTP_AUTH_NONE && auth_attempts < 4) {
502 ffurl_closep(&s->hd);
503 goto redo;
504 } else
505 goto fail;
506 }
507 if ((s->http_code == 301 || s->http_code == 302 ||
508 s->http_code == 303 || s->http_code == 307 || s->http_code == 308) &&
509 s->new_location) {
510 /* url moved, get next */
511 ffurl_closep(&s->hd);
512 if (redirects++ >= s->max_redirects)
513 return AVERROR(EIO);
514
515 if (!s->expires) {
516 s->expires = (s->http_code == 301 || s->http_code == 308) ? INT64_MAX : -1;
517 }
518
519 if (s->expires > time(NULL) && av_dict_count(s->redirect_cache) < MAX_CACHED_REDIRECTS) {
520 redirect_cache_set(s, s->location, s->new_location, s->expires);
521 }
522
523 av_free(s->location);
524 s->location = s->new_location;
525 s->new_location = NULL;
526 s->nb_redirects++;
527
528 /* Restart the authentication process with the new target, which
529 * might use a different auth mechanism. */
530 memset(&s->auth_state, 0, sizeof(s->auth_state));
531 auth_attempts = 0;
532 goto redo;
533 }
534 return 0;
535
536fail:
537 s->off = off;
538 if (s->hd)
539 ffurl_closep(&s->hd);
540 if (ret < 0)
541 return ret;
542 return ff_http_averror(s->http_code, AVERROR(EIO));
543}
544
545int ff_http_do_new_request(URLContext *h, const char *uri) {
546 return ff_http_do_new_request2(h, uri, NULL);
547}
548
550{
551 HTTPContext *s = h->priv_data;
553 int ret;
554 char hostname1[1024], hostname2[1024], proto1[10], proto2[10];
555 int port1, port2;
556
557 if (!h->prot ||
558 !(!strcmp(h->prot->name, "http") ||
559 !strcmp(h->prot->name, "https")))
560 return AVERROR(EINVAL);
561
562 av_url_split(proto1, sizeof(proto1), NULL, 0,
563 hostname1, sizeof(hostname1), &port1,
564 NULL, 0, s->location);
565 av_url_split(proto2, sizeof(proto2), NULL, 0,
566 hostname2, sizeof(hostname2), &port2,
567 NULL, 0, uri);
568 if (strcmp(proto1, proto2) != 0) {
569 av_log(h, AV_LOG_INFO, "Cannot reuse HTTP connection for different protocol %s vs %s\n",
570 proto1, proto2);
571 return AVERROR(EINVAL);
572 }
573 if (port1 != port2 || strncmp(hostname1, hostname2, sizeof(hostname2)) != 0) {
574 av_log(h, AV_LOG_INFO, "Cannot reuse HTTP connection for different host: %s:%d != %s:%d\n",
575 hostname1, port1,
576 hostname2, port2
577 );
578 return AVERROR(EINVAL);
579 }
580
581 if (!s->end_chunked_post) {
582 ret = http_shutdown(h, h->flags);
583 if (ret < 0)
584 return ret;
585 }
586
587 if (s->willclose)
588 return AVERROR_EOF;
589
590 s->end_chunked_post = 0;
591 s->chunkend = 0;
592 s->range_end = 0;
593 s->off = 0;
594 s->icy_data_read = 0;
595
596 av_free(s->location);
597 s->location = av_strdup(uri);
598 if (!s->location)
599 return AVERROR(ENOMEM);
600
601 av_free(s->uri);
602 s->uri = av_strdup(uri);
603 if (!s->uri)
604 return AVERROR(ENOMEM);
605
606 if ((ret = av_opt_set_dict(s, opts)) < 0)
607 return ret;
608
609 av_log(s, AV_LOG_INFO, "Opening \'%s\' for %s\n", uri, h->flags & AVIO_FLAG_WRITE ? "writing" : "reading");
610 ret = http_open_cnx(h, &options);
612 return ret;
613}
614
616{
617 HTTPContext *s = h->priv_data;
618 return s->new_location;
619}
620
621static int http_write_reply(URLContext* h, int status_code)
622{
623 int ret, body = 0, reply_code, message_len;
624 const char *reply_text, *content_type;
625 HTTPContext *s = h->priv_data;
626 char message[BUFFER_SIZE];
627 content_type = "text/plain";
628
629 if (status_code < 0)
630 body = 1;
631 switch (status_code) {
633 case 400:
634 reply_code = 400;
635 reply_text = "Bad Request";
636 break;
638 case 403:
639 reply_code = 403;
640 reply_text = "Forbidden";
641 break;
643 case 404:
644 reply_code = 404;
645 reply_text = "Not Found";
646 break;
648 case 429:
649 reply_code = 429;
650 reply_text = "Too Many Requests";
651 break;
652 case 200:
653 reply_code = 200;
654 reply_text = "OK";
655 content_type = s->content_type ? s->content_type : "application/octet-stream";
656 break;
658 case 500:
659 reply_code = 500;
660 reply_text = "Internal server error";
661 break;
662 default:
663 return AVERROR(EINVAL);
664 }
665 if (body) {
666 s->chunked_post = 0;
667 message_len = snprintf(message, sizeof(message),
668 "HTTP/1.1 %03d %s\r\n"
669 "Content-Type: %s\r\n"
670 "Content-Length: %zu\r\n"
671 "%s"
672 "\r\n"
673 "%03d %s\r\n",
674 reply_code,
675 reply_text,
676 content_type,
677 strlen(reply_text) + 6, // 3 digit status code + space + \r\n
678 s->headers ? s->headers : "",
679 reply_code,
680 reply_text);
681 } else {
682 s->chunked_post = 1;
683 message_len = snprintf(message, sizeof(message),
684 "HTTP/1.1 %03d %s\r\n"
685 "Content-Type: %s\r\n"
686 "Transfer-Encoding: chunked\r\n"
687 "%s"
688 "\r\n",
689 reply_code,
690 reply_text,
691 content_type,
692 s->headers ? s->headers : "");
693 }
694 av_log(h, AV_LOG_TRACE, "HTTP reply header: \n%s----\n", message);
695 if ((ret = ffurl_write(s->hd, message, message_len)) < 0)
696 return ret;
697 return 0;
698}
699
701{
702 av_assert0(error < 0);
704}
705
707{
708 int ret, err;
709 HTTPContext *ch = c->priv_data;
710 URLContext *cl = ch->hd;
711 switch (ch->handshake_step) {
712 case LOWER_PROTO:
713 av_log(c, AV_LOG_TRACE, "Lower protocol\n");
714 if ((ret = ffurl_handshake(cl)) > 0)
715 return 2 + ret;
716 if (ret < 0)
717 return ret;
719 ch->is_connected_server = 1;
720 return 2;
721 case READ_HEADERS:
722 av_log(c, AV_LOG_TRACE, "Read headers\n");
723 if ((err = http_read_header(c)) < 0) {
724 handle_http_errors(c, err);
725 return err;
726 }
728 return 1;
730 av_log(c, AV_LOG_TRACE, "Reply code: %d\n", ch->reply_code);
731 if ((err = http_write_reply(c, ch->reply_code)) < 0)
732 return err;
734 return 1;
735 case FINISH:
736 return 0;
737 }
738 // this should never be reached.
739 return AVERROR(EINVAL);
740}
741
742static int http_listen(URLContext *h, const char *uri, int flags,
744 HTTPContext *s = h->priv_data;
745 int ret;
746 char hostname[1024], proto[10];
747 char lower_url[100];
748 const char *lower_proto = "tcp";
749 int port;
750 av_url_split(proto, sizeof(proto), NULL, 0, hostname, sizeof(hostname), &port,
751 NULL, 0, uri);
752 if (!strcmp(proto, "https"))
753 lower_proto = "tls";
754 ff_url_join(lower_url, sizeof(lower_url), lower_proto, NULL, hostname, port,
755 NULL);
756 if ((ret = av_dict_set_int(options, "listen", s->listen, 0)) < 0)
757 goto fail;
758 if ((ret = ffurl_open_whitelist(&s->hd, lower_url, AVIO_FLAG_READ_WRITE,
759 &h->interrupt_callback, options,
760 h->protocol_whitelist, h->protocol_blacklist, h
761 )) < 0)
762 goto fail;
763 s->handshake_step = LOWER_PROTO;
764 if (s->listen == HTTP_SINGLE) { /* single client */
765 s->reply_code = 200;
766 while ((ret = http_handshake(h)) > 0);
767 }
768fail:
769 av_dict_free(&s->chained_options);
770 av_dict_free(&s->cookie_dict);
771 return ret;
772}
773
774static int http_open(URLContext *h, const char *uri, int flags,
776{
777 HTTPContext *s = h->priv_data;
778 int ret;
779
780 if( s->seekable == 1 )
781 h->is_streamed = 0;
782 else
783 h->is_streamed = 1;
784
785 s->initial_requests = s->seekable != 0 && s->initial_request_size > 0;
786 s->filesize = UINT64_MAX;
787
788 s->location = av_strdup(uri);
789 if (!s->location)
790 return AVERROR(ENOMEM);
791
792 s->uri = av_strdup(uri);
793 if (!s->uri)
794 return AVERROR(ENOMEM);
795
796 if (options)
797 av_dict_copy(&s->chained_options, *options, 0);
798
799 if (s->headers) {
800 int len = strlen(s->headers);
801 if (len < 2 || strcmp("\r\n", s->headers + len - 2)) {
803 "No trailing CRLF found in HTTP header. Adding it.\n");
804 ret = av_reallocp(&s->headers, len + 3);
805 if (ret < 0)
806 goto bail_out;
807 s->headers[len] = '\r';
808 s->headers[len + 1] = '\n';
809 s->headers[len + 2] = '\0';
810 }
811 }
812
813 if (s->listen) {
814 return http_listen(h, uri, flags, options);
815 }
816 ret = http_open_cnx(h, options);
817bail_out:
818 if (ret < 0) {
819 av_dict_free(&s->chained_options);
820 av_dict_free(&s->cookie_dict);
821 av_dict_free(&s->redirect_cache);
822 av_freep(&s->new_location);
823 av_freep(&s->uri);
824 }
825 return ret;
826}
827
829{
830 int ret;
831 HTTPContext *sc = s->priv_data;
832 HTTPContext *cc;
833 URLContext *sl = sc->hd;
834 URLContext *cl = NULL;
835
836 av_assert0(sc->listen);
837 if ((ret = ffurl_alloc(c, s->filename, s->flags, &sl->interrupt_callback)) < 0)
838 goto fail;
839 cc = (*c)->priv_data;
840 if ((ret = ffurl_accept(sl, &cl)) < 0)
841 goto fail;
842 cc->hd = cl;
843 cc->is_multi_client = 1;
844 return 0;
845fail:
846 if (c) {
848 }
849 return ret;
850}
851
853{
854 int len;
855 if (s->buf_ptr >= s->buf_end) {
856 len = ffurl_read(s->hd, s->buffer, BUFFER_SIZE);
857 if (len < 0) {
858 return len;
859 } else if (len == 0) {
860 return AVERROR_EOF;
861 } else {
862 s->buf_ptr = s->buffer;
863 s->buf_end = s->buffer + len;
864 }
865 }
866 return *s->buf_ptr++;
867}
868
869static int http_get_line(HTTPContext *s, char *line, int line_size)
870{
871 int ch;
872 char *q;
873
874 q = line;
875 for (;;) {
876 ch = http_getc(s);
877 if (ch < 0)
878 return ch;
879 if (ch == '\n') {
880 /* process line */
881 if (q > line && q[-1] == '\r')
882 q--;
883 *q = '\0';
884
885 return 0;
886 } else {
887 if ((q - line) < line_size - 1)
888 *q++ = ch;
889 }
890 }
891}
892
893static int check_http_code(URLContext *h, int http_code, const char *end)
894{
895 HTTPContext *s = h->priv_data;
896 /* error codes are 4xx and 5xx, but regard 401 as a success, so we
897 * don't abort until all headers have been parsed. */
898 if (http_code >= 400 && http_code < 600 &&
899 (http_code != 401 || s->auth_state.auth_type != HTTP_AUTH_NONE) &&
900 (http_code != 407 || s->proxy_auth_state.auth_type != HTTP_AUTH_NONE)) {
901 end += strspn(end, SPACE_CHARS);
902 av_log(h, AV_LOG_WARNING, "HTTP error %d %s\n", http_code, end);
903 return ff_http_averror(http_code, AVERROR(EIO));
904 }
905 return 0;
906}
907
908static int parse_location(HTTPContext *s, const char *p)
909{
910 char redirected_location[MAX_URL_SIZE];
911 ff_make_absolute_url(redirected_location, sizeof(redirected_location),
912 s->location, p);
913 av_freep(&s->new_location);
914 s->new_location = av_strdup(redirected_location);
915 if (!s->new_location)
916 return AVERROR(ENOMEM);
917 return 0;
918}
919
920/* "bytes $from-$to/$document_size" */
921static void parse_content_range(URLContext *h, const char *p)
922{
923 HTTPContext *s = h->priv_data;
924 const char *slash, *end;
925
926 if (!strncmp(p, "bytes ", 6)) {
927 p += 6;
928 s->off = strtoull(p, NULL, 10);
929 if ((end = strchr(p, '-')) && strlen(end) > 0)
930 s->range_end = strtoull(end + 1, NULL, 10) + 1;
931 if ((slash = strchr(p, '/')) && strlen(slash) > 0)
932 s->filesize_from_content_range = strtoull(slash + 1, NULL, 10);
933 }
934 if (s->seekable == -1 && (!s->is_akamai || s->filesize != 2147483647))
935 h->is_streamed = 0; /* we _can_ in fact seek */
936}
937
938static int parse_content_encoding(URLContext *h, const char *p)
939{
940 if (!av_strncasecmp(p, "gzip", 4) ||
941 !av_strncasecmp(p, "deflate", 7)) {
942#if CONFIG_ZLIB
943 HTTPContext *s = h->priv_data;
944
945 s->compressed = 1;
946 inflateEnd(&s->inflate_stream);
947 if (inflateInit2(&s->inflate_stream, 32 + 15) != Z_OK) {
948 av_log(h, AV_LOG_WARNING, "Error during zlib initialisation: %s\n",
949 s->inflate_stream.msg);
950 return AVERROR(ENOSYS);
951 }
952 if (zlibCompileFlags() & (1 << 17)) {
954 "Your zlib was compiled without gzip support.\n");
955 return AVERROR(ENOSYS);
956 }
957#else
959 "Compressed (%s) content, need zlib with gzip support\n", p);
960 return AVERROR(ENOSYS);
961#endif /* CONFIG_ZLIB */
962 } else if (!av_strncasecmp(p, "identity", 8)) {
963 // The normal, no-encoding case (although servers shouldn't include
964 // the header at all if this is the case).
965 } else {
966 av_log(h, AV_LOG_WARNING, "Unknown content coding: %s\n", p);
967 }
968 return 0;
969}
970
971// Concat all Icy- header lines
972static int parse_icy(HTTPContext *s, const char *tag, const char *p)
973{
974 int len = 4 + strlen(p) + strlen(tag);
975 int is_first = !s->icy_metadata_headers;
976 int ret;
977
978 av_dict_set(&s->metadata, tag, p, 0);
979
980 if (s->icy_metadata_headers)
981 len += strlen(s->icy_metadata_headers);
982
983 if ((ret = av_reallocp(&s->icy_metadata_headers, len)) < 0)
984 return ret;
985
986 if (is_first)
987 *s->icy_metadata_headers = '\0';
988
989 av_strlcatf(s->icy_metadata_headers, len, "%s: %s\n", tag, p);
990
991 return 0;
992}
993
994static int parse_http_date(const char *date_str, struct tm *buf)
995{
996 char date_buf[MAX_DATE_LEN];
997 int i, j, date_buf_len = MAX_DATE_LEN-1;
998 char *date;
999
1000 // strip off any punctuation or whitespace
1001 for (i = 0, j = 0; date_str[i] != '\0' && j < date_buf_len; i++) {
1002 if ((date_str[i] >= '0' && date_str[i] <= '9') ||
1003 (date_str[i] >= 'A' && date_str[i] <= 'Z') ||
1004 (date_str[i] >= 'a' && date_str[i] <= 'z')) {
1005 date_buf[j] = date_str[i];
1006 j++;
1007 }
1008 }
1009 date_buf[j] = '\0';
1010 date = date_buf;
1011
1012 // move the string beyond the day of week
1013 while ((*date < '0' || *date > '9') && *date != '\0')
1014 date++;
1015
1016 return av_small_strptime(date, "%d%b%Y%H%M%S", buf) ? 0 : AVERROR(EINVAL);
1017}
1018
1019static int parse_set_cookie(const char *set_cookie, AVDictionary **dict)
1020{
1021 char *param, *next_param, *cstr, *back;
1022 char *saveptr = NULL;
1023
1024 if (!set_cookie[0])
1025 return 0;
1026
1027 if (!(cstr = av_strdup(set_cookie)))
1028 return AVERROR(EINVAL);
1029
1030 // strip any trailing whitespace
1031 back = &cstr[strlen(cstr)-1];
1032 while (strchr(WHITESPACES, *back)) {
1033 *back='\0';
1034 if (back == cstr)
1035 break;
1036 back--;
1037 }
1038
1039 next_param = cstr;
1040 while ((param = av_strtok(next_param, ";", &saveptr))) {
1041 char *name, *value;
1042 next_param = NULL;
1043 param += strspn(param, WHITESPACES);
1044 if ((name = av_strtok(param, "=", &value))) {
1045 if (av_dict_set(dict, name, value, 0) < 0) {
1046 av_free(cstr);
1047 return -1;
1048 }
1049 }
1050 }
1051
1052 av_free(cstr);
1053 return 0;
1054}
1055
1056static int parse_cookie(HTTPContext *s, const char *p, AVDictionary **cookies)
1057{
1058 AVDictionary *new_params = NULL;
1059 const AVDictionaryEntry *e, *cookie_entry;
1060 const char *eql;
1061 char *name;
1062
1063 // ensure the cookie is parsable
1064 if (parse_set_cookie(p, &new_params)) {
1065 av_dict_free(&new_params);
1066 return -1;
1067 }
1068
1069 // if there is no cookie value there is nothing to parse
1070 cookie_entry = av_dict_iterate(new_params, NULL);
1071 if (!cookie_entry || !cookie_entry->value) {
1072 av_dict_free(&new_params);
1073 return -1;
1074 }
1075
1076 // ensure the cookie is not expired or older than an existing value
1077 if ((e = av_dict_get(new_params, "expires", NULL, 0)) && e->value) {
1078 struct tm new_tm = {0};
1079 if (!parse_http_date(e->value, &new_tm)) {
1081
1082 // if the cookie has already expired ignore it
1083 if (av_timegm(&new_tm) < av_gettime() / 1000000) {
1084 av_dict_free(&new_params);
1085 return 0;
1086 }
1087
1088 // only replace an older cookie with the same name
1089 e2 = av_dict_get(*cookies, cookie_entry->key, NULL, 0);
1090 if (e2 && e2->value) {
1091 AVDictionary *old_params = NULL;
1092 if (!parse_set_cookie(p, &old_params)) {
1093 e2 = av_dict_get(old_params, "expires", NULL, 0);
1094 if (e2 && e2->value) {
1095 struct tm old_tm = {0};
1096 if (!parse_http_date(e->value, &old_tm)) {
1097 if (av_timegm(&new_tm) < av_timegm(&old_tm)) {
1098 av_dict_free(&new_params);
1099 av_dict_free(&old_params);
1100 return -1;
1101 }
1102 }
1103 }
1104 }
1105 av_dict_free(&old_params);
1106 }
1107 }
1108 }
1109 av_dict_free(&new_params);
1110
1111 // duplicate the cookie name (dict will dupe the value)
1112 if (!(eql = strchr(p, '='))) return AVERROR(EINVAL);
1113 if (!(name = av_strndup(p, eql - p))) return AVERROR(ENOMEM);
1114
1115 // add the cookie to the dictionary
1117
1118 return 0;
1119}
1120
1121static int cookie_string(AVDictionary *dict, char **cookies)
1122{
1123 const AVDictionaryEntry *e = NULL;
1124 int len = 1;
1125
1126 // determine how much memory is needed for the cookies string
1127 while ((e = av_dict_iterate(dict, e)))
1128 len += strlen(e->key) + strlen(e->value) + 1;
1129
1130 // reallocate the cookies
1131 e = NULL;
1132 if (*cookies) av_free(*cookies);
1133 *cookies = av_malloc(len);
1134 if (!*cookies) return AVERROR(ENOMEM);
1135 *cookies[0] = '\0';
1136
1137 // write out the cookies
1138 while ((e = av_dict_iterate(dict, e)))
1139 av_strlcatf(*cookies, len, "%s%s\n", e->key, e->value);
1140
1141 return 0;
1142}
1143
1144static void parse_expires(HTTPContext *s, const char *p)
1145{
1146 struct tm tm;
1147
1148 if (!parse_http_date(p, &tm)) {
1149 s->expires = av_timegm(&tm);
1150 }
1151}
1152
1153static void parse_cache_control(HTTPContext *s, const char *p)
1154{
1155 char *age;
1156 int offset;
1157
1158 /* give 'Expires' higher priority over 'Cache-Control' */
1159 if (s->expires) {
1160 return;
1161 }
1162
1163 if (av_stristr(p, "no-cache") || av_stristr(p, "no-store")) {
1164 s->expires = -1;
1165 return;
1166 }
1167
1168 age = av_stristr(p, "s-maxage=");
1169 offset = 9;
1170 if (!age) {
1171 age = av_stristr(p, "max-age=");
1172 offset = 8;
1173 }
1174
1175 if (age) {
1176 s->expires = time(NULL) + atoi(age + offset);
1177 }
1178}
1179
1180static int process_line(URLContext *h, char *line, int line_count, int *parsed_http_code)
1181{
1182 HTTPContext *s = h->priv_data;
1183 const char *auto_method = h->flags & AVIO_FLAG_READ ? "POST" : "GET";
1184 char *tag, *p, *end, *method, *resource, *version;
1185 int ret;
1186
1187 /* end of header */
1188 if (line[0] == '\0') {
1189 s->end_header = 1;
1190 return 0;
1191 }
1192
1193 p = line;
1194 if (line_count == 0) {
1195 if (s->is_connected_server) {
1196 // HTTP method
1197 method = p;
1198 while (*p && !av_isspace(*p))
1199 p++;
1200 if (!av_isspace(*p))
1202 *(p++) = '\0';
1203 av_log(h, AV_LOG_TRACE, "Received method: %s\n", method);
1204 if (s->method) {
1205 if (av_strcasecmp(s->method, method)) {
1206 av_log(h, AV_LOG_ERROR, "Received and expected HTTP method do not match. (%s expected, %s received)\n",
1207 s->method, method);
1209 }
1210 } else {
1211 // use autodetected HTTP method to expect
1212 av_log(h, AV_LOG_TRACE, "Autodetected %s HTTP method\n", auto_method);
1213 if (av_strcasecmp(auto_method, method)) {
1214 av_log(h, AV_LOG_ERROR, "Received and autodetected HTTP method did not match "
1215 "(%s autodetected %s received)\n", auto_method, method);
1217 }
1218 if (!(s->method = av_strdup(method)))
1219 return AVERROR(ENOMEM);
1220 }
1221
1222 // HTTP resource
1223 while (av_isspace(*p))
1224 p++;
1225 resource = p;
1226 while (*p && !av_isspace(*p))
1227 p++;
1228 if (!av_isspace(*p))
1230 *(p++) = '\0';
1231 av_log(h, AV_LOG_TRACE, "Requested resource: %s\n", resource);
1232 if (!(s->resource = av_strdup(resource)))
1233 return AVERROR(ENOMEM);
1234
1235 // HTTP version
1236 while (av_isspace(*p))
1237 p++;
1238 version = p;
1239 while (*p && !av_isspace(*p))
1240 p++;
1241 *p = '\0';
1242 if (av_strncasecmp(version, "HTTP/", 5)) {
1243 av_log(h, AV_LOG_ERROR, "Malformed HTTP version string.\n");
1245 }
1246 av_log(h, AV_LOG_TRACE, "HTTP version string: %s\n", version);
1247 } else {
1248 if (av_strncasecmp(p, "HTTP/1.0", 8) == 0)
1249 s->willclose = 1;
1250 while (*p != '/' && *p != '\0')
1251 p++;
1252 while (*p == '/')
1253 p++;
1254 av_freep(&s->http_version);
1255 s->http_version = av_strndup(p, 3);
1256 while (!av_isspace(*p) && *p != '\0')
1257 p++;
1258 while (av_isspace(*p))
1259 p++;
1260 s->http_code = strtol(p, &end, 10);
1261
1262 av_log(h, AV_LOG_TRACE, "http_code=%d\n", s->http_code);
1263
1264 *parsed_http_code = 1;
1265
1266 if ((ret = check_http_code(h, s->http_code, end)) < 0)
1267 return ret;
1268 }
1269 } else {
1270 while (*p != '\0' && *p != ':')
1271 p++;
1272 if (*p != ':')
1273 return 1;
1274
1275 *p = '\0';
1276 tag = line;
1277 p++;
1278 while (av_isspace(*p))
1279 p++;
1280 if (!av_strcasecmp(tag, "Location")) {
1281 if ((ret = parse_location(s, p)) < 0)
1282 return ret;
1283 } else if (!av_strcasecmp(tag, "Content-Length") &&
1284 s->filesize == UINT64_MAX) {
1285 s->filesize = strtoull(p, NULL, 10);
1286 } else if (!av_strcasecmp(tag, "Content-Range")) {
1288 } else if (!av_strcasecmp(tag, "Accept-Ranges") &&
1289 !strncmp(p, "bytes", 5) &&
1290 s->seekable == -1) {
1291 h->is_streamed = 0;
1292 } else if (!av_strcasecmp(tag, "Transfer-Encoding") &&
1293 !av_strncasecmp(p, "chunked", 7)) {
1294 s->filesize = UINT64_MAX;
1295 s->chunksize = 0;
1296 } else if (!av_strcasecmp(tag, "WWW-Authenticate")) {
1297 ff_http_auth_handle_header(&s->auth_state, tag, p);
1298 } else if (!av_strcasecmp(tag, "Authentication-Info")) {
1299 ff_http_auth_handle_header(&s->auth_state, tag, p);
1300 } else if (!av_strcasecmp(tag, "Proxy-Authenticate")) {
1301 ff_http_auth_handle_header(&s->proxy_auth_state, tag, p);
1302 } else if (!av_strcasecmp(tag, "Connection")) {
1303 if (!av_strcasecmp(p, "close"))
1304 s->willclose = 1;
1305 } else if (!av_strcasecmp(tag, "Server")) {
1306 if (!av_strcasecmp(p, "AkamaiGHost")) {
1307 s->is_akamai = 1;
1308 } else if (!av_strncasecmp(p, "MediaGateway", 12)) {
1309 s->is_mediagateway = 1;
1310 }
1311 } else if (!av_strcasecmp(tag, "Content-Type")) {
1312 av_free(s->mime_type);
1313 s->mime_type = av_get_token((const char **)&p, ";");
1314 } else if (!av_strcasecmp(tag, "Set-Cookie")) {
1315 if (parse_cookie(s, p, &s->cookie_dict))
1316 av_log(h, AV_LOG_WARNING, "Unable to parse '%s'\n", p);
1317 } else if (!av_strcasecmp(tag, "Icy-MetaInt")) {
1318 s->icy_metaint = strtoull(p, NULL, 10);
1319 } else if (!av_strncasecmp(tag, "Icy-", 4)) {
1320 if ((ret = parse_icy(s, tag, p)) < 0)
1321 return ret;
1322 } else if (!av_strcasecmp(tag, "Content-Encoding")) {
1323 if ((ret = parse_content_encoding(h, p)) < 0)
1324 return ret;
1325 } else if (!av_strcasecmp(tag, "Expires")) {
1326 parse_expires(s, p);
1327 } else if (!av_strcasecmp(tag, "Cache-Control")) {
1329 } else if (!av_strcasecmp(tag, "Retry-After")) {
1330 /* The header can be either an integer that represents seconds, or a date. */
1331 struct tm tm;
1332 int date_ret = parse_http_date(p, &tm);
1333 if (!date_ret) {
1334 time_t retry = av_timegm(&tm);
1335 int64_t now = av_gettime() / 1000000;
1336 int64_t diff = ((int64_t) retry) - now;
1337 s->retry_after = (unsigned int) FFMAX(0, diff);
1338 } else {
1339 s->retry_after = strtoul(p, NULL, 10);
1340 }
1341 }
1342 }
1343 return 1;
1344}
1345
1346/**
1347 * Create a string containing cookie values for use as a HTTP cookie header
1348 * field value for a particular path and domain from the cookie values stored in
1349 * the HTTP protocol context. The cookie string is stored in *cookies, and may
1350 * be NULL if there are no valid cookies.
1351 *
1352 * @return a negative value if an error condition occurred, 0 otherwise
1353 */
1354static int get_cookies(HTTPContext *s, char **cookies, const char *path,
1355 const char *domain)
1356{
1357 // cookie strings will look like Set-Cookie header field values. Multiple
1358 // Set-Cookie fields will result in multiple values delimited by a newline
1359 int ret = 0;
1360 char *cookie, *set_cookies, *next;
1361 char *saveptr = NULL;
1362
1363 // destroy any cookies in the dictionary.
1364 av_dict_free(&s->cookie_dict);
1365
1366 if (!s->cookies)
1367 return 0;
1368
1369 next = set_cookies = av_strdup(s->cookies);
1370 if (!next)
1371 return AVERROR(ENOMEM);
1372
1373 *cookies = NULL;
1374 while ((cookie = av_strtok(next, "\n", &saveptr)) && !ret) {
1375 AVDictionary *cookie_params = NULL;
1376 const AVDictionaryEntry *cookie_entry, *e;
1377
1378 next = NULL;
1379 // store the cookie in a dict in case it is updated in the response
1380 if (parse_cookie(s, cookie, &s->cookie_dict))
1381 av_log(s, AV_LOG_WARNING, "Unable to parse '%s'\n", cookie);
1382
1383 // continue on to the next cookie if this one cannot be parsed
1384 if (parse_set_cookie(cookie, &cookie_params))
1385 goto skip_cookie;
1386
1387 // if the cookie has no value, skip it
1388 cookie_entry = av_dict_iterate(cookie_params, NULL);
1389 if (!cookie_entry || !cookie_entry->value)
1390 goto skip_cookie;
1391
1392 // if the cookie has expired, don't add it
1393 if ((e = av_dict_get(cookie_params, "expires", NULL, 0)) && e->value) {
1394 struct tm tm_buf = {0};
1395 if (!parse_http_date(e->value, &tm_buf)) {
1396 if (av_timegm(&tm_buf) < av_gettime() / 1000000)
1397 goto skip_cookie;
1398 }
1399 }
1400
1401 // if no domain in the cookie assume it applied to this request
1402 if ((e = av_dict_get(cookie_params, "domain", NULL, 0)) && e->value) {
1403 // find the offset comparison is on the min domain (b.com, not a.b.com)
1404 int domain_offset = strlen(domain) - strlen(e->value);
1405 if (domain_offset < 0)
1406 goto skip_cookie;
1407
1408 // match the cookie domain
1409 if (av_strcasecmp(&domain[domain_offset], e->value))
1410 goto skip_cookie;
1411 }
1412
1413 // if a cookie path is provided, ensure the request path is within that path
1414 e = av_dict_get(cookie_params, "path", NULL, 0);
1415 if (e && av_strncasecmp(path, e->value, strlen(e->value)))
1416 goto skip_cookie;
1417
1418 // cookie parameters match, so copy the value
1419 if (!*cookies) {
1420 *cookies = av_asprintf("%s=%s", cookie_entry->key, cookie_entry->value);
1421 } else {
1422 char *tmp = *cookies;
1423 *cookies = av_asprintf("%s; %s=%s", tmp, cookie_entry->key, cookie_entry->value);
1424 av_free(tmp);
1425 }
1426 if (!*cookies)
1427 ret = AVERROR(ENOMEM);
1428
1429 skip_cookie:
1430 av_dict_free(&cookie_params);
1431 }
1432
1433 av_free(set_cookies);
1434
1435 return ret;
1436}
1437
1438static inline int has_header(const char *str, const char *header)
1439{
1440 /* header + 2 to skip over CRLF prefix. (make sure you have one!) */
1441 if (!str)
1442 return 0;
1443 return av_stristart(str, header + 2, NULL) || av_stristr(str, header);
1444}
1445
1447{
1448 HTTPContext *s = h->priv_data;
1449 char line[MAX_URL_SIZE];
1450 int err = 0, http_err = 0;
1451
1452 av_freep(&s->new_location);
1453 s->expires = 0;
1454 s->chunksize = UINT64_MAX;
1455 s->filesize_from_content_range = UINT64_MAX;
1456
1457 for (;;) {
1458 int parsed_http_code = 0;
1459
1460 if ((err = http_get_line(s, line, sizeof(line))) < 0) {
1461 av_log(h, AV_LOG_ERROR, "Error reading HTTP response: %s\n",
1462 av_err2str(err));
1463 return err;
1464 }
1465
1466 av_log(h, AV_LOG_TRACE, "header='%s'\n", line);
1467
1468 err = process_line(h, line, s->line_count, &parsed_http_code);
1469 if (err < 0) {
1470 if (parsed_http_code) {
1471 http_err = err;
1472 } else {
1473 /* Prefer to return HTTP code error if we've already seen one. */
1474 if (http_err)
1475 return http_err;
1476 else
1477 return err;
1478 }
1479 }
1480 if (err == 0)
1481 break;
1482 s->line_count++;
1483 }
1484 if (http_err)
1485 return http_err;
1486
1487 // filesize from Content-Range can always be used, even if using chunked Transfer-Encoding
1488 if (s->filesize_from_content_range != UINT64_MAX)
1489 s->filesize = s->filesize_from_content_range;
1490
1491 if (s->seekable == -1 && s->is_mediagateway && s->filesize == 2000000000)
1492 h->is_streamed = 1; /* we can in fact _not_ seek */
1493
1494 if (h->is_streamed)
1495 s->initial_requests = 0; /* unable to use partial requests */
1496
1497 // add any new cookies into the existing cookie string
1498 cookie_string(s->cookie_dict, &s->cookies);
1499 av_dict_free(&s->cookie_dict);
1500
1501 return err;
1502}
1503
1504/**
1505 * Escape unsafe characters in path in order to pass them safely to the HTTP
1506 * request. Insipred by the algorithm in GNU wget:
1507 * - escape "%" characters not followed by two hex digits
1508 * - escape all "unsafe" characters except which are also "reserved"
1509 * - pass through everything else
1510 */
1511static void bprint_escaped_path(AVBPrint *bp, const char *path)
1512{
1513#define NEEDS_ESCAPE(ch) \
1514 ((ch) <= ' ' || (ch) >= '\x7f' || \
1515 (ch) == '"' || (ch) == '%' || (ch) == '<' || (ch) == '>' || (ch) == '\\' || \
1516 (ch) == '^' || (ch) == '`' || (ch) == '{' || (ch) == '}' || (ch) == '|')
1517 while (*path) {
1518 char buf[1024];
1519 char *q = buf;
1520 while (*path && q - buf < sizeof(buf) - 4) {
1521 if (path[0] == '%' && av_isxdigit(path[1]) && av_isxdigit(path[2])) {
1522 *q++ = *path++;
1523 *q++ = *path++;
1524 *q++ = *path++;
1525 } else if (NEEDS_ESCAPE(*path)) {
1526 q += snprintf(q, 4, "%%%02X", (uint8_t)*path++);
1527 } else {
1528 *q++ = *path++;
1529 }
1530 }
1531 av_bprint_append_data(bp, buf, q - buf);
1532 }
1533}
1534
1535static uint64_t request_size(URLContext *h)
1536{
1537 HTTPContext *s = h->priv_data;
1538 if (s->initial_requests)
1539 return s->initial_request_size;
1540 return s->request_size;
1541}
1542
1543static int http_connect(URLContext *h, const char *path, const char *local_path,
1544 const char *hoststr, const char *auth,
1545 const char *proxyauth)
1546{
1547 HTTPContext *s = h->priv_data;
1548 int post, err;
1549 AVBPrint request;
1550 char *authstr = NULL, *proxyauthstr = NULL;
1551 uint64_t off = s->off;
1552 const char *method;
1553 int send_expect_100 = 0;
1554 int keep_alive = 1;
1555
1556 av_bprint_init_for_buffer(&request, s->buffer, sizeof(s->buffer));
1557
1558 /* send http header */
1559 post = h->flags & AVIO_FLAG_WRITE;
1560
1561 if (s->post_data) {
1562 /* force POST method and disable chunked encoding when
1563 * custom HTTP post data is set */
1564 post = 1;
1565 s->chunked_post = 0;
1566 }
1567
1568 if (s->method)
1569 method = s->method;
1570 else
1571 method = post ? "POST" : "GET";
1572
1573 authstr = ff_http_auth_create_response(&s->auth_state, auth,
1574 local_path, method);
1575 proxyauthstr = ff_http_auth_create_response(&s->proxy_auth_state, proxyauth,
1576 local_path, method);
1577
1578 if (post && !s->post_data) {
1579 if (s->send_expect_100 != -1) {
1580 send_expect_100 = s->send_expect_100;
1581 } else {
1582 send_expect_100 = 0;
1583 /* The user has supplied authentication but we don't know the auth type,
1584 * send Expect: 100-continue to get the 401 response including the
1585 * WWW-Authenticate header, or an 100 continue if no auth actually
1586 * is needed. */
1587 if (auth && *auth &&
1588 s->auth_state.auth_type == HTTP_AUTH_NONE &&
1589 s->http_code != 401)
1590 send_expect_100 = 1;
1591 }
1592 }
1593
1594 av_bprintf(&request, "%s ", method);
1595 bprint_escaped_path(&request, path);
1596 av_bprintf(&request, " HTTP/1.1\r\n");
1597
1598 if (post && s->chunked_post)
1599 av_bprintf(&request, "Transfer-Encoding: chunked\r\n");
1600 /* set default headers if needed */
1601 if (!has_header(s->headers, "\r\nUser-Agent: "))
1602 av_bprintf(&request, "User-Agent: %s\r\n", s->user_agent);
1603 if (s->referer) {
1604 /* set default headers if needed */
1605 if (!has_header(s->headers, "\r\nReferer: "))
1606 av_bprintf(&request, "Referer: %s\r\n", s->referer);
1607 }
1608 if (!has_header(s->headers, "\r\nAccept: "))
1609 av_bprintf(&request, "Accept: */*\r\n");
1610 // Note: we send the Range header on purpose, even when we're probing,
1611 // since it allows us to detect more reliably if a (non-conforming)
1612 // server supports seeking by analysing the reply headers.
1613 int is_partial_request = 0;
1614 if (!has_header(s->headers, "\r\nRange: ") && !post && (s->off > 0 || s->end_off || s->seekable != 0)) {
1615 av_bprintf(&request, "Range: bytes=%"PRIu64"-", s->off);
1616 uint64_t req_size = request_size(h);
1617 if (req_size && s->seekable != 0) {
1618 uint64_t target_off = s->off + req_size;
1619 if (target_off < s->off) /* overflow */
1620 target_off = UINT64_MAX;
1621 if (s->end_off)
1622 target_off = FFMIN(target_off, s->end_off);
1623 if (target_off != UINT64_MAX) {
1624 av_bprintf(&request, "%"PRId64, target_off - 1);
1625 is_partial_request = 1;
1626 }
1627 } else if (s->end_off)
1628 av_bprintf(&request, "%"PRId64, s->end_off - 1);
1629 av_bprintf(&request, "\r\n");
1630 }
1631 if (send_expect_100 && !has_header(s->headers, "\r\nExpect: "))
1632 av_bprintf(&request, "Expect: 100-continue\r\n");
1633
1634 if (!has_header(s->headers, "\r\nConnection: ")) {
1635 keep_alive = s->multiple_requests > 0;
1636 if (s->multiple_requests < 0 /* auto */ && is_partial_request)
1637 keep_alive = 1;
1638 av_bprintf(&request, "Connection: %s\r\n", keep_alive ? "keep-alive" : "close");
1639 }
1640
1641 if (!has_header(s->headers, "\r\nHost: "))
1642 av_bprintf(&request, "Host: %s\r\n", hoststr);
1643 if (!has_header(s->headers, "\r\nContent-Length: ") && s->post_data)
1644 av_bprintf(&request, "Content-Length: %d\r\n", s->post_datalen);
1645
1646 if (!has_header(s->headers, "\r\nContent-Type: ") && s->content_type)
1647 av_bprintf(&request, "Content-Type: %s\r\n", s->content_type);
1648 if (!has_header(s->headers, "\r\nCookie: ") && s->cookies) {
1649 char *cookies = NULL;
1650 if (!get_cookies(s, &cookies, path, hoststr) && cookies) {
1651 av_bprintf(&request, "Cookie: %s\r\n", cookies);
1652 av_free(cookies);
1653 }
1654 }
1655 if (!has_header(s->headers, "\r\nIcy-MetaData: ") && s->icy)
1656 av_bprintf(&request, "Icy-MetaData: 1\r\n");
1657
1658 /* now add in custom headers */
1659 if (s->headers)
1660 av_bprintf(&request, "%s", s->headers);
1661
1662 if (authstr)
1663 av_bprintf(&request, "%s", authstr);
1664 if (proxyauthstr)
1665 av_bprintf(&request, "Proxy-%s", proxyauthstr);
1666 av_bprintf(&request, "\r\n");
1667
1668 av_log(h, AV_LOG_DEBUG, "request: %s\n", request.str);
1669
1670 if (!av_bprint_is_complete(&request)) {
1671 av_log(h, AV_LOG_ERROR, "overlong headers\n");
1672 err = AVERROR(EINVAL);
1673 goto done;
1674 }
1675
1676 if ((err = ffurl_write(s->hd, request.str, request.len)) < 0)
1677 goto done;
1678
1679 if (s->post_data)
1680 if ((err = ffurl_write(s->hd, s->post_data, s->post_datalen)) < 0)
1681 goto done;
1682
1683 /* init input buffer */
1684 s->buf_ptr = s->buffer;
1685 s->buf_end = s->buffer;
1686 s->line_count = 0;
1687 s->off = 0;
1688 s->icy_data_read = 0;
1689 s->filesize = UINT64_MAX;
1690 s->range_end = 0;
1691 s->willclose = !keep_alive;
1692 s->end_chunked_post = 0;
1693 s->end_header = 0;
1694#if CONFIG_ZLIB
1695 s->compressed = 0;
1696#endif
1697 if (post && !s->post_data && !send_expect_100) {
1698 /* Pretend that it did work. We didn't read any header yet, since
1699 * we've still to send the POST data, but the code calling this
1700 * function will check http_code after we return. */
1701 s->http_code = 200;
1702 err = 0;
1703 goto done;
1704 }
1705
1706 /* wait for header */
1707 int64_t latency = av_gettime();
1708 err = http_read_header(h);
1709 latency = av_gettime() - latency;
1710 if (err < 0)
1711 goto done;
1712
1713 s->nb_requests++;
1714 s->sum_latency += latency;
1715 s->max_latency = FFMAX(s->max_latency, latency);
1716
1717 if (s->new_location)
1718 s->off = off;
1719
1720 if (off != s->off) {
1722 "Unexpected offset: expected %"PRIu64", got %"PRIu64"\n",
1723 off, s->off);
1724 err = AVERROR(EIO);
1725 goto done;
1726 }
1727
1728 err = 0;
1729done:
1730 av_freep(&authstr);
1731 av_freep(&proxyauthstr);
1732 return err;
1733}
1734
1735static int http_buf_read(URLContext *h, uint8_t *buf, int size)
1736{
1737 HTTPContext *s = h->priv_data;
1738 int len;
1739
1740 if (!s->hd)
1741 return AVERROR(EIO);
1742
1743 if (s->chunksize != UINT64_MAX) {
1744 if (s->chunkend) {
1745 return AVERROR_EOF;
1746 }
1747 if (!s->chunksize) {
1748 char line[32];
1749 int err;
1750
1751 do {
1752 if ((err = http_get_line(s, line, sizeof(line))) < 0)
1753 return err;
1754 } while (!*line); /* skip CR LF from last chunk */
1755
1756 s->chunksize = strtoull(line, NULL, 16);
1757
1759 "Chunked encoding data size: %"PRIu64"\n",
1760 s->chunksize);
1761
1762 if (!s->chunksize && s->multiple_requests) {
1763 http_get_line(s, line, sizeof(line)); // read empty chunk
1764 s->chunkend = 1;
1765 return 0;
1766 }
1767 else if (!s->chunksize) {
1768 av_log(h, AV_LOG_DEBUG, "Last chunk received, closing conn\n");
1769 ffurl_closep(&s->hd);
1770 return 0;
1771 }
1772 else if (s->chunksize == UINT64_MAX) {
1773 av_log(h, AV_LOG_ERROR, "Invalid chunk size %"PRIu64"\n",
1774 s->chunksize);
1775 return AVERROR(EINVAL);
1776 }
1777 }
1778 size = FFMIN(size, s->chunksize);
1779 }
1780
1781 /* read bytes from input buffer first */
1782 len = s->buf_end - s->buf_ptr;
1783 if (len > 0) {
1784 if (len > size)
1785 len = size;
1786 memcpy(buf, s->buf_ptr, len);
1787 s->buf_ptr += len;
1788 } else {
1789 uint64_t file_end = s->end_off ? s->end_off : s->filesize;
1790 uint64_t target_end = s->range_end ? s->range_end : file_end;
1791 if ((!s->willclose || s->chunksize == UINT64_MAX) && s->off >= file_end)
1792 return AVERROR_EOF;
1793 if (s->off == target_end && target_end < file_end)
1794 return AVERROR(EAGAIN); /* reached end of content range */
1795 len = ffurl_read(s->hd, buf, size);
1796 if ((!len || len == AVERROR_EOF) &&
1797 (!s->willclose || s->chunksize == UINT64_MAX) && s->off < target_end) {
1799 "Stream ends prematurely at %"PRIu64", should be %"PRIu64"\n",
1800 s->off, target_end
1801 );
1802 return AVERROR(EIO);
1803 }
1804 }
1805 if (len > 0) {
1806 s->off += len;
1807 if (s->chunksize > 0 && s->chunksize != UINT64_MAX) {
1808 av_assert0(s->chunksize >= len);
1809 s->chunksize -= len;
1810 }
1811 }
1812 return len;
1813}
1814
1815#if CONFIG_ZLIB
1816#define DECOMPRESS_BUF_SIZE (256 * 1024)
1817static int http_buf_read_compressed(URLContext *h, uint8_t *buf, int size)
1818{
1819 HTTPContext *s = h->priv_data;
1820 int ret;
1821
1822 if (!s->inflate_buffer) {
1823 s->inflate_buffer = av_malloc(DECOMPRESS_BUF_SIZE);
1824 if (!s->inflate_buffer)
1825 return AVERROR(ENOMEM);
1826 }
1827
1828 if (s->inflate_stream.avail_in == 0) {
1829 int read = http_buf_read(h, s->inflate_buffer, DECOMPRESS_BUF_SIZE);
1830 if (read <= 0)
1831 return read;
1832 s->inflate_stream.next_in = s->inflate_buffer;
1833 s->inflate_stream.avail_in = read;
1834 }
1835
1836 s->inflate_stream.avail_out = size;
1837 s->inflate_stream.next_out = buf;
1838
1839 ret = inflate(&s->inflate_stream, Z_SYNC_FLUSH);
1840 if (ret != Z_OK && ret != Z_STREAM_END)
1841 av_log(h, AV_LOG_WARNING, "inflate return value: %d, %s\n",
1842 ret, s->inflate_stream.msg);
1843
1844 return size - s->inflate_stream.avail_out;
1845}
1846#endif /* CONFIG_ZLIB */
1847
1848static int64_t http_seek_internal(URLContext *h, int64_t off, int whence, int force_reconnect);
1849
1850static int http_read_stream(URLContext *h, uint8_t *buf, int size)
1851{
1852 HTTPContext *s = h->priv_data;
1853 int err, read_ret;
1854 int64_t seek_ret;
1855 int reconnect_delay = 0;
1856 int reconnect_delay_total = 0;
1857 int conn_attempts = 1;
1858
1859 if (!s->hd)
1860 return s->off < s->filesize ? AVERROR(EIO) : AVERROR_EOF;
1861
1862 if (s->end_chunked_post && !s->end_header) {
1863 err = http_read_header(h);
1864 if (err < 0)
1865 return err;
1866 }
1867
1868#if CONFIG_ZLIB
1869 if (s->compressed)
1870 return http_buf_read_compressed(h, buf, size);
1871#endif /* CONFIG_ZLIB */
1872
1873retry:
1874 read_ret = http_buf_read(h, buf, size);
1875 while (read_ret < 0) {
1876 uint64_t target = h->is_streamed ? 0 : s->off;
1877 bool is_premature = s->filesize > 0 && s->off < s->filesize;
1878
1879 if (read_ret == AVERROR_EXIT)
1880 break;
1881 else if (read_ret == AVERROR(EAGAIN)) {
1882 /* send new request for more data on existing connection */
1884 if (s->willclose)
1885 ffurl_closep(&s->hd);
1886 s->initial_requests = 0; /* continue streaming uninterrupted from now on */
1887 read_ret = http_open_cnx(h, &options);
1889 if (read_ret == 0)
1890 goto retry;
1891 }
1892
1893 if (h->is_streamed && !s->reconnect_streamed)
1894 break;
1895
1896 if (!(s->reconnect && is_premature) &&
1897 !(s->reconnect_at_eof && read_ret == AVERROR_EOF)) {
1898 if (is_premature)
1899 return AVERROR(EIO);
1900 else
1901 break;
1902 }
1903
1904 if (reconnect_delay > s->reconnect_delay_max || (s->reconnect_max_retries >= 0 && conn_attempts > s->reconnect_max_retries) ||
1905 reconnect_delay_total > s->reconnect_delay_total_max)
1906 return AVERROR(EIO);
1907
1908 av_log(h, AV_LOG_WARNING, "Will %s at %"PRIu64" in %d second(s), error=%s.\n", s->willclose ? "reconnect" : "retry",
1909 s->off, reconnect_delay, av_err2str(read_ret));
1910 err = ff_network_sleep_interruptible(1000U*1000*reconnect_delay, &h->interrupt_callback);
1911 if (err != AVERROR(ETIMEDOUT))
1912 return err;
1913 reconnect_delay_total += reconnect_delay;
1914 reconnect_delay = 1 + 2*reconnect_delay;
1915 conn_attempts++;
1916 seek_ret = http_seek_internal(h, target, SEEK_SET, 1);
1917 if (seek_ret >= 0 && seek_ret != target) {
1918 ffurl_closep(&s->hd);
1919 av_log(h, AV_LOG_ERROR, "Failed to reconnect at %"PRIu64".\n", target);
1920 return read_ret;
1921 }
1922
1923 read_ret = http_buf_read(h, buf, size);
1924 }
1925
1926 return read_ret;
1927}
1928
1929// Like http_read_stream(), but no short reads.
1930// Assumes partial reads are an error.
1931static int http_read_stream_all(URLContext *h, uint8_t *buf, int size)
1932{
1933 int pos = 0;
1934 while (pos < size) {
1935 int len = http_read_stream(h, buf + pos, size - pos);
1936 if (len < 0)
1937 return len;
1938 pos += len;
1939 }
1940 return pos;
1941}
1942
1943static void update_metadata(URLContext *h, char *data)
1944{
1945 char *key;
1946 char *val;
1947 char *end;
1948 char *next = data;
1949 HTTPContext *s = h->priv_data;
1950
1951 while (*next) {
1952 key = next;
1953 val = strstr(key, "='");
1954 if (!val)
1955 break;
1956 end = strstr(val, "';");
1957 if (!end)
1958 break;
1959
1960 *val = '\0';
1961 *end = '\0';
1962 val += 2;
1963
1964 av_dict_set(&s->metadata, key, val, 0);
1965 av_log(h, AV_LOG_VERBOSE, "Metadata update for %s: %s\n", key, val);
1966
1967 next = end + 2;
1968 }
1969}
1970
1971static int store_icy(URLContext *h, int size)
1972{
1973 HTTPContext *s = h->priv_data;
1974 /* until next metadata packet */
1975 uint64_t remaining;
1976
1977 if (s->icy_metaint < s->icy_data_read)
1978 return AVERROR_INVALIDDATA;
1979 remaining = s->icy_metaint - s->icy_data_read;
1980
1981 if (!remaining) {
1982 /* The metadata packet is variable sized. It has a 1 byte header
1983 * which sets the length of the packet (divided by 16). If it's 0,
1984 * the metadata doesn't change. After the packet, icy_metaint bytes
1985 * of normal data follows. */
1986 uint8_t ch;
1987 int len = http_read_stream_all(h, &ch, 1);
1988 if (len < 0)
1989 return len;
1990 if (ch > 0) {
1991 char data[255 * 16 + 1];
1992 int ret;
1993 len = ch * 16;
1994 ret = http_read_stream_all(h, data, len);
1995 if (ret < 0)
1996 return ret;
1997 data[len] = 0;
1998 if ((ret = av_opt_set(s, "icy_metadata_packet", data, 0)) < 0)
1999 return ret;
2001 }
2002 s->icy_data_read = 0;
2003 remaining = s->icy_metaint;
2004 }
2005
2006 return FFMIN(size, remaining);
2007}
2008
2009static int http_read(URLContext *h, uint8_t *buf, int size)
2010{
2011 HTTPContext *s = h->priv_data;
2012
2013 if (s->icy_metaint > 0) {
2014 size = store_icy(h, size);
2015 if (size < 0)
2016 return size;
2017 }
2018
2019 size = http_read_stream(h, buf, size);
2020 if (size > 0)
2021 s->icy_data_read += size;
2022 return size;
2023}
2024
2025/* used only when posting data */
2026static int http_write(URLContext *h, const uint8_t *buf, int size)
2027{
2028 char temp[11] = ""; /* 32-bit hex + CRLF + nul */
2029 int ret;
2030 char crlf[] = "\r\n";
2031 HTTPContext *s = h->priv_data;
2032
2033 if (!s->chunked_post) {
2034 /* non-chunked data is sent without any special encoding */
2035 return ffurl_write(s->hd, buf, size);
2036 }
2037
2038 /* silently ignore zero-size data since chunk encoding that would
2039 * signal EOF */
2040 if (size > 0) {
2041 /* upload data using chunked encoding */
2042 snprintf(temp, sizeof(temp), "%x\r\n", size);
2043
2044 if ((ret = ffurl_write(s->hd, temp, strlen(temp))) < 0 ||
2045 (ret = ffurl_write(s->hd, buf, size)) < 0 ||
2046 (ret = ffurl_write(s->hd, crlf, sizeof(crlf) - 1)) < 0)
2047 return ret;
2048 }
2049 return size;
2050}
2051
2053{
2054 int ret = 0;
2055 char footer[] = "0\r\n\r\n";
2056 HTTPContext *s = h->priv_data;
2057
2058 /* signal end of chunked encoding if used */
2059 if (((flags & AVIO_FLAG_WRITE) && s->chunked_post) ||
2060 ((flags & AVIO_FLAG_READ) && s->chunked_post && s->listen)) {
2061 ret = ffurl_write(s->hd, footer, sizeof(footer) - 1);
2062 ret = ret > 0 ? 0 : ret;
2063 /* flush the receive buffer when it is write only mode */
2064 if (!(flags & AVIO_FLAG_READ)) {
2065 char buf[1024];
2066 int read_ret;
2067 s->hd->flags |= AVIO_FLAG_NONBLOCK;
2068 read_ret = ffurl_read(s->hd, buf, sizeof(buf));
2069 s->hd->flags &= ~AVIO_FLAG_NONBLOCK;
2070 if (read_ret < 0 && read_ret != AVERROR(EAGAIN)) {
2071 av_log(h, AV_LOG_ERROR, "URL read error: %s\n", av_err2str(read_ret));
2072 ret = read_ret;
2073 }
2074 }
2075 s->end_chunked_post = 1;
2076 }
2077
2078 return ret;
2079}
2080
2082{
2083 int ret = 0;
2084 HTTPContext *s = h->priv_data;
2085
2086#if CONFIG_ZLIB
2087 inflateEnd(&s->inflate_stream);
2088 av_freep(&s->inflate_buffer);
2089#endif /* CONFIG_ZLIB */
2090
2091 if (s->hd && !s->end_chunked_post)
2092 /* Close the write direction by sending the end of chunked encoding. */
2093 ret = http_shutdown(h, h->flags);
2094
2095 if (s->hd)
2096 ffurl_closep(&s->hd);
2097 av_dict_free(&s->chained_options);
2098 av_dict_free(&s->cookie_dict);
2099 av_dict_free(&s->redirect_cache);
2100 av_freep(&s->new_location);
2101 av_freep(&s->uri);
2102
2103 av_log(h, AV_LOG_DEBUG, "Statistics: %d connection%s, %d request%s, %d retr%s, %d reconnection%s, %d redirect%s\n",
2104 s->nb_connections, s->nb_connections == 1 ? "" : "s",
2105 s->nb_requests, s->nb_requests == 1 ? "" : "s",
2106 s->nb_retries, s->nb_retries == 1 ? "y" : "ies",
2107 s->nb_reconnects, s->nb_reconnects == 1 ? "" : "s",
2108 s->nb_redirects, s->nb_redirects == 1 ? "" : "s");
2109
2110 if (s->nb_requests > 0) {
2111 av_log(h, AV_LOG_DEBUG, "Latency: %.2f ms avg, %.2f ms max\n",
2112 1e-3 * s->sum_latency / s->nb_requests,
2113 1e-3 * s->max_latency);
2114 }
2115 return ret;
2116}
2117
2118static int64_t http_seek_internal(URLContext *h, int64_t off, int whence, int force_reconnect)
2119{
2120 HTTPContext *s = h->priv_data;
2121 URLContext *old_hd = NULL;
2122 uint64_t old_off = s->off;
2123 uint8_t old_buf[BUFFER_SIZE];
2124 int old_buf_size, ret;
2126 uint8_t discard[4096];
2127
2128 if (whence == AVSEEK_SIZE)
2129 return s->filesize == UINT64_MAX ? AVERROR(ENOSYS) : s->filesize;
2130 else if ((s->filesize == UINT64_MAX && whence == SEEK_END))
2131 return AVERROR(ENOSYS);
2132
2133 if (whence == SEEK_CUR)
2134 off += s->off;
2135 else if (whence == SEEK_END)
2136 off += s->filesize;
2137 else if (whence != SEEK_SET)
2138 return AVERROR(EINVAL);
2139 if (off < 0)
2140 return AVERROR(EINVAL);
2141 if (!force_reconnect && off == s->off)
2142 return s->off;
2143 s->off = off;
2144
2145 if (s->off && h->is_streamed)
2146 return AVERROR(ENOSYS);
2147
2148 /* do not try to make a new connection if seeking past the end of the file */
2149 if (s->end_off || s->filesize != UINT64_MAX) {
2150 uint64_t end_pos = s->end_off ? s->end_off : s->filesize;
2151 if (s->off >= end_pos)
2152 return s->off;
2153 }
2154
2155 /* if the location changed (redirect), revert to the original uri */
2156 if (strcmp(s->uri, s->location)) {
2157 char *new_uri;
2158 new_uri = av_strdup(s->uri);
2159 if (!new_uri)
2160 return AVERROR(ENOMEM);
2161 av_free(s->location);
2162 s->location = new_uri;
2163 }
2164
2165 /* we save the old context in case the seek fails */
2166 old_buf_size = s->buf_end - s->buf_ptr;
2167 memcpy(old_buf, s->buf_ptr, old_buf_size);
2168
2169 /* try to reuse existing connection for small seeks */
2170 int short_seek = ffurl_get_short_seek(h);
2171 uint64_t old_read_pos = old_off + old_buf_size;
2172 if (s->hd && !s->willclose && s->range_end && short_seek > 0 &&
2173 old_read_pos + short_seek >= s->range_end)
2174 {
2175 uint64_t remaining = s->range_end - old_read_pos;
2176 av_assert1(remaining <= short_seek);
2177
2178 /* drain remaining data left on the wire from previous request */
2179 av_log(h, AV_LOG_DEBUG, "Soft-seeking to offset %"PRIu64" by draining "
2180 "%"PRIu64" remaining byte(s)\n", s->off, remaining);
2181 while (remaining) {
2182 ret = ffurl_read(s->hd, discard, FFMIN(remaining, sizeof(discard)));
2183 if (ret < 0 || ret == AVERROR_EOF || (ret == 0 && remaining)) {
2184 /* connection broken or stuck, need to reopen */
2185 ffurl_closep(&s->hd);
2186 break;
2187 }
2188 remaining -= ret;
2189 }
2190
2191 ret = http_open_cnx(h, &options);
2192 if (ret >= 0) {
2193 goto done;
2194 } else {
2195 /* fall back to normal reconnection */
2196 ffurl_closep(&s->hd);
2197 old_hd = NULL;
2198 }
2199 } else {
2200 /* can't soft seek; always open new connection */
2201 old_hd = s->hd;
2202 s->hd = NULL;
2203 }
2204
2205 if ((ret = http_open_cnx(h, &options)) < 0) {
2206 /* if it fails, continue on old connection if possible */
2207 if (old_hd) {
2208 memcpy(s->buffer, old_buf, old_buf_size);
2209 s->buf_ptr = s->buffer;
2210 s->buf_end = s->buffer + old_buf_size;
2211 s->hd = old_hd;
2212 s->off = old_off;
2213 }
2215 return ret;
2216 }
2217
2218done:
2220 ffurl_close(old_hd);
2221 return off;
2222}
2223
2224static int64_t http_seek(URLContext *h, int64_t off, int whence)
2225{
2226 return http_seek_internal(h, off, whence, 0);
2227}
2228
2230{
2231 HTTPContext *s = h->priv_data;
2232 return ffurl_get_file_handle(s->hd);
2233}
2234
2236{
2237 HTTPContext *s = h->priv_data;
2238 if (s->short_seek_size >= 1)
2239 return s->short_seek_size;
2240 return ffurl_get_short_seek(s->hd);
2241}
2242
2243#define HTTP_CLASS(flavor) \
2244static const AVClass flavor ## _context_class = { \
2245 .class_name = # flavor, \
2246 .item_name = av_default_item_name, \
2247 .option = http_options, \
2248 .version = LIBAVUTIL_VERSION_INT, \
2249}
2250
2251#if CONFIG_HTTP_PROTOCOL
2252HTTP_CLASS(http);
2253
2255 .name = "http",
2256 .url_open2 = http_open,
2257 .url_accept = http_accept,
2258 .url_handshake = http_handshake,
2259 .url_read = http_read,
2260 .url_write = http_write,
2261 .url_seek = http_seek,
2262 .url_close = http_close,
2263 .url_get_file_handle = http_get_file_handle,
2264 .url_get_short_seek = http_get_short_seek,
2265 .url_shutdown = http_shutdown,
2266 .priv_data_size = sizeof(HTTPContext),
2267 .priv_data_class = &http_context_class,
2269 .default_whitelist = "http,https,tls,rtp,tcp,udp,crypto,httpproxy,data"
2270};
2271#endif /* CONFIG_HTTP_PROTOCOL */
2272
2273#if CONFIG_HTTPS_PROTOCOL
2274HTTP_CLASS(https);
2275
2277 .name = "https",
2278 .url_open2 = http_open,
2279 .url_read = http_read,
2280 .url_write = http_write,
2281 .url_seek = http_seek,
2282 .url_close = http_close,
2283 .url_get_file_handle = http_get_file_handle,
2284 .url_get_short_seek = http_get_short_seek,
2285 .url_shutdown = http_shutdown,
2286 .priv_data_size = sizeof(HTTPContext),
2287 .priv_data_class = &https_context_class,
2289 .default_whitelist = "http,https,tls,rtp,tcp,udp,crypto,httpproxy"
2290};
2291#endif /* CONFIG_HTTPS_PROTOCOL */
2292
2293#if CONFIG_HTTPPROXY_PROTOCOL
2294static int http_proxy_close(URLContext *h)
2295{
2296 HTTPContext *s = h->priv_data;
2297 if (s->hd)
2298 ffurl_closep(&s->hd);
2299 return 0;
2300}
2301
2302static int http_proxy_open(URLContext *h, const char *uri, int flags)
2303{
2304 HTTPContext *s = h->priv_data;
2305 char hostname[1024], hoststr[1024];
2306 char auth[1024], pathbuf[1024], *path;
2307 char lower_url[100];
2308 int port, ret = 0, auth_attempts = 0;
2309 HTTPAuthType cur_auth_type;
2310 char *authstr;
2311
2312 if( s->seekable == 1 )
2313 h->is_streamed = 0;
2314 else
2315 h->is_streamed = 1;
2316
2317 av_url_split(NULL, 0, auth, sizeof(auth), hostname, sizeof(hostname), &port,
2318 pathbuf, sizeof(pathbuf), uri);
2319 ff_url_join(hoststr, sizeof(hoststr), NULL, NULL, hostname, port, NULL);
2320 path = pathbuf;
2321 if (*path == '/')
2322 path++;
2323
2324 ff_url_join(lower_url, sizeof(lower_url), "tcp", NULL, hostname, port,
2325 NULL);
2326redo:
2327 ret = ffurl_open_whitelist(&s->hd, lower_url, AVIO_FLAG_READ_WRITE,
2328 &h->interrupt_callback, NULL,
2329 h->protocol_whitelist, h->protocol_blacklist, h);
2330 if (ret < 0)
2331 return ret;
2332
2333 authstr = ff_http_auth_create_response(&s->proxy_auth_state, auth,
2334 path, "CONNECT");
2335 snprintf(s->buffer, sizeof(s->buffer),
2336 "CONNECT %s HTTP/1.1\r\n"
2337 "Host: %s\r\n"
2338 "Connection: close\r\n"
2339 "%s%s"
2340 "\r\n",
2341 path,
2342 hoststr,
2343 authstr ? "Proxy-" : "", authstr ? authstr : "");
2344 av_freep(&authstr);
2345
2346 if ((ret = ffurl_write(s->hd, s->buffer, strlen(s->buffer))) < 0)
2347 goto fail;
2348
2349 s->buf_ptr = s->buffer;
2350 s->buf_end = s->buffer;
2351 s->line_count = 0;
2352 s->filesize = UINT64_MAX;
2353 cur_auth_type = s->proxy_auth_state.auth_type;
2354
2355 /* Note: This uses buffering, potentially reading more than the
2356 * HTTP header. If tunneling a protocol where the server starts
2357 * the conversation, we might buffer part of that here, too.
2358 * Reading that requires using the proper ffurl_read() function
2359 * on this URLContext, not using the fd directly (as the tls
2360 * protocol does). This shouldn't be an issue for tls though,
2361 * since the client starts the conversation there, so there
2362 * is no extra data that we might buffer up here.
2363 */
2364 ret = http_read_header(h);
2365 if (ret < 0)
2366 goto fail;
2367
2368 auth_attempts++;
2369 if (s->http_code == 407 &&
2370 (cur_auth_type == HTTP_AUTH_NONE || s->proxy_auth_state.stale) &&
2371 s->proxy_auth_state.auth_type != HTTP_AUTH_NONE && auth_attempts < 2) {
2372 ffurl_closep(&s->hd);
2373 goto redo;
2374 }
2375
2376 if (s->http_code < 400)
2377 return 0;
2378 ret = ff_http_averror(s->http_code, AVERROR(EIO));
2379
2380fail:
2381 http_proxy_close(h);
2382 return ret;
2383}
2384
2385static int http_proxy_write(URLContext *h, const uint8_t *buf, int size)
2386{
2387 HTTPContext *s = h->priv_data;
2388 return ffurl_write(s->hd, buf, size);
2389}
2390
2392 .name = "httpproxy",
2393 .url_open = http_proxy_open,
2394 .url_read = http_buf_read,
2395 .url_write = http_proxy_write,
2396 .url_close = http_proxy_close,
2397 .url_get_file_handle = http_get_file_handle,
2398 .priv_data_size = sizeof(HTTPContext),
2400};
2401#endif /* CONFIG_HTTPPROXY_PROTOCOL */
static double val(void *priv, double ch)
Definition aeval.c:77
static AVDictionary * opts
simple assert() macros that are a bit more flexible than ISO C assert().
#define av_assert1(cond)
assert() equivalent, that does not lie in speed critical code.
Definition avassert.h:58
#define av_assert0(cond)
assert() equivalent, that is always enabled.
Definition avassert.h:42
#define E
Definition avdct.c:34
#define D
Definition avdct.c:35
Main libavformat public API header.
int ffurl_handshake(URLContext *c)
Perform one step of the protocol handshake to accept a new client.
Definition avio.c:294
int ffurl_alloc(URLContext **puc, const char *filename, int flags, const AVIOInterruptCB *int_cb)
Create a URLContext for accessing to the resource indicated by url, but do not initiate the connectio...
Definition avio.c:360
int ffurl_open_whitelist(URLContext **puc, const char *filename, int flags, const AVIOInterruptCB *int_cb, AVDictionary **options, const char *whitelist, const char *blacklist, URLContext *parent)
Create an URLContext for accessing to the resource indicated by url, and open it.
Definition avio.c:461
int ffurl_accept(URLContext *s, URLContext **c)
Accept an URLContext c on an URLContext s.
Definition avio.c:275
int ffurl_closep(URLContext **hh)
Close the resource accessed by the URLContext h, and free the memory used by it.
Definition avio.c:656
int ffurl_close(URLContext *h)
Definition avio.c:679
int ffurl_get_short_seek(void *urlcontext)
Return the current short seek threshold value for this URL.
Definition avio.c:906
int ffurl_get_file_handle(URLContext *h)
Return the file descriptor associated with this URL.
Definition avio.c:882
#define AVIO_FLAG_READ
read-only
Definition avio.h:617
#define AVSEEK_SIZE
Passing this as the "whence" parameter to a seek function causes it to return the filesize without se...
Definition avio.h:468
#define AVIO_FLAG_WRITE
write-only
Definition avio.h:618
#define AVIO_FLAG_READ_WRITE
read-write pseudo flag
Definition avio.h:619
#define AVIO_FLAG_NONBLOCK
Use non-blocking mode.
Definition avio.h:636
char * av_asprintf(const char *fmt,...)
Definition avstring.c:115
size_t av_strlcatf(char *dst, size_t size, const char *fmt,...)
Definition avstring.c:103
static uint32_t BS_FUNC read(BSCTX *bc, unsigned int n)
Return n bits from the buffer, n has to be in the 0-32 range.
void av_bprintf(AVBPrint *buf, const char *fmt,...)
Definition bprint.c:122
AVBPrint public header.
static int FUNC metadata(CodedBitstreamContext *ctx, RWContext *rw, APVRawMetadata *current)
#define flags(name, subs,...)
Definition cbs_h264.c:74
#define i(width, name, range_min, range_max)
Definition cbs_h264.c:63
#define s(width, name)
Definition cbs_vp9.c:198
#define NULL
Definition coverity.c:32
long long int64_t
Definition coverity.c:34
#define SPACE_CHARS
double value
Definition eval.c:102
const char * key
#define BUFFER_SIZE
static char * getenv_utf8(const char *varname)
Definition getenv_utf8.h:67
static void freeenv_utf8(char *var)
Definition getenv_utf8.h:72
#define WHITESPACES
Definition graphparser.c:35
#define fail
Definition test.h:479
#define AV_OPT_FLAG_READONLY
The option may not be set through the AVOptions API, only read.
Definition opt.h:367
#define AV_OPT_FLAG_EXPORT
The option is intended for exporting values to the caller.
Definition opt.h:362
@ AV_OPT_TYPE_CONST
Special option type for declaring named constants.
Definition opt.h:298
@ AV_OPT_TYPE_BINARY
Underlying C type is a uint8_t* that is either NULL or points to an array allocated with the av_mallo...
Definition opt.h:285
@ AV_OPT_TYPE_INT64
Underlying C type is int64_t.
Definition opt.h:262
@ AV_OPT_TYPE_INT
Underlying C type is int.
Definition opt.h:258
@ AV_OPT_TYPE_DICT
Underlying C type is AVDictionary*.
Definition opt.h:289
@ AV_OPT_TYPE_BOOL
Underlying C type is int.
Definition opt.h:326
@ AV_OPT_TYPE_STRING
Underlying C type is a uint8_t* that is either NULL or points to a C string allocated with the av_mal...
Definition opt.h:275
void av_url_split(char *proto, int proto_size, char *authorization, int authorization_size, char *hostname, int hostname_size, int *port_ptr, char *path, int path_size, const char *url)
Split a URL string into components.
Definition utils.c:361
static int av_bprint_is_complete(const AVBPrint *buf)
Test if the print buffer is complete (not truncated).
Definition bprint.h:218
void av_dict_free(AVDictionary **pm)
Free all the memory allocated for an AVDictionary struct and all keys and values.
Definition dict.c:233
AVDictionaryEntry * av_dict_get(const AVDictionary *m, const char *key, const AVDictionaryEntry *prev, int flags)
Get a dictionary entry with matching key.
Definition dict.c:60
const AVDictionaryEntry * av_dict_iterate(const AVDictionary *m, const AVDictionaryEntry *prev)
Iterate over a dictionary.
Definition dict.c:42
int av_dict_copy(AVDictionary **dst, const AVDictionary *src, int flags)
Copy entries from one AVDictionary struct into another.
Definition dict.c:247
#define AV_DICT_DONT_STRDUP_VAL
Take ownership of a value that's been allocated with av_malloc() or another memory allocation functio...
Definition dict.h:79
int av_dict_set(AVDictionary **pm, const char *key, const char *value, int flags)
Set the given entry in *pm, overwriting an existing entry.
Definition dict.c:86
#define AV_DICT_DONT_STRDUP_KEY
Take ownership of a key that's been allocated with av_malloc() or another memory allocation function.
Definition dict.h:77
int av_dict_count(const AVDictionary *m)
Get number of entries in dictionary.
Definition dict.c:37
#define AV_DICT_MATCH_CASE
Only get an entry with exact-case key match.
Definition dict.h:74
int av_dict_set_int(AVDictionary **pm, const char *key, int64_t value, int flags)
Convenience wrapper for av_dict_set() that converts the value to a string and stores it.
Definition dict.c:177
#define AVERROR_HTTP_FORBIDDEN
Definition error.h:80
#define AVERROR_HTTP_BAD_REQUEST
Definition error.h:78
#define AVERROR_EXIT
Immediate exit was requested; the called function should not be restarted.
Definition error.h:58
#define AVERROR_HTTP_SERVER_ERROR
Definition error.h:84
#define AVERROR_HTTP_OTHER_4XX
Definition error.h:83
#define AVERROR_INVALIDDATA
Invalid data found when processing input.
Definition error.h:61
#define AVERROR_HTTP_TOO_MANY_REQUESTS
Definition error.h:82
#define AVERROR_EOF
End of file.
Definition error.h:57
#define av_err2str(errnum)
Convenience macro, the return value should be used only directly in function arguments but never stan...
Definition error.h:122
#define AVERROR_HTTP_UNAUTHORIZED
Definition error.h:79
#define AVERROR(e)
Definition error.h:45
#define AVERROR_HTTP_NOT_FOUND
Definition error.h:81
#define AV_LOG_TRACE
Extremely verbose debugging, useful for libav* development.
Definition log.h:236
#define AV_LOG_DEBUG
Stuff which is only useful for libav* developers.
Definition log.h:231
#define AV_LOG_WARNING
Something somehow does not look correct.
Definition log.h:216
#define AV_LOG_VERBOSE
Detailed information.
Definition log.h:226
#define AV_LOG_INFO
Standard information.
Definition log.h:221
#define AV_LOG_ERROR
Something went wrong and cannot losslessly be recovered.
Definition log.h:210
char * av_strndup(const char *s, size_t len)
Duplicate a substring of a string.
Definition mem.c:284
int av_reallocp(void *ptr, size_t size)
Allocate, reallocate, or free a block of memory through a pointer to a pointer.
Definition mem.c:188
char * av_stristr(const char *s1, const char *s2)
Locate the first case-independent occurrence in the string haystack of the string needle.
Definition avstring.c:58
char * av_strtok(char *s, const char *delim, char **saveptr)
Split the string into several tokens which can be accessed by successive calls to av_strtok().
Definition avstring.c:179
int av_strcasecmp(const char *a, const char *b)
Locale-independent case-insensitive compare.
Definition avstring.c:208
int av_strstart(const char *str, const char *pfx, const char **ptr)
Return non-zero if pfx is a prefix of str.
Definition avstring.c:36
size_t av_strlcpy(char *dst, const char *src, size_t size)
Copy the string src to dst, but no more than size - 1 bytes, and null-terminate dst.
Definition avstring.c:85
static av_const int av_isspace(int c)
Locale-independent conversion of ASCII isspace.
Definition avstring.h:218
int av_match_list(const char *name, const char *list, char separator)
Check if a name is in a list.
Definition avstring.c:440
char * av_get_token(const char **buf, const char *term)
Unescape the given string until a non escaped terminating char, and return the token corresponding to...
Definition avstring.c:143
int av_stristart(const char *str, const char *pfx, const char **ptr)
Return non-zero if pfx is a prefix of str independent of case.
Definition avstring.c:47
int av_strncasecmp(const char *a, const char *b, size_t n)
Locale-independent case-insensitive compare.
Definition avstring.c:218
int av_opt_set(void *obj, const char *name, const char *val, int search_flags)
Definition opt.c:889
int av_opt_set_dict(void *obj, AVDictionary **options)
Set all the options from a given dictionary on an object.
Definition opt.c:2064
static int http_handshake(URLContext *c)
Definition http.c:706
HandshakeState
Definition http.c:65
@ FINISH
Definition http.c:69
@ LOWER_PROTO
Definition http.c:66
@ READ_HEADERS
Definition http.c:67
@ WRITE_REPLY_HEADERS
Definition http.c:68
static int http_open(URLContext *h, const char *uri, int flags, AVDictionary **options)
Definition http.c:774
static int cookie_string(AVDictionary *dict, char **cookies)
Definition http.c:1121
static int redirect_cache_set(HTTPContext *s, const char *source, const char *dest, int64_t expiry)
Definition http.c:406
static int store_icy(URLContext *h, int size)
Definition http.c:1971
static int parse_content_encoding(URLContext *h, const char *p)
Definition http.c:938
static const AVOption http_options[]
Definition http.c:189
static int http_shutdown(URLContext *h, int flags)
Definition http.c:2052
int ff_http_do_new_request2(URLContext *h, const char *uri, AVDictionary **opts)
Send a new HTTP request, reusing the old connection.
Definition http.c:549
static int parse_set_cookie(const char *set_cookie, AVDictionary **dict)
Definition http.c:1019
static int http_read_header(URLContext *h)
Definition http.c:1446
static int http_read(URLContext *h, uint8_t *buf, int size)
Definition http.c:2009
static int http_getc(HTTPContext *s)
Definition http.c:852
static uint64_t request_size(URLContext *h)
Definition http.c:1535
static int process_line(URLContext *h, char *line, int line_count, int *parsed_http_code)
Definition http.c:1180
static int get_cookies(HTTPContext *s, char **cookies, const char *path, const char *domain)
Create a string containing cookie values for use as a HTTP cookie header field value for a particular...
Definition http.c:1354
static int http_open_cnx_internal(URLContext *h, AVDictionary **options)
Definition http.c:249
static void parse_content_range(URLContext *h, const char *p)
Definition http.c:921
static void update_metadata(URLContext *h, char *data)
Definition http.c:1943
static int64_t http_seek_internal(URLContext *h, int64_t off, int whence, int force_reconnect)
Definition http.c:2118
static int http_get_line(HTTPContext *s, char *line, int line_size)
Definition http.c:869
#define MAX_DATE_LEN
Definition http.c:63
static int http_buf_read(URLContext *h, uint8_t *buf, int size)
Definition http.c:1735
static int parse_icy(HTTPContext *s, const char *tag, const char *p)
Definition http.c:972
static int has_header(const char *str, const char *header)
Definition http.c:1438
static int http_listen(URLContext *h, const char *uri, int flags, AVDictionary **options)
Definition http.c:742
#define BUFFER_SIZE
Definition http.c:58
static int check_http_code(URLContext *h, int http_code, const char *end)
Definition http.c:893
static int http_get_short_seek(URLContext *h)
Definition http.c:2235
static int http_get_file_handle(URLContext *h)
Definition http.c:2229
void ff_http_init_auth_state(URLContext *dest, const URLContext *src)
Initialize the authentication state based on another HTTP URLContext.
Definition http.c:239
static int http_write_reply(URLContext *h, int status_code)
Definition http.c:621
#define HTTP_SINGLE
Definition http.c:61
static int http_should_reconnect(HTTPContext *s, int err)
Definition http.c:348
static char * redirect_cache_get(HTTPContext *s)
Definition http.c:382
static void handle_http_errors(URLContext *h, int error)
Definition http.c:700
const char * ff_http_get_new_location(URLContext *h)
Definition http.c:615
#define DEFAULT_USER_AGENT
Definition http.c:187
#define HTTP_CLASS(flavor)
Definition http.c:2243
static void parse_cache_control(HTTPContext *s, const char *p)
Definition http.c:1153
static void parse_expires(HTTPContext *s, const char *p)
Definition http.c:1144
static int http_connect(URLContext *h, const char *path, const char *local_path, const char *hoststr, const char *auth, const char *proxyauth)
Definition http.c:1543
static int http_write(URLContext *h, const uint8_t *buf, int size)
Definition http.c:2026
static void bprint_escaped_path(AVBPrint *bp, const char *path)
Escape unsafe characters in path in order to pass them safely to the HTTP request.
Definition http.c:1511
#define MAX_REDIRECTS
Definition http.c:59
static int64_t http_seek(URLContext *h, int64_t off, int whence)
Definition http.c:2224
#define OFFSET(x)
Definition http.c:184
static int parse_http_date(const char *date_str, struct tm *buf)
Definition http.c:994
static int http_open_cnx(URLContext *h, AVDictionary **options)
Definition http.c:424
static int parse_cookie(HTTPContext *s, const char *p, AVDictionary **cookies)
Definition http.c:1056
static int http_close(URLContext *h)
Definition http.c:2081
int ff_http_do_new_request(URLContext *h, const char *uri)
Send a new HTTP request, reusing the old connection.
Definition http.c:545
#define MAX_CACHED_REDIRECTS
Definition http.c:60
static int http_accept(URLContext *s, URLContext **c)
Definition http.c:828
static int http_read_stream(URLContext *h, uint8_t *buf, int size)
Definition http.c:1850
static int http_read_stream_all(URLContext *h, uint8_t *buf, int size)
Definition http.c:1931
static int parse_location(HTTPContext *s, const char *p)
Definition http.c:908
static int ff_http_averror(int status_code, int default_averror)
Definition http.h:66
char * ff_http_auth_create_response(HTTPAuthState *state, const char *auth, const char *path, const char *method)
Definition httpauth.c:240
void ff_http_auth_handle_header(HTTPAuthState *state, const char *key, const char *value)
Definition httpauth.c:93
HTTPAuthType
Authentication types, ordered from weakest to strongest.
Definition httpauth.h:28
@ HTTP_AUTH_NONE
No authentication specified.
Definition httpauth.h:29
@ HTTP_AUTH_BASIC
HTTP 1.0 Basic auth from RFC 1945 (also in RFC 2617)
Definition httpauth.h:30
unsigned offset
Definition libaomenc.c:763
#define MAX_URL_SIZE
Definition internal.h:30
Libavformat version macros.
version
Definition libkvazaar.c:313
Utility Preprocessor macros.
#define FFMIN(a, b)
Definition macros.h:49
#define FFMAX(a, b)
Definition macros.h:47
static void body(uint32_t ABCD[4], const uint8_t *src, size_t nblocks)
Definition md5.c:103
Memory handling functions.
uint32_t tag
Definition movenc.c:2087
const char data[16]
Definition mxf.c:149
int ff_network_sleep_interruptible(int64_t timeout, AVIOInterruptCB *int_cb)
Waits for up to 'timeout' microseconds.
Definition network.c:103
int ff_http_match_no_proxy(const char *no_proxy, const char *hostname)
Definition network.c:558
#define av_strdup(s)
Definition ops_static.c:55
#define av_malloc(s)
Definition ops_static.c:52
AVOptions.
miscellaneous OS support macros and functions.
char * av_small_strptime(const char *p, const char *fmt, struct tm *dt)
Simplified version of strptime.
Definition parseutils.c:494
time_t av_timegm(struct tm *tm)
Convert the decomposed UTC time in tm to a time_t value.
Definition parseutils.c:573
misc parsing utilities
const URLProtocol ff_https_protocol
const URLProtocol ff_http_protocol
const URLProtocol ff_httpproxy_protocol
const char * name
Definition qsvenc.c:142
static const uint8_t header[24]
Definition sdr2.c:68
#define snprintf
Definition snprintf.h:34
unsigned int pos
Definition spdifenc.c:431
Describe the class of an AVClass context structure.
Definition log.h:76
char * key
Definition dict.h:91
char * value
Definition dict.h:92
AVOption.
Definition opt.h:428
HTTP Authentication state structure.
Definition httpauth.h:55
int64_t sum_latency
Definition http.c:137
HandshakeState handshake_step
Definition http.c:179
int is_akamai
Definition http.c:124
uint64_t chunksize
Definition http.c:149
URLContext * hd
Definition http.c:143
char * resource
Definition http.c:110
char * new_location
Definition http.c:145
int nb_redirects
Definition http.c:136
int nb_retries
Definition http.c:134
char * method
Definition http.c:100
unsigned char * buf_end
Definition http.c:74
int nb_connections
Definition http.c:132
int end_chunked_post
Definition http.c:156
uint64_t range_end
Definition http.c:151
int max_redirects
Definition http.c:113
int64_t max_latency
Definition http.c:138
uint64_t off
Definition http.c:79
AVDictionary * chained_options
Definition http.c:128
int initial_requests
Definition http.c:169
int respect_retry_after
Definition http.c:114
uint64_t filesize_from_content_range
Definition http.c:172
char * location
Definition http.c:80
uint64_t icy_metaint
Definition http.c:162
int reply_code
Definition http.c:111
int listen
Definition http.c:109
uint64_t icy_data_read
Definition http.c:160
char * icy_metadata_packet
Definition http.c:96
char * user_agent
Definition http.c:85
char * reconnect_on_http_error
Definition http.c:108
int seekable
Control seekability, 0 = disable, 1 = enable, -1 = probe.
Definition http.c:88
char * headers
Definition http.c:82
int reconnect_delay_total_max
Definition http.c:107
char * uri
Definition http.c:144
int http_code
Definition http.c:146
int end_header
Definition http.c:158
char * referer
Definition http.c:86
int is_multi_client
Definition http.c:180
AVDictionary * metadata
Definition http.c:97
uint8_t * post_data
Definition http.c:91
unsigned char buffer[BUFFER_SIZE]
Definition http.c:74
char * content_type
Definition http.c:87
AVDictionary * redirect_cache
Definition http.c:129
int nb_requests
Definition http.c:133
int reconnect_on_network_error
Definition http.c:103
char * http_version
Definition http.c:84
int send_expect_100
Definition http.c:99
uint64_t filesize
Definition http.c:123
char * icy_metadata_headers
Definition http.c:95
int willclose
Definition http.c:154
char * mime_type
Definition http.c:83
int short_seek_size
Definition http.c:112
int is_mediagateway
Definition http.c:125
int multiple_requests
A flag which indicates if we use persistent connections.
Definition http.c:90
char * http_proxy
Definition http.c:81
int is_connected_server
Definition http.c:181
int nb_reconnects
Definition http.c:135
HTTPAuthState proxy_auth_state
Definition http.c:122
int reconnect_streamed
Definition http.c:104
int icy
Definition http.c:94
int reconnect
Definition http.c:101
int chunked_post
Definition http.c:89
char * cookies
holds newline ( ) delimited Set-Cookie header field values (without the "Set-Cookie: " field name)
Definition http.c:93
uint64_t end_off
Definition http.c:79
int64_t expires
Definition http.c:147
uint64_t request_size
Definition http.c:115
unsigned int retry_after
Definition http.c:168
int post_datalen
Definition http.c:92
HTTPAuthState auth_state
Definition http.c:121
unsigned char * buf_ptr
Definition http.c:74
AVDictionary * cookie_dict
Definition http.c:127
int reconnect_max_retries
Definition http.c:105
int reconnect_at_eof
Definition http.c:102
int reconnect_delay_max
Definition http.c:106
uint64_t initial_request_size
Definition http.c:116
int line_count
Definition http.c:173
int chunkend
Definition http.c:150
void * priv_data
Definition url.h:38
AVIOInterruptCB interrupt_callback
Definition url.h:44
#define av_free(p)
#define av_freep(p)
#define av_log(a,...)
static void error(const char *err)
static uint8_t tmp[40]
Definition aes_ctr.c:52
#define src
Definition vp8dsp.c:248
int64_t av_gettime(void)
Get the current time in microseconds.
Definition time.c:40
int size
int ff_make_absolute_url(char *buf, int size, const char *base, const char *rel)
Convert a relative url into an absolute url, given a base url.
Definition url.c:321
int ff_url_join(char *str, int size, const char *proto, const char *authorization, const char *hostname, int port, const char *fmt,...)
Definition url.c:40
unbuffered private I/O API
static int ffurl_write(URLContext *h, const uint8_t *buf, int size)
Write size bytes from buf to the resource accessed by h.
Definition url.h:204
static int ffurl_read(URLContext *h, uint8_t *buf, int size)
Read up to size bytes from the resource accessed by h, and store the read bytes in buf.
Definition url.h:183
#define URL_PROTOCOL_FLAG_NETWORK
Definition url.h:33
else temp
Definition vf_mcdeint.c:275
static void inflate(uint8_t *dst, const uint8_t *p1, int width, int threshold, const uint8_t *coordinates[], int coord, int maxc)
static av_always_inline int diff(const struct color_info *a, const struct color_info *b, const int trans_thresh)
int len
static double c[64]