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