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