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