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