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;
328 av_url_split(proto, sizeof(proto), NULL, 0, hostname, sizeof(hostname), &port,
330 if (!strcmp(proto, "https"))
332 ff_url_join(lower_url, sizeof(lower_url), lower_proto, NULL, hostname, port,
334 av_dict_set(options, "listen", "1", 0);
335 if ((ret = ffurl_open(&s->hd, lower_url, AVIO_FLAG_READ_WRITE,
336 &h->interrupt_callback, options)) < 0)
338 if ((ret = http_read_header(h, &new_location)) < 0)
340 if ((ret = ffurl_write(s->hd, header, strlen(header))) < 0)
345 handle_http_errors(h, ret);
346 av_dict_free(&s->chained_options);
350 static int http_open(URLContext *h, const char *uri, int flags,
351 AVDictionary **options)
353 HTTPContext *s = h->priv_data;
356 if( s->seekable == 1 )
362 s->location = av_strdup(uri);
364 return AVERROR(ENOMEM);
366 av_dict_copy(&s->chained_options, *options, 0);
369 int len = strlen(s->headers);
370 if (len < 2 || strcmp("\r\n", s->headers + len - 2))
371 av_log(h, AV_LOG_WARNING,
372 "No trailing CRLF found in HTTP header.\n");
376 return http_listen(h, uri, flags, options);
378 ret = http_open_cnx(h, options);
380 av_dict_free(&s->chained_options);
384 static int http_getc(HTTPContext *s)
387 if (s->buf_ptr >= s->buf_end) {
388 len = ffurl_read(s->hd, s->buffer, BUFFER_SIZE);
391 } else if (len == 0) {
394 s->buf_ptr = s->buffer;
395 s->buf_end = s->buffer + len;
398 return *s->buf_ptr++;
401 static int http_get_line(HTTPContext *s, char *line, int line_size)
413 if (q > line && q[-1] == '\r')
419 if ((q - line) < line_size - 1)
425 static int check_http_code(URLContext *h, int http_code, const char *end)
427 HTTPContext *s = h->priv_data;
428 /* error codes are 4xx and 5xx, but regard 401 as a success, so we
429 * don't abort until all headers have been parsed. */
430 if (http_code >= 400 && http_code < 600 &&
431 (http_code != 401 || s->auth_state.auth_type != HTTP_AUTH_NONE) &&
432 (http_code != 407 || s->proxy_auth_state.auth_type != HTTP_AUTH_NONE)) {
433 end += strspn(end, SPACE_CHARS);
434 av_log(h, AV_LOG_WARNING, "HTTP error %d %s\n", http_code, end);
435 return ff_http_averror(http_code, AVERROR(EIO));
440 static int parse_location(HTTPContext *s, const char *p)
442 char redirected_location[MAX_URL_SIZE], *new_loc;
443 ff_make_absolute_url(redirected_location, sizeof(redirected_location),
445 new_loc = av_strdup(redirected_location);
447 return AVERROR(ENOMEM);
448 av_free(s->location);
449 s->location = new_loc;
453 /* "bytes $from-$to/$document_size" */
454 static void parse_content_range(URLContext *h, const char *p)
456 HTTPContext *s = h->priv_data;
459 if (!strncmp(p, "bytes ", 6)) {
461 s->off = strtoll(p, NULL, 10);
462 if ((slash = strchr(p, '/')) && strlen(slash) > 0)
463 s->filesize = strtoll(slash + 1, NULL, 10);
465 if (s->seekable == -1 && (!s->is_akamai || s->filesize != 2147483647))
466 h->is_streamed = 0; /* we _can_ in fact seek */
469 static int parse_content_encoding(URLContext *h, const char *p)
471 if (!av_strncasecmp(p, "gzip", 4) ||
472 !av_strncasecmp(p, "deflate", 7)) {
474 HTTPContext *s = h->priv_data;
477 inflateEnd(&s->inflate_stream);
478 if (inflateInit2(&s->inflate_stream, 32 + 15) != Z_OK) {
479 av_log(h, AV_LOG_WARNING, "Error during zlib initialisation: %s\n",
480 s->inflate_stream.msg);
481 return AVERROR(ENOSYS);
483 if (zlibCompileFlags() & (1 << 17)) {
484 av_log(h, AV_LOG_WARNING,
485 "Your zlib was compiled without gzip support.\n");
486 return AVERROR(ENOSYS);
489 av_log(h, AV_LOG_WARNING,
490 "Compressed (%s) content, need zlib with gzip support\n", p);
491 return AVERROR(ENOSYS);
492 #endif /* CONFIG_ZLIB */
493 } else if (!av_strncasecmp(p, "identity", 8)) {
494 // The normal, no-encoding case (although servers shouldn't include
495 // the header at all if this is the case).
497 av_log(h, AV_LOG_WARNING, "Unknown content coding: %s\n", p);
502 // Concat all Icy- header lines
503 static int parse_icy(HTTPContext *s, const char *tag, const char *p)
505 int len = 4 + strlen(p) + strlen(tag);
506 int is_first = !s->icy_metadata_headers;
509 av_dict_set(&s->metadata, tag, p, 0);
511 if (s->icy_metadata_headers)
512 len += strlen(s->icy_metadata_headers);
514 if ((ret = av_reallocp(&s->icy_metadata_headers, len)) < 0)
518 *s->icy_metadata_headers = '\0';
520 av_strlcatf(s->icy_metadata_headers, len, "%s: %s\n", tag, p);
525 static int parse_cookie(HTTPContext *s, const char *p, AVDictionary **cookies)
529 // duplicate the cookie name (dict will dupe the value)
530 if (!(eql = strchr(p, '='))) return AVERROR(EINVAL);
531 if (!(name = av_strndup(p, eql - p))) return AVERROR(ENOMEM);
533 // add the cookie to the dictionary
534 av_dict_set(cookies, name, eql, AV_DICT_DONT_STRDUP_KEY);
539 static int cookie_string(AVDictionary *dict, char **cookies)
541 AVDictionaryEntry *e = NULL;
544 // determine how much memory is needed for the cookies string
545 while (e = av_dict_get(dict, "", e, AV_DICT_IGNORE_SUFFIX))
546 len += strlen(e->key) + strlen(e->value) + 1;
548 // reallocate the cookies
550 if (*cookies) av_free(*cookies);
551 *cookies = av_malloc(len);
552 if (!*cookies) return AVERROR(ENOMEM);
555 // write out the cookies
556 while (e = av_dict_get(dict, "", e, AV_DICT_IGNORE_SUFFIX))
557 av_strlcatf(*cookies, len, "%s%s\n", e->key, e->value);
562 static int process_line(URLContext *h, char *line, int line_count,
565 HTTPContext *s = h->priv_data;
566 const char *auto_method = h->flags & AVIO_FLAG_READ ? "POST" : "GET";
567 char *tag, *p, *end, *method, *resource, *version;
571 if (line[0] == '\0') {
577 if (line_count == 0) {
581 while (!av_isspace(*p))
584 av_log(h, AV_LOG_TRACE, "Received method: %s\n", method);
586 if (av_strcasecmp(s->method, method)) {
587 av_log(h, AV_LOG_ERROR, "Received and expected HTTP method do not match. (%s expected, %s received)\n",
589 return ff_http_averror(400, AVERROR(EIO));
592 // use autodetected HTTP method to expect
593 av_log(h, AV_LOG_TRACE, "Autodetected %s HTTP method\n", auto_method);
594 if (av_strcasecmp(auto_method, method)) {
595 av_log(h, AV_LOG_ERROR, "Received and autodetected HTTP method did not match "
596 "(%s autodetected %s received)\n", auto_method, method);
597 return ff_http_averror(400, AVERROR(EIO));
602 while (av_isspace(*p))
605 while (!av_isspace(*p))
608 av_log(h, AV_LOG_TRACE, "Requested resource: %s\n", resource);
611 while (av_isspace(*p))
614 while (!av_isspace(*p))
617 if (av_strncasecmp(version, "HTTP/", 5)) {
618 av_log(h, AV_LOG_ERROR, "Malformed HTTP version string.\n");
619 return ff_http_averror(400, AVERROR(EIO));
621 av_log(h, AV_LOG_TRACE, "HTTP version string: %s\n", version);
623 while (!av_isspace(*p) && *p != '\0')
625 while (av_isspace(*p))
627 s->http_code = strtol(p, &end, 10);
629 av_log(h, AV_LOG_TRACE, "http_code=%d\n", s->http_code);
631 if ((ret = check_http_code(h, s->http_code, end)) < 0)
635 while (*p != '\0' && *p != ':')
643 while (av_isspace(*p))
645 if (!av_strcasecmp(tag, "Location")) {
646 if ((ret = parse_location(s, p)) < 0)
649 } else if (!av_strcasecmp(tag, "Content-Length") && s->filesize == -1) {
650 s->filesize = strtoll(p, NULL, 10);
651 } else if (!av_strcasecmp(tag, "Content-Range")) {
652 parse_content_range(h, p);
653 } else if (!av_strcasecmp(tag, "Accept-Ranges") &&
654 !strncmp(p, "bytes", 5) &&
657 } else if (!av_strcasecmp(tag, "Transfer-Encoding") &&
658 !av_strncasecmp(p, "chunked", 7)) {
661 } else if (!av_strcasecmp(tag, "WWW-Authenticate")) {
662 ff_http_auth_handle_header(&s->auth_state, tag, p);
663 } else if (!av_strcasecmp(tag, "Authentication-Info")) {
664 ff_http_auth_handle_header(&s->auth_state, tag, p);
665 } else if (!av_strcasecmp(tag, "Proxy-Authenticate")) {
666 ff_http_auth_handle_header(&s->proxy_auth_state, tag, p);
667 } else if (!av_strcasecmp(tag, "Connection")) {
668 if (!strcmp(p, "close"))
670 } else if (!av_strcasecmp(tag, "Server")) {
671 if (!av_strcasecmp(p, "AkamaiGHost")) {
673 } else if (!av_strncasecmp(p, "MediaGateway", 12)) {
674 s->is_mediagateway = 1;
676 } else if (!av_strcasecmp(tag, "Content-Type")) {
677 av_free(s->mime_type);
678 s->mime_type = av_strdup(p);
679 } else if (!av_strcasecmp(tag, "Set-Cookie")) {
680 if (parse_cookie(s, p, &s->cookie_dict))
681 av_log(h, AV_LOG_WARNING, "Unable to parse '%s'\n", p);
682 } else if (!av_strcasecmp(tag, "Icy-MetaInt")) {
683 s->icy_metaint = strtoll(p, NULL, 10);
684 } else if (!av_strncasecmp(tag, "Icy-", 4)) {
685 if ((ret = parse_icy(s, tag, p)) < 0)
687 } else if (!av_strcasecmp(tag, "Content-Encoding")) {
688 if ((ret = parse_content_encoding(h, p)) < 0)
696 * Create a string containing cookie values for use as a HTTP cookie header
697 * field value for a particular path and domain from the cookie values stored in
698 * the HTTP protocol context. The cookie string is stored in *cookies.
700 * @return a negative value if an error condition occurred, 0 otherwise
702 static int get_cookies(HTTPContext *s, char **cookies, const char *path,
705 // cookie strings will look like Set-Cookie header field values. Multiple
706 // Set-Cookie fields will result in multiple values delimited by a newline
708 char *next, *cookie, *set_cookies = av_strdup(s->cookies), *cset_cookies = set_cookies;
710 if (!set_cookies) return AVERROR(EINVAL);
712 // destroy any cookies in the dictionary.
713 av_dict_free(&s->cookie_dict);
716 while ((cookie = av_strtok(set_cookies, "\n", &next))) {
717 int domain_offset = 0;
718 char *param, *next_param, *cdomain = NULL, *cpath = NULL, *cvalue = NULL;
721 // store the cookie in a dict in case it is updated in the response
722 if (parse_cookie(s, cookie, &s->cookie_dict))
723 av_log(s, AV_LOG_WARNING, "Unable to parse '%s'\n", cookie);
725 while ((param = av_strtok(cookie, "; ", &next_param))) {
727 // first key-value pair is the actual cookie value
728 cvalue = av_strdup(param);
730 } else if (!av_strncasecmp("path=", param, 5)) {
732 cpath = av_strdup(¶m[5]);
733 } else if (!av_strncasecmp("domain=", param, 7)) {
734 // if the cookie specifies a sub-domain, skip the leading dot thereby
735 // supporting URLs that point to sub-domains and the master domain
736 int leading_dot = (param[7] == '.');
738 cdomain = av_strdup(¶m[7+leading_dot]);
740 // ignore unknown attributes
744 cdomain = av_strdup(domain);
746 // ensure all of the necessary values are valid
747 if (!cdomain || !cpath || !cvalue) {
748 av_log(s, AV_LOG_WARNING,
749 "Invalid cookie found, no value, path or domain specified\n");
753 // check if the request path matches the cookie path
754 if (av_strncasecmp(path, cpath, strlen(cpath)))
757 // the domain should be at least the size of our cookie domain
758 domain_offset = strlen(domain) - strlen(cdomain);
759 if (domain_offset < 0)
762 // match the cookie domain
763 if (av_strcasecmp(&domain[domain_offset], cdomain))
766 // cookie parameters match, so copy the value
768 if (!(*cookies = av_strdup(cvalue))) {
769 ret = AVERROR(ENOMEM);
773 char *tmp = *cookies;
774 size_t str_size = strlen(cvalue) + strlen(*cookies) + 3;
775 if (!(*cookies = av_malloc(str_size))) {
776 ret = AVERROR(ENOMEM);
779 snprintf(*cookies, str_size, "%s; %s", tmp, cvalue);
788 if (*cookies) av_freep(cookies);
789 av_free(cset_cookies);
794 av_free(cset_cookies);
799 static inline int has_header(const char *str, const char *header)
801 /* header + 2 to skip over CRLF prefix. (make sure you have one!) */
804 return av_stristart(str, header + 2, NULL) || av_stristr(str, header);
807 static int http_read_header(URLContext *h, int *new_location)
809 HTTPContext *s = h->priv_data;
810 char line[MAX_URL_SIZE];
816 if ((err = http_get_line(s, line, sizeof(line))) < 0)
819 av_log(h, AV_LOG_TRACE, "header='%s'\n", line);
821 err = process_line(h, line, s->line_count, new_location);
829 if (s->seekable == -1 && s->is_mediagateway && s->filesize == 2000000000)
830 h->is_streamed = 1; /* we can in fact _not_ seek */
832 // add any new cookies into the existing cookie string
833 cookie_string(s->cookie_dict, &s->cookies);
834 av_dict_free(&s->cookie_dict);
839 static int http_connect(URLContext *h, const char *path, const char *local_path,
840 const char *hoststr, const char *auth,
841 const char *proxyauth, int *new_location)
843 HTTPContext *s = h->priv_data;
845 char headers[HTTP_HEADERS_SIZE] = "";
846 char *authstr = NULL, *proxyauthstr = NULL;
847 int64_t off = s->off;
850 int send_expect_100 = 0;
852 /* send http header */
853 post = h->flags & AVIO_FLAG_WRITE;
856 /* force POST method and disable chunked encoding when
857 * custom HTTP post data is set */
865 method = post ? "POST" : "GET";
867 authstr = ff_http_auth_create_response(&s->auth_state, auth,
869 proxyauthstr = ff_http_auth_create_response(&s->proxy_auth_state, proxyauth,
871 if (post && !s->post_data) {
872 send_expect_100 = s->send_expect_100;
873 /* The user has supplied authentication but we don't know the auth type,
874 * send Expect: 100-continue to get the 401 response including the
875 * WWW-Authenticate header, or an 100 continue if no auth actually
878 s->auth_state.auth_type == HTTP_AUTH_NONE &&
883 /* set default headers if needed */
884 if (!has_header(s->headers, "\r\nUser-Agent: "))
885 len += av_strlcatf(headers + len, sizeof(headers) - len,
886 "User-Agent: %s\r\n", s->user_agent);
887 if (!has_header(s->headers, "\r\nAccept: "))
888 len += av_strlcpy(headers + len, "Accept: */*\r\n",
889 sizeof(headers) - len);
890 // Note: we send this on purpose even when s->off is 0 when we're probing,
891 // since it allows us to detect more reliably if a (non-conforming)
892 // server supports seeking by analysing the reply headers.
893 if (!has_header(s->headers, "\r\nRange: ") && !post && (s->off > 0 || s->end_off || s->seekable == -1)) {
894 len += av_strlcatf(headers + len, sizeof(headers) - len,
895 "Range: bytes=%"PRId64"-", s->off);
897 len += av_strlcatf(headers + len, sizeof(headers) - len,
898 "%"PRId64, s->end_off - 1);
899 len += av_strlcpy(headers + len, "\r\n",
900 sizeof(headers) - len);
902 if (send_expect_100 && !has_header(s->headers, "\r\nExpect: "))
903 len += av_strlcatf(headers + len, sizeof(headers) - len,
904 "Expect: 100-continue\r\n");
906 if (!has_header(s->headers, "\r\nConnection: ")) {
907 if (s->multiple_requests)
908 len += av_strlcpy(headers + len, "Connection: keep-alive\r\n",
909 sizeof(headers) - len);
911 len += av_strlcpy(headers + len, "Connection: close\r\n",
912 sizeof(headers) - len);
915 if (!has_header(s->headers, "\r\nHost: "))
916 len += av_strlcatf(headers + len, sizeof(headers) - len,
917 "Host: %s\r\n", hoststr);
918 if (!has_header(s->headers, "\r\nContent-Length: ") && s->post_data)
919 len += av_strlcatf(headers + len, sizeof(headers) - len,
920 "Content-Length: %d\r\n", s->post_datalen);
922 if (!has_header(s->headers, "\r\nContent-Type: ") && s->content_type)
923 len += av_strlcatf(headers + len, sizeof(headers) - len,
924 "Content-Type: %s\r\n", s->content_type);
925 if (!has_header(s->headers, "\r\nCookie: ") && s->cookies) {
926 char *cookies = NULL;
927 if (!get_cookies(s, &cookies, path, hoststr) && cookies) {
928 len += av_strlcatf(headers + len, sizeof(headers) - len,
929 "Cookie: %s\r\n", cookies);
933 if (!has_header(s->headers, "\r\nIcy-MetaData: ") && s->icy)
934 len += av_strlcatf(headers + len, sizeof(headers) - len,
935 "Icy-MetaData: %d\r\n", 1);
937 /* now add in custom headers */
939 av_strlcpy(headers + len, s->headers, sizeof(headers) - len);
941 snprintf(s->buffer, sizeof(s->buffer),
950 post && s->chunked_post ? "Transfer-Encoding: chunked\r\n" : "",
952 authstr ? authstr : "",
953 proxyauthstr ? "Proxy-" : "", proxyauthstr ? proxyauthstr : "");
955 av_log(h, AV_LOG_DEBUG, "request: %s\n", s->buffer);
957 if ((err = ffurl_write(s->hd, s->buffer, strlen(s->buffer))) < 0)
961 if ((err = ffurl_write(s->hd, s->post_data, s->post_datalen)) < 0)
964 /* init input buffer */
965 s->buf_ptr = s->buffer;
966 s->buf_end = s->buffer;
969 s->icy_data_read = 0;
972 s->end_chunked_post = 0;
974 if (post && !s->post_data && !send_expect_100) {
975 /* Pretend that it did work. We didn't read any header yet, since
976 * we've still to send the POST data, but the code calling this
977 * function will check http_code after we return. */
983 /* wait for header */
984 err = http_read_header(h, new_location);
991 err = (off == s->off) ? 0 : -1;
994 av_freep(&proxyauthstr);
998 static int http_buf_read(URLContext *h, uint8_t *buf, int size)
1000 HTTPContext *s = h->priv_data;
1002 /* read bytes from input buffer first */
1003 len = s->buf_end - s->buf_ptr;
1007 memcpy(buf, s->buf_ptr, len);
1010 if ((!s->willclose || s->chunksize < 0) &&
1011 s->filesize >= 0 && s->off >= s->filesize)
1013 len = ffurl_read(s->hd, buf, size);
1014 if (!len && (!s->willclose || s->chunksize < 0) &&
1015 s->filesize >= 0 && s->off < s->filesize) {
1016 av_log(h, AV_LOG_ERROR,
1017 "Stream ends prematurely at %"PRId64", should be %"PRId64"\n",
1020 return AVERROR(EIO);
1025 if (s->chunksize > 0)
1026 s->chunksize -= len;
1032 #define DECOMPRESS_BUF_SIZE (256 * 1024)
1033 static int http_buf_read_compressed(URLContext *h, uint8_t *buf, int size)
1035 HTTPContext *s = h->priv_data;
1038 if (!s->inflate_buffer) {
1039 s->inflate_buffer = av_malloc(DECOMPRESS_BUF_SIZE);
1040 if (!s->inflate_buffer)
1041 return AVERROR(ENOMEM);
1044 if (s->inflate_stream.avail_in == 0) {
1045 int read = http_buf_read(h, s->inflate_buffer, DECOMPRESS_BUF_SIZE);
1048 s->inflate_stream.next_in = s->inflate_buffer;
1049 s->inflate_stream.avail_in = read;
1052 s->inflate_stream.avail_out = size;
1053 s->inflate_stream.next_out = buf;
1055 ret = inflate(&s->inflate_stream, Z_SYNC_FLUSH);
1056 if (ret != Z_OK && ret != Z_STREAM_END)
1057 av_log(h, AV_LOG_WARNING, "inflate return value: %d, %s\n",
1058 ret, s->inflate_stream.msg);
1060 return size - s->inflate_stream.avail_out;
1062 #endif /* CONFIG_ZLIB */
1064 static int64_t http_seek_internal(URLContext *h, int64_t off, int whence, int force_reconnect);
1066 static int http_read_stream(URLContext *h, uint8_t *buf, int size)
1068 HTTPContext *s = h->priv_data;
1069 int err, new_location, read_ret, seek_ret;
1074 if (s->end_chunked_post && !s->end_header) {
1075 err = http_read_header(h, &new_location);
1080 if (s->chunksize >= 0) {
1081 if (!s->chunksize) {
1085 if ((err = http_get_line(s, line, sizeof(line))) < 0)
1087 } while (!*line); /* skip CR LF from last chunk */
1089 s->chunksize = strtoll(line, NULL, 16);
1091 av_log(NULL, AV_LOG_TRACE, "Chunked encoding data size: %"PRId64"'\n",
1097 size = FFMIN(size, s->chunksize);
1101 return http_buf_read_compressed(h, buf, size);
1102 #endif /* CONFIG_ZLIB */
1103 read_ret = http_buf_read(h, buf, size);
1104 if (read_ret < 0 && s->reconnect && !h->is_streamed && s->filesize > 0 && s->off < s->filesize) {
1105 av_log(h, AV_LOG_INFO, "Will reconnect at %"PRId64".\n", s->off);
1106 seek_ret = http_seek_internal(h, s->off, SEEK_SET, 1);
1107 if (seek_ret != s->off) {
1108 av_log(h, AV_LOG_ERROR, "Failed to reconnect at %"PRId64".\n", s->off);
1112 read_ret = http_buf_read(h, buf, size);
1118 // Like http_read_stream(), but no short reads.
1119 // Assumes partial reads are an error.
1120 static int http_read_stream_all(URLContext *h, uint8_t *buf, int size)
1123 while (pos < size) {
1124 int len = http_read_stream(h, buf + pos, size - pos);
1132 static void update_metadata(HTTPContext *s, char *data)
1141 val = strstr(key, "='");
1144 end = strstr(val, "';");
1152 av_dict_set(&s->metadata, key, val, 0);
1158 static int store_icy(URLContext *h, int size)
1160 HTTPContext *s = h->priv_data;
1161 /* until next metadata packet */
1162 int remaining = s->icy_metaint - s->icy_data_read;
1165 return AVERROR_INVALIDDATA;
1168 /* The metadata packet is variable sized. It has a 1 byte header
1169 * which sets the length of the packet (divided by 16). If it's 0,
1170 * the metadata doesn't change. After the packet, icy_metaint bytes
1171 * of normal data follows. */
1173 int len = http_read_stream_all(h, &ch, 1);
1177 char data[255 * 16 + 1];
1180 ret = http_read_stream_all(h, data, len);
1184 if ((ret = av_opt_set(s, "icy_metadata_packet", data, 0)) < 0)
1186 update_metadata(s, data);
1188 s->icy_data_read = 0;
1189 remaining = s->icy_metaint;
1192 return FFMIN(size, remaining);
1195 static int http_read(URLContext *h, uint8_t *buf, int size)
1197 HTTPContext *s = h->priv_data;
1199 if (s->icy_metaint > 0) {
1200 size = store_icy(h, size);
1205 size = http_read_stream(h, buf, size);
1207 s->icy_data_read += size;
1211 /* used only when posting data */
1212 static int http_write(URLContext *h, const uint8_t *buf, int size)
1214 char temp[11] = ""; /* 32-bit hex + CRLF + nul */
1216 char crlf[] = "\r\n";
1217 HTTPContext *s = h->priv_data;
1219 if (!s->chunked_post) {
1220 /* non-chunked data is sent without any special encoding */
1221 return ffurl_write(s->hd, buf, size);
1224 /* silently ignore zero-size data since chunk encoding that would
1227 /* upload data using chunked encoding */
1228 snprintf(temp, sizeof(temp), "%x\r\n", size);
1230 if ((ret = ffurl_write(s->hd, temp, strlen(temp))) < 0 ||
1231 (ret = ffurl_write(s->hd, buf, size)) < 0 ||
1232 (ret = ffurl_write(s->hd, crlf, sizeof(crlf) - 1)) < 0)
1238 static int http_shutdown(URLContext *h, int flags)
1241 char footer[] = "0\r\n\r\n";
1242 HTTPContext *s = h->priv_data;
1244 /* signal end of chunked encoding if used */
1245 if ((flags & AVIO_FLAG_WRITE) && s->chunked_post) {
1246 ret = ffurl_write(s->hd, footer, sizeof(footer) - 1);
1247 ret = ret > 0 ? 0 : ret;
1248 s->end_chunked_post = 1;
1254 static int http_close(URLContext *h)
1257 HTTPContext *s = h->priv_data;
1260 inflateEnd(&s->inflate_stream);
1261 av_freep(&s->inflate_buffer);
1262 #endif /* CONFIG_ZLIB */
1264 if (!s->end_chunked_post)
1265 /* Close the write direction by sending the end of chunked encoding. */
1266 ret = http_shutdown(h, h->flags);
1269 ffurl_closep(&s->hd);
1270 av_dict_free(&s->chained_options);
1274 static int64_t http_seek_internal(URLContext *h, int64_t off, int whence, int force_reconnect)
1276 HTTPContext *s = h->priv_data;
1277 URLContext *old_hd = s->hd;
1278 int64_t old_off = s->off;
1279 uint8_t old_buf[BUFFER_SIZE];
1280 int old_buf_size, ret;
1281 AVDictionary *options = NULL;
1283 if (whence == AVSEEK_SIZE)
1285 else if (!force_reconnect &&
1286 ((whence == SEEK_CUR && off == 0) ||
1287 (whence == SEEK_SET && off == s->off)))
1289 else if ((s->filesize == -1 && whence == SEEK_END) || h->is_streamed)
1290 return AVERROR(ENOSYS);
1292 if (whence == SEEK_CUR)
1294 else if (whence == SEEK_END)
1296 else if (whence != SEEK_SET)
1297 return AVERROR(EINVAL);
1299 return AVERROR(EINVAL);
1302 /* we save the old context in case the seek fails */
1303 old_buf_size = s->buf_end - s->buf_ptr;
1304 memcpy(old_buf, s->buf_ptr, old_buf_size);
1307 /* if it fails, continue on old connection */
1308 if ((ret = http_open_cnx(h, &options)) < 0) {
1309 av_dict_free(&options);
1310 memcpy(s->buffer, old_buf, old_buf_size);
1311 s->buf_ptr = s->buffer;
1312 s->buf_end = s->buffer + old_buf_size;
1317 av_dict_free(&options);
1318 ffurl_close(old_hd);
1322 static int64_t http_seek(URLContext *h, int64_t off, int whence)
1324 return http_seek_internal(h, off, whence, 0);
1327 static int http_get_file_handle(URLContext *h)
1329 HTTPContext *s = h->priv_data;
1330 return ffurl_get_file_handle(s->hd);
1333 #define HTTP_CLASS(flavor) \
1334 static const AVClass flavor ## _context_class = { \
1335 .class_name = # flavor, \
1336 .item_name = av_default_item_name, \
1337 .option = options, \
1338 .version = LIBAVUTIL_VERSION_INT, \
1341 #if CONFIG_HTTP_PROTOCOL
1344 URLProtocol ff_http_protocol = {
1346 .url_open2 = http_open,
1347 .url_read = http_read,
1348 .url_write = http_write,
1349 .url_seek = http_seek,
1350 .url_close = http_close,
1351 .url_get_file_handle = http_get_file_handle,
1352 .url_shutdown = http_shutdown,
1353 .priv_data_size = sizeof(HTTPContext),
1354 .priv_data_class = &http_context_class,
1355 .flags = URL_PROTOCOL_FLAG_NETWORK,
1357 #endif /* CONFIG_HTTP_PROTOCOL */
1359 #if CONFIG_HTTPS_PROTOCOL
1362 URLProtocol ff_https_protocol = {
1364 .url_open2 = http_open,
1365 .url_read = http_read,
1366 .url_write = http_write,
1367 .url_seek = http_seek,
1368 .url_close = http_close,
1369 .url_get_file_handle = http_get_file_handle,
1370 .url_shutdown = http_shutdown,
1371 .priv_data_size = sizeof(HTTPContext),
1372 .priv_data_class = &https_context_class,
1373 .flags = URL_PROTOCOL_FLAG_NETWORK,
1375 #endif /* CONFIG_HTTPS_PROTOCOL */
1377 #if CONFIG_HTTPPROXY_PROTOCOL
1378 static int http_proxy_close(URLContext *h)
1380 HTTPContext *s = h->priv_data;
1382 ffurl_closep(&s->hd);
1386 static int http_proxy_open(URLContext *h, const char *uri, int flags)
1388 HTTPContext *s = h->priv_data;
1389 char hostname[1024], hoststr[1024];
1390 char auth[1024], pathbuf[1024], *path;
1391 char lower_url[100];
1392 int port, ret = 0, attempts = 0;
1393 HTTPAuthType cur_auth_type;
1397 if( s->seekable == 1 )
1402 av_url_split(NULL, 0, auth, sizeof(auth), hostname, sizeof(hostname), &port,
1403 pathbuf, sizeof(pathbuf), uri);
1404 ff_url_join(hoststr, sizeof(hoststr), NULL, NULL, hostname, port, NULL);
1409 ff_url_join(lower_url, sizeof(lower_url), "tcp", NULL, hostname, port,
1412 ret = ffurl_open(&s->hd, lower_url, AVIO_FLAG_READ_WRITE,
1413 &h->interrupt_callback, NULL);
1417 authstr = ff_http_auth_create_response(&s->proxy_auth_state, auth,
1419 snprintf(s->buffer, sizeof(s->buffer),
1420 "CONNECT %s HTTP/1.1\r\n"
1422 "Connection: close\r\n"
1427 authstr ? "Proxy-" : "", authstr ? authstr : "");
1430 if ((ret = ffurl_write(s->hd, s->buffer, strlen(s->buffer))) < 0)
1433 s->buf_ptr = s->buffer;
1434 s->buf_end = s->buffer;
1437 cur_auth_type = s->proxy_auth_state.auth_type;
1439 /* Note: This uses buffering, potentially reading more than the
1440 * HTTP header. If tunneling a protocol where the server starts
1441 * the conversation, we might buffer part of that here, too.
1442 * Reading that requires using the proper ffurl_read() function
1443 * on this URLContext, not using the fd directly (as the tls
1444 * protocol does). This shouldn't be an issue for tls though,
1445 * since the client starts the conversation there, so there
1446 * is no extra data that we might buffer up here.
1448 ret = http_read_header(h, &new_loc);
1453 if (s->http_code == 407 &&
1454 (cur_auth_type == HTTP_AUTH_NONE || s->proxy_auth_state.stale) &&
1455 s->proxy_auth_state.auth_type != HTTP_AUTH_NONE && attempts < 2) {
1456 ffurl_closep(&s->hd);
1460 if (s->http_code < 400)
1462 ret = ff_http_averror(s->http_code, AVERROR(EIO));
1465 http_proxy_close(h);
1469 static int http_proxy_write(URLContext *h, const uint8_t *buf, int size)
1471 HTTPContext *s = h->priv_data;
1472 return ffurl_write(s->hd, buf, size);
1475 URLProtocol ff_httpproxy_protocol = {
1476 .name = "httpproxy",
1477 .url_open = http_proxy_open,
1478 .url_read = http_buf_read,
1479 .url_write = http_proxy_write,
1480 .url_close = http_proxy_close,
1481 .url_get_file_handle = http_get_file_handle,
1482 .priv_data_size = sizeof(HTTPContext),
1483 .flags = URL_PROTOCOL_FLAG_NETWORK,
1485 #endif /* CONFIG_HTTPPROXY_PROTOCOL */