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