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