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