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