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