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