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