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