]> git.sesse.net Git - ffmpeg/blob - libavformat/http.c
Merge commit '364af376f343d4706c4cdb7ab9fe0863994e6c01'
[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 "libavutil/avstring.h"
23 #include "avformat.h"
24 #include "internal.h"
25 #include "network.h"
26 #include "http.h"
27 #include "os_support.h"
28 #include "httpauth.h"
29 #include "url.h"
30 #include "libavutil/opt.h"
31
32 #if CONFIG_ZLIB
33 #include <zlib.h>
34 #endif
35
36 /* XXX: POST protocol is not completely implemented because ffmpeg uses
37    only a subset of it. */
38
39 /* The IO buffer size is unrelated to the max URL size in itself, but needs
40  * to be large enough to fit the full request headers (including long
41  * path names).
42  */
43 #define BUFFER_SIZE MAX_URL_SIZE
44 #define MAX_REDIRECTS 8
45
46 typedef struct {
47     const AVClass *class;
48     URLContext *hd;
49     unsigned char buffer[BUFFER_SIZE], *buf_ptr, *buf_end;
50     int line_count;
51     int http_code;
52     int64_t chunksize;      /**< Used if "Transfer-Encoding: chunked" otherwise -1. */
53     char *content_type;
54     char *user_agent;
55     int64_t off, filesize;
56     int icy_data_read;      ///< how much data was read since last ICY metadata packet
57     int icy_metaint;        ///< after how many bytes of read data a new metadata packet will be found
58     char location[MAX_URL_SIZE];
59     HTTPAuthState auth_state;
60     HTTPAuthState proxy_auth_state;
61     char *headers;
62     int willclose;          /**< Set if the server correctly handles Connection: close and will close the connection after feeding us the content. */
63     int seekable;           /**< Control seekability, 0 = disable, 1 = enable, -1 = probe. */
64     int chunked_post;
65     int end_chunked_post;   /**< A flag which indicates if the end of chunked encoding has been sent. */
66     int end_header;         /**< A flag which indicates we have finished to read POST reply. */
67     int multiple_requests;  /**< A flag which indicates if we use persistent connections. */
68     uint8_t *post_data;
69     int post_datalen;
70     int is_akamai;
71     char *mime_type;
72     char *cookies;          ///< holds newline (\n) delimited Set-Cookie header field values (without the "Set-Cookie: " field name)
73     int icy;
74     char *icy_metadata_headers;
75     char *icy_metadata_packet;
76 #if CONFIG_ZLIB
77     int compressed;
78     z_stream inflate_stream;
79     uint8_t *inflate_buffer;
80 #endif
81     AVDictionary *chained_options;
82 } HTTPContext;
83
84 #define OFFSET(x) offsetof(HTTPContext, x)
85 #define D AV_OPT_FLAG_DECODING_PARAM
86 #define E AV_OPT_FLAG_ENCODING_PARAM
87 #define DEFAULT_USER_AGENT "Lavf/" AV_STRINGIFY(LIBAVFORMAT_VERSION)
88 static const AVOption options[] = {
89 {"seekable", "control seekability of connection", OFFSET(seekable), AV_OPT_TYPE_INT, {.i64 = -1}, -1, 1, D },
90 {"chunked_post", "use chunked transfer-encoding for posts", OFFSET(chunked_post), AV_OPT_TYPE_INT, {.i64 = 1}, 0, 1, E },
91 {"headers", "set custom HTTP headers, can override built in default headers", OFFSET(headers), AV_OPT_TYPE_STRING, { 0 }, 0, 0, D|E },
92 {"content_type", "force a content type", OFFSET(content_type), AV_OPT_TYPE_STRING, { 0 }, 0, 0, D|E },
93 {"user-agent", "override User-Agent header", OFFSET(user_agent), AV_OPT_TYPE_STRING, {.str = DEFAULT_USER_AGENT}, 0, 0, D },
94 {"multiple_requests", "use persistent connections", OFFSET(multiple_requests), AV_OPT_TYPE_INT, {.i64 = 0}, 0, 1, D|E },
95 {"post_data", "set custom HTTP post data", OFFSET(post_data), AV_OPT_TYPE_BINARY, .flags = D|E },
96 {"mime_type", "set MIME type", OFFSET(mime_type), AV_OPT_TYPE_STRING, {0}, 0, 0, 0 },
97 {"cookies", "set cookies to be sent in applicable future requests, use newline delimited Set-Cookie HTTP field value syntax", OFFSET(cookies), AV_OPT_TYPE_STRING, {0}, 0, 0, 0 },
98 {"icy", "request ICY metadata", OFFSET(icy), AV_OPT_TYPE_INT, {.i64 = 0}, 0, 1, D },
99 {"icy_metadata_headers", "return ICY metadata headers", OFFSET(icy_metadata_headers), AV_OPT_TYPE_STRING, {0}, 0, 0, 0 },
100 {"icy_metadata_packet", "return current ICY metadata packet", OFFSET(icy_metadata_packet), AV_OPT_TYPE_STRING, {0}, 0, 0, 0 },
101 {NULL}
102 };
103 #define HTTP_CLASS(flavor)\
104 static const AVClass flavor ## _context_class = {\
105     .class_name     = #flavor,\
106     .item_name      = av_default_item_name,\
107     .option         = options,\
108     .version        = LIBAVUTIL_VERSION_INT,\
109 }
110
111 HTTP_CLASS(http);
112 HTTP_CLASS(https);
113
114 static int http_connect(URLContext *h, const char *path, const char *local_path,
115                         const char *hoststr, const char *auth,
116                         const char *proxyauth, int *new_location);
117
118 void ff_http_init_auth_state(URLContext *dest, const URLContext *src)
119 {
120     memcpy(&((HTTPContext*)dest->priv_data)->auth_state,
121            &((HTTPContext*)src->priv_data)->auth_state, sizeof(HTTPAuthState));
122     memcpy(&((HTTPContext*)dest->priv_data)->proxy_auth_state,
123            &((HTTPContext*)src->priv_data)->proxy_auth_state,
124            sizeof(HTTPAuthState));
125 }
126
127 /* return non zero if error */
128 static int http_open_cnx(URLContext *h, AVDictionary **options)
129 {
130     const char *path, *proxy_path, *lower_proto = "tcp", *local_path;
131     char hostname[1024], hoststr[1024], proto[10];
132     char auth[1024], proxyauth[1024] = "";
133     char path1[MAX_URL_SIZE];
134     char buf[1024], urlbuf[MAX_URL_SIZE];
135     int port, use_proxy, err, location_changed = 0, redirects = 0, attempts = 0;
136     HTTPAuthType cur_auth_type, cur_proxy_auth_type;
137     HTTPContext *s = h->priv_data;
138
139     /* fill the dest addr */
140  redo:
141     /* needed in any case to build the host string */
142     av_url_split(proto, sizeof(proto), auth, sizeof(auth),
143                  hostname, sizeof(hostname), &port,
144                  path1, sizeof(path1), s->location);
145     ff_url_join(hoststr, sizeof(hoststr), NULL, NULL, hostname, port, NULL);
146
147     proxy_path = getenv("http_proxy");
148     use_proxy = !ff_http_match_no_proxy(getenv("no_proxy"), hostname) &&
149                 proxy_path != NULL && av_strstart(proxy_path, "http://", NULL);
150
151     if (!strcmp(proto, "https")) {
152         lower_proto = "tls";
153         use_proxy = 0;
154         if (port < 0)
155             port = 443;
156     }
157     if (port < 0)
158         port = 80;
159
160     if (path1[0] == '\0')
161         path = "/";
162     else
163         path = path1;
164     local_path = path;
165     if (use_proxy) {
166         /* Reassemble the request URL without auth string - we don't
167          * want to leak the auth to the proxy. */
168         ff_url_join(urlbuf, sizeof(urlbuf), proto, NULL, hostname, port, "%s",
169                     path1);
170         path = urlbuf;
171         av_url_split(NULL, 0, proxyauth, sizeof(proxyauth),
172                      hostname, sizeof(hostname), &port, NULL, 0, proxy_path);
173     }
174
175     ff_url_join(buf, sizeof(buf), lower_proto, NULL, hostname, port, NULL);
176
177     if (!s->hd) {
178         err = ffurl_open(&s->hd, buf, AVIO_FLAG_READ_WRITE,
179                          &h->interrupt_callback, options);
180         if (err < 0)
181             goto fail;
182     }
183
184     cur_auth_type = s->auth_state.auth_type;
185     cur_proxy_auth_type = s->auth_state.auth_type;
186     if (http_connect(h, path, local_path, hoststr, auth, proxyauth, &location_changed) < 0)
187         goto fail;
188     attempts++;
189     if (s->http_code == 401) {
190         if ((cur_auth_type == HTTP_AUTH_NONE || s->auth_state.stale) &&
191             s->auth_state.auth_type != HTTP_AUTH_NONE && attempts < 4) {
192             ffurl_closep(&s->hd);
193             goto redo;
194         } else
195             goto fail;
196     }
197     if (s->http_code == 407) {
198         if ((cur_proxy_auth_type == HTTP_AUTH_NONE || s->proxy_auth_state.stale) &&
199             s->proxy_auth_state.auth_type != HTTP_AUTH_NONE && attempts < 4) {
200             ffurl_closep(&s->hd);
201             goto redo;
202         } else
203             goto fail;
204     }
205     if ((s->http_code == 301 || s->http_code == 302 || s->http_code == 303 || s->http_code == 307)
206         && location_changed == 1) {
207         /* url moved, get next */
208         ffurl_closep(&s->hd);
209         if (redirects++ >= MAX_REDIRECTS)
210             return AVERROR(EIO);
211         /* Restart the authentication process with the new target, which
212          * might use a different auth mechanism. */
213         memset(&s->auth_state, 0, sizeof(s->auth_state));
214         attempts = 0;
215         location_changed = 0;
216         goto redo;
217     }
218     return 0;
219  fail:
220     if (s->hd)
221         ffurl_closep(&s->hd);
222     return AVERROR(EIO);
223 }
224
225 int ff_http_do_new_request(URLContext *h, const char *uri)
226 {
227     HTTPContext *s = h->priv_data;
228     AVDictionary *options = NULL;
229     int ret;
230
231     s->off = 0;
232     s->icy_data_read = 0;
233     av_strlcpy(s->location, uri, sizeof(s->location));
234
235     av_dict_copy(&options, s->chained_options, 0);
236     ret = http_open_cnx(h, &options);
237     av_dict_free(&options);
238     return ret;
239 }
240
241 static int http_open(URLContext *h, const char *uri, int flags,
242                      AVDictionary **options)
243 {
244     HTTPContext *s = h->priv_data;
245     int ret;
246
247     if( s->seekable == 1 )
248         h->is_streamed = 0;
249     else
250         h->is_streamed = 1;
251
252     s->filesize = -1;
253     av_strlcpy(s->location, uri, sizeof(s->location));
254     if (options)
255         av_dict_copy(&s->chained_options, *options, 0);
256
257     if (s->headers) {
258         int len = strlen(s->headers);
259         if (len < 2 || strcmp("\r\n", s->headers + len - 2))
260             av_log(h, AV_LOG_WARNING, "No trailing CRLF found in HTTP header.\n");
261     }
262
263     ret = http_open_cnx(h, options);
264     if (ret < 0)
265         av_dict_free(&s->chained_options);
266     return ret;
267 }
268 static int http_getc(HTTPContext *s)
269 {
270     int len;
271     if (s->buf_ptr >= s->buf_end) {
272         len = ffurl_read(s->hd, s->buffer, BUFFER_SIZE);
273         if (len < 0) {
274             return len;
275         } else if (len == 0) {
276             return -1;
277         } else {
278             s->buf_ptr = s->buffer;
279             s->buf_end = s->buffer + len;
280         }
281     }
282     return *s->buf_ptr++;
283 }
284
285 static int http_get_line(HTTPContext *s, char *line, int line_size)
286 {
287     int ch;
288     char *q;
289
290     q = line;
291     for(;;) {
292         ch = http_getc(s);
293         if (ch < 0)
294             return ch;
295         if (ch == '\n') {
296             /* process line */
297             if (q > line && q[-1] == '\r')
298                 q--;
299             *q = '\0';
300
301             return 0;
302         } else {
303             if ((q - line) < line_size - 1)
304                 *q++ = ch;
305         }
306     }
307 }
308
309 static int process_line(URLContext *h, char *line, int line_count,
310                         int *new_location)
311 {
312     HTTPContext *s = h->priv_data;
313     char *tag, *p, *end;
314     char redirected_location[MAX_URL_SIZE];
315
316     /* end of header */
317     if (line[0] == '\0') {
318         s->end_header = 1;
319         return 0;
320     }
321
322     p = line;
323     if (line_count == 0) {
324         while (!av_isspace(*p) && *p != '\0')
325             p++;
326         while (av_isspace(*p))
327             p++;
328         s->http_code = strtol(p, &end, 10);
329
330         av_dlog(NULL, "http_code=%d\n", s->http_code);
331
332         /* error codes are 4xx and 5xx, but regard 401 as a success, so we
333          * don't abort until all headers have been parsed. */
334         if (s->http_code >= 400 && s->http_code < 600 && (s->http_code != 401
335             || s->auth_state.auth_type != HTTP_AUTH_NONE) &&
336             (s->http_code != 407 || s->proxy_auth_state.auth_type != HTTP_AUTH_NONE)) {
337             end += strspn(end, SPACE_CHARS);
338             av_log(h, AV_LOG_WARNING, "HTTP error %d %s\n",
339                    s->http_code, end);
340             return -1;
341         }
342     } else {
343         while (*p != '\0' && *p != ':')
344             p++;
345         if (*p != ':')
346             return 1;
347
348         *p = '\0';
349         tag = line;
350         p++;
351         while (av_isspace(*p))
352             p++;
353         if (!av_strcasecmp(tag, "Location")) {
354             ff_make_absolute_url(redirected_location, sizeof(redirected_location), s->location, p);
355             av_strlcpy(s->location, redirected_location, sizeof(s->location));
356             *new_location = 1;
357         } else if (!av_strcasecmp (tag, "Content-Length") && s->filesize == -1) {
358             s->filesize = strtoll(p, NULL, 10);
359         } else if (!av_strcasecmp (tag, "Content-Range")) {
360             /* "bytes $from-$to/$document_size" */
361             const char *slash;
362             if (!strncmp (p, "bytes ", 6)) {
363                 p += 6;
364                 s->off = strtoll(p, NULL, 10);
365                 if ((slash = strchr(p, '/')) && strlen(slash) > 0)
366                     s->filesize = strtoll(slash+1, NULL, 10);
367             }
368             if (s->seekable == -1 && (!s->is_akamai || s->filesize != 2147483647))
369                 h->is_streamed = 0; /* we _can_ in fact seek */
370         } else if (!av_strcasecmp(tag, "Accept-Ranges") && !strncmp(p, "bytes", 5) && s->seekable == -1) {
371             h->is_streamed = 0;
372         } else if (!av_strcasecmp (tag, "Transfer-Encoding") && !av_strncasecmp(p, "chunked", 7)) {
373             s->filesize = -1;
374             s->chunksize = 0;
375         } else if (!av_strcasecmp (tag, "WWW-Authenticate")) {
376             ff_http_auth_handle_header(&s->auth_state, tag, p);
377         } else if (!av_strcasecmp (tag, "Authentication-Info")) {
378             ff_http_auth_handle_header(&s->auth_state, tag, p);
379         } else if (!av_strcasecmp (tag, "Proxy-Authenticate")) {
380             ff_http_auth_handle_header(&s->proxy_auth_state, tag, p);
381         } else if (!av_strcasecmp (tag, "Connection")) {
382             if (!strcmp(p, "close"))
383                 s->willclose = 1;
384         } else if (!av_strcasecmp (tag, "Server") && !av_strcasecmp (p, "AkamaiGHost")) {
385             s->is_akamai = 1;
386         } else if (!av_strcasecmp (tag, "Content-Type")) {
387             av_free(s->mime_type); s->mime_type = av_strdup(p);
388         } else if (!av_strcasecmp (tag, "Set-Cookie")) {
389             if (!s->cookies) {
390                 if (!(s->cookies = av_strdup(p)))
391                     return AVERROR(ENOMEM);
392             } else {
393                 char *tmp = s->cookies;
394                 size_t str_size = strlen(tmp) + strlen(p) + 2;
395                 if (!(s->cookies = av_malloc(str_size))) {
396                     s->cookies = tmp;
397                     return AVERROR(ENOMEM);
398                 }
399                 snprintf(s->cookies, str_size, "%s\n%s", tmp, p);
400                 av_free(tmp);
401             }
402         } else if (!av_strcasecmp (tag, "Icy-MetaInt")) {
403             s->icy_metaint = strtoll(p, NULL, 10);
404         } else if (!av_strncasecmp(tag, "Icy-", 4)) {
405             // Concat all Icy- header lines
406             char *buf = av_asprintf("%s%s: %s\n",
407                 s->icy_metadata_headers ? s->icy_metadata_headers : "", tag, p);
408             if (!buf)
409                 return AVERROR(ENOMEM);
410             av_freep(&s->icy_metadata_headers);
411             s->icy_metadata_headers = buf;
412         } else if (!av_strcasecmp (tag, "Content-Encoding")) {
413             if (!av_strncasecmp(p, "gzip", 4) || !av_strncasecmp(p, "deflate", 7)) {
414 #if CONFIG_ZLIB
415                 s->compressed = 1;
416                 inflateEnd(&s->inflate_stream);
417                 if (inflateInit2(&s->inflate_stream, 32 + 15) != Z_OK) {
418                     av_log(h, AV_LOG_WARNING, "Error during zlib initialisation: %s\n",
419                            s->inflate_stream.msg);
420                     return AVERROR(ENOSYS);
421                 }
422                 if (zlibCompileFlags() & (1 << 17)) {
423                     av_log(h, AV_LOG_WARNING, "Your zlib was compiled without gzip support.\n");
424                     return AVERROR(ENOSYS);
425                 }
426 #else
427                 av_log(h, AV_LOG_WARNING, "Compressed (%s) content, need zlib with gzip support\n", p);
428                 return AVERROR(ENOSYS);
429 #endif
430             } else if (!av_strncasecmp(p, "identity", 8)) {
431                 // The normal, no-encoding case (although servers shouldn't include
432                 // the header at all if this is the case).
433             } else {
434                 av_log(h, AV_LOG_WARNING, "Unknown content coding: %s\n", p);
435                 return AVERROR(ENOSYS);
436             }
437         }
438     }
439     return 1;
440 }
441
442 /**
443  * Create a string containing cookie values for use as a HTTP cookie header
444  * field value for a particular path and domain from the cookie values stored in
445  * the HTTP protocol context. The cookie string is stored in *cookies.
446  *
447  * @return a negative value if an error condition occurred, 0 otherwise
448  */
449 static int get_cookies(HTTPContext *s, char **cookies, const char *path,
450                        const char *domain)
451 {
452     // cookie strings will look like Set-Cookie header field values.  Multiple
453     // Set-Cookie fields will result in multiple values delimited by a newline
454     int ret = 0;
455     char *next, *cookie, *set_cookies = av_strdup(s->cookies), *cset_cookies = set_cookies;
456
457     if (!set_cookies) return AVERROR(EINVAL);
458
459     *cookies = NULL;
460     while ((cookie = av_strtok(set_cookies, "\n", &next))) {
461         int domain_offset = 0;
462         char *param, *next_param, *cdomain = NULL, *cpath = NULL, *cvalue = NULL;
463         set_cookies = NULL;
464
465         while ((param = av_strtok(cookie, "; ", &next_param))) {
466             cookie = NULL;
467             if        (!av_strncasecmp("path=",   param, 5)) {
468                 av_free(cpath);
469                 cpath = av_strdup(&param[5]);
470             } else if (!av_strncasecmp("domain=", param, 7)) {
471                 av_free(cdomain);
472                 cdomain = av_strdup(&param[7]);
473             } else if (!av_strncasecmp("secure",  param, 6) ||
474                        !av_strncasecmp("comment", param, 7) ||
475                        !av_strncasecmp("max-age", param, 7) ||
476                        !av_strncasecmp("version", param, 7)) {
477                 // ignore Comment, Max-Age, Secure and Version
478             } else {
479                 av_free(cvalue);
480                 cvalue = av_strdup(param);
481             }
482         }
483         if (!cdomain)
484             cdomain = av_strdup(domain);
485
486         // ensure all of the necessary values are valid
487         if (!cdomain || !cpath || !cvalue) {
488             av_log(s, AV_LOG_WARNING,
489                    "Invalid cookie found, no value, path or domain specified\n");
490             goto done_cookie;
491         }
492
493         // check if the request path matches the cookie path
494         if (av_strncasecmp(path, cpath, strlen(cpath)))
495             goto done_cookie;
496
497         // the domain should be at least the size of our cookie domain
498         domain_offset = strlen(domain) - strlen(cdomain);
499         if (domain_offset < 0)
500             goto done_cookie;
501
502         // match the cookie domain
503         if (av_strcasecmp(&domain[domain_offset], cdomain))
504             goto done_cookie;
505
506         // cookie parameters match, so copy the value
507         if (!*cookies) {
508             if (!(*cookies = av_strdup(cvalue))) {
509                 ret = AVERROR(ENOMEM);
510                 goto done_cookie;
511             }
512         } else {
513             char *tmp = *cookies;
514             size_t str_size = strlen(cvalue) + strlen(*cookies) + 3;
515             if (!(*cookies = av_malloc(str_size))) {
516                 ret = AVERROR(ENOMEM);
517                 goto done_cookie;
518             }
519             snprintf(*cookies, str_size, "%s; %s", tmp, cvalue);
520             av_free(tmp);
521         }
522
523         done_cookie:
524         av_free(cdomain);
525         av_free(cpath);
526         av_free(cvalue);
527         if (ret < 0) {
528             if (*cookies) av_freep(cookies);
529             av_free(cset_cookies);
530             return ret;
531         }
532     }
533
534     av_free(cset_cookies);
535
536     return 0;
537 }
538
539 static inline int has_header(const char *str, const char *header)
540 {
541     /* header + 2 to skip over CRLF prefix. (make sure you have one!) */
542     if (!str)
543         return 0;
544     return av_stristart(str, header + 2, NULL) || av_stristr(str, header);
545 }
546
547 static int http_read_header(URLContext *h, int *new_location)
548 {
549     HTTPContext *s = h->priv_data;
550     char line[MAX_URL_SIZE];
551     int err = 0;
552
553     s->chunksize = -1;
554
555     for (;;) {
556         if ((err = http_get_line(s, line, sizeof(line))) < 0)
557             return err;
558
559         av_dlog(NULL, "header='%s'\n", line);
560
561         err = process_line(h, line, s->line_count, new_location);
562         if (err < 0)
563             return err;
564         if (err == 0)
565             break;
566         s->line_count++;
567     }
568
569     return err;
570 }
571
572 static int http_connect(URLContext *h, const char *path, const char *local_path,
573                         const char *hoststr, const char *auth,
574                         const char *proxyauth, int *new_location)
575 {
576     HTTPContext *s = h->priv_data;
577     int post, err;
578     char headers[4096] = "";
579     char *authstr = NULL, *proxyauthstr = NULL;
580     int64_t off = s->off;
581     int len = 0;
582     const char *method;
583
584
585     /* send http header */
586     post = h->flags & AVIO_FLAG_WRITE;
587
588     if (s->post_data) {
589         /* force POST method and disable chunked encoding when
590          * custom HTTP post data is set */
591         post = 1;
592         s->chunked_post = 0;
593     }
594
595     method = post ? "POST" : "GET";
596     authstr = ff_http_auth_create_response(&s->auth_state, auth, local_path,
597                                            method);
598     proxyauthstr = ff_http_auth_create_response(&s->proxy_auth_state, proxyauth,
599                                                 local_path, method);
600
601     /* set default headers if needed */
602     if (!has_header(s->headers, "\r\nUser-Agent: "))
603         len += av_strlcatf(headers + len, sizeof(headers) - len,
604                            "User-Agent: %s\r\n", s->user_agent);
605     if (!has_header(s->headers, "\r\nAccept: "))
606         len += av_strlcpy(headers + len, "Accept: */*\r\n",
607                           sizeof(headers) - len);
608     // Note: we send this on purpose even when s->off is 0 when we're probing,
609     // since it allows us to detect more reliably if a (non-conforming)
610     // server supports seeking by analysing the reply headers.
611     if (!has_header(s->headers, "\r\nRange: ") && !post && (s->off > 0 || s->seekable == -1))
612         len += av_strlcatf(headers + len, sizeof(headers) - len,
613                            "Range: bytes=%"PRId64"-\r\n", s->off);
614
615     if (!has_header(s->headers, "\r\nConnection: ")) {
616         if (s->multiple_requests) {
617             len += av_strlcpy(headers + len, "Connection: keep-alive\r\n",
618                               sizeof(headers) - len);
619         } else {
620             len += av_strlcpy(headers + len, "Connection: close\r\n",
621                               sizeof(headers) - len);
622         }
623     }
624
625     if (!has_header(s->headers, "\r\nHost: "))
626         len += av_strlcatf(headers + len, sizeof(headers) - len,
627                            "Host: %s\r\n", hoststr);
628     if (!has_header(s->headers, "\r\nContent-Length: ") && s->post_data)
629         len += av_strlcatf(headers + len, sizeof(headers) - len,
630                            "Content-Length: %d\r\n", s->post_datalen);
631     if (!has_header(s->headers, "\r\nContent-Type: ") && s->content_type)
632         len += av_strlcatf(headers + len, sizeof(headers) - len,
633                            "Content-Type: %s\r\n", s->content_type);
634     if (!has_header(s->headers, "\r\nCookie: ") && s->cookies) {
635         char *cookies = NULL;
636         if (!get_cookies(s, &cookies, path, hoststr)) {
637             len += av_strlcatf(headers + len, sizeof(headers) - len,
638                                "Cookie: %s\r\n", cookies);
639             av_free(cookies);
640         }
641     }
642     if (!has_header(s->headers, "\r\nIcy-MetaData: ") && s->icy) {
643         len += av_strlcatf(headers + len, sizeof(headers) - len,
644                            "Icy-MetaData: %d\r\n", 1);
645     }
646
647     /* now add in custom headers */
648     if (s->headers)
649         av_strlcpy(headers + len, s->headers, sizeof(headers) - len);
650
651     snprintf(s->buffer, sizeof(s->buffer),
652              "%s %s HTTP/1.1\r\n"
653              "%s"
654              "%s"
655              "%s"
656              "%s%s"
657              "\r\n",
658              method,
659              path,
660              post && s->chunked_post ? "Transfer-Encoding: chunked\r\n" : "",
661              headers,
662              authstr ? authstr : "",
663              proxyauthstr ? "Proxy-" : "", proxyauthstr ? proxyauthstr : "");
664
665     av_freep(&authstr);
666     av_freep(&proxyauthstr);
667     if ((err = ffurl_write(s->hd, s->buffer, strlen(s->buffer))) < 0)
668         return err;
669
670     if (s->post_data)
671         if ((err = ffurl_write(s->hd, s->post_data, s->post_datalen)) < 0)
672             return err;
673
674     /* init input buffer */
675     s->buf_ptr = s->buffer;
676     s->buf_end = s->buffer;
677     s->line_count = 0;
678     s->off = 0;
679     s->icy_data_read = 0;
680     s->filesize = -1;
681     s->willclose = 0;
682     s->end_chunked_post = 0;
683     s->end_header = 0;
684     if (post && !s->post_data) {
685         /* Pretend that it did work. We didn't read any header yet, since
686          * we've still to send the POST data, but the code calling this
687          * function will check http_code after we return. */
688         s->http_code = 200;
689         return 0;
690     }
691
692     /* wait for header */
693     err = http_read_header(h, new_location);
694     if (err < 0)
695         return err;
696
697     return (off == s->off) ? 0 : -1;
698 }
699
700
701 static int http_buf_read(URLContext *h, uint8_t *buf, int size)
702 {
703     HTTPContext *s = h->priv_data;
704     int len;
705     /* read bytes from input buffer first */
706     len = s->buf_end - s->buf_ptr;
707     if (len > 0) {
708         if (len > size)
709             len = size;
710         memcpy(buf, s->buf_ptr, len);
711         s->buf_ptr += len;
712     } else {
713         if (!s->willclose && s->filesize >= 0 && s->off >= s->filesize)
714             return AVERROR_EOF;
715         len = ffurl_read(s->hd, buf, size);
716     }
717     if (len > 0) {
718         s->off += len;
719         s->icy_data_read += len;
720         if (s->chunksize > 0)
721             s->chunksize -= len;
722     }
723     return len;
724 }
725
726 #if CONFIG_ZLIB
727 #define DECOMPRESS_BUF_SIZE (256 * 1024)
728 static int http_buf_read_compressed(URLContext *h, uint8_t *buf, int size)
729 {
730     HTTPContext *s = h->priv_data;
731     int ret;
732
733     if (!s->inflate_buffer) {
734         s->inflate_buffer = av_malloc(DECOMPRESS_BUF_SIZE);
735         if (!s->inflate_buffer)
736             return AVERROR(ENOMEM);
737     }
738
739     if (s->inflate_stream.avail_in == 0) {
740         int read = http_buf_read(h, s->inflate_buffer, DECOMPRESS_BUF_SIZE);
741         if (read <= 0)
742             return read;
743         s->inflate_stream.next_in  = s->inflate_buffer;
744         s->inflate_stream.avail_in = read;
745     }
746
747     s->inflate_stream.avail_out = size;
748     s->inflate_stream.next_out  = buf;
749
750     ret = inflate(&s->inflate_stream, Z_SYNC_FLUSH);
751     if (ret != Z_OK && ret != Z_STREAM_END)
752         av_log(h, AV_LOG_WARNING, "inflate return value: %d, %s\n", ret, s->inflate_stream.msg);
753
754     return size - s->inflate_stream.avail_out;
755 }
756 #endif
757
758 static int http_read(URLContext *h, uint8_t *buf, int size)
759 {
760     HTTPContext *s = h->priv_data;
761     int err, new_location;
762
763     if (!s->hd)
764         return AVERROR_EOF;
765
766     if (s->end_chunked_post && !s->end_header) {
767         err = http_read_header(h, &new_location);
768         if (err < 0)
769             return err;
770     }
771
772     if (s->chunksize >= 0) {
773         if (!s->chunksize) {
774             char line[32];
775
776             for(;;) {
777                 do {
778                     if ((err = http_get_line(s, line, sizeof(line))) < 0)
779                         return err;
780                 } while (!*line);    /* skip CR LF from last chunk */
781
782                 s->chunksize = strtoll(line, NULL, 16);
783
784                 av_dlog(NULL, "Chunked encoding data size: %"PRId64"'\n", s->chunksize);
785
786                 if (!s->chunksize)
787                     return 0;
788                 break;
789             }
790         }
791         size = FFMIN(size, s->chunksize);
792     }
793     if (s->icy_metaint > 0) {
794         int remaining = s->icy_metaint - s->icy_data_read; /* until next metadata packet */
795         if (!remaining) {
796             // The metadata packet is variable sized. It has a 1 byte header
797             // which sets the length of the packet (divided by 16). If it's 0,
798             // the metadata doesn't change. After the packet, icy_metaint bytes
799             // of normal data follow.
800             int ch = http_getc(s);
801             if (ch < 0)
802                 return ch;
803             if (ch > 0) {
804                 char data[255 * 16 + 1];
805                 int n;
806                 int ret;
807                 ch *= 16;
808                 for (n = 0; n < ch; n++)
809                     data[n] = http_getc(s);
810                 data[ch + 1] = 0;
811                 if ((ret = av_opt_set(s, "icy_metadata_packet", data, 0)) < 0)
812                     return ret;
813             }
814             s->icy_data_read = 0;
815             remaining = s->icy_metaint;
816         }
817         size = FFMIN(size, remaining);
818     }
819 #if CONFIG_ZLIB
820     if (s->compressed)
821         return http_buf_read_compressed(h, buf, size);
822 #endif
823     return http_buf_read(h, buf, size);
824 }
825
826 /* used only when posting data */
827 static int http_write(URLContext *h, const uint8_t *buf, int size)
828 {
829     char temp[11] = "";  /* 32-bit hex + CRLF + nul */
830     int ret;
831     char crlf[] = "\r\n";
832     HTTPContext *s = h->priv_data;
833
834     if (!s->chunked_post) {
835         /* non-chunked data is sent without any special encoding */
836         return ffurl_write(s->hd, buf, size);
837     }
838
839     /* silently ignore zero-size data since chunk encoding that would
840      * signal EOF */
841     if (size > 0) {
842         /* upload data using chunked encoding */
843         snprintf(temp, sizeof(temp), "%x\r\n", size);
844
845         if ((ret = ffurl_write(s->hd, temp, strlen(temp))) < 0 ||
846             (ret = ffurl_write(s->hd, buf, size)) < 0 ||
847             (ret = ffurl_write(s->hd, crlf, sizeof(crlf) - 1)) < 0)
848             return ret;
849     }
850     return size;
851 }
852
853 static int http_shutdown(URLContext *h, int flags)
854 {
855     int ret = 0;
856     char footer[] = "0\r\n\r\n";
857     HTTPContext *s = h->priv_data;
858
859     /* signal end of chunked encoding if used */
860     if ((flags & AVIO_FLAG_WRITE) && s->chunked_post) {
861         ret = ffurl_write(s->hd, footer, sizeof(footer) - 1);
862         ret = ret > 0 ? 0 : ret;
863         s->end_chunked_post = 1;
864     }
865
866     return ret;
867 }
868
869 static int http_close(URLContext *h)
870 {
871     int ret = 0;
872     HTTPContext *s = h->priv_data;
873
874 #if CONFIG_ZLIB
875     inflateEnd(&s->inflate_stream);
876     av_freep(&s->inflate_buffer);
877 #endif
878
879     if (!s->end_chunked_post) {
880         /* Close the write direction by sending the end of chunked encoding. */
881         ret = http_shutdown(h, h->flags);
882     }
883
884     if (s->hd)
885         ffurl_closep(&s->hd);
886     av_dict_free(&s->chained_options);
887     return ret;
888 }
889
890 static int64_t http_seek(URLContext *h, int64_t off, int whence)
891 {
892     HTTPContext *s = h->priv_data;
893     URLContext *old_hd = s->hd;
894     int64_t old_off = s->off;
895     uint8_t old_buf[BUFFER_SIZE];
896     int old_buf_size;
897     AVDictionary *options = NULL;
898
899     if (whence == AVSEEK_SIZE)
900         return s->filesize;
901     else if ((s->filesize == -1 && whence == SEEK_END) || h->is_streamed)
902         return -1;
903
904     /* we save the old context in case the seek fails */
905     old_buf_size = s->buf_end - s->buf_ptr;
906     memcpy(old_buf, s->buf_ptr, old_buf_size);
907     s->hd = NULL;
908     if (whence == SEEK_CUR)
909         off += s->off;
910     else if (whence == SEEK_END)
911         off += s->filesize;
912     s->off = off;
913
914     /* if it fails, continue on old connection */
915     av_dict_copy(&options, s->chained_options, 0);
916     if (http_open_cnx(h, &options) < 0) {
917         av_dict_free(&options);
918         memcpy(s->buffer, old_buf, old_buf_size);
919         s->buf_ptr = s->buffer;
920         s->buf_end = s->buffer + old_buf_size;
921         s->hd = old_hd;
922         s->off = old_off;
923         return -1;
924     }
925     av_dict_free(&options);
926     ffurl_close(old_hd);
927     return off;
928 }
929
930 static int
931 http_get_file_handle(URLContext *h)
932 {
933     HTTPContext *s = h->priv_data;
934     return ffurl_get_file_handle(s->hd);
935 }
936
937 #if CONFIG_HTTP_PROTOCOL
938 URLProtocol ff_http_protocol = {
939     .name                = "http",
940     .url_open2           = http_open,
941     .url_read            = http_read,
942     .url_write           = http_write,
943     .url_seek            = http_seek,
944     .url_close           = http_close,
945     .url_get_file_handle = http_get_file_handle,
946     .url_shutdown        = http_shutdown,
947     .priv_data_size      = sizeof(HTTPContext),
948     .priv_data_class     = &http_context_class,
949     .flags               = URL_PROTOCOL_FLAG_NETWORK,
950 };
951 #endif
952 #if CONFIG_HTTPS_PROTOCOL
953 URLProtocol ff_https_protocol = {
954     .name                = "https",
955     .url_open2           = http_open,
956     .url_read            = http_read,
957     .url_write           = http_write,
958     .url_seek            = http_seek,
959     .url_close           = http_close,
960     .url_get_file_handle = http_get_file_handle,
961     .url_shutdown        = http_shutdown,
962     .priv_data_size      = sizeof(HTTPContext),
963     .priv_data_class     = &https_context_class,
964     .flags               = URL_PROTOCOL_FLAG_NETWORK,
965 };
966 #endif
967
968 #if CONFIG_HTTPPROXY_PROTOCOL
969 static int http_proxy_close(URLContext *h)
970 {
971     HTTPContext *s = h->priv_data;
972     if (s->hd)
973         ffurl_closep(&s->hd);
974     return 0;
975 }
976
977 static int http_proxy_open(URLContext *h, const char *uri, int flags)
978 {
979     HTTPContext *s = h->priv_data;
980     char hostname[1024], hoststr[1024];
981     char auth[1024], pathbuf[1024], *path;
982     char lower_url[100];
983     int port, ret = 0, attempts = 0;
984     HTTPAuthType cur_auth_type;
985     char *authstr;
986     int new_loc;
987
988     if( s->seekable == 1 )
989         h->is_streamed = 0;
990     else
991         h->is_streamed = 1;
992
993     av_url_split(NULL, 0, auth, sizeof(auth), hostname, sizeof(hostname), &port,
994                  pathbuf, sizeof(pathbuf), uri);
995     ff_url_join(hoststr, sizeof(hoststr), NULL, NULL, hostname, port, NULL);
996     path = pathbuf;
997     if (*path == '/')
998         path++;
999
1000     ff_url_join(lower_url, sizeof(lower_url), "tcp", NULL, hostname, port,
1001                 NULL);
1002 redo:
1003     ret = ffurl_open(&s->hd, lower_url, AVIO_FLAG_READ_WRITE,
1004                      &h->interrupt_callback, NULL);
1005     if (ret < 0)
1006         return ret;
1007
1008     authstr = ff_http_auth_create_response(&s->proxy_auth_state, auth,
1009                                            path, "CONNECT");
1010     snprintf(s->buffer, sizeof(s->buffer),
1011              "CONNECT %s HTTP/1.1\r\n"
1012              "Host: %s\r\n"
1013              "Connection: close\r\n"
1014              "%s%s"
1015              "\r\n",
1016              path,
1017              hoststr,
1018              authstr ? "Proxy-" : "", authstr ? authstr : "");
1019     av_freep(&authstr);
1020
1021     if ((ret = ffurl_write(s->hd, s->buffer, strlen(s->buffer))) < 0)
1022         goto fail;
1023
1024     s->buf_ptr = s->buffer;
1025     s->buf_end = s->buffer;
1026     s->line_count = 0;
1027     s->filesize = -1;
1028     cur_auth_type = s->proxy_auth_state.auth_type;
1029
1030     /* Note: This uses buffering, potentially reading more than the
1031      * HTTP header. If tunneling a protocol where the server starts
1032      * the conversation, we might buffer part of that here, too.
1033      * Reading that requires using the proper ffurl_read() function
1034      * on this URLContext, not using the fd directly (as the tls
1035      * protocol does). This shouldn't be an issue for tls though,
1036      * since the client starts the conversation there, so there
1037      * is no extra data that we might buffer up here.
1038      */
1039     ret = http_read_header(h, &new_loc);
1040     if (ret < 0)
1041         goto fail;
1042
1043     attempts++;
1044     if (s->http_code == 407 &&
1045         (cur_auth_type == HTTP_AUTH_NONE || s->proxy_auth_state.stale) &&
1046         s->proxy_auth_state.auth_type != HTTP_AUTH_NONE && attempts < 2) {
1047         ffurl_closep(&s->hd);
1048         goto redo;
1049     }
1050
1051     if (s->http_code < 400)
1052         return 0;
1053     ret = AVERROR(EIO);
1054
1055 fail:
1056     http_proxy_close(h);
1057     return ret;
1058 }
1059
1060 static int http_proxy_write(URLContext *h, const uint8_t *buf, int size)
1061 {
1062     HTTPContext *s = h->priv_data;
1063     return ffurl_write(s->hd, buf, size);
1064 }
1065
1066 URLProtocol ff_httpproxy_protocol = {
1067     .name                = "httpproxy",
1068     .url_open            = http_proxy_open,
1069     .url_read            = http_buf_read,
1070     .url_write           = http_proxy_write,
1071     .url_close           = http_proxy_close,
1072     .url_get_file_handle = http_get_file_handle,
1073     .priv_data_size      = sizeof(HTTPContext),
1074     .flags               = URL_PROTOCOL_FLAG_NETWORK,
1075 };
1076 #endif