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