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