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