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