2 * HTTP protocol for ffmpeg client
3 * Copyright (c) 2000, 2001 Fabrice Bellard
5 * This file is part of FFmpeg.
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.
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.
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
26 #endif /* CONFIG_ZLIB */
28 #include "libavutil/avstring.h"
29 #include "libavutil/opt.h"
36 #include "os_support.h"
39 /* XXX: POST protocol is not completely implemented because ffmpeg uses
40 * only a subset of it. */
42 /* The IO buffer size is unrelated to the max URL size in itself, but needs
43 * to be large enough to fit the full request headers (including long
45 #define BUFFER_SIZE MAX_URL_SIZE
46 #define MAX_REDIRECTS 8
48 typedef struct HTTPContext {
51 unsigned char buffer[BUFFER_SIZE], *buf_ptr, *buf_end;
54 /* Used if "Transfer-Encoding: chunked" otherwise -1. */
56 int64_t off, end_off, filesize;
58 HTTPAuthState auth_state;
59 HTTPAuthState proxy_auth_state;
64 /* Set if the server correctly handles Connection: close and will close
65 * the connection after feeding us the content. */
67 int seekable; /**< Control seekability, 0 = disable, 1 = enable, -1 = probe. */
69 /* A flag which indicates if the end of chunked encoding has been sent. */
71 /* A flag which indicates we have finished to read POST reply. */
73 /* A flag which indicates if we use persistent connections. */
74 int multiple_requests;
79 char *cookies; ///< holds newline (\n) delimited Set-Cookie header field values (without the "Set-Cookie: " field name)
80 /* A dictionary containing cookies keyed by cookie name */
81 AVDictionary *cookie_dict;
83 /* how much data was read since the last ICY metadata packet */
85 /* after how many bytes of read data a new metadata packet will be found */
87 char *icy_metadata_headers;
88 char *icy_metadata_packet;
89 AVDictionary *metadata;
92 z_stream inflate_stream;
93 uint8_t *inflate_buffer;
94 #endif /* CONFIG_ZLIB */
95 AVDictionary *chained_options;
102 #define OFFSET(x) offsetof(HTTPContext, x)
103 #define D AV_OPT_FLAG_DECODING_PARAM
104 #define E AV_OPT_FLAG_ENCODING_PARAM
105 #define DEFAULT_USER_AGENT "Lavf/" AV_STRINGIFY(LIBAVFORMAT_VERSION)
107 static const AVOption options[] = {
108 { "seekable", "control seekability of connection", OFFSET(seekable), AV_OPT_TYPE_INT, { .i64 = -1 }, -1, 1, D },
109 { "chunked_post", "use chunked transfer-encoding for posts", OFFSET(chunked_post), AV_OPT_TYPE_INT, { .i64 = 1 }, 0, 1, E },
110 { "headers", "set custom HTTP headers, can override built in default headers", OFFSET(headers), AV_OPT_TYPE_STRING, { 0 }, 0, 0, D | E },
111 { "content_type", "set a specific content type for the POST messages", OFFSET(content_type), AV_OPT_TYPE_STRING, { 0 }, 0, 0, D | E },
112 { "user_agent", "override User-Agent header", OFFSET(user_agent), AV_OPT_TYPE_STRING, { .str = DEFAULT_USER_AGENT }, 0, 0, D },
113 { "user-agent", "override User-Agent header", OFFSET(user_agent), AV_OPT_TYPE_STRING, { .str = DEFAULT_USER_AGENT }, 0, 0, D },
114 { "multiple_requests", "use persistent connections", OFFSET(multiple_requests), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 1, D | E },
115 { "post_data", "set custom HTTP post data", OFFSET(post_data), AV_OPT_TYPE_BINARY, .flags = D | E },
116 { "mime_type", "export the MIME type", OFFSET(mime_type), AV_OPT_TYPE_STRING, { 0 }, 0, 0, AV_OPT_FLAG_EXPORT | AV_OPT_FLAG_READONLY },
117 { "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 },
118 { "icy", "request ICY metadata", OFFSET(icy), AV_OPT_TYPE_INT, { .i64 = 1 }, 0, 1, D },
119 { "icy_metadata_headers", "return ICY metadata headers", OFFSET(icy_metadata_headers), AV_OPT_TYPE_STRING, { 0 }, 0, 0, AV_OPT_FLAG_EXPORT },
120 { "icy_metadata_packet", "return current ICY metadata packet", OFFSET(icy_metadata_packet), AV_OPT_TYPE_STRING, { 0 }, 0, 0, AV_OPT_FLAG_EXPORT },
121 { "metadata", "metadata read from the bitstream", OFFSET(metadata), AV_OPT_TYPE_DICT, {0}, 0, 0, AV_OPT_FLAG_EXPORT },
122 { "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"},
123 { "none", "No auth method set, autodetect", 0, AV_OPT_TYPE_CONST, { .i64 = HTTP_AUTH_NONE }, 0, 0, D | E, "auth_type"},
124 { "basic", "HTTP basic authentication", 0, AV_OPT_TYPE_CONST, { .i64 = HTTP_AUTH_BASIC }, 0, 0, D | E, "auth_type"},
125 { "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 },
126 { "location", "The actual location of the data received", OFFSET(location), AV_OPT_TYPE_STRING, { 0 }, 0, 0, D | E },
127 { "offset", "initial byte offset", OFFSET(off), AV_OPT_TYPE_INT64, { .i64 = 0 }, 0, INT64_MAX, D },
128 { "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 },
129 { "method", "Override the HTTP method or set the expected HTTP method from a client", OFFSET(method), AV_OPT_TYPE_STRING, { .str = NULL }, 0, 0, D | E },
130 { "reconnect", "auto reconnect after disconnect before EOF", OFFSET(reconnect), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 1, D },
131 { "listen", "listen on HTTP", OFFSET(listen), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 1, D | E },
135 static int http_connect(URLContext *h, const char *path, const char *local_path,
136 const char *hoststr, const char *auth,
137 const char *proxyauth, int *new_location);
138 static int http_read_header(URLContext *h, int *new_location);
140 void ff_http_init_auth_state(URLContext *dest, const URLContext *src)
142 memcpy(&((HTTPContext *)dest->priv_data)->auth_state,
143 &((HTTPContext *)src->priv_data)->auth_state,
144 sizeof(HTTPAuthState));
145 memcpy(&((HTTPContext *)dest->priv_data)->proxy_auth_state,
146 &((HTTPContext *)src->priv_data)->proxy_auth_state,
147 sizeof(HTTPAuthState));
150 static int http_open_cnx_internal(URLContext *h, AVDictionary **options)
152 const char *path, *proxy_path, *lower_proto = "tcp", *local_path;
153 char hostname[1024], hoststr[1024], proto[10];
154 char auth[1024], proxyauth[1024] = "";
155 char path1[MAX_URL_SIZE];
156 char buf[1024], urlbuf[MAX_URL_SIZE];
157 int port, use_proxy, err, location_changed = 0;
158 HTTPContext *s = h->priv_data;
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);
165 proxy_path = getenv("http_proxy");
166 use_proxy = !ff_http_match_no_proxy(getenv("no_proxy"), hostname) &&
167 proxy_path && av_strstart(proxy_path, "http://", NULL);
169 if (!strcmp(proto, "https")) {
178 if (path1[0] == '\0')
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",
189 av_url_split(NULL, 0, proxyauth, sizeof(proxyauth),
190 hostname, sizeof(hostname), &port, NULL, 0, proxy_path);
193 ff_url_join(buf, sizeof(buf), lower_proto, NULL, hostname, port, NULL);
196 err = ffurl_open(&s->hd, buf, AVIO_FLAG_READ_WRITE,
197 &h->interrupt_callback, options);
202 err = http_connect(h, path, local_path, hoststr,
203 auth, proxyauth, &location_changed);
207 return location_changed;
210 /* return non zero if error */
211 static int http_open_cnx(URLContext *h, AVDictionary **options)
213 HTTPAuthType cur_auth_type, cur_proxy_auth_type;
214 HTTPContext *s = h->priv_data;
215 int location_changed, attempts = 0, redirects = 0;
217 av_dict_copy(options, s->chained_options, 0);
219 cur_auth_type = s->auth_state.auth_type;
220 cur_proxy_auth_type = s->auth_state.auth_type;
222 location_changed = http_open_cnx_internal(h, options);
223 if (location_changed < 0)
227 if (s->http_code == 401) {
228 if ((cur_auth_type == HTTP_AUTH_NONE || s->auth_state.stale) &&
229 s->auth_state.auth_type != HTTP_AUTH_NONE && attempts < 4) {
230 ffurl_closep(&s->hd);
235 if (s->http_code == 407) {
236 if ((cur_proxy_auth_type == HTTP_AUTH_NONE || s->proxy_auth_state.stale) &&
237 s->proxy_auth_state.auth_type != HTTP_AUTH_NONE && attempts < 4) {
238 ffurl_closep(&s->hd);
243 if ((s->http_code == 301 || s->http_code == 302 ||
244 s->http_code == 303 || s->http_code == 307) &&
245 location_changed == 1) {
246 /* url moved, get next */
247 ffurl_closep(&s->hd);
248 if (redirects++ >= MAX_REDIRECTS)
250 /* Restart the authentication process with the new target, which
251 * might use a different auth mechanism. */
252 memset(&s->auth_state, 0, sizeof(s->auth_state));
254 location_changed = 0;
261 ffurl_closep(&s->hd);
262 if (location_changed < 0)
263 return location_changed;
264 return ff_http_averror(s->http_code, AVERROR(EIO));
267 int ff_http_do_new_request(URLContext *h, const char *uri)
269 HTTPContext *s = h->priv_data;
270 AVDictionary *options = NULL;
274 s->icy_data_read = 0;
275 av_free(s->location);
276 s->location = av_strdup(uri);
278 return AVERROR(ENOMEM);
280 ret = http_open_cnx(h, &options);
281 av_dict_free(&options);
285 int ff_http_averror(int status_code, int default_averror)
287 switch (status_code) {
288 case 400: return AVERROR_HTTP_BAD_REQUEST;
289 case 401: return AVERROR_HTTP_UNAUTHORIZED;
290 case 403: return AVERROR_HTTP_FORBIDDEN;
291 case 404: return AVERROR_HTTP_NOT_FOUND;
294 if (status_code >= 400 && status_code <= 499)
295 return AVERROR_HTTP_OTHER_4XX;
296 else if (status_code >= 500)
297 return AVERROR_HTTP_SERVER_ERROR;
299 return default_averror;
302 static void handle_http_errors(URLContext *h, int error)
304 static const char bad_request[] = "HTTP/1.1 400 Bad Request\r\nContent-Type: text/plain\r\n\r\n400 Bad Request\r\n";
305 static const char internal_server_error[] = "HTTP/1.1 500 Internal server error\r\nContent-Type: text/plain\r\n\r\n500 Internal server error\r\n";
306 HTTPContext *s = h->priv_data;
307 if (h->is_connected) {
309 case AVERROR_HTTP_BAD_REQUEST:
310 ffurl_write(s->hd, bad_request, strlen(bad_request));
313 av_log(h, AV_LOG_ERROR, "Unhandled HTTP error.\n");
314 ffurl_write(s->hd, internal_server_error, strlen(internal_server_error));
319 static int http_listen(URLContext *h, const char *uri, int flags,
320 AVDictionary **options) {
321 HTTPContext *s = h->priv_data;
323 static const char header[] = "HTTP/1.1 200 OK\r\nContent-Type: application/octet-stream\r\nTransfer-Encoding: chunked\r\n\r\n";
324 char hostname[1024], proto[10];
326 const char *lower_proto = "tcp";
327 int port, new_location;
329 av_url_split(proto, sizeof(proto), NULL, 0, hostname, sizeof(hostname), &port,
331 if (!strcmp(proto, "https"))
333 ff_url_join(lower_url, sizeof(lower_url), lower_proto, NULL, hostname, port,
335 av_dict_set(options, "listen", "1", 0);
336 if ((ret = ffurl_open(&s->hd, lower_url, AVIO_FLAG_READ_WRITE,
337 &h->interrupt_callback, options)) < 0)
339 if ((ret = http_read_header(h, &new_location)) < 0)
341 if ((ret = ffurl_write(s->hd, header, strlen(header))) < 0)
346 handle_http_errors(h, ret);
347 av_dict_free(&s->chained_options);
351 static int http_open(URLContext *h, const char *uri, int flags,
352 AVDictionary **options)
354 HTTPContext *s = h->priv_data;
357 if( s->seekable == 1 )
363 s->location = av_strdup(uri);
365 return AVERROR(ENOMEM);
367 av_dict_copy(&s->chained_options, *options, 0);
370 int len = strlen(s->headers);
371 if (len < 2 || strcmp("\r\n", s->headers + len - 2))
372 av_log(h, AV_LOG_WARNING,
373 "No trailing CRLF found in HTTP header.\n");
377 return http_listen(h, uri, flags, options);
379 ret = http_open_cnx(h, options);
381 av_dict_free(&s->chained_options);
385 static int http_getc(HTTPContext *s)
388 if (s->buf_ptr >= s->buf_end) {
389 len = ffurl_read(s->hd, s->buffer, BUFFER_SIZE);
392 } else if (len == 0) {
395 s->buf_ptr = s->buffer;
396 s->buf_end = s->buffer + len;
399 return *s->buf_ptr++;
402 static int http_get_line(HTTPContext *s, char *line, int line_size)
414 if (q > line && q[-1] == '\r')
420 if ((q - line) < line_size - 1)
426 static int check_http_code(URLContext *h, int http_code, const char *end)
428 HTTPContext *s = h->priv_data;
429 /* error codes are 4xx and 5xx, but regard 401 as a success, so we
430 * don't abort until all headers have been parsed. */
431 if (http_code >= 400 && http_code < 600 &&
432 (http_code != 401 || s->auth_state.auth_type != HTTP_AUTH_NONE) &&
433 (http_code != 407 || s->proxy_auth_state.auth_type != HTTP_AUTH_NONE)) {
434 end += strspn(end, SPACE_CHARS);
435 av_log(h, AV_LOG_WARNING, "HTTP error %d %s\n", http_code, end);
436 return ff_http_averror(http_code, AVERROR(EIO));
441 static int parse_location(HTTPContext *s, const char *p)
443 char redirected_location[MAX_URL_SIZE], *new_loc;
444 ff_make_absolute_url(redirected_location, sizeof(redirected_location),
446 new_loc = av_strdup(redirected_location);
448 return AVERROR(ENOMEM);
449 av_free(s->location);
450 s->location = new_loc;
454 /* "bytes $from-$to/$document_size" */
455 static void parse_content_range(URLContext *h, const char *p)
457 HTTPContext *s = h->priv_data;
460 if (!strncmp(p, "bytes ", 6)) {
462 s->off = strtoll(p, NULL, 10);
463 if ((slash = strchr(p, '/')) && strlen(slash) > 0)
464 s->filesize = strtoll(slash + 1, NULL, 10);
466 if (s->seekable == -1 && (!s->is_akamai || s->filesize != 2147483647))
467 h->is_streamed = 0; /* we _can_ in fact seek */
470 static int parse_content_encoding(URLContext *h, const char *p)
472 if (!av_strncasecmp(p, "gzip", 4) ||
473 !av_strncasecmp(p, "deflate", 7)) {
475 HTTPContext *s = h->priv_data;
478 inflateEnd(&s->inflate_stream);
479 if (inflateInit2(&s->inflate_stream, 32 + 15) != Z_OK) {
480 av_log(h, AV_LOG_WARNING, "Error during zlib initialisation: %s\n",
481 s->inflate_stream.msg);
482 return AVERROR(ENOSYS);
484 if (zlibCompileFlags() & (1 << 17)) {
485 av_log(h, AV_LOG_WARNING,
486 "Your zlib was compiled without gzip support.\n");
487 return AVERROR(ENOSYS);
490 av_log(h, AV_LOG_WARNING,
491 "Compressed (%s) content, need zlib with gzip support\n", p);
492 return AVERROR(ENOSYS);
493 #endif /* CONFIG_ZLIB */
494 } else if (!av_strncasecmp(p, "identity", 8)) {
495 // The normal, no-encoding case (although servers shouldn't include
496 // the header at all if this is the case).
498 av_log(h, AV_LOG_WARNING, "Unknown content coding: %s\n", p);
503 // Concat all Icy- header lines
504 static int parse_icy(HTTPContext *s, const char *tag, const char *p)
506 int len = 4 + strlen(p) + strlen(tag);
507 int is_first = !s->icy_metadata_headers;
510 av_dict_set(&s->metadata, tag, p, 0);
512 if (s->icy_metadata_headers)
513 len += strlen(s->icy_metadata_headers);
515 if ((ret = av_reallocp(&s->icy_metadata_headers, len)) < 0)
519 *s->icy_metadata_headers = '\0';
521 av_strlcatf(s->icy_metadata_headers, len, "%s: %s\n", tag, p);
526 static int parse_cookie(HTTPContext *s, const char *p, AVDictionary **cookies)
530 // duplicate the cookie name (dict will dupe the value)
531 if (!(eql = strchr(p, '='))) return AVERROR(EINVAL);
532 if (!(name = av_strndup(p, eql - p))) return AVERROR(ENOMEM);
534 // add the cookie to the dictionary
535 av_dict_set(cookies, name, eql, AV_DICT_DONT_STRDUP_KEY);
540 static int cookie_string(AVDictionary *dict, char **cookies)
542 AVDictionaryEntry *e = NULL;
545 // determine how much memory is needed for the cookies string
546 while (e = av_dict_get(dict, "", e, AV_DICT_IGNORE_SUFFIX))
547 len += strlen(e->key) + strlen(e->value) + 1;
549 // reallocate the cookies
551 if (*cookies) av_free(*cookies);
552 *cookies = av_malloc(len);
553 if (!*cookies) return AVERROR(ENOMEM);
556 // write out the cookies
557 while (e = av_dict_get(dict, "", e, AV_DICT_IGNORE_SUFFIX))
558 av_strlcatf(*cookies, len, "%s%s\n", e->key, e->value);
563 static int process_line(URLContext *h, char *line, int line_count,
566 HTTPContext *s = h->priv_data;
567 const char *auto_method = h->flags & AVIO_FLAG_READ ? "POST" : "GET";
568 char *tag, *p, *end, *method, *resource, *version;
572 if (line[0] == '\0') {
578 if (line_count == 0) {
582 while (!av_isspace(*p))
585 av_log(h, AV_LOG_TRACE, "Received method: %s\n", method);
587 if (av_strcasecmp(s->method, method)) {
588 av_log(h, AV_LOG_ERROR, "Received and expected HTTP method do not match. (%s expected, %s received)\n",
590 return ff_http_averror(400, AVERROR(EIO));
593 // use autodetected HTTP method to expect
594 av_log(h, AV_LOG_TRACE, "Autodetected %s HTTP method\n", auto_method);
595 if (av_strcasecmp(auto_method, method)) {
596 av_log(h, AV_LOG_ERROR, "Received and autodetected HTTP method did not match "
597 "(%s autodetected %s received)\n", auto_method, method);
598 return ff_http_averror(400, AVERROR(EIO));
603 while (av_isspace(*p))
606 while (!av_isspace(*p))
609 av_log(h, AV_LOG_TRACE, "Requested resource: %s\n", resource);
612 while (av_isspace(*p))
615 while (!av_isspace(*p))
618 if (av_strncasecmp(version, "HTTP/", 5)) {
619 av_log(h, AV_LOG_ERROR, "Malformed HTTP version string.\n");
620 return ff_http_averror(400, AVERROR(EIO));
622 av_log(h, AV_LOG_TRACE, "HTTP version string: %s\n", version);
624 while (!av_isspace(*p) && *p != '\0')
626 while (av_isspace(*p))
628 s->http_code = strtol(p, &end, 10);
630 av_log(h, AV_LOG_TRACE, "http_code=%d\n", s->http_code);
632 if ((ret = check_http_code(h, s->http_code, end)) < 0)
636 while (*p != '\0' && *p != ':')
644 while (av_isspace(*p))
646 if (!av_strcasecmp(tag, "Location")) {
647 if ((ret = parse_location(s, p)) < 0)
650 } else if (!av_strcasecmp(tag, "Content-Length") && s->filesize == -1) {
651 s->filesize = strtoll(p, NULL, 10);
652 } else if (!av_strcasecmp(tag, "Content-Range")) {
653 parse_content_range(h, p);
654 } else if (!av_strcasecmp(tag, "Accept-Ranges") &&
655 !strncmp(p, "bytes", 5) &&
658 } else if (!av_strcasecmp(tag, "Transfer-Encoding") &&
659 !av_strncasecmp(p, "chunked", 7)) {
662 } else if (!av_strcasecmp(tag, "WWW-Authenticate")) {
663 ff_http_auth_handle_header(&s->auth_state, tag, p);
664 } else if (!av_strcasecmp(tag, "Authentication-Info")) {
665 ff_http_auth_handle_header(&s->auth_state, tag, p);
666 } else if (!av_strcasecmp(tag, "Proxy-Authenticate")) {
667 ff_http_auth_handle_header(&s->proxy_auth_state, tag, p);
668 } else if (!av_strcasecmp(tag, "Connection")) {
669 if (!strcmp(p, "close"))
671 } else if (!av_strcasecmp(tag, "Server")) {
672 if (!av_strcasecmp(p, "AkamaiGHost")) {
674 } else if (!av_strncasecmp(p, "MediaGateway", 12)) {
675 s->is_mediagateway = 1;
677 } else if (!av_strcasecmp(tag, "Content-Type")) {
678 av_free(s->mime_type);
679 s->mime_type = av_strdup(p);
680 } else if (!av_strcasecmp(tag, "Set-Cookie")) {
681 if (parse_cookie(s, p, &s->cookie_dict))
682 av_log(h, AV_LOG_WARNING, "Unable to parse '%s'\n", p);
683 } else if (!av_strcasecmp(tag, "Icy-MetaInt")) {
684 s->icy_metaint = strtoll(p, NULL, 10);
685 } else if (!av_strncasecmp(tag, "Icy-", 4)) {
686 if ((ret = parse_icy(s, tag, p)) < 0)
688 } else if (!av_strcasecmp(tag, "Content-Encoding")) {
689 if ((ret = parse_content_encoding(h, p)) < 0)
697 * Create a string containing cookie values for use as a HTTP cookie header
698 * field value for a particular path and domain from the cookie values stored in
699 * the HTTP protocol context. The cookie string is stored in *cookies.
701 * @return a negative value if an error condition occurred, 0 otherwise
703 static int get_cookies(HTTPContext *s, char **cookies, const char *path,
706 // cookie strings will look like Set-Cookie header field values. Multiple
707 // Set-Cookie fields will result in multiple values delimited by a newline
709 char *next, *cookie, *set_cookies = av_strdup(s->cookies), *cset_cookies = set_cookies;
711 if (!set_cookies) return AVERROR(EINVAL);
713 // destroy any cookies in the dictionary.
714 av_dict_free(&s->cookie_dict);
717 while ((cookie = av_strtok(set_cookies, "\n", &next))) {
718 int domain_offset = 0;
719 char *param, *next_param, *cdomain = NULL, *cpath = NULL, *cvalue = NULL;
722 // store the cookie in a dict in case it is updated in the response
723 if (parse_cookie(s, cookie, &s->cookie_dict))
724 av_log(s, AV_LOG_WARNING, "Unable to parse '%s'\n", cookie);
726 while ((param = av_strtok(cookie, "; ", &next_param))) {
728 // first key-value pair is the actual cookie value
729 cvalue = av_strdup(param);
731 } else if (!av_strncasecmp("path=", param, 5)) {
733 cpath = av_strdup(¶m[5]);
734 } else if (!av_strncasecmp("domain=", param, 7)) {
735 // if the cookie specifies a sub-domain, skip the leading dot thereby
736 // supporting URLs that point to sub-domains and the master domain
737 int leading_dot = (param[7] == '.');
739 cdomain = av_strdup(¶m[7+leading_dot]);
741 // ignore unknown attributes
745 cdomain = av_strdup(domain);
747 // ensure all of the necessary values are valid
748 if (!cdomain || !cpath || !cvalue) {
749 av_log(s, AV_LOG_WARNING,
750 "Invalid cookie found, no value, path or domain specified\n");
754 // check if the request path matches the cookie path
755 if (av_strncasecmp(path, cpath, strlen(cpath)))
758 // the domain should be at least the size of our cookie domain
759 domain_offset = strlen(domain) - strlen(cdomain);
760 if (domain_offset < 0)
763 // match the cookie domain
764 if (av_strcasecmp(&domain[domain_offset], cdomain))
767 // cookie parameters match, so copy the value
769 if (!(*cookies = av_strdup(cvalue))) {
770 ret = AVERROR(ENOMEM);
774 char *tmp = *cookies;
775 size_t str_size = strlen(cvalue) + strlen(*cookies) + 3;
776 if (!(*cookies = av_malloc(str_size))) {
777 ret = AVERROR(ENOMEM);
780 snprintf(*cookies, str_size, "%s; %s", tmp, cvalue);
789 if (*cookies) av_freep(cookies);
790 av_free(cset_cookies);
795 av_free(cset_cookies);
800 static inline int has_header(const char *str, const char *header)
802 /* header + 2 to skip over CRLF prefix. (make sure you have one!) */
805 return av_stristart(str, header + 2, NULL) || av_stristr(str, header);
808 static int http_read_header(URLContext *h, int *new_location)
810 HTTPContext *s = h->priv_data;
811 char line[MAX_URL_SIZE];
817 if ((err = http_get_line(s, line, sizeof(line))) < 0)
820 av_log(h, AV_LOG_TRACE, "header='%s'\n", line);
822 err = process_line(h, line, s->line_count, new_location);
830 if (s->seekable == -1 && s->is_mediagateway && s->filesize == 2000000000)
831 h->is_streamed = 1; /* we can in fact _not_ seek */
833 // add any new cookies into the existing cookie string
834 cookie_string(s->cookie_dict, &s->cookies);
835 av_dict_free(&s->cookie_dict);
840 static int http_connect(URLContext *h, const char *path, const char *local_path,
841 const char *hoststr, const char *auth,
842 const char *proxyauth, int *new_location)
844 HTTPContext *s = h->priv_data;
846 char headers[HTTP_HEADERS_SIZE] = "";
847 char *authstr = NULL, *proxyauthstr = NULL;
848 int64_t off = s->off;
851 int send_expect_100 = 0;
853 /* send http header */
854 post = h->flags & AVIO_FLAG_WRITE;
857 /* force POST method and disable chunked encoding when
858 * custom HTTP post data is set */
866 method = post ? "POST" : "GET";
868 authstr = ff_http_auth_create_response(&s->auth_state, auth,
870 proxyauthstr = ff_http_auth_create_response(&s->proxy_auth_state, proxyauth,
872 if (post && !s->post_data) {
873 send_expect_100 = s->send_expect_100;
874 /* The user has supplied authentication but we don't know the auth type,
875 * send Expect: 100-continue to get the 401 response including the
876 * WWW-Authenticate header, or an 100 continue if no auth actually
879 s->auth_state.auth_type == HTTP_AUTH_NONE &&
884 /* set default headers if needed */
885 if (!has_header(s->headers, "\r\nUser-Agent: "))
886 len += av_strlcatf(headers + len, sizeof(headers) - len,
887 "User-Agent: %s\r\n", s->user_agent);
888 if (!has_header(s->headers, "\r\nAccept: "))
889 len += av_strlcpy(headers + len, "Accept: */*\r\n",
890 sizeof(headers) - len);
891 // Note: we send this on purpose even when s->off is 0 when we're probing,
892 // since it allows us to detect more reliably if a (non-conforming)
893 // server supports seeking by analysing the reply headers.
894 if (!has_header(s->headers, "\r\nRange: ") && !post && (s->off > 0 || s->end_off || s->seekable == -1)) {
895 len += av_strlcatf(headers + len, sizeof(headers) - len,
896 "Range: bytes=%"PRId64"-", s->off);
898 len += av_strlcatf(headers + len, sizeof(headers) - len,
899 "%"PRId64, s->end_off - 1);
900 len += av_strlcpy(headers + len, "\r\n",
901 sizeof(headers) - len);
903 if (send_expect_100 && !has_header(s->headers, "\r\nExpect: "))
904 len += av_strlcatf(headers + len, sizeof(headers) - len,
905 "Expect: 100-continue\r\n");
907 if (!has_header(s->headers, "\r\nConnection: ")) {
908 if (s->multiple_requests)
909 len += av_strlcpy(headers + len, "Connection: keep-alive\r\n",
910 sizeof(headers) - len);
912 len += av_strlcpy(headers + len, "Connection: close\r\n",
913 sizeof(headers) - len);
916 if (!has_header(s->headers, "\r\nHost: "))
917 len += av_strlcatf(headers + len, sizeof(headers) - len,
918 "Host: %s\r\n", hoststr);
919 if (!has_header(s->headers, "\r\nContent-Length: ") && s->post_data)
920 len += av_strlcatf(headers + len, sizeof(headers) - len,
921 "Content-Length: %d\r\n", s->post_datalen);
923 if (!has_header(s->headers, "\r\nContent-Type: ") && s->content_type)
924 len += av_strlcatf(headers + len, sizeof(headers) - len,
925 "Content-Type: %s\r\n", s->content_type);
926 if (!has_header(s->headers, "\r\nCookie: ") && s->cookies) {
927 char *cookies = NULL;
928 if (!get_cookies(s, &cookies, path, hoststr) && cookies) {
929 len += av_strlcatf(headers + len, sizeof(headers) - len,
930 "Cookie: %s\r\n", cookies);
934 if (!has_header(s->headers, "\r\nIcy-MetaData: ") && s->icy)
935 len += av_strlcatf(headers + len, sizeof(headers) - len,
936 "Icy-MetaData: %d\r\n", 1);
938 /* now add in custom headers */
940 av_strlcpy(headers + len, s->headers, sizeof(headers) - len);
942 snprintf(s->buffer, sizeof(s->buffer),
951 post && s->chunked_post ? "Transfer-Encoding: chunked\r\n" : "",
953 authstr ? authstr : "",
954 proxyauthstr ? "Proxy-" : "", proxyauthstr ? proxyauthstr : "");
956 av_log(h, AV_LOG_DEBUG, "request: %s\n", s->buffer);
958 if ((err = ffurl_write(s->hd, s->buffer, strlen(s->buffer))) < 0)
962 if ((err = ffurl_write(s->hd, s->post_data, s->post_datalen)) < 0)
965 /* init input buffer */
966 s->buf_ptr = s->buffer;
967 s->buf_end = s->buffer;
970 s->icy_data_read = 0;
973 s->end_chunked_post = 0;
975 if (post && !s->post_data && !send_expect_100) {
976 /* Pretend that it did work. We didn't read any header yet, since
977 * we've still to send the POST data, but the code calling this
978 * function will check http_code after we return. */
984 /* wait for header */
985 err = http_read_header(h, new_location);
992 err = (off == s->off) ? 0 : -1;
995 av_freep(&proxyauthstr);
999 static int http_buf_read(URLContext *h, uint8_t *buf, int size)
1001 HTTPContext *s = h->priv_data;
1003 /* read bytes from input buffer first */
1004 len = s->buf_end - s->buf_ptr;
1008 memcpy(buf, s->buf_ptr, len);
1011 if ((!s->willclose || s->chunksize < 0) &&
1012 s->filesize >= 0 && s->off >= s->filesize)
1014 len = ffurl_read(s->hd, buf, size);
1015 if (!len && (!s->willclose || s->chunksize < 0) &&
1016 s->filesize >= 0 && s->off < s->filesize) {
1017 av_log(h, AV_LOG_ERROR,
1018 "Stream ends prematurely at %"PRId64", should be %"PRId64"\n",
1021 return AVERROR(EIO);
1026 if (s->chunksize > 0)
1027 s->chunksize -= len;
1033 #define DECOMPRESS_BUF_SIZE (256 * 1024)
1034 static int http_buf_read_compressed(URLContext *h, uint8_t *buf, int size)
1036 HTTPContext *s = h->priv_data;
1039 if (!s->inflate_buffer) {
1040 s->inflate_buffer = av_malloc(DECOMPRESS_BUF_SIZE);
1041 if (!s->inflate_buffer)
1042 return AVERROR(ENOMEM);
1045 if (s->inflate_stream.avail_in == 0) {
1046 int read = http_buf_read(h, s->inflate_buffer, DECOMPRESS_BUF_SIZE);
1049 s->inflate_stream.next_in = s->inflate_buffer;
1050 s->inflate_stream.avail_in = read;
1053 s->inflate_stream.avail_out = size;
1054 s->inflate_stream.next_out = buf;
1056 ret = inflate(&s->inflate_stream, Z_SYNC_FLUSH);
1057 if (ret != Z_OK && ret != Z_STREAM_END)
1058 av_log(h, AV_LOG_WARNING, "inflate return value: %d, %s\n",
1059 ret, s->inflate_stream.msg);
1061 return size - s->inflate_stream.avail_out;
1063 #endif /* CONFIG_ZLIB */
1065 static int64_t http_seek_internal(URLContext *h, int64_t off, int whence, int force_reconnect);
1067 static int http_read_stream(URLContext *h, uint8_t *buf, int size)
1069 HTTPContext *s = h->priv_data;
1070 int err, new_location, read_ret, seek_ret;
1075 if (s->end_chunked_post && !s->end_header) {
1076 err = http_read_header(h, &new_location);
1081 if (s->chunksize >= 0) {
1082 if (!s->chunksize) {
1086 if ((err = http_get_line(s, line, sizeof(line))) < 0)
1088 } while (!*line); /* skip CR LF from last chunk */
1090 s->chunksize = strtoll(line, NULL, 16);
1092 av_log(NULL, AV_LOG_TRACE, "Chunked encoding data size: %"PRId64"'\n",
1098 size = FFMIN(size, s->chunksize);
1102 return http_buf_read_compressed(h, buf, size);
1103 #endif /* CONFIG_ZLIB */
1104 read_ret = http_buf_read(h, buf, size);
1105 if (read_ret < 0 && s->reconnect && !h->is_streamed && s->filesize > 0 && s->off < s->filesize) {
1106 av_log(h, AV_LOG_INFO, "Will reconnect at %"PRId64".\n", s->off);
1107 seek_ret = http_seek_internal(h, s->off, SEEK_SET, 1);
1108 if (seek_ret != s->off) {
1109 av_log(h, AV_LOG_ERROR, "Failed to reconnect at %"PRId64".\n", s->off);
1113 read_ret = http_buf_read(h, buf, size);
1119 // Like http_read_stream(), but no short reads.
1120 // Assumes partial reads are an error.
1121 static int http_read_stream_all(URLContext *h, uint8_t *buf, int size)
1124 while (pos < size) {
1125 int len = http_read_stream(h, buf + pos, size - pos);
1133 static void update_metadata(HTTPContext *s, char *data)
1142 val = strstr(key, "='");
1145 end = strstr(val, "';");
1153 av_dict_set(&s->metadata, key, val, 0);
1159 static int store_icy(URLContext *h, int size)
1161 HTTPContext *s = h->priv_data;
1162 /* until next metadata packet */
1163 int remaining = s->icy_metaint - s->icy_data_read;
1166 return AVERROR_INVALIDDATA;
1169 /* The metadata packet is variable sized. It has a 1 byte header
1170 * which sets the length of the packet (divided by 16). If it's 0,
1171 * the metadata doesn't change. After the packet, icy_metaint bytes
1172 * of normal data follows. */
1174 int len = http_read_stream_all(h, &ch, 1);
1178 char data[255 * 16 + 1];
1181 ret = http_read_stream_all(h, data, len);
1185 if ((ret = av_opt_set(s, "icy_metadata_packet", data, 0)) < 0)
1187 update_metadata(s, data);
1189 s->icy_data_read = 0;
1190 remaining = s->icy_metaint;
1193 return FFMIN(size, remaining);
1196 static int http_read(URLContext *h, uint8_t *buf, int size)
1198 HTTPContext *s = h->priv_data;
1200 if (s->icy_metaint > 0) {
1201 size = store_icy(h, size);
1206 size = http_read_stream(h, buf, size);
1208 s->icy_data_read += size;
1212 /* used only when posting data */
1213 static int http_write(URLContext *h, const uint8_t *buf, int size)
1215 char temp[11] = ""; /* 32-bit hex + CRLF + nul */
1217 char crlf[] = "\r\n";
1218 HTTPContext *s = h->priv_data;
1220 if (!s->chunked_post) {
1221 /* non-chunked data is sent without any special encoding */
1222 return ffurl_write(s->hd, buf, size);
1225 /* silently ignore zero-size data since chunk encoding that would
1228 /* upload data using chunked encoding */
1229 snprintf(temp, sizeof(temp), "%x\r\n", size);
1231 if ((ret = ffurl_write(s->hd, temp, strlen(temp))) < 0 ||
1232 (ret = ffurl_write(s->hd, buf, size)) < 0 ||
1233 (ret = ffurl_write(s->hd, crlf, sizeof(crlf) - 1)) < 0)
1239 static int http_shutdown(URLContext *h, int flags)
1242 char footer[] = "0\r\n\r\n";
1243 HTTPContext *s = h->priv_data;
1245 /* signal end of chunked encoding if used */
1246 if (((flags & AVIO_FLAG_WRITE) && s->chunked_post) ||
1247 ((flags & AVIO_FLAG_READ) && s->chunked_post && s->listen)) {
1248 ret = ffurl_write(s->hd, footer, sizeof(footer) - 1);
1249 ret = ret > 0 ? 0 : ret;
1250 s->end_chunked_post = 1;
1256 static int http_close(URLContext *h)
1259 HTTPContext *s = h->priv_data;
1262 inflateEnd(&s->inflate_stream);
1263 av_freep(&s->inflate_buffer);
1264 #endif /* CONFIG_ZLIB */
1266 if (!s->end_chunked_post)
1267 /* Close the write direction by sending the end of chunked encoding. */
1268 ret = http_shutdown(h, h->flags);
1271 ffurl_closep(&s->hd);
1272 av_dict_free(&s->chained_options);
1276 static int64_t http_seek_internal(URLContext *h, int64_t off, int whence, int force_reconnect)
1278 HTTPContext *s = h->priv_data;
1279 URLContext *old_hd = s->hd;
1280 int64_t old_off = s->off;
1281 uint8_t old_buf[BUFFER_SIZE];
1282 int old_buf_size, ret;
1283 AVDictionary *options = NULL;
1285 if (whence == AVSEEK_SIZE)
1287 else if (!force_reconnect &&
1288 ((whence == SEEK_CUR && off == 0) ||
1289 (whence == SEEK_SET && off == s->off)))
1291 else if ((s->filesize == -1 && whence == SEEK_END) || h->is_streamed)
1292 return AVERROR(ENOSYS);
1294 if (whence == SEEK_CUR)
1296 else if (whence == SEEK_END)
1298 else if (whence != SEEK_SET)
1299 return AVERROR(EINVAL);
1301 return AVERROR(EINVAL);
1304 /* we save the old context in case the seek fails */
1305 old_buf_size = s->buf_end - s->buf_ptr;
1306 memcpy(old_buf, s->buf_ptr, old_buf_size);
1309 /* if it fails, continue on old connection */
1310 if ((ret = http_open_cnx(h, &options)) < 0) {
1311 av_dict_free(&options);
1312 memcpy(s->buffer, old_buf, old_buf_size);
1313 s->buf_ptr = s->buffer;
1314 s->buf_end = s->buffer + old_buf_size;
1319 av_dict_free(&options);
1320 ffurl_close(old_hd);
1324 static int64_t http_seek(URLContext *h, int64_t off, int whence)
1326 return http_seek_internal(h, off, whence, 0);
1329 static int http_get_file_handle(URLContext *h)
1331 HTTPContext *s = h->priv_data;
1332 return ffurl_get_file_handle(s->hd);
1335 #define HTTP_CLASS(flavor) \
1336 static const AVClass flavor ## _context_class = { \
1337 .class_name = # flavor, \
1338 .item_name = av_default_item_name, \
1339 .option = options, \
1340 .version = LIBAVUTIL_VERSION_INT, \
1343 #if CONFIG_HTTP_PROTOCOL
1346 URLProtocol ff_http_protocol = {
1348 .url_open2 = http_open,
1349 .url_read = http_read,
1350 .url_write = http_write,
1351 .url_seek = http_seek,
1352 .url_close = http_close,
1353 .url_get_file_handle = http_get_file_handle,
1354 .url_shutdown = http_shutdown,
1355 .priv_data_size = sizeof(HTTPContext),
1356 .priv_data_class = &http_context_class,
1357 .flags = URL_PROTOCOL_FLAG_NETWORK,
1359 #endif /* CONFIG_HTTP_PROTOCOL */
1361 #if CONFIG_HTTPS_PROTOCOL
1364 URLProtocol ff_https_protocol = {
1366 .url_open2 = http_open,
1367 .url_read = http_read,
1368 .url_write = http_write,
1369 .url_seek = http_seek,
1370 .url_close = http_close,
1371 .url_get_file_handle = http_get_file_handle,
1372 .url_shutdown = http_shutdown,
1373 .priv_data_size = sizeof(HTTPContext),
1374 .priv_data_class = &https_context_class,
1375 .flags = URL_PROTOCOL_FLAG_NETWORK,
1377 #endif /* CONFIG_HTTPS_PROTOCOL */
1379 #if CONFIG_HTTPPROXY_PROTOCOL
1380 static int http_proxy_close(URLContext *h)
1382 HTTPContext *s = h->priv_data;
1384 ffurl_closep(&s->hd);
1388 static int http_proxy_open(URLContext *h, const char *uri, int flags)
1390 HTTPContext *s = h->priv_data;
1391 char hostname[1024], hoststr[1024];
1392 char auth[1024], pathbuf[1024], *path;
1393 char lower_url[100];
1394 int port, ret = 0, attempts = 0;
1395 HTTPAuthType cur_auth_type;
1399 if( s->seekable == 1 )
1404 av_url_split(NULL, 0, auth, sizeof(auth), hostname, sizeof(hostname), &port,
1405 pathbuf, sizeof(pathbuf), uri);
1406 ff_url_join(hoststr, sizeof(hoststr), NULL, NULL, hostname, port, NULL);
1411 ff_url_join(lower_url, sizeof(lower_url), "tcp", NULL, hostname, port,
1414 ret = ffurl_open(&s->hd, lower_url, AVIO_FLAG_READ_WRITE,
1415 &h->interrupt_callback, NULL);
1419 authstr = ff_http_auth_create_response(&s->proxy_auth_state, auth,
1421 snprintf(s->buffer, sizeof(s->buffer),
1422 "CONNECT %s HTTP/1.1\r\n"
1424 "Connection: close\r\n"
1429 authstr ? "Proxy-" : "", authstr ? authstr : "");
1432 if ((ret = ffurl_write(s->hd, s->buffer, strlen(s->buffer))) < 0)
1435 s->buf_ptr = s->buffer;
1436 s->buf_end = s->buffer;
1439 cur_auth_type = s->proxy_auth_state.auth_type;
1441 /* Note: This uses buffering, potentially reading more than the
1442 * HTTP header. If tunneling a protocol where the server starts
1443 * the conversation, we might buffer part of that here, too.
1444 * Reading that requires using the proper ffurl_read() function
1445 * on this URLContext, not using the fd directly (as the tls
1446 * protocol does). This shouldn't be an issue for tls though,
1447 * since the client starts the conversation there, so there
1448 * is no extra data that we might buffer up here.
1450 ret = http_read_header(h, &new_loc);
1455 if (s->http_code == 407 &&
1456 (cur_auth_type == HTTP_AUTH_NONE || s->proxy_auth_state.stale) &&
1457 s->proxy_auth_state.auth_type != HTTP_AUTH_NONE && attempts < 2) {
1458 ffurl_closep(&s->hd);
1462 if (s->http_code < 400)
1464 ret = ff_http_averror(s->http_code, AVERROR(EIO));
1467 http_proxy_close(h);
1471 static int http_proxy_write(URLContext *h, const uint8_t *buf, int size)
1473 HTTPContext *s = h->priv_data;
1474 return ffurl_write(s->hd, buf, size);
1477 URLProtocol ff_httpproxy_protocol = {
1478 .name = "httpproxy",
1479 .url_open = http_proxy_open,
1480 .url_read = http_buf_read,
1481 .url_write = http_proxy_write,
1482 .url_close = http_proxy_close,
1483 .url_get_file_handle = http_get_file_handle,
1484 .priv_data_size = sizeof(HTTPContext),
1485 .flags = URL_PROTOCOL_FLAG_NETWORK,
1487 #endif /* CONFIG_HTTPPROXY_PROTOCOL */