]> git.sesse.net Git - ffmpeg/blob - libavformat/http.c
a376f1a488468e0949cb4c4f0c5e27fbb0407f01
[ffmpeg] / libavformat / http.c
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 "config.h"
23
24 #if CONFIG_ZLIB
25 #include <zlib.h>
26 #endif /* CONFIG_ZLIB */
27
28 #include "libavutil/avassert.h"
29 #include "libavutil/avstring.h"
30 #include "libavutil/opt.h"
31 #include "libavutil/time.h"
32 #include "libavutil/parseutils.h"
33
34 #include "avformat.h"
35 #include "http.h"
36 #include "httpauth.h"
37 #include "internal.h"
38 #include "network.h"
39 #include "os_support.h"
40 #include "url.h"
41
42 /* XXX: POST protocol is not completely implemented because ffmpeg uses
43  * only a subset of it. */
44
45 /* The IO buffer size is unrelated to the max URL size in itself, but needs
46  * to be large enough to fit the full request headers (including long
47  * path names). */
48 #define BUFFER_SIZE   MAX_URL_SIZE
49 #define MAX_REDIRECTS 8
50 #define HTTP_SINGLE   1
51 #define HTTP_MUTLI    2
52 #define MAX_EXPIRY    19
53 #define WHITESPACES " \n\t\r"
54 typedef enum {
55     LOWER_PROTO,
56     READ_HEADERS,
57     WRITE_REPLY_HEADERS,
58     FINISH
59 }HandshakeState;
60
61 typedef struct HTTPContext {
62     const AVClass *class;
63     URLContext *hd;
64     unsigned char buffer[BUFFER_SIZE], *buf_ptr, *buf_end;
65     int line_count;
66     int http_code;
67     /* Used if "Transfer-Encoding: chunked" otherwise -1. */
68     uint64_t chunksize;
69     int chunkend;
70     uint64_t off, end_off, filesize;
71     char *location;
72     HTTPAuthState auth_state;
73     HTTPAuthState proxy_auth_state;
74     char *http_proxy;
75     char *headers;
76     char *mime_type;
77     char *http_version;
78     char *user_agent;
79 #if FF_API_HTTP_USER_AGENT
80     char *user_agent_deprecated;
81 #endif
82     char *content_type;
83     /* Set if the server correctly handles Connection: close and will close
84      * the connection after feeding us the content. */
85     int willclose;
86     int seekable;           /**< Control seekability, 0 = disable, 1 = enable, -1 = probe. */
87     int chunked_post;
88     /* A flag which indicates if the end of chunked encoding has been sent. */
89     int end_chunked_post;
90     /* A flag which indicates we have finished to read POST reply. */
91     int end_header;
92     /* A flag which indicates if we use persistent connections. */
93     int multiple_requests;
94     uint8_t *post_data;
95     int post_datalen;
96     int is_akamai;
97     int is_mediagateway;
98     char *cookies;          ///< holds newline (\n) delimited Set-Cookie header field values (without the "Set-Cookie: " field name)
99     /* A dictionary containing cookies keyed by cookie name */
100     AVDictionary *cookie_dict;
101     int icy;
102     /* how much data was read since the last ICY metadata packet */
103     uint64_t icy_data_read;
104     /* after how many bytes of read data a new metadata packet will be found */
105     uint64_t icy_metaint;
106     char *icy_metadata_headers;
107     char *icy_metadata_packet;
108     AVDictionary *metadata;
109 #if CONFIG_ZLIB
110     int compressed;
111     z_stream inflate_stream;
112     uint8_t *inflate_buffer;
113 #endif /* CONFIG_ZLIB */
114     AVDictionary *chained_options;
115     int send_expect_100;
116     char *method;
117     int reconnect;
118     int reconnect_at_eof;
119     int reconnect_streamed;
120     int reconnect_delay;
121     int reconnect_delay_max;
122     int listen;
123     char *resource;
124     int reply_code;
125     int is_multi_client;
126     HandshakeState handshake_step;
127     int is_connected_server;
128 } HTTPContext;
129
130 #define OFFSET(x) offsetof(HTTPContext, x)
131 #define D AV_OPT_FLAG_DECODING_PARAM
132 #define E AV_OPT_FLAG_ENCODING_PARAM
133 #define DEFAULT_USER_AGENT "Lavf/" AV_STRINGIFY(LIBAVFORMAT_VERSION)
134
135 static const AVOption options[] = {
136     { "seekable", "control seekability of connection", OFFSET(seekable), AV_OPT_TYPE_BOOL, { .i64 = -1 }, -1, 1, D },
137     { "chunked_post", "use chunked transfer-encoding for posts", OFFSET(chunked_post), AV_OPT_TYPE_BOOL, { .i64 = 1 }, 0, 1, E },
138     { "http_proxy", "set HTTP proxy to tunnel through", OFFSET(http_proxy), AV_OPT_TYPE_STRING, { .str = NULL }, 0, 0, D | E },
139     { "headers", "set custom HTTP headers, can override built in default headers", OFFSET(headers), AV_OPT_TYPE_STRING, { .str = NULL }, 0, 0, D | E },
140     { "content_type", "set a specific content type for the POST messages", OFFSET(content_type), AV_OPT_TYPE_STRING, { .str = NULL }, 0, 0, D | E },
141     { "user_agent", "override User-Agent header", OFFSET(user_agent), AV_OPT_TYPE_STRING, { .str = DEFAULT_USER_AGENT }, 0, 0, D },
142 #if FF_API_HTTP_USER_AGENT
143     { "user-agent", "override User-Agent header", OFFSET(user_agent_deprecated), AV_OPT_TYPE_STRING, { .str = DEFAULT_USER_AGENT }, 0, 0, D },
144 #endif
145     { "multiple_requests", "use persistent connections", OFFSET(multiple_requests), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, D | E },
146     { "post_data", "set custom HTTP post data", OFFSET(post_data), AV_OPT_TYPE_BINARY, .flags = D | E },
147     { "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 },
148     { "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 },
149     { "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 },
150     { "icy", "request ICY metadata", OFFSET(icy), AV_OPT_TYPE_BOOL, { .i64 = 1 }, 0, 1, D },
151     { "icy_metadata_headers", "return ICY metadata headers", OFFSET(icy_metadata_headers), AV_OPT_TYPE_STRING, { .str = NULL }, 0, 0, AV_OPT_FLAG_EXPORT },
152     { "icy_metadata_packet", "return current ICY metadata packet", OFFSET(icy_metadata_packet), AV_OPT_TYPE_STRING, { .str = NULL }, 0, 0, AV_OPT_FLAG_EXPORT },
153     { "metadata", "metadata read from the bitstream", OFFSET(metadata), AV_OPT_TYPE_DICT, {0}, 0, 0, AV_OPT_FLAG_EXPORT },
154     { "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, "auth_type"},
155     { "none", "No auth method set, autodetect", 0, AV_OPT_TYPE_CONST, { .i64 = HTTP_AUTH_NONE }, 0, 0, D | E, "auth_type"},
156     { "basic", "HTTP basic authentication", 0, AV_OPT_TYPE_CONST, { .i64 = HTTP_AUTH_BASIC }, 0, 0, D | E, "auth_type"},
157     { "send_expect_100", "Force sending an Expect: 100-continue header for POST", OFFSET(send_expect_100), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, E },
158     { "location", "The actual location of the data received", OFFSET(location), AV_OPT_TYPE_STRING, { .str = NULL }, 0, 0, D | E },
159     { "offset", "initial byte offset", OFFSET(off), AV_OPT_TYPE_INT64, { .i64 = 0 }, 0, INT64_MAX, D },
160     { "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 },
161     { "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 },
162     { "reconnect", "auto reconnect after disconnect before EOF", OFFSET(reconnect), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, D },
163     { "reconnect_at_eof", "auto reconnect at EOF", OFFSET(reconnect_at_eof), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, D },
164     { "reconnect_streamed", "auto reconnect streamed / non seekable streams", OFFSET(reconnect_streamed), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, D },
165     { "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 },
166     { "listen", "listen on HTTP", OFFSET(listen), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 2, D | E },
167     { "resource", "The resource requested by a client", OFFSET(resource), AV_OPT_TYPE_STRING, { .str = NULL }, 0, 0, E },
168     { "reply_code", "The http status code to return to a client", OFFSET(reply_code), AV_OPT_TYPE_INT, { .i64 = 200}, INT_MIN, 599, E},
169     { NULL }
170 };
171
172 static int http_connect(URLContext *h, const char *path, const char *local_path,
173                         const char *hoststr, const char *auth,
174                         const char *proxyauth, int *new_location);
175 static int http_read_header(URLContext *h, int *new_location);
176 static int http_shutdown(URLContext *h, int flags);
177
178 void ff_http_init_auth_state(URLContext *dest, const URLContext *src)
179 {
180     memcpy(&((HTTPContext *)dest->priv_data)->auth_state,
181            &((HTTPContext *)src->priv_data)->auth_state,
182            sizeof(HTTPAuthState));
183     memcpy(&((HTTPContext *)dest->priv_data)->proxy_auth_state,
184            &((HTTPContext *)src->priv_data)->proxy_auth_state,
185            sizeof(HTTPAuthState));
186 }
187
188 static int http_open_cnx_internal(URLContext *h, AVDictionary **options)
189 {
190     const char *path, *proxy_path, *lower_proto = "tcp", *local_path;
191     char hostname[1024], hoststr[1024], proto[10];
192     char auth[1024], proxyauth[1024] = "";
193     char path1[MAX_URL_SIZE];
194     char buf[1024], urlbuf[MAX_URL_SIZE];
195     int port, use_proxy, err, location_changed = 0;
196     HTTPContext *s = h->priv_data;
197
198     av_url_split(proto, sizeof(proto), auth, sizeof(auth),
199                  hostname, sizeof(hostname), &port,
200                  path1, sizeof(path1), s->location);
201     ff_url_join(hoststr, sizeof(hoststr), NULL, NULL, hostname, port, NULL);
202
203     proxy_path = s->http_proxy ? s->http_proxy : getenv("http_proxy");
204     use_proxy  = !ff_http_match_no_proxy(getenv("no_proxy"), hostname) &&
205                  proxy_path && av_strstart(proxy_path, "http://", NULL);
206
207     if (!strcmp(proto, "https")) {
208         lower_proto = "tls";
209         use_proxy   = 0;
210         if (port < 0)
211             port = 443;
212     }
213     if (port < 0)
214         port = 80;
215
216     if (path1[0] == '\0')
217         path = "/";
218     else
219         path = path1;
220     local_path = path;
221     if (use_proxy) {
222         /* Reassemble the request URL without auth string - we don't
223          * want to leak the auth to the proxy. */
224         ff_url_join(urlbuf, sizeof(urlbuf), proto, NULL, hostname, port, "%s",
225                     path1);
226         path = urlbuf;
227         av_url_split(NULL, 0, proxyauth, sizeof(proxyauth),
228                      hostname, sizeof(hostname), &port, NULL, 0, proxy_path);
229     }
230
231     ff_url_join(buf, sizeof(buf), lower_proto, NULL, hostname, port, NULL);
232
233     if (!s->hd) {
234         err = ffurl_open_whitelist(&s->hd, buf, AVIO_FLAG_READ_WRITE,
235                                    &h->interrupt_callback, options,
236                                    h->protocol_whitelist, h->protocol_blacklist, h);
237         if (err < 0)
238             return err;
239     }
240
241     err = http_connect(h, path, local_path, hoststr,
242                        auth, proxyauth, &location_changed);
243     if (err < 0)
244         return err;
245
246     return location_changed;
247 }
248
249 /* return non zero if error */
250 static int http_open_cnx(URLContext *h, AVDictionary **options)
251 {
252     HTTPAuthType cur_auth_type, cur_proxy_auth_type;
253     HTTPContext *s = h->priv_data;
254     int location_changed, attempts = 0, redirects = 0;
255 redo:
256     av_dict_copy(options, s->chained_options, 0);
257
258     cur_auth_type       = s->auth_state.auth_type;
259     cur_proxy_auth_type = s->auth_state.auth_type;
260
261     location_changed = http_open_cnx_internal(h, options);
262     if (location_changed < 0)
263         goto fail;
264
265     attempts++;
266     if (s->http_code == 401) {
267         if ((cur_auth_type == HTTP_AUTH_NONE || s->auth_state.stale) &&
268             s->auth_state.auth_type != HTTP_AUTH_NONE && attempts < 4) {
269             ffurl_closep(&s->hd);
270             goto redo;
271         } else
272             goto fail;
273     }
274     if (s->http_code == 407) {
275         if ((cur_proxy_auth_type == HTTP_AUTH_NONE || s->proxy_auth_state.stale) &&
276             s->proxy_auth_state.auth_type != HTTP_AUTH_NONE && attempts < 4) {
277             ffurl_closep(&s->hd);
278             goto redo;
279         } else
280             goto fail;
281     }
282     if ((s->http_code == 301 || s->http_code == 302 ||
283          s->http_code == 303 || s->http_code == 307) &&
284         location_changed == 1) {
285         /* url moved, get next */
286         ffurl_closep(&s->hd);
287         if (redirects++ >= MAX_REDIRECTS)
288             return AVERROR(EIO);
289         /* Restart the authentication process with the new target, which
290          * might use a different auth mechanism. */
291         memset(&s->auth_state, 0, sizeof(s->auth_state));
292         attempts         = 0;
293         location_changed = 0;
294         goto redo;
295     }
296     return 0;
297
298 fail:
299     if (s->hd)
300         ffurl_closep(&s->hd);
301     if (location_changed < 0)
302         return location_changed;
303     return ff_http_averror(s->http_code, AVERROR(EIO));
304 }
305
306 int ff_http_do_new_request(URLContext *h, const char *uri)
307 {
308     HTTPContext *s = h->priv_data;
309     AVDictionary *options = NULL;
310     int ret;
311     char hostname1[1024], hostname2[1024], proto1[10], proto2[10];
312     int port1, port2;
313
314     av_url_split(proto1, sizeof(proto1), NULL, 0,
315                  hostname1, sizeof(hostname1), &port1,
316                  NULL, 0, s->location);
317     av_url_split(proto2, sizeof(proto2), NULL, 0,
318                  hostname2, sizeof(hostname2), &port2,
319                  NULL, 0, uri);
320     if (port1 != port2 || strncmp(hostname1, hostname2, sizeof(hostname2)) != 0) {
321         av_log(h, AV_LOG_ERROR, "Cannot reuse HTTP connection for different host: %s:%d != %s:%d\n",
322             hostname1, port1,
323             hostname2, port2
324         );
325         return AVERROR(EINVAL);
326     }
327
328     if (!s->end_chunked_post) {
329         ret = http_shutdown(h, h->flags);
330         if (ret < 0)
331             return ret;
332     }
333
334     if (s->willclose)
335         return AVERROR_EOF;
336
337     s->end_chunked_post = 0;
338     s->chunkend      = 0;
339     s->off           = 0;
340     s->icy_data_read = 0;
341     av_free(s->location);
342     s->location = av_strdup(uri);
343     if (!s->location)
344         return AVERROR(ENOMEM);
345
346     av_log(s, AV_LOG_INFO, "Opening \'%s\' for %s\n", uri, h->flags & AVIO_FLAG_WRITE ? "writing" : "reading");
347     ret = http_open_cnx(h, &options);
348     av_dict_free(&options);
349     return ret;
350 }
351
352 int ff_http_averror(int status_code, int default_averror)
353 {
354     switch (status_code) {
355         case 400: return AVERROR_HTTP_BAD_REQUEST;
356         case 401: return AVERROR_HTTP_UNAUTHORIZED;
357         case 403: return AVERROR_HTTP_FORBIDDEN;
358         case 404: return AVERROR_HTTP_NOT_FOUND;
359         default: break;
360     }
361     if (status_code >= 400 && status_code <= 499)
362         return AVERROR_HTTP_OTHER_4XX;
363     else if (status_code >= 500)
364         return AVERROR_HTTP_SERVER_ERROR;
365     else
366         return default_averror;
367 }
368
369 static int http_write_reply(URLContext* h, int status_code)
370 {
371     int ret, body = 0, reply_code, message_len;
372     const char *reply_text, *content_type;
373     HTTPContext *s = h->priv_data;
374     char message[BUFFER_SIZE];
375     content_type = "text/plain";
376
377     if (status_code < 0)
378         body = 1;
379     switch (status_code) {
380     case AVERROR_HTTP_BAD_REQUEST:
381     case 400:
382         reply_code = 400;
383         reply_text = "Bad Request";
384         break;
385     case AVERROR_HTTP_FORBIDDEN:
386     case 403:
387         reply_code = 403;
388         reply_text = "Forbidden";
389         break;
390     case AVERROR_HTTP_NOT_FOUND:
391     case 404:
392         reply_code = 404;
393         reply_text = "Not Found";
394         break;
395     case 200:
396         reply_code = 200;
397         reply_text = "OK";
398         content_type = s->content_type ? s->content_type : "application/octet-stream";
399         break;
400     case AVERROR_HTTP_SERVER_ERROR:
401     case 500:
402         reply_code = 500;
403         reply_text = "Internal server error";
404         break;
405     default:
406         return AVERROR(EINVAL);
407     }
408     if (body) {
409         s->chunked_post = 0;
410         message_len = snprintf(message, sizeof(message),
411                  "HTTP/1.1 %03d %s\r\n"
412                  "Content-Type: %s\r\n"
413                  "Content-Length: %"SIZE_SPECIFIER"\r\n"
414                  "%s"
415                  "\r\n"
416                  "%03d %s\r\n",
417                  reply_code,
418                  reply_text,
419                  content_type,
420                  strlen(reply_text) + 6, // 3 digit status code + space + \r\n
421                  s->headers ? s->headers : "",
422                  reply_code,
423                  reply_text);
424     } else {
425         s->chunked_post = 1;
426         message_len = snprintf(message, sizeof(message),
427                  "HTTP/1.1 %03d %s\r\n"
428                  "Content-Type: %s\r\n"
429                  "Transfer-Encoding: chunked\r\n"
430                  "%s"
431                  "\r\n",
432                  reply_code,
433                  reply_text,
434                  content_type,
435                  s->headers ? s->headers : "");
436     }
437     av_log(h, AV_LOG_TRACE, "HTTP reply header: \n%s----\n", message);
438     if ((ret = ffurl_write(s->hd, message, message_len)) < 0)
439         return ret;
440     return 0;
441 }
442
443 static void handle_http_errors(URLContext *h, int error)
444 {
445     av_assert0(error < 0);
446     http_write_reply(h, error);
447 }
448
449 static int http_handshake(URLContext *c)
450 {
451     int ret, err, new_location;
452     HTTPContext *ch = c->priv_data;
453     URLContext *cl = ch->hd;
454     switch (ch->handshake_step) {
455     case LOWER_PROTO:
456         av_log(c, AV_LOG_TRACE, "Lower protocol\n");
457         if ((ret = ffurl_handshake(cl)) > 0)
458             return 2 + ret;
459         if (ret < 0)
460             return ret;
461         ch->handshake_step = READ_HEADERS;
462         ch->is_connected_server = 1;
463         return 2;
464     case READ_HEADERS:
465         av_log(c, AV_LOG_TRACE, "Read headers\n");
466         if ((err = http_read_header(c, &new_location)) < 0) {
467             handle_http_errors(c, err);
468             return err;
469         }
470         ch->handshake_step = WRITE_REPLY_HEADERS;
471         return 1;
472     case WRITE_REPLY_HEADERS:
473         av_log(c, AV_LOG_TRACE, "Reply code: %d\n", ch->reply_code);
474         if ((err = http_write_reply(c, ch->reply_code)) < 0)
475             return err;
476         ch->handshake_step = FINISH;
477         return 1;
478     case FINISH:
479         return 0;
480     }
481     // this should never be reached.
482     return AVERROR(EINVAL);
483 }
484
485 static int http_listen(URLContext *h, const char *uri, int flags,
486                        AVDictionary **options) {
487     HTTPContext *s = h->priv_data;
488     int ret;
489     char hostname[1024], proto[10];
490     char lower_url[100];
491     const char *lower_proto = "tcp";
492     int port;
493     av_url_split(proto, sizeof(proto), NULL, 0, hostname, sizeof(hostname), &port,
494                  NULL, 0, uri);
495     if (!strcmp(proto, "https"))
496         lower_proto = "tls";
497     ff_url_join(lower_url, sizeof(lower_url), lower_proto, NULL, hostname, port,
498                 NULL);
499     if ((ret = av_dict_set_int(options, "listen", s->listen, 0)) < 0)
500         goto fail;
501     if ((ret = ffurl_open_whitelist(&s->hd, lower_url, AVIO_FLAG_READ_WRITE,
502                                     &h->interrupt_callback, options,
503                                     h->protocol_whitelist, h->protocol_blacklist, h
504                                    )) < 0)
505         goto fail;
506     s->handshake_step = LOWER_PROTO;
507     if (s->listen == HTTP_SINGLE) { /* single client */
508         s->reply_code = 200;
509         while ((ret = http_handshake(h)) > 0);
510     }
511 fail:
512     av_dict_free(&s->chained_options);
513     return ret;
514 }
515
516 static int http_open(URLContext *h, const char *uri, int flags,
517                      AVDictionary **options)
518 {
519     HTTPContext *s = h->priv_data;
520     int ret;
521
522     if( s->seekable == 1 )
523         h->is_streamed = 0;
524     else
525         h->is_streamed = 1;
526
527     s->filesize = UINT64_MAX;
528     s->location = av_strdup(uri);
529     if (!s->location)
530         return AVERROR(ENOMEM);
531     if (options)
532         av_dict_copy(&s->chained_options, *options, 0);
533
534     if (s->headers) {
535         int len = strlen(s->headers);
536         if (len < 2 || strcmp("\r\n", s->headers + len - 2)) {
537             av_log(h, AV_LOG_WARNING,
538                    "No trailing CRLF found in HTTP header.\n");
539             ret = av_reallocp(&s->headers, len + 3);
540             if (ret < 0)
541                 return ret;
542             s->headers[len]     = '\r';
543             s->headers[len + 1] = '\n';
544             s->headers[len + 2] = '\0';
545         }
546     }
547
548     if (s->listen) {
549         return http_listen(h, uri, flags, options);
550     }
551     ret = http_open_cnx(h, options);
552     if (ret < 0)
553         av_dict_free(&s->chained_options);
554     return ret;
555 }
556
557 static int http_accept(URLContext *s, URLContext **c)
558 {
559     int ret;
560     HTTPContext *sc = s->priv_data;
561     HTTPContext *cc;
562     URLContext *sl = sc->hd;
563     URLContext *cl = NULL;
564
565     av_assert0(sc->listen);
566     if ((ret = ffurl_alloc(c, s->filename, s->flags, &sl->interrupt_callback)) < 0)
567         goto fail;
568     cc = (*c)->priv_data;
569     if ((ret = ffurl_accept(sl, &cl)) < 0)
570         goto fail;
571     cc->hd = cl;
572     cc->is_multi_client = 1;
573 fail:
574     return ret;
575 }
576
577 static int http_getc(HTTPContext *s)
578 {
579     int len;
580     if (s->buf_ptr >= s->buf_end) {
581         len = ffurl_read(s->hd, s->buffer, BUFFER_SIZE);
582         if (len < 0) {
583             return len;
584         } else if (len == 0) {
585             return AVERROR_EOF;
586         } else {
587             s->buf_ptr = s->buffer;
588             s->buf_end = s->buffer + len;
589         }
590     }
591     return *s->buf_ptr++;
592 }
593
594 static int http_get_line(HTTPContext *s, char *line, int line_size)
595 {
596     int ch;
597     char *q;
598
599     q = line;
600     for (;;) {
601         ch = http_getc(s);
602         if (ch < 0)
603             return ch;
604         if (ch == '\n') {
605             /* process line */
606             if (q > line && q[-1] == '\r')
607                 q--;
608             *q = '\0';
609
610             return 0;
611         } else {
612             if ((q - line) < line_size - 1)
613                 *q++ = ch;
614         }
615     }
616 }
617
618 static int check_http_code(URLContext *h, int http_code, const char *end)
619 {
620     HTTPContext *s = h->priv_data;
621     /* error codes are 4xx and 5xx, but regard 401 as a success, so we
622      * don't abort until all headers have been parsed. */
623     if (http_code >= 400 && http_code < 600 &&
624         (http_code != 401 || s->auth_state.auth_type != HTTP_AUTH_NONE) &&
625         (http_code != 407 || s->proxy_auth_state.auth_type != HTTP_AUTH_NONE)) {
626         end += strspn(end, SPACE_CHARS);
627         av_log(h, AV_LOG_WARNING, "HTTP error %d %s\n", http_code, end);
628         return ff_http_averror(http_code, AVERROR(EIO));
629     }
630     return 0;
631 }
632
633 static int parse_location(HTTPContext *s, const char *p)
634 {
635     char redirected_location[MAX_URL_SIZE], *new_loc;
636     ff_make_absolute_url(redirected_location, sizeof(redirected_location),
637                          s->location, p);
638     new_loc = av_strdup(redirected_location);
639     if (!new_loc)
640         return AVERROR(ENOMEM);
641     av_free(s->location);
642     s->location = new_loc;
643     return 0;
644 }
645
646 /* "bytes $from-$to/$document_size" */
647 static void parse_content_range(URLContext *h, const char *p)
648 {
649     HTTPContext *s = h->priv_data;
650     const char *slash;
651
652     if (!strncmp(p, "bytes ", 6)) {
653         p     += 6;
654         s->off = strtoull(p, NULL, 10);
655         if ((slash = strchr(p, '/')) && strlen(slash) > 0)
656             s->filesize = strtoull(slash + 1, NULL, 10);
657     }
658     if (s->seekable == -1 && (!s->is_akamai || s->filesize != 2147483647))
659         h->is_streamed = 0; /* we _can_ in fact seek */
660 }
661
662 static int parse_content_encoding(URLContext *h, const char *p)
663 {
664     if (!av_strncasecmp(p, "gzip", 4) ||
665         !av_strncasecmp(p, "deflate", 7)) {
666 #if CONFIG_ZLIB
667         HTTPContext *s = h->priv_data;
668
669         s->compressed = 1;
670         inflateEnd(&s->inflate_stream);
671         if (inflateInit2(&s->inflate_stream, 32 + 15) != Z_OK) {
672             av_log(h, AV_LOG_WARNING, "Error during zlib initialisation: %s\n",
673                    s->inflate_stream.msg);
674             return AVERROR(ENOSYS);
675         }
676         if (zlibCompileFlags() & (1 << 17)) {
677             av_log(h, AV_LOG_WARNING,
678                    "Your zlib was compiled without gzip support.\n");
679             return AVERROR(ENOSYS);
680         }
681 #else
682         av_log(h, AV_LOG_WARNING,
683                "Compressed (%s) content, need zlib with gzip support\n", p);
684         return AVERROR(ENOSYS);
685 #endif /* CONFIG_ZLIB */
686     } else if (!av_strncasecmp(p, "identity", 8)) {
687         // The normal, no-encoding case (although servers shouldn't include
688         // the header at all if this is the case).
689     } else {
690         av_log(h, AV_LOG_WARNING, "Unknown content coding: %s\n", p);
691     }
692     return 0;
693 }
694
695 // Concat all Icy- header lines
696 static int parse_icy(HTTPContext *s, const char *tag, const char *p)
697 {
698     int len = 4 + strlen(p) + strlen(tag);
699     int is_first = !s->icy_metadata_headers;
700     int ret;
701
702     av_dict_set(&s->metadata, tag, p, 0);
703
704     if (s->icy_metadata_headers)
705         len += strlen(s->icy_metadata_headers);
706
707     if ((ret = av_reallocp(&s->icy_metadata_headers, len)) < 0)
708         return ret;
709
710     if (is_first)
711         *s->icy_metadata_headers = '\0';
712
713     av_strlcatf(s->icy_metadata_headers, len, "%s: %s\n", tag, p);
714
715     return 0;
716 }
717
718 static int parse_set_cookie_expiry_time(const char *exp_str, struct tm *buf)
719 {
720     char exp_buf[MAX_EXPIRY];
721     int i, j, exp_buf_len = MAX_EXPIRY-1;
722     char *expiry;
723
724     // strip off any punctuation or whitespace
725     for (i = 0, j = 0; exp_str[i] != '\0' && j < exp_buf_len; i++) {
726         if ((exp_str[i] >= '0' && exp_str[i] <= '9') ||
727             (exp_str[i] >= 'A' && exp_str[i] <= 'Z') ||
728             (exp_str[i] >= 'a' && exp_str[i] <= 'z')) {
729             exp_buf[j] = exp_str[i];
730             j++;
731         }
732     }
733     exp_buf[j] = '\0';
734     expiry = exp_buf;
735
736     // move the string beyond the day of week
737     while ((*expiry < '0' || *expiry > '9') && *expiry != '\0')
738         expiry++;
739
740     return av_small_strptime(expiry, "%d%b%Y%H%M%S", buf) ? 0 : AVERROR(EINVAL);
741 }
742
743 static int parse_set_cookie(const char *set_cookie, AVDictionary **dict)
744 {
745     char *param, *next_param, *cstr, *back;
746
747     if (!(cstr = av_strdup(set_cookie)))
748         return AVERROR(EINVAL);
749
750     // strip any trailing whitespace
751     back = &cstr[strlen(cstr)-1];
752     while (strchr(WHITESPACES, *back)) {
753         *back='\0';
754         back--;
755     }
756
757     next_param = cstr;
758     while ((param = av_strtok(next_param, ";", &next_param))) {
759         char *name, *value;
760         param += strspn(param, WHITESPACES);
761         if ((name = av_strtok(param, "=", &value))) {
762             if (av_dict_set(dict, name, value, 0) < 0) {
763                 av_free(cstr);
764                 return -1;
765             }
766         }
767     }
768
769     av_free(cstr);
770     return 0;
771 }
772
773 static int parse_cookie(HTTPContext *s, const char *p, AVDictionary **cookies)
774 {
775     AVDictionary *new_params = NULL;
776     AVDictionaryEntry *e, *cookie_entry;
777     char *eql, *name;
778
779     // ensure the cookie is parsable
780     if (parse_set_cookie(p, &new_params))
781         return -1;
782
783     // if there is no cookie value there is nothing to parse
784     cookie_entry = av_dict_get(new_params, "", NULL, AV_DICT_IGNORE_SUFFIX);
785     if (!cookie_entry || !cookie_entry->value) {
786         av_dict_free(&new_params);
787         return -1;
788     }
789
790     // ensure the cookie is not expired or older than an existing value
791     if ((e = av_dict_get(new_params, "expires", NULL, 0)) && e->value) {
792         struct tm new_tm = {0};
793         if (!parse_set_cookie_expiry_time(e->value, &new_tm)) {
794             AVDictionaryEntry *e2;
795
796             // if the cookie has already expired ignore it
797             if (av_timegm(&new_tm) < av_gettime() / 1000000) {
798                 av_dict_free(&new_params);
799                 return -1;
800             }
801
802             // only replace an older cookie with the same name
803             e2 = av_dict_get(*cookies, cookie_entry->key, NULL, 0);
804             if (e2 && e2->value) {
805                 AVDictionary *old_params = NULL;
806                 if (!parse_set_cookie(p, &old_params)) {
807                     e2 = av_dict_get(old_params, "expires", NULL, 0);
808                     if (e2 && e2->value) {
809                         struct tm old_tm = {0};
810                         if (!parse_set_cookie_expiry_time(e->value, &old_tm)) {
811                             if (av_timegm(&new_tm) < av_timegm(&old_tm)) {
812                                 av_dict_free(&new_params);
813                                 av_dict_free(&old_params);
814                                 return -1;
815                             }
816                         }
817                     }
818                 }
819                 av_dict_free(&old_params);
820             }
821         }
822     }
823
824     // duplicate the cookie name (dict will dupe the value)
825     if (!(eql = strchr(p, '='))) return AVERROR(EINVAL);
826     if (!(name = av_strndup(p, eql - p))) return AVERROR(ENOMEM);
827
828     // add the cookie to the dictionary
829     av_dict_set(cookies, name, eql, AV_DICT_DONT_STRDUP_KEY);
830
831     return 0;
832 }
833
834 static int cookie_string(AVDictionary *dict, char **cookies)
835 {
836     AVDictionaryEntry *e = NULL;
837     int len = 1;
838
839     // determine how much memory is needed for the cookies string
840     while (e = av_dict_get(dict, "", e, AV_DICT_IGNORE_SUFFIX))
841         len += strlen(e->key) + strlen(e->value) + 1;
842
843     // reallocate the cookies
844     e = NULL;
845     if (*cookies) av_free(*cookies);
846     *cookies = av_malloc(len);
847     if (!*cookies) return AVERROR(ENOMEM);
848     *cookies[0] = '\0';
849
850     // write out the cookies
851     while (e = av_dict_get(dict, "", e, AV_DICT_IGNORE_SUFFIX))
852         av_strlcatf(*cookies, len, "%s%s\n", e->key, e->value);
853
854     return 0;
855 }
856
857 static int process_line(URLContext *h, char *line, int line_count,
858                         int *new_location)
859 {
860     HTTPContext *s = h->priv_data;
861     const char *auto_method =  h->flags & AVIO_FLAG_READ ? "POST" : "GET";
862     char *tag, *p, *end, *method, *resource, *version;
863     int ret;
864
865     /* end of header */
866     if (line[0] == '\0') {
867         s->end_header = 1;
868         return 0;
869     }
870
871     p = line;
872     if (line_count == 0) {
873         if (s->is_connected_server) {
874             // HTTP method
875             method = p;
876             while (*p && !av_isspace(*p))
877                 p++;
878             *(p++) = '\0';
879             av_log(h, AV_LOG_TRACE, "Received method: %s\n", method);
880             if (s->method) {
881                 if (av_strcasecmp(s->method, method)) {
882                     av_log(h, AV_LOG_ERROR, "Received and expected HTTP method do not match. (%s expected, %s received)\n",
883                            s->method, method);
884                     return ff_http_averror(400, AVERROR(EIO));
885                 }
886             } else {
887                 // use autodetected HTTP method to expect
888                 av_log(h, AV_LOG_TRACE, "Autodetected %s HTTP method\n", auto_method);
889                 if (av_strcasecmp(auto_method, method)) {
890                     av_log(h, AV_LOG_ERROR, "Received and autodetected HTTP method did not match "
891                            "(%s autodetected %s received)\n", auto_method, method);
892                     return ff_http_averror(400, AVERROR(EIO));
893                 }
894                 if (!(s->method = av_strdup(method)))
895                     return AVERROR(ENOMEM);
896             }
897
898             // HTTP resource
899             while (av_isspace(*p))
900                 p++;
901             resource = p;
902             while (!av_isspace(*p))
903                 p++;
904             *(p++) = '\0';
905             av_log(h, AV_LOG_TRACE, "Requested resource: %s\n", resource);
906             if (!(s->resource = av_strdup(resource)))
907                 return AVERROR(ENOMEM);
908
909             // HTTP version
910             while (av_isspace(*p))
911                 p++;
912             version = p;
913             while (*p && !av_isspace(*p))
914                 p++;
915             *p = '\0';
916             if (av_strncasecmp(version, "HTTP/", 5)) {
917                 av_log(h, AV_LOG_ERROR, "Malformed HTTP version string.\n");
918                 return ff_http_averror(400, AVERROR(EIO));
919             }
920             av_log(h, AV_LOG_TRACE, "HTTP version string: %s\n", version);
921         } else {
922             if (av_strncasecmp(p, "HTTP/1.0", 8) == 0)
923                 s->willclose = 1;
924             while (*p != '/' && *p != '\0')
925                 p++;
926             while (*p == '/')
927                 p++;
928             av_freep(&s->http_version);
929             s->http_version = av_strndup(p, 3);
930             while (!av_isspace(*p) && *p != '\0')
931                 p++;
932             while (av_isspace(*p))
933                 p++;
934             s->http_code = strtol(p, &end, 10);
935
936             av_log(h, AV_LOG_TRACE, "http_code=%d\n", s->http_code);
937
938             if ((ret = check_http_code(h, s->http_code, end)) < 0)
939                 return ret;
940         }
941     } else {
942         while (*p != '\0' && *p != ':')
943             p++;
944         if (*p != ':')
945             return 1;
946
947         *p  = '\0';
948         tag = line;
949         p++;
950         while (av_isspace(*p))
951             p++;
952         if (!av_strcasecmp(tag, "Location")) {
953             if ((ret = parse_location(s, p)) < 0)
954                 return ret;
955             *new_location = 1;
956         } else if (!av_strcasecmp(tag, "Content-Length") &&
957                    s->filesize == UINT64_MAX) {
958             s->filesize = strtoull(p, NULL, 10);
959         } else if (!av_strcasecmp(tag, "Content-Range")) {
960             parse_content_range(h, p);
961         } else if (!av_strcasecmp(tag, "Accept-Ranges") &&
962                    !strncmp(p, "bytes", 5) &&
963                    s->seekable == -1) {
964             h->is_streamed = 0;
965         } else if (!av_strcasecmp(tag, "Transfer-Encoding") &&
966                    !av_strncasecmp(p, "chunked", 7)) {
967             s->filesize  = UINT64_MAX;
968             s->chunksize = 0;
969         } else if (!av_strcasecmp(tag, "WWW-Authenticate")) {
970             ff_http_auth_handle_header(&s->auth_state, tag, p);
971         } else if (!av_strcasecmp(tag, "Authentication-Info")) {
972             ff_http_auth_handle_header(&s->auth_state, tag, p);
973         } else if (!av_strcasecmp(tag, "Proxy-Authenticate")) {
974             ff_http_auth_handle_header(&s->proxy_auth_state, tag, p);
975         } else if (!av_strcasecmp(tag, "Connection")) {
976             if (!strcmp(p, "close"))
977                 s->willclose = 1;
978         } else if (!av_strcasecmp(tag, "Server")) {
979             if (!av_strcasecmp(p, "AkamaiGHost")) {
980                 s->is_akamai = 1;
981             } else if (!av_strncasecmp(p, "MediaGateway", 12)) {
982                 s->is_mediagateway = 1;
983             }
984         } else if (!av_strcasecmp(tag, "Content-Type")) {
985             av_free(s->mime_type);
986             s->mime_type = av_strdup(p);
987         } else if (!av_strcasecmp(tag, "Set-Cookie")) {
988             if (parse_cookie(s, p, &s->cookie_dict))
989                 av_log(h, AV_LOG_WARNING, "Unable to parse '%s'\n", p);
990         } else if (!av_strcasecmp(tag, "Icy-MetaInt")) {
991             s->icy_metaint = strtoull(p, NULL, 10);
992         } else if (!av_strncasecmp(tag, "Icy-", 4)) {
993             if ((ret = parse_icy(s, tag, p)) < 0)
994                 return ret;
995         } else if (!av_strcasecmp(tag, "Content-Encoding")) {
996             if ((ret = parse_content_encoding(h, p)) < 0)
997                 return ret;
998         }
999     }
1000     return 1;
1001 }
1002
1003 /**
1004  * Create a string containing cookie values for use as a HTTP cookie header
1005  * field value for a particular path and domain from the cookie values stored in
1006  * the HTTP protocol context. The cookie string is stored in *cookies.
1007  *
1008  * @return a negative value if an error condition occurred, 0 otherwise
1009  */
1010 static int get_cookies(HTTPContext *s, char **cookies, const char *path,
1011                        const char *domain)
1012 {
1013     // cookie strings will look like Set-Cookie header field values.  Multiple
1014     // Set-Cookie fields will result in multiple values delimited by a newline
1015     int ret = 0;
1016     char *cookie, *set_cookies = av_strdup(s->cookies), *next = set_cookies;
1017
1018     if (!set_cookies) return AVERROR(EINVAL);
1019
1020     // destroy any cookies in the dictionary.
1021     av_dict_free(&s->cookie_dict);
1022
1023     *cookies = NULL;
1024     while ((cookie = av_strtok(next, "\n", &next))) {
1025         AVDictionary *cookie_params = NULL;
1026         AVDictionaryEntry *cookie_entry, *e;
1027
1028         // store the cookie in a dict in case it is updated in the response
1029         if (parse_cookie(s, cookie, &s->cookie_dict))
1030             av_log(s, AV_LOG_WARNING, "Unable to parse '%s'\n", cookie);
1031
1032         // continue on to the next cookie if this one cannot be parsed
1033         if (parse_set_cookie(cookie, &cookie_params))
1034             continue;
1035
1036         // if the cookie has no value, skip it
1037         cookie_entry = av_dict_get(cookie_params, "", NULL, AV_DICT_IGNORE_SUFFIX);
1038         if (!cookie_entry || !cookie_entry->value) {
1039             av_dict_free(&cookie_params);
1040             continue;
1041         }
1042
1043         // if the cookie has expired, don't add it
1044         if ((e = av_dict_get(cookie_params, "expires", NULL, 0)) && e->value) {
1045             struct tm tm_buf = {0};
1046             if (!parse_set_cookie_expiry_time(e->value, &tm_buf)) {
1047                 if (av_timegm(&tm_buf) < av_gettime() / 1000000) {
1048                     av_dict_free(&cookie_params);
1049                     continue;
1050                 }
1051             }
1052         }
1053
1054         // if no domain in the cookie assume it appied to this request
1055         if ((e = av_dict_get(cookie_params, "domain", NULL, 0)) && e->value) {
1056             // find the offset comparison is on the min domain (b.com, not a.b.com)
1057             int domain_offset = strlen(domain) - strlen(e->value);
1058             if (domain_offset < 0) {
1059                 av_dict_free(&cookie_params);
1060                 continue;
1061             }
1062
1063             // match the cookie domain
1064             if (av_strcasecmp(&domain[domain_offset], e->value)) {
1065                 av_dict_free(&cookie_params);
1066                 continue;
1067             }
1068         }
1069
1070         // ensure this cookie matches the path
1071         e = av_dict_get(cookie_params, "path", NULL, 0);
1072         if (!e || av_strncasecmp(path, e->value, strlen(e->value))) {
1073             av_dict_free(&cookie_params);
1074             continue;
1075         }
1076
1077         // cookie parameters match, so copy the value
1078         if (!*cookies) {
1079             if (!(*cookies = av_asprintf("%s=%s", cookie_entry->key, cookie_entry->value))) {
1080                 ret = AVERROR(ENOMEM);
1081                 break;
1082             }
1083         } else {
1084             char *tmp = *cookies;
1085             size_t str_size = strlen(cookie_entry->key) + strlen(cookie_entry->value) + strlen(*cookies) + 4;
1086             if (!(*cookies = av_malloc(str_size))) {
1087                 ret = AVERROR(ENOMEM);
1088                 av_free(tmp);
1089                 break;
1090             }
1091             snprintf(*cookies, str_size, "%s; %s=%s", tmp, cookie_entry->key, cookie_entry->value);
1092             av_free(tmp);
1093         }
1094     }
1095
1096     av_free(set_cookies);
1097
1098     return ret;
1099 }
1100
1101 static inline int has_header(const char *str, const char *header)
1102 {
1103     /* header + 2 to skip over CRLF prefix. (make sure you have one!) */
1104     if (!str)
1105         return 0;
1106     return av_stristart(str, header + 2, NULL) || av_stristr(str, header);
1107 }
1108
1109 static int http_read_header(URLContext *h, int *new_location)
1110 {
1111     HTTPContext *s = h->priv_data;
1112     char line[MAX_URL_SIZE];
1113     int err = 0;
1114
1115     s->chunksize = UINT64_MAX;
1116
1117     for (;;) {
1118         if ((err = http_get_line(s, line, sizeof(line))) < 0)
1119             return err;
1120
1121         av_log(h, AV_LOG_TRACE, "header='%s'\n", line);
1122
1123         err = process_line(h, line, s->line_count, new_location);
1124         if (err < 0)
1125             return err;
1126         if (err == 0)
1127             break;
1128         s->line_count++;
1129     }
1130
1131     if (s->seekable == -1 && s->is_mediagateway && s->filesize == 2000000000)
1132         h->is_streamed = 1; /* we can in fact _not_ seek */
1133
1134     // add any new cookies into the existing cookie string
1135     cookie_string(s->cookie_dict, &s->cookies);
1136     av_dict_free(&s->cookie_dict);
1137
1138     return err;
1139 }
1140
1141 static int http_connect(URLContext *h, const char *path, const char *local_path,
1142                         const char *hoststr, const char *auth,
1143                         const char *proxyauth, int *new_location)
1144 {
1145     HTTPContext *s = h->priv_data;
1146     int post, err;
1147     char headers[HTTP_HEADERS_SIZE] = "";
1148     char *authstr = NULL, *proxyauthstr = NULL;
1149     uint64_t off = s->off;
1150     int len = 0;
1151     const char *method;
1152     int send_expect_100 = 0;
1153     int ret;
1154
1155     /* send http header */
1156     post = h->flags & AVIO_FLAG_WRITE;
1157
1158     if (s->post_data) {
1159         /* force POST method and disable chunked encoding when
1160          * custom HTTP post data is set */
1161         post            = 1;
1162         s->chunked_post = 0;
1163     }
1164
1165     if (s->method)
1166         method = s->method;
1167     else
1168         method = post ? "POST" : "GET";
1169
1170     authstr      = ff_http_auth_create_response(&s->auth_state, auth,
1171                                                 local_path, method);
1172     proxyauthstr = ff_http_auth_create_response(&s->proxy_auth_state, proxyauth,
1173                                                 local_path, method);
1174     if (post && !s->post_data) {
1175         send_expect_100 = s->send_expect_100;
1176         /* The user has supplied authentication but we don't know the auth type,
1177          * send Expect: 100-continue to get the 401 response including the
1178          * WWW-Authenticate header, or an 100 continue if no auth actually
1179          * is needed. */
1180         if (auth && *auth &&
1181             s->auth_state.auth_type == HTTP_AUTH_NONE &&
1182             s->http_code != 401)
1183             send_expect_100 = 1;
1184     }
1185
1186 #if FF_API_HTTP_USER_AGENT
1187     if (strcmp(s->user_agent_deprecated, DEFAULT_USER_AGENT)) {
1188         av_log(s, AV_LOG_WARNING, "the user-agent option is deprecated, please use user_agent option\n");
1189         s->user_agent = av_strdup(s->user_agent_deprecated);
1190     }
1191 #endif
1192     /* set default headers if needed */
1193     if (!has_header(s->headers, "\r\nUser-Agent: "))
1194         len += av_strlcatf(headers + len, sizeof(headers) - len,
1195                            "User-Agent: %s\r\n", s->user_agent);
1196     if (!has_header(s->headers, "\r\nAccept: "))
1197         len += av_strlcpy(headers + len, "Accept: */*\r\n",
1198                           sizeof(headers) - len);
1199     // Note: we send this on purpose even when s->off is 0 when we're probing,
1200     // since it allows us to detect more reliably if a (non-conforming)
1201     // server supports seeking by analysing the reply headers.
1202     if (!has_header(s->headers, "\r\nRange: ") && !post && (s->off > 0 || s->end_off || s->seekable == -1)) {
1203         len += av_strlcatf(headers + len, sizeof(headers) - len,
1204                            "Range: bytes=%"PRIu64"-", s->off);
1205         if (s->end_off)
1206             len += av_strlcatf(headers + len, sizeof(headers) - len,
1207                                "%"PRId64, s->end_off - 1);
1208         len += av_strlcpy(headers + len, "\r\n",
1209                           sizeof(headers) - len);
1210     }
1211     if (send_expect_100 && !has_header(s->headers, "\r\nExpect: "))
1212         len += av_strlcatf(headers + len, sizeof(headers) - len,
1213                            "Expect: 100-continue\r\n");
1214
1215     if (!has_header(s->headers, "\r\nConnection: ")) {
1216         if (s->multiple_requests)
1217             len += av_strlcpy(headers + len, "Connection: keep-alive\r\n",
1218                               sizeof(headers) - len);
1219         else
1220             len += av_strlcpy(headers + len, "Connection: close\r\n",
1221                               sizeof(headers) - len);
1222     }
1223
1224     if (!has_header(s->headers, "\r\nHost: "))
1225         len += av_strlcatf(headers + len, sizeof(headers) - len,
1226                            "Host: %s\r\n", hoststr);
1227     if (!has_header(s->headers, "\r\nContent-Length: ") && s->post_data)
1228         len += av_strlcatf(headers + len, sizeof(headers) - len,
1229                            "Content-Length: %d\r\n", s->post_datalen);
1230
1231     if (!has_header(s->headers, "\r\nContent-Type: ") && s->content_type)
1232         len += av_strlcatf(headers + len, sizeof(headers) - len,
1233                            "Content-Type: %s\r\n", s->content_type);
1234     if (!has_header(s->headers, "\r\nCookie: ") && s->cookies) {
1235         char *cookies = NULL;
1236         if (!get_cookies(s, &cookies, path, hoststr) && cookies) {
1237             len += av_strlcatf(headers + len, sizeof(headers) - len,
1238                                "Cookie: %s\r\n", cookies);
1239             av_free(cookies);
1240         }
1241     }
1242     if (!has_header(s->headers, "\r\nIcy-MetaData: ") && s->icy)
1243         len += av_strlcatf(headers + len, sizeof(headers) - len,
1244                            "Icy-MetaData: %d\r\n", 1);
1245
1246     /* now add in custom headers */
1247     if (s->headers)
1248         av_strlcpy(headers + len, s->headers, sizeof(headers) - len);
1249
1250     ret = snprintf(s->buffer, sizeof(s->buffer),
1251              "%s %s HTTP/1.1\r\n"
1252              "%s"
1253              "%s"
1254              "%s"
1255              "%s%s"
1256              "\r\n",
1257              method,
1258              path,
1259              post && s->chunked_post ? "Transfer-Encoding: chunked\r\n" : "",
1260              headers,
1261              authstr ? authstr : "",
1262              proxyauthstr ? "Proxy-" : "", proxyauthstr ? proxyauthstr : "");
1263
1264     av_log(h, AV_LOG_DEBUG, "request: %s\n", s->buffer);
1265
1266     if (strlen(headers) + 1 == sizeof(headers) ||
1267         ret >= sizeof(s->buffer)) {
1268         av_log(h, AV_LOG_ERROR, "overlong headers\n");
1269         err = AVERROR(EINVAL);
1270         goto done;
1271     }
1272
1273
1274     if ((err = ffurl_write(s->hd, s->buffer, strlen(s->buffer))) < 0)
1275         goto done;
1276
1277     if (s->post_data)
1278         if ((err = ffurl_write(s->hd, s->post_data, s->post_datalen)) < 0)
1279             goto done;
1280
1281     /* init input buffer */
1282     s->buf_ptr          = s->buffer;
1283     s->buf_end          = s->buffer;
1284     s->line_count       = 0;
1285     s->off              = 0;
1286     s->icy_data_read    = 0;
1287     s->filesize         = UINT64_MAX;
1288     s->willclose        = 0;
1289     s->end_chunked_post = 0;
1290     s->end_header       = 0;
1291 #if CONFIG_ZLIB
1292     s->compressed       = 0;
1293 #endif
1294     if (post && !s->post_data && !send_expect_100) {
1295         /* Pretend that it did work. We didn't read any header yet, since
1296          * we've still to send the POST data, but the code calling this
1297          * function will check http_code after we return. */
1298         s->http_code = 200;
1299         err = 0;
1300         goto done;
1301     }
1302
1303     /* wait for header */
1304     err = http_read_header(h, new_location);
1305     if (err < 0)
1306         goto done;
1307
1308     if (*new_location)
1309         s->off = off;
1310
1311     err = (off == s->off) ? 0 : -1;
1312 done:
1313     av_freep(&authstr);
1314     av_freep(&proxyauthstr);
1315     return err;
1316 }
1317
1318 static int http_buf_read(URLContext *h, uint8_t *buf, int size)
1319 {
1320     HTTPContext *s = h->priv_data;
1321     int len;
1322
1323     if (s->chunksize != UINT64_MAX) {
1324         if (s->chunkend) {
1325             return AVERROR_EOF;
1326         }
1327         if (!s->chunksize) {
1328             char line[32];
1329             int err;
1330
1331             do {
1332                 if ((err = http_get_line(s, line, sizeof(line))) < 0)
1333                     return err;
1334             } while (!*line);    /* skip CR LF from last chunk */
1335
1336             s->chunksize = strtoull(line, NULL, 16);
1337
1338             av_log(h, AV_LOG_TRACE,
1339                    "Chunked encoding data size: %"PRIu64"\n",
1340                     s->chunksize);
1341
1342             if (!s->chunksize && s->multiple_requests) {
1343                 http_get_line(s, line, sizeof(line)); // read empty chunk
1344                 s->chunkend = 1;
1345                 return 0;
1346             }
1347             else if (!s->chunksize) {
1348                 av_log(h, AV_LOG_DEBUG, "Last chunk received, closing conn\n");
1349                 ffurl_closep(&s->hd);
1350                 return 0;
1351             }
1352             else if (s->chunksize == UINT64_MAX) {
1353                 av_log(h, AV_LOG_ERROR, "Invalid chunk size %"PRIu64"\n",
1354                        s->chunksize);
1355                 return AVERROR(EINVAL);
1356             }
1357         }
1358         size = FFMIN(size, s->chunksize);
1359     }
1360
1361     /* read bytes from input buffer first */
1362     len = s->buf_end - s->buf_ptr;
1363     if (len > 0) {
1364         if (len > size)
1365             len = size;
1366         memcpy(buf, s->buf_ptr, len);
1367         s->buf_ptr += len;
1368     } else {
1369         uint64_t target_end = s->end_off ? s->end_off : s->filesize;
1370         if ((!s->willclose || s->chunksize == UINT64_MAX) && s->off >= target_end)
1371             return AVERROR_EOF;
1372         len = ffurl_read(s->hd, buf, size);
1373         if (!len && (!s->willclose || s->chunksize == UINT64_MAX) && s->off < target_end) {
1374             av_log(h, AV_LOG_ERROR,
1375                    "Stream ends prematurely at %"PRIu64", should be %"PRIu64"\n",
1376                    s->off, target_end
1377                   );
1378             return AVERROR(EIO);
1379         }
1380     }
1381     if (len > 0) {
1382         s->off += len;
1383         if (s->chunksize > 0 && s->chunksize != UINT64_MAX) {
1384             av_assert0(s->chunksize >= len);
1385             s->chunksize -= len;
1386         }
1387     }
1388     return len;
1389 }
1390
1391 #if CONFIG_ZLIB
1392 #define DECOMPRESS_BUF_SIZE (256 * 1024)
1393 static int http_buf_read_compressed(URLContext *h, uint8_t *buf, int size)
1394 {
1395     HTTPContext *s = h->priv_data;
1396     int ret;
1397
1398     if (!s->inflate_buffer) {
1399         s->inflate_buffer = av_malloc(DECOMPRESS_BUF_SIZE);
1400         if (!s->inflate_buffer)
1401             return AVERROR(ENOMEM);
1402     }
1403
1404     if (s->inflate_stream.avail_in == 0) {
1405         int read = http_buf_read(h, s->inflate_buffer, DECOMPRESS_BUF_SIZE);
1406         if (read <= 0)
1407             return read;
1408         s->inflate_stream.next_in  = s->inflate_buffer;
1409         s->inflate_stream.avail_in = read;
1410     }
1411
1412     s->inflate_stream.avail_out = size;
1413     s->inflate_stream.next_out  = buf;
1414
1415     ret = inflate(&s->inflate_stream, Z_SYNC_FLUSH);
1416     if (ret != Z_OK && ret != Z_STREAM_END)
1417         av_log(h, AV_LOG_WARNING, "inflate return value: %d, %s\n",
1418                ret, s->inflate_stream.msg);
1419
1420     return size - s->inflate_stream.avail_out;
1421 }
1422 #endif /* CONFIG_ZLIB */
1423
1424 static int64_t http_seek_internal(URLContext *h, int64_t off, int whence, int force_reconnect);
1425
1426 static int http_read_stream(URLContext *h, uint8_t *buf, int size)
1427 {
1428     HTTPContext *s = h->priv_data;
1429     int err, new_location, read_ret;
1430     int64_t seek_ret;
1431
1432     if (!s->hd)
1433         return AVERROR_EOF;
1434
1435     if (s->end_chunked_post && !s->end_header) {
1436         err = http_read_header(h, &new_location);
1437         if (err < 0)
1438             return err;
1439     }
1440
1441 #if CONFIG_ZLIB
1442     if (s->compressed)
1443         return http_buf_read_compressed(h, buf, size);
1444 #endif /* CONFIG_ZLIB */
1445     read_ret = http_buf_read(h, buf, size);
1446     if (   (read_ret  < 0 && s->reconnect        && (!h->is_streamed || s->reconnect_streamed) && s->filesize > 0 && s->off < s->filesize)
1447         || (read_ret == 0 && s->reconnect_at_eof && (!h->is_streamed || s->reconnect_streamed))) {
1448         uint64_t target = h->is_streamed ? 0 : s->off;
1449
1450         if (s->reconnect_delay > s->reconnect_delay_max)
1451             return AVERROR(EIO);
1452
1453         av_log(h, AV_LOG_INFO, "Will reconnect at %"PRIu64" error=%s.\n", s->off, av_err2str(read_ret));
1454         av_usleep(1000U*1000*s->reconnect_delay);
1455         s->reconnect_delay = 1 + 2*s->reconnect_delay;
1456         seek_ret = http_seek_internal(h, target, SEEK_SET, 1);
1457         if (seek_ret != target) {
1458             av_log(h, AV_LOG_ERROR, "Failed to reconnect at %"PRIu64".\n", target);
1459             return read_ret;
1460         }
1461
1462         read_ret = http_buf_read(h, buf, size);
1463     } else
1464         s->reconnect_delay = 0;
1465
1466     return read_ret;
1467 }
1468
1469 // Like http_read_stream(), but no short reads.
1470 // Assumes partial reads are an error.
1471 static int http_read_stream_all(URLContext *h, uint8_t *buf, int size)
1472 {
1473     int pos = 0;
1474     while (pos < size) {
1475         int len = http_read_stream(h, buf + pos, size - pos);
1476         if (len < 0)
1477             return len;
1478         pos += len;
1479     }
1480     return pos;
1481 }
1482
1483 static void update_metadata(HTTPContext *s, char *data)
1484 {
1485     char *key;
1486     char *val;
1487     char *end;
1488     char *next = data;
1489
1490     while (*next) {
1491         key = next;
1492         val = strstr(key, "='");
1493         if (!val)
1494             break;
1495         end = strstr(val, "';");
1496         if (!end)
1497             break;
1498
1499         *val = '\0';
1500         *end = '\0';
1501         val += 2;
1502
1503         av_dict_set(&s->metadata, key, val, 0);
1504
1505         next = end + 2;
1506     }
1507 }
1508
1509 static int store_icy(URLContext *h, int size)
1510 {
1511     HTTPContext *s = h->priv_data;
1512     /* until next metadata packet */
1513     uint64_t remaining;
1514
1515     if (s->icy_metaint < s->icy_data_read)
1516         return AVERROR_INVALIDDATA;
1517     remaining = s->icy_metaint - s->icy_data_read;
1518
1519     if (!remaining) {
1520         /* The metadata packet is variable sized. It has a 1 byte header
1521          * which sets the length of the packet (divided by 16). If it's 0,
1522          * the metadata doesn't change. After the packet, icy_metaint bytes
1523          * of normal data follows. */
1524         uint8_t ch;
1525         int len = http_read_stream_all(h, &ch, 1);
1526         if (len < 0)
1527             return len;
1528         if (ch > 0) {
1529             char data[255 * 16 + 1];
1530             int ret;
1531             len = ch * 16;
1532             ret = http_read_stream_all(h, data, len);
1533             if (ret < 0)
1534                 return ret;
1535             data[len + 1] = 0;
1536             if ((ret = av_opt_set(s, "icy_metadata_packet", data, 0)) < 0)
1537                 return ret;
1538             update_metadata(s, data);
1539         }
1540         s->icy_data_read = 0;
1541         remaining        = s->icy_metaint;
1542     }
1543
1544     return FFMIN(size, remaining);
1545 }
1546
1547 static int http_read(URLContext *h, uint8_t *buf, int size)
1548 {
1549     HTTPContext *s = h->priv_data;
1550
1551     if (s->icy_metaint > 0) {
1552         size = store_icy(h, size);
1553         if (size < 0)
1554             return size;
1555     }
1556
1557     size = http_read_stream(h, buf, size);
1558     if (size > 0)
1559         s->icy_data_read += size;
1560     return size;
1561 }
1562
1563 /* used only when posting data */
1564 static int http_write(URLContext *h, const uint8_t *buf, int size)
1565 {
1566     char temp[11] = "";  /* 32-bit hex + CRLF + nul */
1567     int ret;
1568     char crlf[] = "\r\n";
1569     HTTPContext *s = h->priv_data;
1570
1571     if (!s->chunked_post) {
1572         /* non-chunked data is sent without any special encoding */
1573         return ffurl_write(s->hd, buf, size);
1574     }
1575
1576     /* silently ignore zero-size data since chunk encoding that would
1577      * signal EOF */
1578     if (size > 0) {
1579         /* upload data using chunked encoding */
1580         snprintf(temp, sizeof(temp), "%x\r\n", size);
1581
1582         if ((ret = ffurl_write(s->hd, temp, strlen(temp))) < 0 ||
1583             (ret = ffurl_write(s->hd, buf, size)) < 0          ||
1584             (ret = ffurl_write(s->hd, crlf, sizeof(crlf) - 1)) < 0)
1585             return ret;
1586     }
1587     return size;
1588 }
1589
1590 static int http_shutdown(URLContext *h, int flags)
1591 {
1592     int ret = 0;
1593     char footer[] = "0\r\n\r\n";
1594     HTTPContext *s = h->priv_data;
1595
1596     /* signal end of chunked encoding if used */
1597     if (((flags & AVIO_FLAG_WRITE) && s->chunked_post) ||
1598         ((flags & AVIO_FLAG_READ) && s->chunked_post && s->listen)) {
1599         ret = ffurl_write(s->hd, footer, sizeof(footer) - 1);
1600         ret = ret > 0 ? 0 : ret;
1601         s->end_chunked_post = 1;
1602     }
1603
1604     return ret;
1605 }
1606
1607 static int http_close(URLContext *h)
1608 {
1609     int ret = 0;
1610     HTTPContext *s = h->priv_data;
1611
1612 #if CONFIG_ZLIB
1613     inflateEnd(&s->inflate_stream);
1614     av_freep(&s->inflate_buffer);
1615 #endif /* CONFIG_ZLIB */
1616
1617     if (!s->end_chunked_post)
1618         /* Close the write direction by sending the end of chunked encoding. */
1619         ret = http_shutdown(h, h->flags);
1620
1621     if (s->hd)
1622         ffurl_closep(&s->hd);
1623     av_dict_free(&s->chained_options);
1624     return ret;
1625 }
1626
1627 static int64_t http_seek_internal(URLContext *h, int64_t off, int whence, int force_reconnect)
1628 {
1629     HTTPContext *s = h->priv_data;
1630     URLContext *old_hd = s->hd;
1631     uint64_t old_off = s->off;
1632     uint8_t old_buf[BUFFER_SIZE];
1633     int old_buf_size, ret;
1634     AVDictionary *options = NULL;
1635
1636     if (whence == AVSEEK_SIZE)
1637         return s->filesize;
1638     else if (!force_reconnect &&
1639              ((whence == SEEK_CUR && off == 0) ||
1640               (whence == SEEK_SET && off == s->off)))
1641         return s->off;
1642     else if ((s->filesize == UINT64_MAX && whence == SEEK_END))
1643         return AVERROR(ENOSYS);
1644
1645     if (whence == SEEK_CUR)
1646         off += s->off;
1647     else if (whence == SEEK_END)
1648         off += s->filesize;
1649     else if (whence != SEEK_SET)
1650         return AVERROR(EINVAL);
1651     if (off < 0)
1652         return AVERROR(EINVAL);
1653     s->off = off;
1654
1655     if (s->off && h->is_streamed)
1656         return AVERROR(ENOSYS);
1657
1658     /* we save the old context in case the seek fails */
1659     old_buf_size = s->buf_end - s->buf_ptr;
1660     memcpy(old_buf, s->buf_ptr, old_buf_size);
1661     s->hd = NULL;
1662
1663     /* if it fails, continue on old connection */
1664     if ((ret = http_open_cnx(h, &options)) < 0) {
1665         av_dict_free(&options);
1666         memcpy(s->buffer, old_buf, old_buf_size);
1667         s->buf_ptr = s->buffer;
1668         s->buf_end = s->buffer + old_buf_size;
1669         s->hd      = old_hd;
1670         s->off     = old_off;
1671         return ret;
1672     }
1673     av_dict_free(&options);
1674     ffurl_close(old_hd);
1675     return off;
1676 }
1677
1678 static int64_t http_seek(URLContext *h, int64_t off, int whence)
1679 {
1680     return http_seek_internal(h, off, whence, 0);
1681 }
1682
1683 static int http_get_file_handle(URLContext *h)
1684 {
1685     HTTPContext *s = h->priv_data;
1686     return ffurl_get_file_handle(s->hd);
1687 }
1688
1689 static int http_get_short_seek(URLContext *h)
1690 {
1691     HTTPContext *s = h->priv_data;
1692     return ffurl_get_short_seek(s->hd);
1693 }
1694
1695 #define HTTP_CLASS(flavor)                          \
1696 static const AVClass flavor ## _context_class = {   \
1697     .class_name = # flavor,                         \
1698     .item_name  = av_default_item_name,             \
1699     .option     = options,                          \
1700     .version    = LIBAVUTIL_VERSION_INT,            \
1701 }
1702
1703 #if CONFIG_HTTP_PROTOCOL
1704 HTTP_CLASS(http);
1705
1706 const URLProtocol ff_http_protocol = {
1707     .name                = "http",
1708     .url_open2           = http_open,
1709     .url_accept          = http_accept,
1710     .url_handshake       = http_handshake,
1711     .url_read            = http_read,
1712     .url_write           = http_write,
1713     .url_seek            = http_seek,
1714     .url_close           = http_close,
1715     .url_get_file_handle = http_get_file_handle,
1716     .url_get_short_seek  = http_get_short_seek,
1717     .url_shutdown        = http_shutdown,
1718     .priv_data_size      = sizeof(HTTPContext),
1719     .priv_data_class     = &http_context_class,
1720     .flags               = URL_PROTOCOL_FLAG_NETWORK,
1721     .default_whitelist   = "http,https,tls,rtp,tcp,udp,crypto,httpproxy"
1722 };
1723 #endif /* CONFIG_HTTP_PROTOCOL */
1724
1725 #if CONFIG_HTTPS_PROTOCOL
1726 HTTP_CLASS(https);
1727
1728 const URLProtocol ff_https_protocol = {
1729     .name                = "https",
1730     .url_open2           = http_open,
1731     .url_read            = http_read,
1732     .url_write           = http_write,
1733     .url_seek            = http_seek,
1734     .url_close           = http_close,
1735     .url_get_file_handle = http_get_file_handle,
1736     .url_get_short_seek  = http_get_short_seek,
1737     .url_shutdown        = http_shutdown,
1738     .priv_data_size      = sizeof(HTTPContext),
1739     .priv_data_class     = &https_context_class,
1740     .flags               = URL_PROTOCOL_FLAG_NETWORK,
1741     .default_whitelist   = "http,https,tls,rtp,tcp,udp,crypto,httpproxy"
1742 };
1743 #endif /* CONFIG_HTTPS_PROTOCOL */
1744
1745 #if CONFIG_HTTPPROXY_PROTOCOL
1746 static int http_proxy_close(URLContext *h)
1747 {
1748     HTTPContext *s = h->priv_data;
1749     if (s->hd)
1750         ffurl_closep(&s->hd);
1751     return 0;
1752 }
1753
1754 static int http_proxy_open(URLContext *h, const char *uri, int flags)
1755 {
1756     HTTPContext *s = h->priv_data;
1757     char hostname[1024], hoststr[1024];
1758     char auth[1024], pathbuf[1024], *path;
1759     char lower_url[100];
1760     int port, ret = 0, attempts = 0;
1761     HTTPAuthType cur_auth_type;
1762     char *authstr;
1763     int new_loc;
1764
1765     if( s->seekable == 1 )
1766         h->is_streamed = 0;
1767     else
1768         h->is_streamed = 1;
1769
1770     av_url_split(NULL, 0, auth, sizeof(auth), hostname, sizeof(hostname), &port,
1771                  pathbuf, sizeof(pathbuf), uri);
1772     ff_url_join(hoststr, sizeof(hoststr), NULL, NULL, hostname, port, NULL);
1773     path = pathbuf;
1774     if (*path == '/')
1775         path++;
1776
1777     ff_url_join(lower_url, sizeof(lower_url), "tcp", NULL, hostname, port,
1778                 NULL);
1779 redo:
1780     ret = ffurl_open_whitelist(&s->hd, lower_url, AVIO_FLAG_READ_WRITE,
1781                                &h->interrupt_callback, NULL,
1782                                h->protocol_whitelist, h->protocol_blacklist, h);
1783     if (ret < 0)
1784         return ret;
1785
1786     authstr = ff_http_auth_create_response(&s->proxy_auth_state, auth,
1787                                            path, "CONNECT");
1788     snprintf(s->buffer, sizeof(s->buffer),
1789              "CONNECT %s HTTP/1.1\r\n"
1790              "Host: %s\r\n"
1791              "Connection: close\r\n"
1792              "%s%s"
1793              "\r\n",
1794              path,
1795              hoststr,
1796              authstr ? "Proxy-" : "", authstr ? authstr : "");
1797     av_freep(&authstr);
1798
1799     if ((ret = ffurl_write(s->hd, s->buffer, strlen(s->buffer))) < 0)
1800         goto fail;
1801
1802     s->buf_ptr    = s->buffer;
1803     s->buf_end    = s->buffer;
1804     s->line_count = 0;
1805     s->filesize   = UINT64_MAX;
1806     cur_auth_type = s->proxy_auth_state.auth_type;
1807
1808     /* Note: This uses buffering, potentially reading more than the
1809      * HTTP header. If tunneling a protocol where the server starts
1810      * the conversation, we might buffer part of that here, too.
1811      * Reading that requires using the proper ffurl_read() function
1812      * on this URLContext, not using the fd directly (as the tls
1813      * protocol does). This shouldn't be an issue for tls though,
1814      * since the client starts the conversation there, so there
1815      * is no extra data that we might buffer up here.
1816      */
1817     ret = http_read_header(h, &new_loc);
1818     if (ret < 0)
1819         goto fail;
1820
1821     attempts++;
1822     if (s->http_code == 407 &&
1823         (cur_auth_type == HTTP_AUTH_NONE || s->proxy_auth_state.stale) &&
1824         s->proxy_auth_state.auth_type != HTTP_AUTH_NONE && attempts < 2) {
1825         ffurl_closep(&s->hd);
1826         goto redo;
1827     }
1828
1829     if (s->http_code < 400)
1830         return 0;
1831     ret = ff_http_averror(s->http_code, AVERROR(EIO));
1832
1833 fail:
1834     http_proxy_close(h);
1835     return ret;
1836 }
1837
1838 static int http_proxy_write(URLContext *h, const uint8_t *buf, int size)
1839 {
1840     HTTPContext *s = h->priv_data;
1841     return ffurl_write(s->hd, buf, size);
1842 }
1843
1844 const URLProtocol ff_httpproxy_protocol = {
1845     .name                = "httpproxy",
1846     .url_open            = http_proxy_open,
1847     .url_read            = http_buf_read,
1848     .url_write           = http_proxy_write,
1849     .url_close           = http_proxy_close,
1850     .url_get_file_handle = http_get_file_handle,
1851     .priv_data_size      = sizeof(HTTPContext),
1852     .flags               = URL_PROTOCOL_FLAG_NETWORK,
1853 };
1854 #endif /* CONFIG_HTTPPROXY_PROTOCOL */