FFmpeg coverage


Directory: ../../../ffmpeg/
File: src/libavformat/http.c
Date: 2026-09-24 20:08:24
Exec Total Coverage
Lines: 26 1331 2.0%
Functions: 1 56 1.8%
Branches: 25 1111 2.3%

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