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", OFFSET(method), AV_OPT_TYPE_STRING, { .str = NULL }, 0, 0, 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, 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);
139 void ff_http_init_auth_state(URLContext *dest, const URLContext *src)
141 memcpy(&((HTTPContext *)dest->priv_data)->auth_state,
142 &((HTTPContext *)src->priv_data)->auth_state,
143 sizeof(HTTPAuthState));
144 memcpy(&((HTTPContext *)dest->priv_data)->proxy_auth_state,
145 &((HTTPContext *)src->priv_data)->proxy_auth_state,
146 sizeof(HTTPAuthState));
149 static int http_open_cnx_internal(URLContext *h, AVDictionary **options)
151 const char *path, *proxy_path, *lower_proto = "tcp", *local_path;
152 char hostname[1024], hoststr[1024], proto[10];
153 char auth[1024], proxyauth[1024] = "";
154 char path1[MAX_URL_SIZE];
155 char buf[1024], urlbuf[MAX_URL_SIZE];
156 int port, use_proxy, err, location_changed = 0;
157 HTTPContext *s = h->priv_data;
159 av_url_split(proto, sizeof(proto), auth, sizeof(auth),
160 hostname, sizeof(hostname), &port,
161 path1, sizeof(path1), s->location);
162 ff_url_join(hoststr, sizeof(hoststr), NULL, NULL, hostname, port, NULL);
164 proxy_path = getenv("http_proxy");
165 use_proxy = !ff_http_match_no_proxy(getenv("no_proxy"), hostname) &&
166 proxy_path && av_strstart(proxy_path, "http://", NULL);
168 if (!strcmp(proto, "https")) {
177 if (path1[0] == '\0')
183 /* Reassemble the request URL without auth string - we don't
184 * want to leak the auth to the proxy. */
185 ff_url_join(urlbuf, sizeof(urlbuf), proto, NULL, hostname, port, "%s",
188 av_url_split(NULL, 0, proxyauth, sizeof(proxyauth),
189 hostname, sizeof(hostname), &port, NULL, 0, proxy_path);
192 ff_url_join(buf, sizeof(buf), lower_proto, NULL, hostname, port, NULL);
195 err = ffurl_open(&s->hd, buf, AVIO_FLAG_READ_WRITE,
196 &h->interrupt_callback, options);
201 err = http_connect(h, path, local_path, hoststr,
202 auth, proxyauth, &location_changed);
206 return location_changed;
209 /* return non zero if error */
210 static int http_open_cnx(URLContext *h, AVDictionary **options)
212 HTTPAuthType cur_auth_type, cur_proxy_auth_type;
213 HTTPContext *s = h->priv_data;
214 int location_changed, attempts = 0, redirects = 0;
216 av_dict_copy(options, s->chained_options, 0);
218 cur_auth_type = s->auth_state.auth_type;
219 cur_proxy_auth_type = s->auth_state.auth_type;
221 location_changed = http_open_cnx_internal(h, options);
222 if (location_changed < 0)
226 if (s->http_code == 401) {
227 if ((cur_auth_type == HTTP_AUTH_NONE || s->auth_state.stale) &&
228 s->auth_state.auth_type != HTTP_AUTH_NONE && attempts < 4) {
229 ffurl_closep(&s->hd);
234 if (s->http_code == 407) {
235 if ((cur_proxy_auth_type == HTTP_AUTH_NONE || s->proxy_auth_state.stale) &&
236 s->proxy_auth_state.auth_type != HTTP_AUTH_NONE && attempts < 4) {
237 ffurl_closep(&s->hd);
242 if ((s->http_code == 301 || s->http_code == 302 ||
243 s->http_code == 303 || s->http_code == 307) &&
244 location_changed == 1) {
245 /* url moved, get next */
246 ffurl_closep(&s->hd);
247 if (redirects++ >= MAX_REDIRECTS)
249 /* Restart the authentication process with the new target, which
250 * might use a different auth mechanism. */
251 memset(&s->auth_state, 0, sizeof(s->auth_state));
253 location_changed = 0;
260 ffurl_closep(&s->hd);
261 if (location_changed < 0)
262 return location_changed;
263 return ff_http_averror(s->http_code, AVERROR(EIO));
266 int ff_http_do_new_request(URLContext *h, const char *uri)
268 HTTPContext *s = h->priv_data;
269 AVDictionary *options = NULL;
273 s->icy_data_read = 0;
274 av_free(s->location);
275 s->location = av_strdup(uri);
277 return AVERROR(ENOMEM);
279 ret = http_open_cnx(h, &options);
280 av_dict_free(&options);
284 int ff_http_averror(int status_code, int default_averror)
286 switch (status_code) {
287 case 400: return AVERROR_HTTP_BAD_REQUEST;
288 case 401: return AVERROR_HTTP_UNAUTHORIZED;
289 case 403: return AVERROR_HTTP_FORBIDDEN;
290 case 404: return AVERROR_HTTP_NOT_FOUND;
293 if (status_code >= 400 && status_code <= 499)
294 return AVERROR_HTTP_OTHER_4XX;
295 else if (status_code >= 500)
296 return AVERROR_HTTP_SERVER_ERROR;
298 return default_averror;
301 static int http_listen(URLContext *h, const char *uri, int flags,
302 AVDictionary **options) {
303 HTTPContext *s = h->priv_data;
305 static const char header[] = "HTTP/1.1 200 OK\r\nContent-Type: application/octet-stream\r\nTransfer-Encoding: chunked\r\n\r\n";
309 av_url_split(NULL, 0, NULL, 0, hostname, sizeof(hostname), &port,
311 ff_url_join(lower_url, sizeof(lower_url), "tcp", NULL, hostname, port,
313 av_dict_set(options, "listen", "1", 0);
314 if (ret = ffurl_open(&s->hd, lower_url, AVIO_FLAG_READ_WRITE,
315 &h->interrupt_callback, options) < 0)
317 if (ret = ffurl_write(s->hd, header, strlen(header)) < 0)
322 av_dict_free(&s->chained_options);
326 static int http_open(URLContext *h, const char *uri, int flags,
327 AVDictionary **options)
329 HTTPContext *s = h->priv_data;
332 if( s->seekable == 1 )
338 s->location = av_strdup(uri);
340 return AVERROR(ENOMEM);
342 av_dict_copy(&s->chained_options, *options, 0);
345 int len = strlen(s->headers);
346 if (len < 2 || strcmp("\r\n", s->headers + len - 2))
347 av_log(h, AV_LOG_WARNING,
348 "No trailing CRLF found in HTTP header.\n");
352 return http_listen(h, uri, flags, options);
354 ret = http_open_cnx(h, options);
356 av_dict_free(&s->chained_options);
360 static int http_getc(HTTPContext *s)
363 if (s->buf_ptr >= s->buf_end) {
364 len = ffurl_read(s->hd, s->buffer, BUFFER_SIZE);
367 } else if (len == 0) {
370 s->buf_ptr = s->buffer;
371 s->buf_end = s->buffer + len;
374 return *s->buf_ptr++;
377 static int http_get_line(HTTPContext *s, char *line, int line_size)
389 if (q > line && q[-1] == '\r')
395 if ((q - line) < line_size - 1)
401 static int check_http_code(URLContext *h, int http_code, const char *end)
403 HTTPContext *s = h->priv_data;
404 /* error codes are 4xx and 5xx, but regard 401 as a success, so we
405 * don't abort until all headers have been parsed. */
406 if (http_code >= 400 && http_code < 600 &&
407 (http_code != 401 || s->auth_state.auth_type != HTTP_AUTH_NONE) &&
408 (http_code != 407 || s->proxy_auth_state.auth_type != HTTP_AUTH_NONE)) {
409 end += strspn(end, SPACE_CHARS);
410 av_log(h, AV_LOG_WARNING, "HTTP error %d %s\n", http_code, end);
411 return ff_http_averror(http_code, AVERROR(EIO));
416 static int parse_location(HTTPContext *s, const char *p)
418 char redirected_location[MAX_URL_SIZE], *new_loc;
419 ff_make_absolute_url(redirected_location, sizeof(redirected_location),
421 new_loc = av_strdup(redirected_location);
423 return AVERROR(ENOMEM);
424 av_free(s->location);
425 s->location = new_loc;
429 /* "bytes $from-$to/$document_size" */
430 static void parse_content_range(URLContext *h, const char *p)
432 HTTPContext *s = h->priv_data;
435 if (!strncmp(p, "bytes ", 6)) {
437 s->off = strtoll(p, NULL, 10);
438 if ((slash = strchr(p, '/')) && strlen(slash) > 0)
439 s->filesize = strtoll(slash + 1, NULL, 10);
441 if (s->seekable == -1 && (!s->is_akamai || s->filesize != 2147483647))
442 h->is_streamed = 0; /* we _can_ in fact seek */
445 static int parse_content_encoding(URLContext *h, const char *p)
447 if (!av_strncasecmp(p, "gzip", 4) ||
448 !av_strncasecmp(p, "deflate", 7)) {
450 HTTPContext *s = h->priv_data;
453 inflateEnd(&s->inflate_stream);
454 if (inflateInit2(&s->inflate_stream, 32 + 15) != Z_OK) {
455 av_log(h, AV_LOG_WARNING, "Error during zlib initialisation: %s\n",
456 s->inflate_stream.msg);
457 return AVERROR(ENOSYS);
459 if (zlibCompileFlags() & (1 << 17)) {
460 av_log(h, AV_LOG_WARNING,
461 "Your zlib was compiled without gzip support.\n");
462 return AVERROR(ENOSYS);
465 av_log(h, AV_LOG_WARNING,
466 "Compressed (%s) content, need zlib with gzip support\n", p);
467 return AVERROR(ENOSYS);
468 #endif /* CONFIG_ZLIB */
469 } else if (!av_strncasecmp(p, "identity", 8)) {
470 // The normal, no-encoding case (although servers shouldn't include
471 // the header at all if this is the case).
473 av_log(h, AV_LOG_WARNING, "Unknown content coding: %s\n", p);
478 // Concat all Icy- header lines
479 static int parse_icy(HTTPContext *s, const char *tag, const char *p)
481 int len = 4 + strlen(p) + strlen(tag);
482 int is_first = !s->icy_metadata_headers;
485 av_dict_set(&s->metadata, tag, p, 0);
487 if (s->icy_metadata_headers)
488 len += strlen(s->icy_metadata_headers);
490 if ((ret = av_reallocp(&s->icy_metadata_headers, len)) < 0)
494 *s->icy_metadata_headers = '\0';
496 av_strlcatf(s->icy_metadata_headers, len, "%s: %s\n", tag, p);
501 static int parse_cookie(HTTPContext *s, const char *p, AVDictionary **cookies)
505 // duplicate the cookie name (dict will dupe the value)
506 if (!(eql = strchr(p, '='))) return AVERROR(EINVAL);
507 if (!(name = av_strndup(p, eql - p))) return AVERROR(ENOMEM);
509 // add the cookie to the dictionary
510 av_dict_set(cookies, name, eql, AV_DICT_DONT_STRDUP_KEY);
515 static int cookie_string(AVDictionary *dict, char **cookies)
517 AVDictionaryEntry *e = NULL;
520 // determine how much memory is needed for the cookies string
521 while (e = av_dict_get(dict, "", e, AV_DICT_IGNORE_SUFFIX))
522 len += strlen(e->key) + strlen(e->value) + 1;
524 // reallocate the cookies
526 if (*cookies) av_free(*cookies);
527 *cookies = av_malloc(len);
528 if (!*cookies) return AVERROR(ENOMEM);
531 // write out the cookies
532 while (e = av_dict_get(dict, "", e, AV_DICT_IGNORE_SUFFIX))
533 av_strlcatf(*cookies, len, "%s%s\n", e->key, e->value);
538 static int process_line(URLContext *h, char *line, int line_count,
541 HTTPContext *s = h->priv_data;
546 if (line[0] == '\0') {
552 if (line_count == 0) {
553 while (!av_isspace(*p) && *p != '\0')
555 while (av_isspace(*p))
557 s->http_code = strtol(p, &end, 10);
559 av_log(h, AV_LOG_DEBUG, "http_code=%d\n", s->http_code);
561 if ((ret = check_http_code(h, s->http_code, end)) < 0)
564 while (*p != '\0' && *p != ':')
572 while (av_isspace(*p))
574 if (!av_strcasecmp(tag, "Location")) {
575 if ((ret = parse_location(s, p)) < 0)
578 } else if (!av_strcasecmp(tag, "Content-Length") && s->filesize == -1) {
579 s->filesize = strtoll(p, NULL, 10);
580 } else if (!av_strcasecmp(tag, "Content-Range")) {
581 parse_content_range(h, p);
582 } else if (!av_strcasecmp(tag, "Accept-Ranges") &&
583 !strncmp(p, "bytes", 5) &&
586 } else if (!av_strcasecmp(tag, "Transfer-Encoding") &&
587 !av_strncasecmp(p, "chunked", 7)) {
590 } else if (!av_strcasecmp(tag, "WWW-Authenticate")) {
591 ff_http_auth_handle_header(&s->auth_state, tag, p);
592 } else if (!av_strcasecmp(tag, "Authentication-Info")) {
593 ff_http_auth_handle_header(&s->auth_state, tag, p);
594 } else if (!av_strcasecmp(tag, "Proxy-Authenticate")) {
595 ff_http_auth_handle_header(&s->proxy_auth_state, tag, p);
596 } else if (!av_strcasecmp(tag, "Connection")) {
597 if (!strcmp(p, "close"))
599 } else if (!av_strcasecmp(tag, "Server")) {
600 if (!av_strcasecmp(p, "AkamaiGHost")) {
602 } else if (!av_strncasecmp(p, "MediaGateway", 12)) {
603 s->is_mediagateway = 1;
605 } else if (!av_strcasecmp(tag, "Content-Type")) {
606 av_free(s->mime_type);
607 s->mime_type = av_strdup(p);
608 } else if (!av_strcasecmp(tag, "Set-Cookie")) {
609 if (parse_cookie(s, p, &s->cookie_dict))
610 av_log(h, AV_LOG_WARNING, "Unable to parse '%s'\n", p);
611 } else if (!av_strcasecmp(tag, "Icy-MetaInt")) {
612 s->icy_metaint = strtoll(p, NULL, 10);
613 } else if (!av_strncasecmp(tag, "Icy-", 4)) {
614 if ((ret = parse_icy(s, tag, p)) < 0)
616 } else if (!av_strcasecmp(tag, "Content-Encoding")) {
617 if ((ret = parse_content_encoding(h, p)) < 0)
625 * Create a string containing cookie values for use as a HTTP cookie header
626 * field value for a particular path and domain from the cookie values stored in
627 * the HTTP protocol context. The cookie string is stored in *cookies.
629 * @return a negative value if an error condition occurred, 0 otherwise
631 static int get_cookies(HTTPContext *s, char **cookies, const char *path,
634 // cookie strings will look like Set-Cookie header field values. Multiple
635 // Set-Cookie fields will result in multiple values delimited by a newline
637 char *next, *cookie, *set_cookies = av_strdup(s->cookies), *cset_cookies = set_cookies;
639 if (!set_cookies) return AVERROR(EINVAL);
641 // destroy any cookies in the dictionary.
642 av_dict_free(&s->cookie_dict);
645 while ((cookie = av_strtok(set_cookies, "\n", &next))) {
646 int domain_offset = 0;
647 char *param, *next_param, *cdomain = NULL, *cpath = NULL, *cvalue = NULL;
650 // store the cookie in a dict in case it is updated in the response
651 if (parse_cookie(s, cookie, &s->cookie_dict))
652 av_log(s, AV_LOG_WARNING, "Unable to parse '%s'\n", cookie);
654 while ((param = av_strtok(cookie, "; ", &next_param))) {
656 // first key-value pair is the actual cookie value
657 cvalue = av_strdup(param);
659 } else if (!av_strncasecmp("path=", param, 5)) {
661 cpath = av_strdup(¶m[5]);
662 } else if (!av_strncasecmp("domain=", param, 7)) {
663 // if the cookie specifies a sub-domain, skip the leading dot thereby
664 // supporting URLs that point to sub-domains and the master domain
665 int leading_dot = (param[7] == '.');
667 cdomain = av_strdup(¶m[7+leading_dot]);
669 // ignore unknown attributes
673 cdomain = av_strdup(domain);
675 // ensure all of the necessary values are valid
676 if (!cdomain || !cpath || !cvalue) {
677 av_log(s, AV_LOG_WARNING,
678 "Invalid cookie found, no value, path or domain specified\n");
682 // check if the request path matches the cookie path
683 if (av_strncasecmp(path, cpath, strlen(cpath)))
686 // the domain should be at least the size of our cookie domain
687 domain_offset = strlen(domain) - strlen(cdomain);
688 if (domain_offset < 0)
691 // match the cookie domain
692 if (av_strcasecmp(&domain[domain_offset], cdomain))
695 // cookie parameters match, so copy the value
697 if (!(*cookies = av_strdup(cvalue))) {
698 ret = AVERROR(ENOMEM);
702 char *tmp = *cookies;
703 size_t str_size = strlen(cvalue) + strlen(*cookies) + 3;
704 if (!(*cookies = av_malloc(str_size))) {
705 ret = AVERROR(ENOMEM);
708 snprintf(*cookies, str_size, "%s; %s", tmp, cvalue);
717 if (*cookies) av_freep(cookies);
718 av_free(cset_cookies);
723 av_free(cset_cookies);
728 static inline int has_header(const char *str, const char *header)
730 /* header + 2 to skip over CRLF prefix. (make sure you have one!) */
733 return av_stristart(str, header + 2, NULL) || av_stristr(str, header);
736 static int http_read_header(URLContext *h, int *new_location)
738 HTTPContext *s = h->priv_data;
739 char line[MAX_URL_SIZE];
745 if ((err = http_get_line(s, line, sizeof(line))) < 0)
748 av_log(h, AV_LOG_DEBUG, "header='%s'\n", line);
750 err = process_line(h, line, s->line_count, new_location);
758 if (s->seekable == -1 && s->is_mediagateway && s->filesize == 2000000000)
759 h->is_streamed = 1; /* we can in fact _not_ seek */
761 // add any new cookies into the existing cookie string
762 cookie_string(s->cookie_dict, &s->cookies);
763 av_dict_free(&s->cookie_dict);
768 static int http_connect(URLContext *h, const char *path, const char *local_path,
769 const char *hoststr, const char *auth,
770 const char *proxyauth, int *new_location)
772 HTTPContext *s = h->priv_data;
774 char headers[HTTP_HEADERS_SIZE] = "";
775 char *authstr = NULL, *proxyauthstr = NULL;
776 int64_t off = s->off;
779 int send_expect_100 = 0;
781 /* send http header */
782 post = h->flags & AVIO_FLAG_WRITE;
785 /* force POST method and disable chunked encoding when
786 * custom HTTP post data is set */
794 method = post ? "POST" : "GET";
796 authstr = ff_http_auth_create_response(&s->auth_state, auth,
798 proxyauthstr = ff_http_auth_create_response(&s->proxy_auth_state, proxyauth,
800 if (post && !s->post_data) {
801 send_expect_100 = s->send_expect_100;
802 /* The user has supplied authentication but we don't know the auth type,
803 * send Expect: 100-continue to get the 401 response including the
804 * WWW-Authenticate header, or an 100 continue if no auth actually
807 s->auth_state.auth_type == HTTP_AUTH_NONE &&
812 /* set default headers if needed */
813 if (!has_header(s->headers, "\r\nUser-Agent: "))
814 len += av_strlcatf(headers + len, sizeof(headers) - len,
815 "User-Agent: %s\r\n", s->user_agent);
816 if (!has_header(s->headers, "\r\nAccept: "))
817 len += av_strlcpy(headers + len, "Accept: */*\r\n",
818 sizeof(headers) - len);
819 // Note: we send this on purpose even when s->off is 0 when we're probing,
820 // since it allows us to detect more reliably if a (non-conforming)
821 // server supports seeking by analysing the reply headers.
822 if (!has_header(s->headers, "\r\nRange: ") && !post && (s->off > 0 || s->end_off || s->seekable == -1)) {
823 len += av_strlcatf(headers + len, sizeof(headers) - len,
824 "Range: bytes=%"PRId64"-", s->off);
826 len += av_strlcatf(headers + len, sizeof(headers) - len,
827 "%"PRId64, s->end_off - 1);
828 len += av_strlcpy(headers + len, "\r\n",
829 sizeof(headers) - len);
831 if (send_expect_100 && !has_header(s->headers, "\r\nExpect: "))
832 len += av_strlcatf(headers + len, sizeof(headers) - len,
833 "Expect: 100-continue\r\n");
835 if (!has_header(s->headers, "\r\nConnection: ")) {
836 if (s->multiple_requests)
837 len += av_strlcpy(headers + len, "Connection: keep-alive\r\n",
838 sizeof(headers) - len);
840 len += av_strlcpy(headers + len, "Connection: close\r\n",
841 sizeof(headers) - len);
844 if (!has_header(s->headers, "\r\nHost: "))
845 len += av_strlcatf(headers + len, sizeof(headers) - len,
846 "Host: %s\r\n", hoststr);
847 if (!has_header(s->headers, "\r\nContent-Length: ") && s->post_data)
848 len += av_strlcatf(headers + len, sizeof(headers) - len,
849 "Content-Length: %d\r\n", s->post_datalen);
851 if (!has_header(s->headers, "\r\nContent-Type: ") && s->content_type)
852 len += av_strlcatf(headers + len, sizeof(headers) - len,
853 "Content-Type: %s\r\n", s->content_type);
854 if (!has_header(s->headers, "\r\nCookie: ") && s->cookies) {
855 char *cookies = NULL;
856 if (!get_cookies(s, &cookies, path, hoststr) && cookies) {
857 len += av_strlcatf(headers + len, sizeof(headers) - len,
858 "Cookie: %s\r\n", cookies);
862 if (!has_header(s->headers, "\r\nIcy-MetaData: ") && s->icy)
863 len += av_strlcatf(headers + len, sizeof(headers) - len,
864 "Icy-MetaData: %d\r\n", 1);
866 /* now add in custom headers */
868 av_strlcpy(headers + len, s->headers, sizeof(headers) - len);
870 snprintf(s->buffer, sizeof(s->buffer),
879 post && s->chunked_post ? "Transfer-Encoding: chunked\r\n" : "",
881 authstr ? authstr : "",
882 proxyauthstr ? "Proxy-" : "", proxyauthstr ? proxyauthstr : "");
884 av_log(h, AV_LOG_DEBUG, "request: %s\n", s->buffer);
886 if ((err = ffurl_write(s->hd, s->buffer, strlen(s->buffer))) < 0)
890 if ((err = ffurl_write(s->hd, s->post_data, s->post_datalen)) < 0)
893 /* init input buffer */
894 s->buf_ptr = s->buffer;
895 s->buf_end = s->buffer;
898 s->icy_data_read = 0;
901 s->end_chunked_post = 0;
903 if (post && !s->post_data && !send_expect_100) {
904 /* Pretend that it did work. We didn't read any header yet, since
905 * we've still to send the POST data, but the code calling this
906 * function will check http_code after we return. */
912 /* wait for header */
913 err = http_read_header(h, new_location);
917 err = (off == s->off) ? 0 : -1;
920 av_freep(&proxyauthstr);
924 static int http_buf_read(URLContext *h, uint8_t *buf, int size)
926 HTTPContext *s = h->priv_data;
928 /* read bytes from input buffer first */
929 len = s->buf_end - s->buf_ptr;
933 memcpy(buf, s->buf_ptr, len);
936 if ((!s->willclose || s->chunksize < 0) &&
937 s->filesize >= 0 && s->off >= s->filesize)
939 len = ffurl_read(s->hd, buf, size);
943 if (s->chunksize > 0)
950 #define DECOMPRESS_BUF_SIZE (256 * 1024)
951 static int http_buf_read_compressed(URLContext *h, uint8_t *buf, int size)
953 HTTPContext *s = h->priv_data;
956 if (!s->inflate_buffer) {
957 s->inflate_buffer = av_malloc(DECOMPRESS_BUF_SIZE);
958 if (!s->inflate_buffer)
959 return AVERROR(ENOMEM);
962 if (s->inflate_stream.avail_in == 0) {
963 int read = http_buf_read(h, s->inflate_buffer, DECOMPRESS_BUF_SIZE);
966 s->inflate_stream.next_in = s->inflate_buffer;
967 s->inflate_stream.avail_in = read;
970 s->inflate_stream.avail_out = size;
971 s->inflate_stream.next_out = buf;
973 ret = inflate(&s->inflate_stream, Z_SYNC_FLUSH);
974 if (ret != Z_OK && ret != Z_STREAM_END)
975 av_log(h, AV_LOG_WARNING, "inflate return value: %d, %s\n",
976 ret, s->inflate_stream.msg);
978 return size - s->inflate_stream.avail_out;
980 #endif /* CONFIG_ZLIB */
982 static int64_t http_seek_internal(URLContext *h, int64_t off, int whence, int force_reconnect);
984 static int http_read_stream(URLContext *h, uint8_t *buf, int size)
986 HTTPContext *s = h->priv_data;
987 int err, new_location, read_ret, seek_ret;
992 if (s->end_chunked_post && !s->end_header) {
993 err = http_read_header(h, &new_location);
998 if (s->chunksize >= 0) {
1003 if ((err = http_get_line(s, line, sizeof(line))) < 0)
1005 } while (!*line); /* skip CR LF from last chunk */
1007 s->chunksize = strtoll(line, NULL, 16);
1009 av_dlog(NULL, "Chunked encoding data size: %"PRId64"'\n",
1015 size = FFMIN(size, s->chunksize);
1019 return http_buf_read_compressed(h, buf, size);
1020 #endif /* CONFIG_ZLIB */
1021 read_ret = http_buf_read(h, buf, size);
1022 if (read_ret < 0 && s->reconnect && !h->is_streamed && s->filesize > 0 && s->off < s->filesize) {
1023 av_log(h, AV_LOG_INFO, "Will reconnect at %"PRId64".\n", s->off);
1024 seek_ret = http_seek_internal(h, s->off, SEEK_SET, 1);
1025 if (seek_ret != s->off) {
1026 av_log(h, AV_LOG_ERROR, "Failed to reconnect at %"PRId64".\n", s->off);
1030 read_ret = http_buf_read(h, buf, size);
1036 // Like http_read_stream(), but no short reads.
1037 // Assumes partial reads are an error.
1038 static int http_read_stream_all(URLContext *h, uint8_t *buf, int size)
1041 while (pos < size) {
1042 int len = http_read_stream(h, buf + pos, size - pos);
1050 static void update_metadata(HTTPContext *s, char *data)
1059 val = strstr(key, "='");
1062 end = strstr(val, "';");
1070 av_dict_set(&s->metadata, key, val, 0);
1076 static int store_icy(URLContext *h, int size)
1078 HTTPContext *s = h->priv_data;
1079 /* until next metadata packet */
1080 int remaining = s->icy_metaint - s->icy_data_read;
1083 return AVERROR_INVALIDDATA;
1086 /* The metadata packet is variable sized. It has a 1 byte header
1087 * which sets the length of the packet (divided by 16). If it's 0,
1088 * the metadata doesn't change. After the packet, icy_metaint bytes
1089 * of normal data follows. */
1091 int len = http_read_stream_all(h, &ch, 1);
1095 char data[255 * 16 + 1];
1098 ret = http_read_stream_all(h, data, len);
1102 if ((ret = av_opt_set(s, "icy_metadata_packet", data, 0)) < 0)
1104 update_metadata(s, data);
1106 s->icy_data_read = 0;
1107 remaining = s->icy_metaint;
1110 return FFMIN(size, remaining);
1113 static int http_read(URLContext *h, uint8_t *buf, int size)
1115 HTTPContext *s = h->priv_data;
1117 if (s->icy_metaint > 0) {
1118 size = store_icy(h, size);
1123 size = http_read_stream(h, buf, size);
1125 s->icy_data_read += size;
1129 /* used only when posting data */
1130 static int http_write(URLContext *h, const uint8_t *buf, int size)
1132 char temp[11] = ""; /* 32-bit hex + CRLF + nul */
1134 char crlf[] = "\r\n";
1135 HTTPContext *s = h->priv_data;
1137 if (!s->chunked_post) {
1138 /* non-chunked data is sent without any special encoding */
1139 return ffurl_write(s->hd, buf, size);
1142 /* silently ignore zero-size data since chunk encoding that would
1145 /* upload data using chunked encoding */
1146 snprintf(temp, sizeof(temp), "%x\r\n", size);
1148 if ((ret = ffurl_write(s->hd, temp, strlen(temp))) < 0 ||
1149 (ret = ffurl_write(s->hd, buf, size)) < 0 ||
1150 (ret = ffurl_write(s->hd, crlf, sizeof(crlf) - 1)) < 0)
1156 static int http_shutdown(URLContext *h, int flags)
1159 char footer[] = "0\r\n\r\n";
1160 HTTPContext *s = h->priv_data;
1162 /* signal end of chunked encoding if used */
1163 if ((flags & AVIO_FLAG_WRITE) && s->chunked_post) {
1164 ret = ffurl_write(s->hd, footer, sizeof(footer) - 1);
1165 ret = ret > 0 ? 0 : ret;
1166 s->end_chunked_post = 1;
1172 static int http_close(URLContext *h)
1175 HTTPContext *s = h->priv_data;
1178 inflateEnd(&s->inflate_stream);
1179 av_freep(&s->inflate_buffer);
1180 #endif /* CONFIG_ZLIB */
1182 if (!s->end_chunked_post)
1183 /* Close the write direction by sending the end of chunked encoding. */
1184 ret = http_shutdown(h, h->flags);
1187 ffurl_closep(&s->hd);
1188 av_dict_free(&s->chained_options);
1192 static int64_t http_seek_internal(URLContext *h, int64_t off, int whence, int force_reconnect)
1194 HTTPContext *s = h->priv_data;
1195 URLContext *old_hd = s->hd;
1196 int64_t old_off = s->off;
1197 uint8_t old_buf[BUFFER_SIZE];
1198 int old_buf_size, ret;
1199 AVDictionary *options = NULL;
1201 if (whence == AVSEEK_SIZE)
1203 else if (!force_reconnect &&
1204 ((whence == SEEK_CUR && off == 0) ||
1205 (whence == SEEK_SET && off == s->off)))
1207 else if ((s->filesize == -1 && whence == SEEK_END) || h->is_streamed)
1208 return AVERROR(ENOSYS);
1210 if (whence == SEEK_CUR)
1212 else if (whence == SEEK_END)
1214 else if (whence != SEEK_SET)
1215 return AVERROR(EINVAL);
1217 return AVERROR(EINVAL);
1220 /* we save the old context in case the seek fails */
1221 old_buf_size = s->buf_end - s->buf_ptr;
1222 memcpy(old_buf, s->buf_ptr, old_buf_size);
1225 /* if it fails, continue on old connection */
1226 if ((ret = http_open_cnx(h, &options)) < 0) {
1227 av_dict_free(&options);
1228 memcpy(s->buffer, old_buf, old_buf_size);
1229 s->buf_ptr = s->buffer;
1230 s->buf_end = s->buffer + old_buf_size;
1235 av_dict_free(&options);
1236 ffurl_close(old_hd);
1240 static int64_t http_seek(URLContext *h, int64_t off, int whence)
1242 return http_seek_internal(h, off, whence, 0);
1245 static int http_get_file_handle(URLContext *h)
1247 HTTPContext *s = h->priv_data;
1248 return ffurl_get_file_handle(s->hd);
1251 #define HTTP_CLASS(flavor) \
1252 static const AVClass flavor ## _context_class = { \
1253 .class_name = # flavor, \
1254 .item_name = av_default_item_name, \
1255 .option = options, \
1256 .version = LIBAVUTIL_VERSION_INT, \
1259 #if CONFIG_HTTP_PROTOCOL
1262 URLProtocol ff_http_protocol = {
1264 .url_open2 = http_open,
1265 .url_read = http_read,
1266 .url_write = http_write,
1267 .url_seek = http_seek,
1268 .url_close = http_close,
1269 .url_get_file_handle = http_get_file_handle,
1270 .url_shutdown = http_shutdown,
1271 .priv_data_size = sizeof(HTTPContext),
1272 .priv_data_class = &http_context_class,
1273 .flags = URL_PROTOCOL_FLAG_NETWORK,
1275 #endif /* CONFIG_HTTP_PROTOCOL */
1277 #if CONFIG_HTTPS_PROTOCOL
1280 URLProtocol ff_https_protocol = {
1282 .url_open2 = http_open,
1283 .url_read = http_read,
1284 .url_write = http_write,
1285 .url_seek = http_seek,
1286 .url_close = http_close,
1287 .url_get_file_handle = http_get_file_handle,
1288 .url_shutdown = http_shutdown,
1289 .priv_data_size = sizeof(HTTPContext),
1290 .priv_data_class = &https_context_class,
1291 .flags = URL_PROTOCOL_FLAG_NETWORK,
1293 #endif /* CONFIG_HTTPS_PROTOCOL */
1295 #if CONFIG_HTTPPROXY_PROTOCOL
1296 static int http_proxy_close(URLContext *h)
1298 HTTPContext *s = h->priv_data;
1300 ffurl_closep(&s->hd);
1304 static int http_proxy_open(URLContext *h, const char *uri, int flags)
1306 HTTPContext *s = h->priv_data;
1307 char hostname[1024], hoststr[1024];
1308 char auth[1024], pathbuf[1024], *path;
1309 char lower_url[100];
1310 int port, ret = 0, attempts = 0;
1311 HTTPAuthType cur_auth_type;
1315 if( s->seekable == 1 )
1320 av_url_split(NULL, 0, auth, sizeof(auth), hostname, sizeof(hostname), &port,
1321 pathbuf, sizeof(pathbuf), uri);
1322 ff_url_join(hoststr, sizeof(hoststr), NULL, NULL, hostname, port, NULL);
1327 ff_url_join(lower_url, sizeof(lower_url), "tcp", NULL, hostname, port,
1330 ret = ffurl_open(&s->hd, lower_url, AVIO_FLAG_READ_WRITE,
1331 &h->interrupt_callback, NULL);
1335 authstr = ff_http_auth_create_response(&s->proxy_auth_state, auth,
1337 snprintf(s->buffer, sizeof(s->buffer),
1338 "CONNECT %s HTTP/1.1\r\n"
1340 "Connection: close\r\n"
1345 authstr ? "Proxy-" : "", authstr ? authstr : "");
1348 if ((ret = ffurl_write(s->hd, s->buffer, strlen(s->buffer))) < 0)
1351 s->buf_ptr = s->buffer;
1352 s->buf_end = s->buffer;
1355 cur_auth_type = s->proxy_auth_state.auth_type;
1357 /* Note: This uses buffering, potentially reading more than the
1358 * HTTP header. If tunneling a protocol where the server starts
1359 * the conversation, we might buffer part of that here, too.
1360 * Reading that requires using the proper ffurl_read() function
1361 * on this URLContext, not using the fd directly (as the tls
1362 * protocol does). This shouldn't be an issue for tls though,
1363 * since the client starts the conversation there, so there
1364 * is no extra data that we might buffer up here.
1366 ret = http_read_header(h, &new_loc);
1371 if (s->http_code == 407 &&
1372 (cur_auth_type == HTTP_AUTH_NONE || s->proxy_auth_state.stale) &&
1373 s->proxy_auth_state.auth_type != HTTP_AUTH_NONE && attempts < 2) {
1374 ffurl_closep(&s->hd);
1378 if (s->http_code < 400)
1380 ret = ff_http_averror(s->http_code, AVERROR(EIO));
1383 http_proxy_close(h);
1387 static int http_proxy_write(URLContext *h, const uint8_t *buf, int size)
1389 HTTPContext *s = h->priv_data;
1390 return ffurl_write(s->hd, buf, size);
1393 URLProtocol ff_httpproxy_protocol = {
1394 .name = "httpproxy",
1395 .url_open = http_proxy_open,
1396 .url_read = http_buf_read,
1397 .url_write = http_proxy_write,
1398 .url_close = http_proxy_close,
1399 .url_get_file_handle = http_get_file_handle,
1400 .priv_data_size = sizeof(HTTPContext),
1401 .flags = URL_PROTOCOL_FLAG_NETWORK,
1403 #endif /* CONFIG_HTTPPROXY_PROTOCOL */