FFmpeg coverage


Directory: ../../../ffmpeg/
File: src/libavformat/http.c
Date: 2026-09-05 04:28:30
Exec Total Coverage
Lines: 26 1291 2.0%
Functions: 1 53 1.9%
Branches: 25 1045 2.4%

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