]> git.sesse.net Git - ffmpeg/blob - libavformat/http.c
Merge commit 'd7f530b0d67fe3996dbfa990a47c865e0d1400a2'
[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/avstring.h"
29 #include "libavutil/opt.h"
30
31 #include "avformat.h"
32 #include "http.h"
33 #include "httpauth.h"
34 #include "internal.h"
35 #include "network.h"
36 #include "os_support.h"
37 #include "url.h"
38
39 /* XXX: POST protocol is not completely implemented because ffmpeg uses
40  * only a subset of it. */
41
42 /* The IO buffer size is unrelated to the max URL size in itself, but needs
43  * to be large enough to fit the full request headers (including long
44  * path names). */
45 #define BUFFER_SIZE   MAX_URL_SIZE
46 #define MAX_REDIRECTS 8
47
48 typedef struct {
49     const AVClass *class;
50     URLContext *hd;
51     unsigned char buffer[BUFFER_SIZE], *buf_ptr, *buf_end;
52     int line_count;
53     int http_code;
54     /* Used if "Transfer-Encoding: chunked" otherwise -1. */
55     int64_t chunksize;
56     int64_t off, end_off, filesize;
57     char *location;
58     HTTPAuthState auth_state;
59     HTTPAuthState proxy_auth_state;
60     char *headers;
61     char *mime_type;
62     char *user_agent;
63     char *content_type;
64     /* Set if the server correctly handles Connection: close and will close
65      * the connection after feeding us the content. */
66     int willclose;
67     int seekable;           /**< Control seekability, 0 = disable, 1 = enable, -1 = probe. */
68     int chunked_post;
69     /* A flag which indicates if the end of chunked encoding has been sent. */
70     int end_chunked_post;
71     /* A flag which indicates we have finished to read POST reply. */
72     int end_header;
73     /* A flag which indicates if we use persistent connections. */
74     int multiple_requests;
75     uint8_t *post_data;
76     int post_datalen;
77     int is_akamai;
78     int is_mediagateway;
79     char *cookies;          ///< holds newline (\n) delimited Set-Cookie header field values (without the "Set-Cookie: " field name)
80     int icy;
81     /* how much data was read since the last ICY metadata packet */
82     int icy_data_read;
83     /* after how many bytes of read data a new metadata packet will be found */
84     int icy_metaint;
85     char *icy_metadata_headers;
86     char *icy_metadata_packet;
87     AVDictionary *metadata;
88 #if CONFIG_ZLIB
89     int compressed;
90     z_stream inflate_stream;
91     uint8_t *inflate_buffer;
92 #endif /* CONFIG_ZLIB */
93     AVDictionary *chained_options;
94     int send_expect_100;
95     char *method;
96 } HTTPContext;
97
98 #define OFFSET(x) offsetof(HTTPContext, x)
99 #define D AV_OPT_FLAG_DECODING_PARAM
100 #define E AV_OPT_FLAG_ENCODING_PARAM
101 #define DEFAULT_USER_AGENT "Lavf/" AV_STRINGIFY(LIBAVFORMAT_VERSION)
102
103 static const AVOption options[] = {
104     { "seekable", "control seekability of connection", OFFSET(seekable), AV_OPT_TYPE_INT, { .i64 = -1 }, -1, 1, D },
105     { "chunked_post", "use chunked transfer-encoding for posts", OFFSET(chunked_post), AV_OPT_TYPE_INT, { .i64 = 1 }, 0, 1, E },
106     { "headers", "set custom HTTP headers, can override built in default headers", OFFSET(headers), AV_OPT_TYPE_STRING, { 0 }, 0, 0, D | E },
107     { "content_type", "set a specific content type for the POST messages", OFFSET(content_type), AV_OPT_TYPE_STRING, { 0 }, 0, 0, D | E },
108     { "user_agent", "override User-Agent header", OFFSET(user_agent), AV_OPT_TYPE_STRING, { .str = DEFAULT_USER_AGENT }, 0, 0, D },
109     { "user-agent", "override User-Agent header", OFFSET(user_agent), AV_OPT_TYPE_STRING, { .str = DEFAULT_USER_AGENT }, 0, 0, D },
110     { "multiple_requests", "use persistent connections", OFFSET(multiple_requests), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 1, D | E },
111     { "post_data", "set custom HTTP post data", OFFSET(post_data), AV_OPT_TYPE_BINARY, .flags = D | E },
112     { "mime_type", "export the MIME type", OFFSET(mime_type), AV_OPT_TYPE_STRING, { 0 }, 0, 0, AV_OPT_FLAG_EXPORT | AV_OPT_FLAG_READONLY },
113     { "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, { 0 }, 0, 0, D },
114     { "icy", "request ICY metadata", OFFSET(icy), AV_OPT_TYPE_INT, { .i64 = 1 }, 0, 1, D },
115     { "icy_metadata_headers", "return ICY metadata headers", OFFSET(icy_metadata_headers), AV_OPT_TYPE_STRING, { 0 }, 0, 0, AV_OPT_FLAG_EXPORT },
116     { "icy_metadata_packet", "return current ICY metadata packet", OFFSET(icy_metadata_packet), AV_OPT_TYPE_STRING, { 0 }, 0, 0, AV_OPT_FLAG_EXPORT },
117     { "metadata", "metadata read from the bitstream", OFFSET(metadata), AV_OPT_TYPE_DICT, {0}, 0, 0, AV_OPT_FLAG_EXPORT },
118     { "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"},
119     { "none", "No auth method set, autodetect", 0, AV_OPT_TYPE_CONST, { .i64 = HTTP_AUTH_NONE }, 0, 0, D | E, "auth_type"},
120     { "basic", "HTTP basic authentication", 0, AV_OPT_TYPE_CONST, { .i64 = HTTP_AUTH_BASIC }, 0, 0, D | E, "auth_type"},
121     { "send_expect_100", "Force sending an Expect: 100-continue header for POST", OFFSET(send_expect_100), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 1, E },
122     { "location", "The actual location of the data received", OFFSET(location), AV_OPT_TYPE_STRING, { 0 }, 0, 0, D | E },
123     { "offset", "initial byte offset", OFFSET(off), AV_OPT_TYPE_INT64, { .i64 = 0 }, 0, INT64_MAX, D },
124     { "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 },
125     { "method", "Override the HTTP method", OFFSET(method), AV_OPT_TYPE_STRING, { .str = NULL }, 0, 0, E },
126     { NULL }
127 };
128
129 static int http_connect(URLContext *h, const char *path, const char *local_path,
130                         const char *hoststr, const char *auth,
131                         const char *proxyauth, int *new_location);
132
133 void ff_http_init_auth_state(URLContext *dest, const URLContext *src)
134 {
135     memcpy(&((HTTPContext *)dest->priv_data)->auth_state,
136            &((HTTPContext *)src->priv_data)->auth_state,
137            sizeof(HTTPAuthState));
138     memcpy(&((HTTPContext *)dest->priv_data)->proxy_auth_state,
139            &((HTTPContext *)src->priv_data)->proxy_auth_state,
140            sizeof(HTTPAuthState));
141 }
142
143 static int http_open_cnx_internal(URLContext *h, AVDictionary **options)
144 {
145     const char *path, *proxy_path, *lower_proto = "tcp", *local_path;
146     char hostname[1024], hoststr[1024], proto[10];
147     char auth[1024], proxyauth[1024] = "";
148     char path1[MAX_URL_SIZE];
149     char buf[1024], urlbuf[MAX_URL_SIZE];
150     int port, use_proxy, err, location_changed = 0;
151     HTTPContext *s = h->priv_data;
152
153     av_url_split(proto, sizeof(proto), auth, sizeof(auth),
154                  hostname, sizeof(hostname), &port,
155                  path1, sizeof(path1), s->location);
156     ff_url_join(hoststr, sizeof(hoststr), NULL, NULL, hostname, port, NULL);
157
158     proxy_path = getenv("http_proxy");
159     use_proxy  = !ff_http_match_no_proxy(getenv("no_proxy"), hostname) &&
160                  proxy_path && av_strstart(proxy_path, "http://", NULL);
161
162     if (!strcmp(proto, "https")) {
163         lower_proto = "tls";
164         use_proxy   = 0;
165         if (port < 0)
166             port = 443;
167     }
168     if (port < 0)
169         port = 80;
170
171     if (path1[0] == '\0')
172         path = "/";
173     else
174         path = path1;
175     local_path = path;
176     if (use_proxy) {
177         /* Reassemble the request URL without auth string - we don't
178          * want to leak the auth to the proxy. */
179         ff_url_join(urlbuf, sizeof(urlbuf), proto, NULL, hostname, port, "%s",
180                     path1);
181         path = urlbuf;
182         av_url_split(NULL, 0, proxyauth, sizeof(proxyauth),
183                      hostname, sizeof(hostname), &port, NULL, 0, proxy_path);
184     }
185
186     ff_url_join(buf, sizeof(buf), lower_proto, NULL, hostname, port, NULL);
187
188     if (!s->hd) {
189         err = ffurl_open(&s->hd, buf, AVIO_FLAG_READ_WRITE,
190                          &h->interrupt_callback, options);
191         if (err < 0)
192             return err;
193     }
194
195     err = http_connect(h, path, local_path, hoststr,
196                        auth, proxyauth, &location_changed);
197     if (err < 0)
198         return err;
199
200     return location_changed;
201 }
202
203 /* return non zero if error */
204 static int http_open_cnx(URLContext *h, AVDictionary **options)
205 {
206     HTTPAuthType cur_auth_type, cur_proxy_auth_type;
207     HTTPContext *s = h->priv_data;
208     int location_changed, attempts = 0, redirects = 0;
209 redo:
210     cur_auth_type       = s->auth_state.auth_type;
211     cur_proxy_auth_type = s->auth_state.auth_type;
212
213     location_changed = http_open_cnx_internal(h, options);
214     if (location_changed < 0)
215         goto fail;
216
217     attempts++;
218     if (s->http_code == 401) {
219         if ((cur_auth_type == HTTP_AUTH_NONE || s->auth_state.stale) &&
220             s->auth_state.auth_type != HTTP_AUTH_NONE && attempts < 4) {
221             ffurl_closep(&s->hd);
222             goto redo;
223         } else
224             goto fail;
225     }
226     if (s->http_code == 407) {
227         if ((cur_proxy_auth_type == HTTP_AUTH_NONE || s->proxy_auth_state.stale) &&
228             s->proxy_auth_state.auth_type != HTTP_AUTH_NONE && attempts < 4) {
229             ffurl_closep(&s->hd);
230             goto redo;
231         } else
232             goto fail;
233     }
234     if ((s->http_code == 301 || s->http_code == 302 ||
235          s->http_code == 303 || s->http_code == 307) &&
236         location_changed == 1) {
237         /* url moved, get next */
238         ffurl_closep(&s->hd);
239         if (redirects++ >= MAX_REDIRECTS)
240             return AVERROR(EIO);
241         /* Restart the authentication process with the new target, which
242          * might use a different auth mechanism. */
243         memset(&s->auth_state, 0, sizeof(s->auth_state));
244         attempts         = 0;
245         location_changed = 0;
246         goto redo;
247     }
248     return 0;
249
250 fail:
251     if (s->hd)
252         ffurl_closep(&s->hd);
253     return ff_http_averror(s->http_code, AVERROR(EIO));
254 }
255
256 int ff_http_do_new_request(URLContext *h, const char *uri)
257 {
258     HTTPContext *s = h->priv_data;
259     AVDictionary *options = NULL;
260     int ret;
261
262     s->off           = 0;
263     s->icy_data_read = 0;
264     av_free(s->location);
265     s->location = av_strdup(uri);
266     if (!s->location)
267         return AVERROR(ENOMEM);
268
269     av_dict_copy(&options, s->chained_options, 0);
270     ret = http_open_cnx(h, &options);
271     av_dict_free(&options);
272     return ret;
273 }
274
275 int ff_http_averror(int status_code, int default_averror)
276 {
277     switch (status_code) {
278         case 400: return AVERROR_HTTP_BAD_REQUEST;
279         case 401: return AVERROR_HTTP_UNAUTHORIZED;
280         case 403: return AVERROR_HTTP_FORBIDDEN;
281         case 404: return AVERROR_HTTP_NOT_FOUND;
282         default: break;
283     }
284     if (status_code >= 400 && status_code <= 499)
285         return AVERROR_HTTP_OTHER_4XX;
286     else if (status_code >= 500)
287         return AVERROR_HTTP_SERVER_ERROR;
288     else
289         return default_averror;
290 }
291
292 static int http_open(URLContext *h, const char *uri, int flags,
293                      AVDictionary **options)
294 {
295     HTTPContext *s = h->priv_data;
296     int ret;
297
298     if( s->seekable == 1 )
299         h->is_streamed = 0;
300     else
301         h->is_streamed = 1;
302
303     s->filesize = -1;
304     s->location = av_strdup(uri);
305     if (!s->location)
306         return AVERROR(ENOMEM);
307     if (options)
308         av_dict_copy(&s->chained_options, *options, 0);
309
310     if (s->headers) {
311         int len = strlen(s->headers);
312         if (len < 2 || strcmp("\r\n", s->headers + len - 2))
313             av_log(h, AV_LOG_WARNING,
314                    "No trailing CRLF found in HTTP header.\n");
315     }
316
317     ret = http_open_cnx(h, options);
318     if (ret < 0)
319         av_dict_free(&s->chained_options);
320     return ret;
321 }
322
323 static int http_getc(HTTPContext *s)
324 {
325     int len;
326     if (s->buf_ptr >= s->buf_end) {
327         len = ffurl_read(s->hd, s->buffer, BUFFER_SIZE);
328         if (len < 0) {
329             return len;
330         } else if (len == 0) {
331             return AVERROR_EOF;
332         } else {
333             s->buf_ptr = s->buffer;
334             s->buf_end = s->buffer + len;
335         }
336     }
337     return *s->buf_ptr++;
338 }
339
340 static int http_get_line(HTTPContext *s, char *line, int line_size)
341 {
342     int ch;
343     char *q;
344
345     q = line;
346     for (;;) {
347         ch = http_getc(s);
348         if (ch < 0)
349             return ch;
350         if (ch == '\n') {
351             /* process line */
352             if (q > line && q[-1] == '\r')
353                 q--;
354             *q = '\0';
355
356             return 0;
357         } else {
358             if ((q - line) < line_size - 1)
359                 *q++ = ch;
360         }
361     }
362 }
363
364 static int check_http_code(URLContext *h, int http_code, const char *end)
365 {
366     HTTPContext *s = h->priv_data;
367     /* error codes are 4xx and 5xx, but regard 401 as a success, so we
368      * don't abort until all headers have been parsed. */
369     if (http_code >= 400 && http_code < 600 &&
370         (http_code != 401 || s->auth_state.auth_type != HTTP_AUTH_NONE) &&
371         (http_code != 407 || s->proxy_auth_state.auth_type != HTTP_AUTH_NONE)) {
372         end += strspn(end, SPACE_CHARS);
373         av_log(h, AV_LOG_WARNING, "HTTP error %d %s\n", http_code, end);
374         return ff_http_averror(http_code, AVERROR(EIO));
375     }
376     return 0;
377 }
378
379 static int parse_location(HTTPContext *s, const char *p)
380 {
381     char redirected_location[MAX_URL_SIZE], *new_loc;
382     ff_make_absolute_url(redirected_location, sizeof(redirected_location),
383                          s->location, p);
384     new_loc = av_strdup(redirected_location);
385     if (!new_loc)
386         return AVERROR(ENOMEM);
387     av_free(s->location);
388     s->location = new_loc;
389     return 0;
390 }
391
392 /* "bytes $from-$to/$document_size" */
393 static void parse_content_range(URLContext *h, const char *p)
394 {
395     HTTPContext *s = h->priv_data;
396     const char *slash;
397
398     if (!strncmp(p, "bytes ", 6)) {
399         p     += 6;
400         s->off = strtoll(p, NULL, 10);
401         if ((slash = strchr(p, '/')) && strlen(slash) > 0)
402             s->filesize = strtoll(slash + 1, NULL, 10);
403     }
404     if (s->seekable == -1 && (!s->is_akamai || s->filesize != 2147483647))
405         h->is_streamed = 0; /* we _can_ in fact seek */
406 }
407
408 static int parse_content_encoding(URLContext *h, const char *p)
409 {
410     if (!av_strncasecmp(p, "gzip", 4) ||
411         !av_strncasecmp(p, "deflate", 7)) {
412 #if CONFIG_ZLIB
413         HTTPContext *s = h->priv_data;
414
415         s->compressed = 1;
416         inflateEnd(&s->inflate_stream);
417         if (inflateInit2(&s->inflate_stream, 32 + 15) != Z_OK) {
418             av_log(h, AV_LOG_WARNING, "Error during zlib initialisation: %s\n",
419                    s->inflate_stream.msg);
420             return AVERROR(ENOSYS);
421         }
422         if (zlibCompileFlags() & (1 << 17)) {
423             av_log(h, AV_LOG_WARNING,
424                    "Your zlib was compiled without gzip support.\n");
425             return AVERROR(ENOSYS);
426         }
427 #else
428         av_log(h, AV_LOG_WARNING,
429                "Compressed (%s) content, need zlib with gzip support\n", p);
430         return AVERROR(ENOSYS);
431 #endif /* CONFIG_ZLIB */
432     } else if (!av_strncasecmp(p, "identity", 8)) {
433         // The normal, no-encoding case (although servers shouldn't include
434         // the header at all if this is the case).
435     } else {
436         av_log(h, AV_LOG_WARNING, "Unknown content coding: %s\n", p);
437     }
438     return 0;
439 }
440
441 // Concat all Icy- header lines
442 static int parse_icy(HTTPContext *s, const char *tag, const char *p)
443 {
444     int len = 4 + strlen(p) + strlen(tag);
445     int is_first = !s->icy_metadata_headers;
446     int ret;
447
448     av_dict_set(&s->metadata, tag, p, 0);
449
450     if (s->icy_metadata_headers)
451         len += strlen(s->icy_metadata_headers);
452
453     if ((ret = av_reallocp(&s->icy_metadata_headers, len)) < 0)
454         return ret;
455
456     if (is_first)
457         *s->icy_metadata_headers = '\0';
458
459     av_strlcatf(s->icy_metadata_headers, len, "%s: %s\n", tag, p);
460
461     return 0;
462 }
463
464 static int process_line(URLContext *h, char *line, int line_count,
465                         int *new_location)
466 {
467     HTTPContext *s = h->priv_data;
468     char *tag, *p, *end;
469     int ret;
470
471     /* end of header */
472     if (line[0] == '\0') {
473         s->end_header = 1;
474         return 0;
475     }
476
477     p = line;
478     if (line_count == 0) {
479         while (!av_isspace(*p) && *p != '\0')
480             p++;
481         while (av_isspace(*p))
482             p++;
483         s->http_code = strtol(p, &end, 10);
484
485         av_log(h, AV_LOG_DEBUG, "http_code=%d\n", s->http_code);
486
487         if ((ret = check_http_code(h, s->http_code, end)) < 0)
488             return ret;
489     } else {
490         while (*p != '\0' && *p != ':')
491             p++;
492         if (*p != ':')
493             return 1;
494
495         *p  = '\0';
496         tag = line;
497         p++;
498         while (av_isspace(*p))
499             p++;
500         if (!av_strcasecmp(tag, "Location")) {
501             if ((ret = parse_location(s, p)) < 0)
502                 return ret;
503             *new_location = 1;
504         } else if (!av_strcasecmp(tag, "Content-Length") && s->filesize == -1) {
505             s->filesize = strtoll(p, NULL, 10);
506         } else if (!av_strcasecmp(tag, "Content-Range")) {
507             parse_content_range(h, p);
508         } else if (!av_strcasecmp(tag, "Accept-Ranges") &&
509                    !strncmp(p, "bytes", 5) &&
510                    s->seekable == -1) {
511             h->is_streamed = 0;
512         } else if (!av_strcasecmp(tag, "Transfer-Encoding") &&
513                    !av_strncasecmp(p, "chunked", 7)) {
514             s->filesize  = -1;
515             s->chunksize = 0;
516         } else if (!av_strcasecmp(tag, "WWW-Authenticate")) {
517             ff_http_auth_handle_header(&s->auth_state, tag, p);
518         } else if (!av_strcasecmp(tag, "Authentication-Info")) {
519             ff_http_auth_handle_header(&s->auth_state, tag, p);
520         } else if (!av_strcasecmp(tag, "Proxy-Authenticate")) {
521             ff_http_auth_handle_header(&s->proxy_auth_state, tag, p);
522         } else if (!av_strcasecmp(tag, "Connection")) {
523             if (!strcmp(p, "close"))
524                 s->willclose = 1;
525         } else if (!av_strcasecmp(tag, "Server")) {
526             if (!av_strcasecmp(p, "AkamaiGHost")) {
527                 s->is_akamai = 1;
528             } else if (!av_strncasecmp(p, "MediaGateway", 12)) {
529                 s->is_mediagateway = 1;
530             }
531         } else if (!av_strcasecmp(tag, "Content-Type")) {
532             av_free(s->mime_type);
533             s->mime_type = av_strdup(p);
534         } else if (!av_strcasecmp(tag, "Set-Cookie")) {
535             if (!s->cookies) {
536                 if (!(s->cookies = av_strdup(p)))
537                     return AVERROR(ENOMEM);
538             } else {
539                 char *tmp = s->cookies;
540                 size_t str_size = strlen(tmp) + strlen(p) + 2;
541                 if (!(s->cookies = av_malloc(str_size))) {
542                     s->cookies = tmp;
543                     return AVERROR(ENOMEM);
544                 }
545                 snprintf(s->cookies, str_size, "%s\n%s", tmp, p);
546                 av_free(tmp);
547             }
548         } else if (!av_strcasecmp(tag, "Icy-MetaInt")) {
549             s->icy_metaint = strtoll(p, NULL, 10);
550         } else if (!av_strncasecmp(tag, "Icy-", 4)) {
551             if ((ret = parse_icy(s, tag, p)) < 0)
552                 return ret;
553         } else if (!av_strcasecmp(tag, "Content-Encoding")) {
554             if ((ret = parse_content_encoding(h, p)) < 0)
555                 return ret;
556         }
557     }
558     return 1;
559 }
560
561 /**
562  * Create a string containing cookie values for use as a HTTP cookie header
563  * field value for a particular path and domain from the cookie values stored in
564  * the HTTP protocol context. The cookie string is stored in *cookies.
565  *
566  * @return a negative value if an error condition occurred, 0 otherwise
567  */
568 static int get_cookies(HTTPContext *s, char **cookies, const char *path,
569                        const char *domain)
570 {
571     // cookie strings will look like Set-Cookie header field values.  Multiple
572     // Set-Cookie fields will result in multiple values delimited by a newline
573     int ret = 0;
574     char *next, *cookie, *set_cookies = av_strdup(s->cookies), *cset_cookies = set_cookies;
575
576     if (!set_cookies) return AVERROR(EINVAL);
577
578     *cookies = NULL;
579     while ((cookie = av_strtok(set_cookies, "\n", &next))) {
580         int domain_offset = 0;
581         char *param, *next_param, *cdomain = NULL, *cpath = NULL, *cvalue = NULL;
582         set_cookies = NULL;
583
584         while ((param = av_strtok(cookie, "; ", &next_param))) {
585             if (cookie) {
586                 // first key-value pair is the actual cookie value
587                 cvalue = av_strdup(param);
588                 cookie = NULL;
589             } else if (!av_strncasecmp("path=",   param, 5)) {
590                 av_free(cpath);
591                 cpath = av_strdup(&param[5]);
592             } else if (!av_strncasecmp("domain=", param, 7)) {
593                 // if the cookie specifies a sub-domain, skip the leading dot thereby
594                 // supporting URLs that point to sub-domains and the master domain
595                 int leading_dot = (param[7] == '.');
596                 av_free(cdomain);
597                 cdomain = av_strdup(&param[7+leading_dot]);
598             } else {
599                 // ignore unknown attributes
600             }
601         }
602         if (!cdomain)
603             cdomain = av_strdup(domain);
604
605         // ensure all of the necessary values are valid
606         if (!cdomain || !cpath || !cvalue) {
607             av_log(s, AV_LOG_WARNING,
608                    "Invalid cookie found, no value, path or domain specified\n");
609             goto done_cookie;
610         }
611
612         // check if the request path matches the cookie path
613         if (av_strncasecmp(path, cpath, strlen(cpath)))
614             goto done_cookie;
615
616         // the domain should be at least the size of our cookie domain
617         domain_offset = strlen(domain) - strlen(cdomain);
618         if (domain_offset < 0)
619             goto done_cookie;
620
621         // match the cookie domain
622         if (av_strcasecmp(&domain[domain_offset], cdomain))
623             goto done_cookie;
624
625         // cookie parameters match, so copy the value
626         if (!*cookies) {
627             if (!(*cookies = av_strdup(cvalue))) {
628                 ret = AVERROR(ENOMEM);
629                 goto done_cookie;
630             }
631         } else {
632             char *tmp = *cookies;
633             size_t str_size = strlen(cvalue) + strlen(*cookies) + 3;
634             if (!(*cookies = av_malloc(str_size))) {
635                 ret = AVERROR(ENOMEM);
636                 goto done_cookie;
637             }
638             snprintf(*cookies, str_size, "%s; %s", tmp, cvalue);
639             av_free(tmp);
640         }
641
642         done_cookie:
643         av_free(cdomain);
644         av_free(cpath);
645         av_free(cvalue);
646         if (ret < 0) {
647             if (*cookies) av_freep(cookies);
648             av_free(cset_cookies);
649             return ret;
650         }
651     }
652
653     av_free(cset_cookies);
654
655     return 0;
656 }
657
658 static inline int has_header(const char *str, const char *header)
659 {
660     /* header + 2 to skip over CRLF prefix. (make sure you have one!) */
661     if (!str)
662         return 0;
663     return av_stristart(str, header + 2, NULL) || av_stristr(str, header);
664 }
665
666 static int http_read_header(URLContext *h, int *new_location)
667 {
668     HTTPContext *s = h->priv_data;
669     char line[MAX_URL_SIZE];
670     int err = 0;
671
672     s->chunksize = -1;
673
674     for (;;) {
675         if ((err = http_get_line(s, line, sizeof(line))) < 0)
676             return err;
677
678         av_log(h, AV_LOG_DEBUG, "header='%s'\n", line);
679
680         err = process_line(h, line, s->line_count, new_location);
681         if (err < 0)
682             return err;
683         if (err == 0)
684             break;
685         s->line_count++;
686     }
687
688     if (s->seekable == -1 && s->is_mediagateway && s->filesize == 2000000000)
689         h->is_streamed = 1; /* we can in fact _not_ seek */
690
691     return err;
692 }
693
694 static int http_connect(URLContext *h, const char *path, const char *local_path,
695                         const char *hoststr, const char *auth,
696                         const char *proxyauth, int *new_location)
697 {
698     HTTPContext *s = h->priv_data;
699     int post, err;
700     char headers[HTTP_HEADERS_SIZE] = "";
701     char *authstr = NULL, *proxyauthstr = NULL;
702     int64_t off = s->off;
703     int len = 0;
704     const char *method;
705     int send_expect_100 = 0;
706
707     /* send http header */
708     post = h->flags & AVIO_FLAG_WRITE;
709
710     if (s->post_data) {
711         /* force POST method and disable chunked encoding when
712          * custom HTTP post data is set */
713         post            = 1;
714         s->chunked_post = 0;
715     }
716
717     if (s->method)
718         method = s->method;
719     else
720         method = post ? "POST" : "GET";
721
722     authstr      = ff_http_auth_create_response(&s->auth_state, auth,
723                                                 local_path, method);
724     proxyauthstr = ff_http_auth_create_response(&s->proxy_auth_state, proxyauth,
725                                                 local_path, method);
726     if (post && !s->post_data) {
727         send_expect_100 = s->send_expect_100;
728         /* The user has supplied authentication but we don't know the auth type,
729          * send Expect: 100-continue to get the 401 response including the
730          * WWW-Authenticate header, or an 100 continue if no auth actually
731          * is needed. */
732         if (auth && *auth &&
733             s->auth_state.auth_type == HTTP_AUTH_NONE &&
734             s->http_code != 401)
735             send_expect_100 = 1;
736     }
737
738     /* set default headers if needed */
739     if (!has_header(s->headers, "\r\nUser-Agent: "))
740         len += av_strlcatf(headers + len, sizeof(headers) - len,
741                            "User-Agent: %s\r\n", s->user_agent);
742     if (!has_header(s->headers, "\r\nAccept: "))
743         len += av_strlcpy(headers + len, "Accept: */*\r\n",
744                           sizeof(headers) - len);
745     // Note: we send this on purpose even when s->off is 0 when we're probing,
746     // since it allows us to detect more reliably if a (non-conforming)
747     // server supports seeking by analysing the reply headers.
748     if (!has_header(s->headers, "\r\nRange: ") && !post && (s->off > 0 || s->end_off || s->seekable == -1)) {
749         len += av_strlcatf(headers + len, sizeof(headers) - len,
750                            "Range: bytes=%"PRId64"-", s->off);
751         if (s->end_off)
752             len += av_strlcatf(headers + len, sizeof(headers) - len,
753                                "%"PRId64, s->end_off - 1);
754         len += av_strlcpy(headers + len, "\r\n",
755                           sizeof(headers) - len);
756     }
757     if (send_expect_100 && !has_header(s->headers, "\r\nExpect: "))
758         len += av_strlcatf(headers + len, sizeof(headers) - len,
759                            "Expect: 100-continue\r\n");
760
761     if (!has_header(s->headers, "\r\nConnection: ")) {
762         if (s->multiple_requests)
763             len += av_strlcpy(headers + len, "Connection: keep-alive\r\n",
764                               sizeof(headers) - len);
765         else
766             len += av_strlcpy(headers + len, "Connection: close\r\n",
767                               sizeof(headers) - len);
768     }
769
770     if (!has_header(s->headers, "\r\nHost: "))
771         len += av_strlcatf(headers + len, sizeof(headers) - len,
772                            "Host: %s\r\n", hoststr);
773     if (!has_header(s->headers, "\r\nContent-Length: ") && s->post_data)
774         len += av_strlcatf(headers + len, sizeof(headers) - len,
775                            "Content-Length: %d\r\n", s->post_datalen);
776
777     if (!has_header(s->headers, "\r\nContent-Type: ") && s->content_type)
778         len += av_strlcatf(headers + len, sizeof(headers) - len,
779                            "Content-Type: %s\r\n", s->content_type);
780     if (!has_header(s->headers, "\r\nCookie: ") && s->cookies) {
781         char *cookies = NULL;
782         if (!get_cookies(s, &cookies, path, hoststr) && cookies) {
783             len += av_strlcatf(headers + len, sizeof(headers) - len,
784                                "Cookie: %s\r\n", cookies);
785             av_free(cookies);
786         }
787     }
788     if (!has_header(s->headers, "\r\nIcy-MetaData: ") && s->icy)
789         len += av_strlcatf(headers + len, sizeof(headers) - len,
790                            "Icy-MetaData: %d\r\n", 1);
791
792     /* now add in custom headers */
793     if (s->headers)
794         av_strlcpy(headers + len, s->headers, sizeof(headers) - len);
795
796     snprintf(s->buffer, sizeof(s->buffer),
797              "%s %s HTTP/1.1\r\n"
798              "%s"
799              "%s"
800              "%s"
801              "%s%s"
802              "\r\n",
803              method,
804              path,
805              post && s->chunked_post ? "Transfer-Encoding: chunked\r\n" : "",
806              headers,
807              authstr ? authstr : "",
808              proxyauthstr ? "Proxy-" : "", proxyauthstr ? proxyauthstr : "");
809
810     av_log(h, AV_LOG_DEBUG, "request: %s\n", s->buffer);
811
812     if ((err = ffurl_write(s->hd, s->buffer, strlen(s->buffer))) < 0)
813         goto done;
814
815     if (s->post_data)
816         if ((err = ffurl_write(s->hd, s->post_data, s->post_datalen)) < 0)
817             goto done;
818
819     /* init input buffer */
820     s->buf_ptr          = s->buffer;
821     s->buf_end          = s->buffer;
822     s->line_count       = 0;
823     s->off              = 0;
824     s->icy_data_read    = 0;
825     s->filesize         = -1;
826     s->willclose        = 0;
827     s->end_chunked_post = 0;
828     s->end_header       = 0;
829     if (post && !s->post_data && !send_expect_100) {
830         /* Pretend that it did work. We didn't read any header yet, since
831          * we've still to send the POST data, but the code calling this
832          * function will check http_code after we return. */
833         s->http_code = 200;
834         err = 0;
835         goto done;
836     }
837
838     /* wait for header */
839     err = http_read_header(h, new_location);
840     if (err < 0)
841         goto done;
842
843     err = (off == s->off) ? 0 : -1;
844 done:
845     av_freep(&authstr);
846     av_freep(&proxyauthstr);
847     return err;
848 }
849
850 static int http_buf_read(URLContext *h, uint8_t *buf, int size)
851 {
852     HTTPContext *s = h->priv_data;
853     int len;
854     /* read bytes from input buffer first */
855     len = s->buf_end - s->buf_ptr;
856     if (len > 0) {
857         if (len > size)
858             len = size;
859         memcpy(buf, s->buf_ptr, len);
860         s->buf_ptr += len;
861     } else {
862         if ((!s->willclose || s->chunksize < 0) &&
863             s->filesize >= 0 && s->off >= s->filesize)
864             return AVERROR_EOF;
865         len = ffurl_read(s->hd, buf, size);
866     }
867     if (len > 0) {
868         s->off += len;
869         if (s->chunksize > 0)
870             s->chunksize -= len;
871     }
872     return len;
873 }
874
875 #if CONFIG_ZLIB
876 #define DECOMPRESS_BUF_SIZE (256 * 1024)
877 static int http_buf_read_compressed(URLContext *h, uint8_t *buf, int size)
878 {
879     HTTPContext *s = h->priv_data;
880     int ret;
881
882     if (!s->inflate_buffer) {
883         s->inflate_buffer = av_malloc(DECOMPRESS_BUF_SIZE);
884         if (!s->inflate_buffer)
885             return AVERROR(ENOMEM);
886     }
887
888     if (s->inflate_stream.avail_in == 0) {
889         int read = http_buf_read(h, s->inflate_buffer, DECOMPRESS_BUF_SIZE);
890         if (read <= 0)
891             return read;
892         s->inflate_stream.next_in  = s->inflate_buffer;
893         s->inflate_stream.avail_in = read;
894     }
895
896     s->inflate_stream.avail_out = size;
897     s->inflate_stream.next_out  = buf;
898
899     ret = inflate(&s->inflate_stream, Z_SYNC_FLUSH);
900     if (ret != Z_OK && ret != Z_STREAM_END)
901         av_log(h, AV_LOG_WARNING, "inflate return value: %d, %s\n",
902                ret, s->inflate_stream.msg);
903
904     return size - s->inflate_stream.avail_out;
905 }
906 #endif /* CONFIG_ZLIB */
907
908 static int http_read_stream(URLContext *h, uint8_t *buf, int size)
909 {
910     HTTPContext *s = h->priv_data;
911     int err, new_location;
912
913     if (!s->hd)
914         return AVERROR_EOF;
915
916     if (s->end_chunked_post && !s->end_header) {
917         err = http_read_header(h, &new_location);
918         if (err < 0)
919             return err;
920     }
921
922     if (s->chunksize >= 0) {
923         if (!s->chunksize) {
924             char line[32];
925
926                 do {
927                     if ((err = http_get_line(s, line, sizeof(line))) < 0)
928                         return err;
929                 } while (!*line);    /* skip CR LF from last chunk */
930
931                 s->chunksize = strtoll(line, NULL, 16);
932
933                 av_dlog(NULL, "Chunked encoding data size: %"PRId64"'\n",
934                         s->chunksize);
935
936                 if (!s->chunksize)
937                     return 0;
938         }
939         size = FFMIN(size, s->chunksize);
940     }
941 #if CONFIG_ZLIB
942     if (s->compressed)
943         return http_buf_read_compressed(h, buf, size);
944 #endif /* CONFIG_ZLIB */
945     return http_buf_read(h, buf, size);
946 }
947
948 // Like http_read_stream(), but no short reads.
949 // Assumes partial reads are an error.
950 static int http_read_stream_all(URLContext *h, uint8_t *buf, int size)
951 {
952     int pos = 0;
953     while (pos < size) {
954         int len = http_read_stream(h, buf + pos, size - pos);
955         if (len < 0)
956             return len;
957         pos += len;
958     }
959     return pos;
960 }
961
962 static void update_metadata(HTTPContext *s, char *data)
963 {
964     char *key;
965     char *val;
966     char *end;
967     char *next = data;
968
969     while (*next) {
970         key = next;
971         val = strstr(key, "='");
972         if (!val)
973             break;
974         end = strstr(val, "';");
975         if (!end)
976             break;
977
978         *val = '\0';
979         *end = '\0';
980         val += 2;
981
982         av_dict_set(&s->metadata, key, val, 0);
983
984         next = end + 2;
985     }
986 }
987
988 static int store_icy(URLContext *h, int size)
989 {
990     HTTPContext *s = h->priv_data;
991     /* until next metadata packet */
992     int remaining = s->icy_metaint - s->icy_data_read;
993
994     if (remaining < 0)
995         return AVERROR_INVALIDDATA;
996
997     if (!remaining) {
998         /* The metadata packet is variable sized. It has a 1 byte header
999          * which sets the length of the packet (divided by 16). If it's 0,
1000          * the metadata doesn't change. After the packet, icy_metaint bytes
1001          * of normal data follows. */
1002         uint8_t ch;
1003         int len = http_read_stream_all(h, &ch, 1);
1004         if (len < 0)
1005             return len;
1006         if (ch > 0) {
1007             char data[255 * 16 + 1];
1008             int ret;
1009             len = ch * 16;
1010             ret = http_read_stream_all(h, data, len);
1011             if (ret < 0)
1012                 return ret;
1013             data[len + 1] = 0;
1014             if ((ret = av_opt_set(s, "icy_metadata_packet", data, 0)) < 0)
1015                 return ret;
1016             update_metadata(s, data);
1017         }
1018         s->icy_data_read = 0;
1019         remaining        = s->icy_metaint;
1020     }
1021
1022     return FFMIN(size, remaining);
1023 }
1024
1025 static int http_read(URLContext *h, uint8_t *buf, int size)
1026 {
1027     HTTPContext *s = h->priv_data;
1028
1029     if (s->icy_metaint > 0) {
1030         size = store_icy(h, size);
1031         if (size < 0)
1032             return size;
1033     }
1034
1035     size = http_read_stream(h, buf, size);
1036     if (size > 0)
1037         s->icy_data_read += size;
1038     return size;
1039 }
1040
1041 /* used only when posting data */
1042 static int http_write(URLContext *h, const uint8_t *buf, int size)
1043 {
1044     char temp[11] = "";  /* 32-bit hex + CRLF + nul */
1045     int ret;
1046     char crlf[] = "\r\n";
1047     HTTPContext *s = h->priv_data;
1048
1049     if (!s->chunked_post) {
1050         /* non-chunked data is sent without any special encoding */
1051         return ffurl_write(s->hd, buf, size);
1052     }
1053
1054     /* silently ignore zero-size data since chunk encoding that would
1055      * signal EOF */
1056     if (size > 0) {
1057         /* upload data using chunked encoding */
1058         snprintf(temp, sizeof(temp), "%x\r\n", size);
1059
1060         if ((ret = ffurl_write(s->hd, temp, strlen(temp))) < 0 ||
1061             (ret = ffurl_write(s->hd, buf, size)) < 0          ||
1062             (ret = ffurl_write(s->hd, crlf, sizeof(crlf) - 1)) < 0)
1063             return ret;
1064     }
1065     return size;
1066 }
1067
1068 static int http_shutdown(URLContext *h, int flags)
1069 {
1070     int ret = 0;
1071     char footer[] = "0\r\n\r\n";
1072     HTTPContext *s = h->priv_data;
1073
1074     /* signal end of chunked encoding if used */
1075     if ((flags & AVIO_FLAG_WRITE) && s->chunked_post) {
1076         ret = ffurl_write(s->hd, footer, sizeof(footer) - 1);
1077         ret = ret > 0 ? 0 : ret;
1078         s->end_chunked_post = 1;
1079     }
1080
1081     return ret;
1082 }
1083
1084 static int http_close(URLContext *h)
1085 {
1086     int ret = 0;
1087     HTTPContext *s = h->priv_data;
1088
1089 #if CONFIG_ZLIB
1090     inflateEnd(&s->inflate_stream);
1091     av_freep(&s->inflate_buffer);
1092 #endif /* CONFIG_ZLIB */
1093
1094     if (!s->end_chunked_post)
1095         /* Close the write direction by sending the end of chunked encoding. */
1096         ret = http_shutdown(h, h->flags);
1097
1098     if (s->hd)
1099         ffurl_closep(&s->hd);
1100     av_dict_free(&s->chained_options);
1101     return ret;
1102 }
1103
1104 static int64_t http_seek(URLContext *h, int64_t off, int whence)
1105 {
1106     HTTPContext *s = h->priv_data;
1107     URLContext *old_hd = s->hd;
1108     int64_t old_off = s->off;
1109     uint8_t old_buf[BUFFER_SIZE];
1110     int old_buf_size, ret;
1111     AVDictionary *options = NULL;
1112
1113     if (whence == AVSEEK_SIZE)
1114         return s->filesize;
1115     else if ((whence == SEEK_CUR && off == 0) ||
1116              (whence == SEEK_SET && off == s->off))
1117         return s->off;
1118     else if ((s->filesize == -1 && whence == SEEK_END) || h->is_streamed)
1119         return AVERROR(ENOSYS);
1120
1121     if (whence == SEEK_CUR)
1122         off += s->off;
1123     else if (whence == SEEK_END)
1124         off += s->filesize;
1125     else if (whence != SEEK_SET)
1126         return AVERROR(EINVAL);
1127     if (off < 0)
1128         return AVERROR(EINVAL);
1129     s->off = off;
1130
1131     /* we save the old context in case the seek fails */
1132     old_buf_size = s->buf_end - s->buf_ptr;
1133     memcpy(old_buf, s->buf_ptr, old_buf_size);
1134     s->hd = NULL;
1135
1136     /* if it fails, continue on old connection */
1137     av_dict_copy(&options, s->chained_options, 0);
1138     if ((ret = http_open_cnx(h, &options)) < 0) {
1139         av_dict_free(&options);
1140         memcpy(s->buffer, old_buf, old_buf_size);
1141         s->buf_ptr = s->buffer;
1142         s->buf_end = s->buffer + old_buf_size;
1143         s->hd      = old_hd;
1144         s->off     = old_off;
1145         return ret;
1146     }
1147     av_dict_free(&options);
1148     ffurl_close(old_hd);
1149     return off;
1150 }
1151
1152 static int http_get_file_handle(URLContext *h)
1153 {
1154     HTTPContext *s = h->priv_data;
1155     return ffurl_get_file_handle(s->hd);
1156 }
1157
1158 #define HTTP_CLASS(flavor)                          \
1159 static const AVClass flavor ## _context_class = {   \
1160     .class_name = # flavor,                         \
1161     .item_name  = av_default_item_name,             \
1162     .option     = options,                          \
1163     .version    = LIBAVUTIL_VERSION_INT,            \
1164 }
1165
1166 #if CONFIG_HTTP_PROTOCOL
1167 HTTP_CLASS(http);
1168
1169 URLProtocol ff_http_protocol = {
1170     .name                = "http",
1171     .url_open2           = http_open,
1172     .url_read            = http_read,
1173     .url_write           = http_write,
1174     .url_seek            = http_seek,
1175     .url_close           = http_close,
1176     .url_get_file_handle = http_get_file_handle,
1177     .url_shutdown        = http_shutdown,
1178     .priv_data_size      = sizeof(HTTPContext),
1179     .priv_data_class     = &http_context_class,
1180     .flags               = URL_PROTOCOL_FLAG_NETWORK,
1181 };
1182 #endif /* CONFIG_HTTP_PROTOCOL */
1183
1184 #if CONFIG_HTTPS_PROTOCOL
1185 HTTP_CLASS(https);
1186
1187 URLProtocol ff_https_protocol = {
1188     .name                = "https",
1189     .url_open2           = http_open,
1190     .url_read            = http_read,
1191     .url_write           = http_write,
1192     .url_seek            = http_seek,
1193     .url_close           = http_close,
1194     .url_get_file_handle = http_get_file_handle,
1195     .url_shutdown        = http_shutdown,
1196     .priv_data_size      = sizeof(HTTPContext),
1197     .priv_data_class     = &https_context_class,
1198     .flags               = URL_PROTOCOL_FLAG_NETWORK,
1199 };
1200 #endif /* CONFIG_HTTPS_PROTOCOL */
1201
1202 #if CONFIG_HTTPPROXY_PROTOCOL
1203 static int http_proxy_close(URLContext *h)
1204 {
1205     HTTPContext *s = h->priv_data;
1206     if (s->hd)
1207         ffurl_closep(&s->hd);
1208     return 0;
1209 }
1210
1211 static int http_proxy_open(URLContext *h, const char *uri, int flags)
1212 {
1213     HTTPContext *s = h->priv_data;
1214     char hostname[1024], hoststr[1024];
1215     char auth[1024], pathbuf[1024], *path;
1216     char lower_url[100];
1217     int port, ret = 0, attempts = 0;
1218     HTTPAuthType cur_auth_type;
1219     char *authstr;
1220     int new_loc;
1221
1222     if( s->seekable == 1 )
1223         h->is_streamed = 0;
1224     else
1225         h->is_streamed = 1;
1226
1227     av_url_split(NULL, 0, auth, sizeof(auth), hostname, sizeof(hostname), &port,
1228                  pathbuf, sizeof(pathbuf), uri);
1229     ff_url_join(hoststr, sizeof(hoststr), NULL, NULL, hostname, port, NULL);
1230     path = pathbuf;
1231     if (*path == '/')
1232         path++;
1233
1234     ff_url_join(lower_url, sizeof(lower_url), "tcp", NULL, hostname, port,
1235                 NULL);
1236 redo:
1237     ret = ffurl_open(&s->hd, lower_url, AVIO_FLAG_READ_WRITE,
1238                      &h->interrupt_callback, NULL);
1239     if (ret < 0)
1240         return ret;
1241
1242     authstr = ff_http_auth_create_response(&s->proxy_auth_state, auth,
1243                                            path, "CONNECT");
1244     snprintf(s->buffer, sizeof(s->buffer),
1245              "CONNECT %s HTTP/1.1\r\n"
1246              "Host: %s\r\n"
1247              "Connection: close\r\n"
1248              "%s%s"
1249              "\r\n",
1250              path,
1251              hoststr,
1252              authstr ? "Proxy-" : "", authstr ? authstr : "");
1253     av_freep(&authstr);
1254
1255     if ((ret = ffurl_write(s->hd, s->buffer, strlen(s->buffer))) < 0)
1256         goto fail;
1257
1258     s->buf_ptr    = s->buffer;
1259     s->buf_end    = s->buffer;
1260     s->line_count = 0;
1261     s->filesize   = -1;
1262     cur_auth_type = s->proxy_auth_state.auth_type;
1263
1264     /* Note: This uses buffering, potentially reading more than the
1265      * HTTP header. If tunneling a protocol where the server starts
1266      * the conversation, we might buffer part of that here, too.
1267      * Reading that requires using the proper ffurl_read() function
1268      * on this URLContext, not using the fd directly (as the tls
1269      * protocol does). This shouldn't be an issue for tls though,
1270      * since the client starts the conversation there, so there
1271      * is no extra data that we might buffer up here.
1272      */
1273     ret = http_read_header(h, &new_loc);
1274     if (ret < 0)
1275         goto fail;
1276
1277     attempts++;
1278     if (s->http_code == 407 &&
1279         (cur_auth_type == HTTP_AUTH_NONE || s->proxy_auth_state.stale) &&
1280         s->proxy_auth_state.auth_type != HTTP_AUTH_NONE && attempts < 2) {
1281         ffurl_closep(&s->hd);
1282         goto redo;
1283     }
1284
1285     if (s->http_code < 400)
1286         return 0;
1287     ret = ff_http_averror(s->http_code, AVERROR(EIO));
1288
1289 fail:
1290     http_proxy_close(h);
1291     return ret;
1292 }
1293
1294 static int http_proxy_write(URLContext *h, const uint8_t *buf, int size)
1295 {
1296     HTTPContext *s = h->priv_data;
1297     return ffurl_write(s->hd, buf, size);
1298 }
1299
1300 URLProtocol ff_httpproxy_protocol = {
1301     .name                = "httpproxy",
1302     .url_open            = http_proxy_open,
1303     .url_read            = http_buf_read,
1304     .url_write           = http_proxy_write,
1305     .url_close           = http_proxy_close,
1306     .url_get_file_handle = http_get_file_handle,
1307     .priv_data_size      = sizeof(HTTPContext),
1308     .flags               = URL_PROTOCOL_FLAG_NETWORK,
1309 };
1310 #endif /* CONFIG_HTTPPROXY_PROTOCOL */