FFmpeg coverage


Directory: ../../../ffmpeg/
File: src/libavformat/http.c
Date: 2026-10-29 07:45:57
Exec Total Coverage
Lines: 26 1421 1.8%
Functions: 1 60 1.7%
Branches: 25 1191 2.1%

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