]> git.sesse.net Git - ffmpeg/blob - libavformat/http.c
Merge commit '61e7c7f27b0a2652bf5cd282b97762ee99d025ef'
[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                 // if the cookie specifies a sub-domain, skip the leading dot thereby
494                 // supporting URLs that point to sub-domains and the master domain
495                 int leading_dot = (param[7] == '.');
496                 av_free(cdomain);
497                 cdomain = av_strdup(&param[7+leading_dot]);
498             } else if (!av_strncasecmp("secure",  param, 6) ||
499                        !av_strncasecmp("comment", param, 7) ||
500                        !av_strncasecmp("max-age", param, 7) ||
501                        !av_strncasecmp("version", param, 7)) {
502                 // ignore Comment, Max-Age, Secure and Version
503             } else {
504                 av_free(cvalue);
505                 cvalue = av_strdup(param);
506             }
507         }
508         if (!cdomain)
509             cdomain = av_strdup(domain);
510
511         // ensure all of the necessary values are valid
512         if (!cdomain || !cpath || !cvalue) {
513             av_log(s, AV_LOG_WARNING,
514                    "Invalid cookie found, no value, path or domain specified\n");
515             goto done_cookie;
516         }
517
518         // check if the request path matches the cookie path
519         if (av_strncasecmp(path, cpath, strlen(cpath)))
520             goto done_cookie;
521
522         // the domain should be at least the size of our cookie domain
523         domain_offset = strlen(domain) - strlen(cdomain);
524         if (domain_offset < 0)
525             goto done_cookie;
526
527         // match the cookie domain
528         if (av_strcasecmp(&domain[domain_offset], cdomain))
529             goto done_cookie;
530
531         // cookie parameters match, so copy the value
532         if (!*cookies) {
533             if (!(*cookies = av_strdup(cvalue))) {
534                 ret = AVERROR(ENOMEM);
535                 goto done_cookie;
536             }
537         } else {
538             char *tmp = *cookies;
539             size_t str_size = strlen(cvalue) + strlen(*cookies) + 3;
540             if (!(*cookies = av_malloc(str_size))) {
541                 ret = AVERROR(ENOMEM);
542                 goto done_cookie;
543             }
544             snprintf(*cookies, str_size, "%s; %s", tmp, cvalue);
545             av_free(tmp);
546         }
547
548         done_cookie:
549         av_free(cdomain);
550         av_free(cpath);
551         av_free(cvalue);
552         if (ret < 0) {
553             if (*cookies) av_freep(cookies);
554             av_free(cset_cookies);
555             return ret;
556         }
557     }
558
559     av_free(cset_cookies);
560
561     return 0;
562 }
563
564 static inline int has_header(const char *str, const char *header)
565 {
566     /* header + 2 to skip over CRLF prefix. (make sure you have one!) */
567     if (!str)
568         return 0;
569     return av_stristart(str, header + 2, NULL) || av_stristr(str, header);
570 }
571
572 static int http_read_header(URLContext *h, int *new_location)
573 {
574     HTTPContext *s = h->priv_data;
575     char line[MAX_URL_SIZE];
576     int err = 0;
577
578     s->chunksize = -1;
579
580     for (;;) {
581         if ((err = http_get_line(s, line, sizeof(line))) < 0)
582             return err;
583
584         av_log(h, AV_LOG_DEBUG, "header='%s'\n", line);
585
586         err = process_line(h, line, s->line_count, new_location);
587         if (err < 0)
588             return err;
589         if (err == 0)
590             break;
591         s->line_count++;
592     }
593
594     if (s->seekable == -1 && s->is_mediagateway && s->filesize == 2000000000)
595         h->is_streamed = 1; /* we can in fact _not_ seek */
596
597     return err;
598 }
599
600 static int http_connect(URLContext *h, const char *path, const char *local_path,
601                         const char *hoststr, const char *auth,
602                         const char *proxyauth, int *new_location)
603 {
604     HTTPContext *s = h->priv_data;
605     int post, err;
606     char headers[4096] = "";
607     char *authstr = NULL, *proxyauthstr = NULL;
608     int64_t off = s->off;
609     int len = 0;
610     const char *method;
611     int send_expect_100 = 0;
612
613
614     /* send http header */
615     post = h->flags & AVIO_FLAG_WRITE;
616
617     if (s->post_data) {
618         /* force POST method and disable chunked encoding when
619          * custom HTTP post data is set */
620         post = 1;
621         s->chunked_post = 0;
622     }
623
624     method = post ? "POST" : "GET";
625     authstr = ff_http_auth_create_response(&s->auth_state, auth, local_path,
626                                            method);
627     proxyauthstr = ff_http_auth_create_response(&s->proxy_auth_state, proxyauth,
628                                                 local_path, method);
629     if (post && !s->post_data) {
630         send_expect_100 = s->send_expect_100;
631         /* The user has supplied authentication but we don't know the auth type,
632          * send Expect: 100-continue to get the 401 response including the
633          * WWW-Authenticate header, or an 100 continue if no auth actually
634          * is needed. */
635         if (auth && *auth &&
636             s->auth_state.auth_type == HTTP_AUTH_NONE &&
637             s->http_code != 401)
638             send_expect_100 = 1;
639     }
640
641     /* set default headers if needed */
642     if (!has_header(s->headers, "\r\nUser-Agent: "))
643         len += av_strlcatf(headers + len, sizeof(headers) - len,
644                            "User-Agent: %s\r\n", s->user_agent);
645     if (!has_header(s->headers, "\r\nAccept: "))
646         len += av_strlcpy(headers + len, "Accept: */*\r\n",
647                           sizeof(headers) - len);
648     // Note: we send this on purpose even when s->off is 0 when we're probing,
649     // since it allows us to detect more reliably if a (non-conforming)
650     // server supports seeking by analysing the reply headers.
651     if (!has_header(s->headers, "\r\nRange: ") && !post && (s->off > 0 || s->req_end_offset || s->seekable == -1)) {
652         len += av_strlcatf(headers + len, sizeof(headers) - len,
653                            "Range: bytes=%"PRId64"-", s->off);
654         if (s->req_end_offset)
655             len += av_strlcatf(headers + len, sizeof(headers) - len,
656                                "%"PRId64, s->req_end_offset - 1);
657         len += av_strlcpy(headers + len, "\r\n",
658                           sizeof(headers) - len);
659     }
660     if (send_expect_100 && !has_header(s->headers, "\r\nExpect: "))
661         len += av_strlcatf(headers + len, sizeof(headers) - len,
662                            "Expect: 100-continue\r\n");
663
664     if (!has_header(s->headers, "\r\nConnection: ")) {
665         if (s->multiple_requests) {
666             len += av_strlcpy(headers + len, "Connection: keep-alive\r\n",
667                               sizeof(headers) - len);
668         } else {
669             len += av_strlcpy(headers + len, "Connection: close\r\n",
670                               sizeof(headers) - len);
671         }
672     }
673
674     if (!has_header(s->headers, "\r\nHost: "))
675         len += av_strlcatf(headers + len, sizeof(headers) - len,
676                            "Host: %s\r\n", hoststr);
677     if (!has_header(s->headers, "\r\nContent-Length: ") && s->post_data)
678         len += av_strlcatf(headers + len, sizeof(headers) - len,
679                            "Content-Length: %d\r\n", s->post_datalen);
680     if (!has_header(s->headers, "\r\nContent-Type: ") && s->content_type)
681         len += av_strlcatf(headers + len, sizeof(headers) - len,
682                            "Content-Type: %s\r\n", s->content_type);
683     if (!has_header(s->headers, "\r\nCookie: ") && s->cookies) {
684         char *cookies = NULL;
685         if (!get_cookies(s, &cookies, path, hoststr)) {
686             len += av_strlcatf(headers + len, sizeof(headers) - len,
687                                "Cookie: %s\r\n", cookies);
688             av_free(cookies);
689         }
690     }
691     if (!has_header(s->headers, "\r\nIcy-MetaData: ") && s->icy) {
692         len += av_strlcatf(headers + len, sizeof(headers) - len,
693                            "Icy-MetaData: %d\r\n", 1);
694     }
695
696     /* now add in custom headers */
697     if (s->headers)
698         av_strlcpy(headers + len, s->headers, sizeof(headers) - len);
699
700     snprintf(s->buffer, sizeof(s->buffer),
701              "%s %s HTTP/1.1\r\n"
702              "%s"
703              "%s"
704              "%s"
705              "%s%s"
706              "\r\n",
707              method,
708              path,
709              post && s->chunked_post ? "Transfer-Encoding: chunked\r\n" : "",
710              headers,
711              authstr ? authstr : "",
712              proxyauthstr ? "Proxy-" : "", proxyauthstr ? proxyauthstr : "");
713
714     av_freep(&authstr);
715     av_freep(&proxyauthstr);
716
717     av_log(h, AV_LOG_DEBUG, "request: %s\n", s->buffer);
718
719     if ((err = ffurl_write(s->hd, s->buffer, strlen(s->buffer))) < 0)
720         return err;
721
722     if (s->post_data)
723         if ((err = ffurl_write(s->hd, s->post_data, s->post_datalen)) < 0)
724             return err;
725
726     /* init input buffer */
727     s->buf_ptr = s->buffer;
728     s->buf_end = s->buffer;
729     s->line_count = 0;
730     s->off = 0;
731     s->icy_data_read = 0;
732     s->filesize = -1;
733     s->willclose = 0;
734     s->end_chunked_post = 0;
735     s->end_header = 0;
736     if (post && !s->post_data && !send_expect_100) {
737         /* Pretend that it did work. We didn't read any header yet, since
738          * we've still to send the POST data, but the code calling this
739          * function will check http_code after we return. */
740         s->http_code = 200;
741         return 0;
742     }
743
744     /* wait for header */
745     err = http_read_header(h, new_location);
746     if (err < 0)
747         return err;
748
749     return (off == s->off) ? 0 : -1;
750 }
751
752
753 static int http_buf_read(URLContext *h, uint8_t *buf, int size)
754 {
755     HTTPContext *s = h->priv_data;
756     int len;
757     /* read bytes from input buffer first */
758     len = s->buf_end - s->buf_ptr;
759     if (len > 0) {
760         if (len > size)
761             len = size;
762         memcpy(buf, s->buf_ptr, len);
763         s->buf_ptr += len;
764     } else {
765         if (!s->willclose && s->filesize >= 0 && s->off >= s->filesize)
766             return AVERROR_EOF;
767         len = ffurl_read(s->hd, buf, size);
768     }
769     if (len > 0) {
770         s->off += len;
771         s->icy_data_read += len;
772         if (s->chunksize > 0)
773             s->chunksize -= len;
774     }
775     return len;
776 }
777
778 #if CONFIG_ZLIB
779 #define DECOMPRESS_BUF_SIZE (256 * 1024)
780 static int http_buf_read_compressed(URLContext *h, uint8_t *buf, int size)
781 {
782     HTTPContext *s = h->priv_data;
783     int ret;
784
785     if (!s->inflate_buffer) {
786         s->inflate_buffer = av_malloc(DECOMPRESS_BUF_SIZE);
787         if (!s->inflate_buffer)
788             return AVERROR(ENOMEM);
789     }
790
791     if (s->inflate_stream.avail_in == 0) {
792         int read = http_buf_read(h, s->inflate_buffer, DECOMPRESS_BUF_SIZE);
793         if (read <= 0)
794             return read;
795         s->inflate_stream.next_in  = s->inflate_buffer;
796         s->inflate_stream.avail_in = read;
797     }
798
799     s->inflate_stream.avail_out = size;
800     s->inflate_stream.next_out  = buf;
801
802     ret = inflate(&s->inflate_stream, Z_SYNC_FLUSH);
803     if (ret != Z_OK && ret != Z_STREAM_END)
804         av_log(h, AV_LOG_WARNING, "inflate return value: %d, %s\n", ret, s->inflate_stream.msg);
805
806     return size - s->inflate_stream.avail_out;
807 }
808 #endif
809
810 static int http_read(URLContext *h, uint8_t *buf, int size)
811 {
812     HTTPContext *s = h->priv_data;
813     int err, new_location;
814
815     if (!s->hd)
816         return AVERROR_EOF;
817
818     if (s->end_chunked_post && !s->end_header) {
819         err = http_read_header(h, &new_location);
820         if (err < 0)
821             return err;
822     }
823
824     if (s->chunksize >= 0) {
825         if (!s->chunksize) {
826             char line[32];
827
828             for(;;) {
829                 do {
830                     if ((err = http_get_line(s, line, sizeof(line))) < 0)
831                         return err;
832                 } while (!*line);    /* skip CR LF from last chunk */
833
834                 s->chunksize = strtoll(line, NULL, 16);
835
836                 av_dlog(NULL, "Chunked encoding data size: %"PRId64"'\n", s->chunksize);
837
838                 if (!s->chunksize)
839                     return 0;
840                 break;
841             }
842         }
843         size = FFMIN(size, s->chunksize);
844     }
845     if (s->icy_metaint > 0) {
846         int remaining = s->icy_metaint - s->icy_data_read; /* until next metadata packet */
847         if (!remaining) {
848             // The metadata packet is variable sized. It has a 1 byte header
849             // which sets the length of the packet (divided by 16). If it's 0,
850             // the metadata doesn't change. After the packet, icy_metaint bytes
851             // of normal data follow.
852             int ch = http_getc(s);
853             if (ch < 0)
854                 return ch;
855             if (ch > 0) {
856                 char data[255 * 16 + 1];
857                 int n;
858                 int ret;
859                 ch *= 16;
860                 for (n = 0; n < ch; n++)
861                     data[n] = http_getc(s);
862                 data[ch + 1] = 0;
863                 if ((ret = av_opt_set(s, "icy_metadata_packet", data, 0)) < 0)
864                     return ret;
865             }
866             s->icy_data_read = 0;
867             remaining = s->icy_metaint;
868         }
869         size = FFMIN(size, remaining);
870     }
871 #if CONFIG_ZLIB
872     if (s->compressed)
873         return http_buf_read_compressed(h, buf, size);
874 #endif
875     return http_buf_read(h, buf, size);
876 }
877
878 /* used only when posting data */
879 static int http_write(URLContext *h, const uint8_t *buf, int size)
880 {
881     char temp[11] = "";  /* 32-bit hex + CRLF + nul */
882     int ret;
883     char crlf[] = "\r\n";
884     HTTPContext *s = h->priv_data;
885
886     if (!s->chunked_post) {
887         /* non-chunked data is sent without any special encoding */
888         return ffurl_write(s->hd, buf, size);
889     }
890
891     /* silently ignore zero-size data since chunk encoding that would
892      * signal EOF */
893     if (size > 0) {
894         /* upload data using chunked encoding */
895         snprintf(temp, sizeof(temp), "%x\r\n", size);
896
897         if ((ret = ffurl_write(s->hd, temp, strlen(temp))) < 0 ||
898             (ret = ffurl_write(s->hd, buf, size)) < 0 ||
899             (ret = ffurl_write(s->hd, crlf, sizeof(crlf) - 1)) < 0)
900             return ret;
901     }
902     return size;
903 }
904
905 static int http_shutdown(URLContext *h, int flags)
906 {
907     int ret = 0;
908     char footer[] = "0\r\n\r\n";
909     HTTPContext *s = h->priv_data;
910
911     /* signal end of chunked encoding if used */
912     if ((flags & AVIO_FLAG_WRITE) && s->chunked_post) {
913         ret = ffurl_write(s->hd, footer, sizeof(footer) - 1);
914         ret = ret > 0 ? 0 : ret;
915         s->end_chunked_post = 1;
916     }
917
918     return ret;
919 }
920
921 static int http_close(URLContext *h)
922 {
923     int ret = 0;
924     HTTPContext *s = h->priv_data;
925
926 #if CONFIG_ZLIB
927     inflateEnd(&s->inflate_stream);
928     av_freep(&s->inflate_buffer);
929 #endif
930
931     if (!s->end_chunked_post) {
932         /* Close the write direction by sending the end of chunked encoding. */
933         ret = http_shutdown(h, h->flags);
934     }
935
936     if (s->hd)
937         ffurl_closep(&s->hd);
938     av_dict_free(&s->chained_options);
939     return ret;
940 }
941
942 static int64_t http_seek(URLContext *h, int64_t off, int whence)
943 {
944     HTTPContext *s = h->priv_data;
945     URLContext *old_hd = s->hd;
946     int64_t old_off = s->off;
947     uint8_t old_buf[BUFFER_SIZE];
948     int old_buf_size;
949     AVDictionary *options = NULL;
950
951     if (whence == AVSEEK_SIZE)
952         return s->filesize;
953     else if ((whence == SEEK_CUR && off == 0) || (whence == SEEK_SET && off == s->off))
954         return s->off;
955     else if ((s->filesize == -1 && whence == SEEK_END) || h->is_streamed)
956         return -1;
957
958     /* we save the old context in case the seek fails */
959     old_buf_size = s->buf_end - s->buf_ptr;
960     memcpy(old_buf, s->buf_ptr, old_buf_size);
961     s->hd = NULL;
962     if (whence == SEEK_CUR)
963         off += s->off;
964     else if (whence == SEEK_END)
965         off += s->filesize;
966     s->off = off;
967
968     /* if it fails, continue on old connection */
969     av_dict_copy(&options, s->chained_options, 0);
970     if (http_open_cnx(h, &options) < 0) {
971         av_dict_free(&options);
972         memcpy(s->buffer, old_buf, old_buf_size);
973         s->buf_ptr = s->buffer;
974         s->buf_end = s->buffer + old_buf_size;
975         s->hd = old_hd;
976         s->off = old_off;
977         return -1;
978     }
979     av_dict_free(&options);
980     ffurl_close(old_hd);
981     return off;
982 }
983
984 static int
985 http_get_file_handle(URLContext *h)
986 {
987     HTTPContext *s = h->priv_data;
988     return ffurl_get_file_handle(s->hd);
989 }
990
991 #if CONFIG_HTTP_PROTOCOL
992 URLProtocol ff_http_protocol = {
993     .name                = "http",
994     .url_open2           = http_open,
995     .url_read            = http_read,
996     .url_write           = http_write,
997     .url_seek            = http_seek,
998     .url_close           = http_close,
999     .url_get_file_handle = http_get_file_handle,
1000     .url_shutdown        = http_shutdown,
1001     .priv_data_size      = sizeof(HTTPContext),
1002     .priv_data_class     = &http_context_class,
1003     .flags               = URL_PROTOCOL_FLAG_NETWORK,
1004 };
1005 #endif
1006 #if CONFIG_HTTPS_PROTOCOL
1007 URLProtocol ff_https_protocol = {
1008     .name                = "https",
1009     .url_open2           = http_open,
1010     .url_read            = http_read,
1011     .url_write           = http_write,
1012     .url_seek            = http_seek,
1013     .url_close           = http_close,
1014     .url_get_file_handle = http_get_file_handle,
1015     .url_shutdown        = http_shutdown,
1016     .priv_data_size      = sizeof(HTTPContext),
1017     .priv_data_class     = &https_context_class,
1018     .flags               = URL_PROTOCOL_FLAG_NETWORK,
1019 };
1020 #endif
1021
1022 #if CONFIG_HTTPPROXY_PROTOCOL
1023 static int http_proxy_close(URLContext *h)
1024 {
1025     HTTPContext *s = h->priv_data;
1026     if (s->hd)
1027         ffurl_closep(&s->hd);
1028     return 0;
1029 }
1030
1031 static int http_proxy_open(URLContext *h, const char *uri, int flags)
1032 {
1033     HTTPContext *s = h->priv_data;
1034     char hostname[1024], hoststr[1024];
1035     char auth[1024], pathbuf[1024], *path;
1036     char lower_url[100];
1037     int port, ret = 0, attempts = 0;
1038     HTTPAuthType cur_auth_type;
1039     char *authstr;
1040     int new_loc;
1041
1042     if( s->seekable == 1 )
1043         h->is_streamed = 0;
1044     else
1045         h->is_streamed = 1;
1046
1047     av_url_split(NULL, 0, auth, sizeof(auth), hostname, sizeof(hostname), &port,
1048                  pathbuf, sizeof(pathbuf), uri);
1049     ff_url_join(hoststr, sizeof(hoststr), NULL, NULL, hostname, port, NULL);
1050     path = pathbuf;
1051     if (*path == '/')
1052         path++;
1053
1054     ff_url_join(lower_url, sizeof(lower_url), "tcp", NULL, hostname, port,
1055                 NULL);
1056 redo:
1057     ret = ffurl_open(&s->hd, lower_url, AVIO_FLAG_READ_WRITE,
1058                      &h->interrupt_callback, NULL);
1059     if (ret < 0)
1060         return ret;
1061
1062     authstr = ff_http_auth_create_response(&s->proxy_auth_state, auth,
1063                                            path, "CONNECT");
1064     snprintf(s->buffer, sizeof(s->buffer),
1065              "CONNECT %s HTTP/1.1\r\n"
1066              "Host: %s\r\n"
1067              "Connection: close\r\n"
1068              "%s%s"
1069              "\r\n",
1070              path,
1071              hoststr,
1072              authstr ? "Proxy-" : "", authstr ? authstr : "");
1073     av_freep(&authstr);
1074
1075     if ((ret = ffurl_write(s->hd, s->buffer, strlen(s->buffer))) < 0)
1076         goto fail;
1077
1078     s->buf_ptr = s->buffer;
1079     s->buf_end = s->buffer;
1080     s->line_count = 0;
1081     s->filesize = -1;
1082     cur_auth_type = s->proxy_auth_state.auth_type;
1083
1084     /* Note: This uses buffering, potentially reading more than the
1085      * HTTP header. If tunneling a protocol where the server starts
1086      * the conversation, we might buffer part of that here, too.
1087      * Reading that requires using the proper ffurl_read() function
1088      * on this URLContext, not using the fd directly (as the tls
1089      * protocol does). This shouldn't be an issue for tls though,
1090      * since the client starts the conversation there, so there
1091      * is no extra data that we might buffer up here.
1092      */
1093     ret = http_read_header(h, &new_loc);
1094     if (ret < 0)
1095         goto fail;
1096
1097     attempts++;
1098     if (s->http_code == 407 &&
1099         (cur_auth_type == HTTP_AUTH_NONE || s->proxy_auth_state.stale) &&
1100         s->proxy_auth_state.auth_type != HTTP_AUTH_NONE && attempts < 2) {
1101         ffurl_closep(&s->hd);
1102         goto redo;
1103     }
1104
1105     if (s->http_code < 400)
1106         return 0;
1107     ret = AVERROR(EIO);
1108
1109 fail:
1110     http_proxy_close(h);
1111     return ret;
1112 }
1113
1114 static int http_proxy_write(URLContext *h, const uint8_t *buf, int size)
1115 {
1116     HTTPContext *s = h->priv_data;
1117     return ffurl_write(s->hd, buf, size);
1118 }
1119
1120 URLProtocol ff_httpproxy_protocol = {
1121     .name                = "httpproxy",
1122     .url_open            = http_proxy_open,
1123     .url_read            = http_buf_read,
1124     .url_write           = http_proxy_write,
1125     .url_close           = http_proxy_close,
1126     .url_get_file_handle = http_get_file_handle,
1127     .priv_data_size      = sizeof(HTTPContext),
1128     .flags               = URL_PROTOCOL_FLAG_NETWORK,
1129 };
1130 #endif