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