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;
101 #define OFFSET(x) offsetof(HTTPContext, x)
102 #define D AV_OPT_FLAG_DECODING_PARAM
103 #define E AV_OPT_FLAG_ENCODING_PARAM
104 #define DEFAULT_USER_AGENT "Lavf/" AV_STRINGIFY(LIBAVFORMAT_VERSION)
106 static const AVOption options[] = {
107 { "seekable", "control seekability of connection", OFFSET(seekable), AV_OPT_TYPE_INT, { .i64 = -1 }, -1, 1, D },
108 { "chunked_post", "use chunked transfer-encoding for posts", OFFSET(chunked_post), AV_OPT_TYPE_INT, { .i64 = 1 }, 0, 1, E },
109 { "headers", "set custom HTTP headers, can override built in default headers", OFFSET(headers), AV_OPT_TYPE_STRING, { 0 }, 0, 0, D | E },
110 { "content_type", "set a specific content type for the POST messages", OFFSET(content_type), AV_OPT_TYPE_STRING, { 0 }, 0, 0, D | E },
111 { "user_agent", "override User-Agent header", OFFSET(user_agent), AV_OPT_TYPE_STRING, { .str = DEFAULT_USER_AGENT }, 0, 0, D },
112 { "user-agent", "override User-Agent header", OFFSET(user_agent), AV_OPT_TYPE_STRING, { .str = DEFAULT_USER_AGENT }, 0, 0, D },
113 { "multiple_requests", "use persistent connections", OFFSET(multiple_requests), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 1, D | E },
114 { "post_data", "set custom HTTP post data", OFFSET(post_data), AV_OPT_TYPE_BINARY, .flags = D | E },
115 { "mime_type", "export the MIME type", OFFSET(mime_type), AV_OPT_TYPE_STRING, { 0 }, 0, 0, AV_OPT_FLAG_EXPORT | AV_OPT_FLAG_READONLY },
116 { "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 },
117 { "icy", "request ICY metadata", OFFSET(icy), AV_OPT_TYPE_INT, { .i64 = 1 }, 0, 1, D },
118 { "icy_metadata_headers", "return ICY metadata headers", OFFSET(icy_metadata_headers), AV_OPT_TYPE_STRING, { 0 }, 0, 0, AV_OPT_FLAG_EXPORT },
119 { "icy_metadata_packet", "return current ICY metadata packet", OFFSET(icy_metadata_packet), AV_OPT_TYPE_STRING, { 0 }, 0, 0, AV_OPT_FLAG_EXPORT },
120 { "metadata", "metadata read from the bitstream", OFFSET(metadata), AV_OPT_TYPE_DICT, {0}, 0, 0, AV_OPT_FLAG_EXPORT },
121 { "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"},
122 { "none", "No auth method set, autodetect", 0, AV_OPT_TYPE_CONST, { .i64 = HTTP_AUTH_NONE }, 0, 0, D | E, "auth_type"},
123 { "basic", "HTTP basic authentication", 0, AV_OPT_TYPE_CONST, { .i64 = HTTP_AUTH_BASIC }, 0, 0, D | E, "auth_type"},
124 { "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 },
125 { "location", "The actual location of the data received", OFFSET(location), AV_OPT_TYPE_STRING, { 0 }, 0, 0, D | E },
126 { "offset", "initial byte offset", OFFSET(off), AV_OPT_TYPE_INT64, { .i64 = 0 }, 0, INT64_MAX, D },
127 { "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 },
128 { "method", "Override the HTTP method", OFFSET(method), AV_OPT_TYPE_STRING, { .str = NULL }, 0, 0, E },
129 { "reconnect", "auto reconnect after disconnect before EOF", OFFSET(reconnect), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 1, D },
133 static int http_connect(URLContext *h, const char *path, const char *local_path,
134 const char *hoststr, const char *auth,
135 const char *proxyauth, int *new_location);
137 void ff_http_init_auth_state(URLContext *dest, const URLContext *src)
139 memcpy(&((HTTPContext *)dest->priv_data)->auth_state,
140 &((HTTPContext *)src->priv_data)->auth_state,
141 sizeof(HTTPAuthState));
142 memcpy(&((HTTPContext *)dest->priv_data)->proxy_auth_state,
143 &((HTTPContext *)src->priv_data)->proxy_auth_state,
144 sizeof(HTTPAuthState));
147 static int http_open_cnx_internal(URLContext *h, AVDictionary **options)
149 const char *path, *proxy_path, *lower_proto = "tcp", *local_path;
150 char hostname[1024], hoststr[1024], proto[10];
151 char auth[1024], proxyauth[1024] = "";
152 char path1[MAX_URL_SIZE];
153 char buf[1024], urlbuf[MAX_URL_SIZE];
154 int port, use_proxy, err, location_changed = 0;
155 HTTPContext *s = h->priv_data;
157 av_url_split(proto, sizeof(proto), auth, sizeof(auth),
158 hostname, sizeof(hostname), &port,
159 path1, sizeof(path1), s->location);
160 ff_url_join(hoststr, sizeof(hoststr), NULL, NULL, hostname, port, NULL);
162 proxy_path = getenv("http_proxy");
163 use_proxy = !ff_http_match_no_proxy(getenv("no_proxy"), hostname) &&
164 proxy_path && av_strstart(proxy_path, "http://", NULL);
166 if (!strcmp(proto, "https")) {
175 if (path1[0] == '\0')
181 /* Reassemble the request URL without auth string - we don't
182 * want to leak the auth to the proxy. */
183 ff_url_join(urlbuf, sizeof(urlbuf), proto, NULL, hostname, port, "%s",
186 av_url_split(NULL, 0, proxyauth, sizeof(proxyauth),
187 hostname, sizeof(hostname), &port, NULL, 0, proxy_path);
190 ff_url_join(buf, sizeof(buf), lower_proto, NULL, hostname, port, NULL);
193 err = ffurl_open(&s->hd, buf, AVIO_FLAG_READ_WRITE,
194 &h->interrupt_callback, options);
199 err = http_connect(h, path, local_path, hoststr,
200 auth, proxyauth, &location_changed);
204 return location_changed;
207 /* return non zero if error */
208 static int http_open_cnx(URLContext *h, AVDictionary **options)
210 HTTPAuthType cur_auth_type, cur_proxy_auth_type;
211 HTTPContext *s = h->priv_data;
212 int location_changed, attempts = 0, redirects = 0;
214 av_dict_copy(options, s->chained_options, 0);
216 cur_auth_type = s->auth_state.auth_type;
217 cur_proxy_auth_type = s->auth_state.auth_type;
219 location_changed = http_open_cnx_internal(h, options);
220 if (location_changed < 0)
224 if (s->http_code == 401) {
225 if ((cur_auth_type == HTTP_AUTH_NONE || s->auth_state.stale) &&
226 s->auth_state.auth_type != HTTP_AUTH_NONE && attempts < 4) {
227 ffurl_closep(&s->hd);
232 if (s->http_code == 407) {
233 if ((cur_proxy_auth_type == HTTP_AUTH_NONE || s->proxy_auth_state.stale) &&
234 s->proxy_auth_state.auth_type != HTTP_AUTH_NONE && attempts < 4) {
235 ffurl_closep(&s->hd);
240 if ((s->http_code == 301 || s->http_code == 302 ||
241 s->http_code == 303 || s->http_code == 307) &&
242 location_changed == 1) {
243 /* url moved, get next */
244 ffurl_closep(&s->hd);
245 if (redirects++ >= MAX_REDIRECTS)
247 /* Restart the authentication process with the new target, which
248 * might use a different auth mechanism. */
249 memset(&s->auth_state, 0, sizeof(s->auth_state));
251 location_changed = 0;
258 ffurl_closep(&s->hd);
259 if (location_changed < 0)
260 return location_changed;
261 return ff_http_averror(s->http_code, AVERROR(EIO));
264 int ff_http_do_new_request(URLContext *h, const char *uri)
266 HTTPContext *s = h->priv_data;
267 AVDictionary *options = NULL;
271 s->icy_data_read = 0;
272 av_free(s->location);
273 s->location = av_strdup(uri);
275 return AVERROR(ENOMEM);
277 ret = http_open_cnx(h, &options);
278 av_dict_free(&options);
282 int ff_http_averror(int status_code, int default_averror)
284 switch (status_code) {
285 case 400: return AVERROR_HTTP_BAD_REQUEST;
286 case 401: return AVERROR_HTTP_UNAUTHORIZED;
287 case 403: return AVERROR_HTTP_FORBIDDEN;
288 case 404: return AVERROR_HTTP_NOT_FOUND;
291 if (status_code >= 400 && status_code <= 499)
292 return AVERROR_HTTP_OTHER_4XX;
293 else if (status_code >= 500)
294 return AVERROR_HTTP_SERVER_ERROR;
296 return default_averror;
299 static int http_open(URLContext *h, const char *uri, int flags,
300 AVDictionary **options)
302 HTTPContext *s = h->priv_data;
305 if( s->seekable == 1 )
311 s->location = av_strdup(uri);
313 return AVERROR(ENOMEM);
315 av_dict_copy(&s->chained_options, *options, 0);
318 int len = strlen(s->headers);
319 if (len < 2 || strcmp("\r\n", s->headers + len - 2))
320 av_log(h, AV_LOG_WARNING,
321 "No trailing CRLF found in HTTP header.\n");
324 ret = http_open_cnx(h, options);
326 av_dict_free(&s->chained_options);
330 static int http_getc(HTTPContext *s)
333 if (s->buf_ptr >= s->buf_end) {
334 len = ffurl_read(s->hd, s->buffer, BUFFER_SIZE);
337 } else if (len == 0) {
340 s->buf_ptr = s->buffer;
341 s->buf_end = s->buffer + len;
344 return *s->buf_ptr++;
347 static int http_get_line(HTTPContext *s, char *line, int line_size)
359 if (q > line && q[-1] == '\r')
365 if ((q - line) < line_size - 1)
371 static int check_http_code(URLContext *h, int http_code, const char *end)
373 HTTPContext *s = h->priv_data;
374 /* error codes are 4xx and 5xx, but regard 401 as a success, so we
375 * don't abort until all headers have been parsed. */
376 if (http_code >= 400 && http_code < 600 &&
377 (http_code != 401 || s->auth_state.auth_type != HTTP_AUTH_NONE) &&
378 (http_code != 407 || s->proxy_auth_state.auth_type != HTTP_AUTH_NONE)) {
379 end += strspn(end, SPACE_CHARS);
380 av_log(h, AV_LOG_WARNING, "HTTP error %d %s\n", http_code, end);
381 return ff_http_averror(http_code, AVERROR(EIO));
386 static int parse_location(HTTPContext *s, const char *p)
388 char redirected_location[MAX_URL_SIZE], *new_loc;
389 ff_make_absolute_url(redirected_location, sizeof(redirected_location),
391 new_loc = av_strdup(redirected_location);
393 return AVERROR(ENOMEM);
394 av_free(s->location);
395 s->location = new_loc;
399 /* "bytes $from-$to/$document_size" */
400 static void parse_content_range(URLContext *h, const char *p)
402 HTTPContext *s = h->priv_data;
405 if (!strncmp(p, "bytes ", 6)) {
407 s->off = strtoll(p, NULL, 10);
408 if ((slash = strchr(p, '/')) && strlen(slash) > 0)
409 s->filesize = strtoll(slash + 1, NULL, 10);
411 if (s->seekable == -1 && (!s->is_akamai || s->filesize != 2147483647))
412 h->is_streamed = 0; /* we _can_ in fact seek */
415 static int parse_content_encoding(URLContext *h, const char *p)
417 if (!av_strncasecmp(p, "gzip", 4) ||
418 !av_strncasecmp(p, "deflate", 7)) {
420 HTTPContext *s = h->priv_data;
423 inflateEnd(&s->inflate_stream);
424 if (inflateInit2(&s->inflate_stream, 32 + 15) != Z_OK) {
425 av_log(h, AV_LOG_WARNING, "Error during zlib initialisation: %s\n",
426 s->inflate_stream.msg);
427 return AVERROR(ENOSYS);
429 if (zlibCompileFlags() & (1 << 17)) {
430 av_log(h, AV_LOG_WARNING,
431 "Your zlib was compiled without gzip support.\n");
432 return AVERROR(ENOSYS);
435 av_log(h, AV_LOG_WARNING,
436 "Compressed (%s) content, need zlib with gzip support\n", p);
437 return AVERROR(ENOSYS);
438 #endif /* CONFIG_ZLIB */
439 } else if (!av_strncasecmp(p, "identity", 8)) {
440 // The normal, no-encoding case (although servers shouldn't include
441 // the header at all if this is the case).
443 av_log(h, AV_LOG_WARNING, "Unknown content coding: %s\n", p);
448 // Concat all Icy- header lines
449 static int parse_icy(HTTPContext *s, const char *tag, const char *p)
451 int len = 4 + strlen(p) + strlen(tag);
452 int is_first = !s->icy_metadata_headers;
455 av_dict_set(&s->metadata, tag, p, 0);
457 if (s->icy_metadata_headers)
458 len += strlen(s->icy_metadata_headers);
460 if ((ret = av_reallocp(&s->icy_metadata_headers, len)) < 0)
464 *s->icy_metadata_headers = '\0';
466 av_strlcatf(s->icy_metadata_headers, len, "%s: %s\n", tag, p);
471 static int parse_cookie(HTTPContext *s, const char *p, AVDictionary **cookies)
475 // duplicate the cookie name (dict will dupe the value)
476 if (!(eql = strchr(p, '='))) return AVERROR(EINVAL);
477 if (!(name = av_strndup(p, eql - p))) return AVERROR(ENOMEM);
479 // add the cookie to the dictionary
480 av_dict_set(cookies, name, eql, AV_DICT_DONT_STRDUP_KEY);
485 static int cookie_string(AVDictionary *dict, char **cookies)
487 AVDictionaryEntry *e = NULL;
490 // determine how much memory is needed for the cookies string
491 while (e = av_dict_get(dict, "", e, AV_DICT_IGNORE_SUFFIX))
492 len += strlen(e->key) + strlen(e->value) + 1;
494 // reallocate the cookies
496 if (*cookies) av_free(*cookies);
497 *cookies = av_malloc(len);
498 if (!*cookies) return AVERROR(ENOMEM);
501 // write out the cookies
502 while (e = av_dict_get(dict, "", e, AV_DICT_IGNORE_SUFFIX))
503 av_strlcatf(*cookies, len, "%s%s\n", e->key, e->value);
508 static int process_line(URLContext *h, char *line, int line_count,
511 HTTPContext *s = h->priv_data;
516 if (line[0] == '\0') {
522 if (line_count == 0) {
523 while (!av_isspace(*p) && *p != '\0')
525 while (av_isspace(*p))
527 s->http_code = strtol(p, &end, 10);
529 av_log(h, AV_LOG_DEBUG, "http_code=%d\n", s->http_code);
531 if ((ret = check_http_code(h, s->http_code, end)) < 0)
534 while (*p != '\0' && *p != ':')
542 while (av_isspace(*p))
544 if (!av_strcasecmp(tag, "Location")) {
545 if ((ret = parse_location(s, p)) < 0)
548 } else if (!av_strcasecmp(tag, "Content-Length") && s->filesize == -1) {
549 s->filesize = strtoll(p, NULL, 10);
550 } else if (!av_strcasecmp(tag, "Content-Range")) {
551 parse_content_range(h, p);
552 } else if (!av_strcasecmp(tag, "Accept-Ranges") &&
553 !strncmp(p, "bytes", 5) &&
556 } else if (!av_strcasecmp(tag, "Transfer-Encoding") &&
557 !av_strncasecmp(p, "chunked", 7)) {
560 } else if (!av_strcasecmp(tag, "WWW-Authenticate")) {
561 ff_http_auth_handle_header(&s->auth_state, tag, p);
562 } else if (!av_strcasecmp(tag, "Authentication-Info")) {
563 ff_http_auth_handle_header(&s->auth_state, tag, p);
564 } else if (!av_strcasecmp(tag, "Proxy-Authenticate")) {
565 ff_http_auth_handle_header(&s->proxy_auth_state, tag, p);
566 } else if (!av_strcasecmp(tag, "Connection")) {
567 if (!strcmp(p, "close"))
569 } else if (!av_strcasecmp(tag, "Server")) {
570 if (!av_strcasecmp(p, "AkamaiGHost")) {
572 } else if (!av_strncasecmp(p, "MediaGateway", 12)) {
573 s->is_mediagateway = 1;
575 } else if (!av_strcasecmp(tag, "Content-Type")) {
576 av_free(s->mime_type);
577 s->mime_type = av_strdup(p);
578 } else if (!av_strcasecmp(tag, "Set-Cookie")) {
579 if (parse_cookie(s, p, &s->cookie_dict))
580 av_log(h, AV_LOG_WARNING, "Unable to parse '%s'\n", p);
581 } else if (!av_strcasecmp(tag, "Icy-MetaInt")) {
582 s->icy_metaint = strtoll(p, NULL, 10);
583 } else if (!av_strncasecmp(tag, "Icy-", 4)) {
584 if ((ret = parse_icy(s, tag, p)) < 0)
586 } else if (!av_strcasecmp(tag, "Content-Encoding")) {
587 if ((ret = parse_content_encoding(h, p)) < 0)
595 * Create a string containing cookie values for use as a HTTP cookie header
596 * field value for a particular path and domain from the cookie values stored in
597 * the HTTP protocol context. The cookie string is stored in *cookies.
599 * @return a negative value if an error condition occurred, 0 otherwise
601 static int get_cookies(HTTPContext *s, char **cookies, const char *path,
604 // cookie strings will look like Set-Cookie header field values. Multiple
605 // Set-Cookie fields will result in multiple values delimited by a newline
607 char *next, *cookie, *set_cookies = av_strdup(s->cookies), *cset_cookies = set_cookies;
609 if (!set_cookies) return AVERROR(EINVAL);
611 // destroy any cookies in the dictionary.
612 av_dict_free(&s->cookie_dict);
615 while ((cookie = av_strtok(set_cookies, "\n", &next))) {
616 int domain_offset = 0;
617 char *param, *next_param, *cdomain = NULL, *cpath = NULL, *cvalue = NULL;
620 // store the cookie in a dict in case it is updated in the response
621 if (parse_cookie(s, cookie, &s->cookie_dict))
622 av_log(s, AV_LOG_WARNING, "Unable to parse '%s'\n", cookie);
624 while ((param = av_strtok(cookie, "; ", &next_param))) {
626 // first key-value pair is the actual cookie value
627 cvalue = av_strdup(param);
629 } else if (!av_strncasecmp("path=", param, 5)) {
631 cpath = av_strdup(¶m[5]);
632 } else if (!av_strncasecmp("domain=", param, 7)) {
633 // if the cookie specifies a sub-domain, skip the leading dot thereby
634 // supporting URLs that point to sub-domains and the master domain
635 int leading_dot = (param[7] == '.');
637 cdomain = av_strdup(¶m[7+leading_dot]);
639 // ignore unknown attributes
643 cdomain = av_strdup(domain);
645 // ensure all of the necessary values are valid
646 if (!cdomain || !cpath || !cvalue) {
647 av_log(s, AV_LOG_WARNING,
648 "Invalid cookie found, no value, path or domain specified\n");
652 // check if the request path matches the cookie path
653 if (av_strncasecmp(path, cpath, strlen(cpath)))
656 // the domain should be at least the size of our cookie domain
657 domain_offset = strlen(domain) - strlen(cdomain);
658 if (domain_offset < 0)
661 // match the cookie domain
662 if (av_strcasecmp(&domain[domain_offset], cdomain))
665 // cookie parameters match, so copy the value
667 if (!(*cookies = av_strdup(cvalue))) {
668 ret = AVERROR(ENOMEM);
672 char *tmp = *cookies;
673 size_t str_size = strlen(cvalue) + strlen(*cookies) + 3;
674 if (!(*cookies = av_malloc(str_size))) {
675 ret = AVERROR(ENOMEM);
678 snprintf(*cookies, str_size, "%s; %s", tmp, cvalue);
687 if (*cookies) av_freep(cookies);
688 av_free(cset_cookies);
693 av_free(cset_cookies);
698 static inline int has_header(const char *str, const char *header)
700 /* header + 2 to skip over CRLF prefix. (make sure you have one!) */
703 return av_stristart(str, header + 2, NULL) || av_stristr(str, header);
706 static int http_read_header(URLContext *h, int *new_location)
708 HTTPContext *s = h->priv_data;
709 char line[MAX_URL_SIZE];
715 if ((err = http_get_line(s, line, sizeof(line))) < 0)
718 av_log(h, AV_LOG_DEBUG, "header='%s'\n", line);
720 err = process_line(h, line, s->line_count, new_location);
728 if (s->seekable == -1 && s->is_mediagateway && s->filesize == 2000000000)
729 h->is_streamed = 1; /* we can in fact _not_ seek */
731 // add any new cookies into the existing cookie string
732 cookie_string(s->cookie_dict, &s->cookies);
733 av_dict_free(&s->cookie_dict);
738 static int http_connect(URLContext *h, const char *path, const char *local_path,
739 const char *hoststr, const char *auth,
740 const char *proxyauth, int *new_location)
742 HTTPContext *s = h->priv_data;
744 char headers[HTTP_HEADERS_SIZE] = "";
745 char *authstr = NULL, *proxyauthstr = NULL;
746 int64_t off = s->off;
749 int send_expect_100 = 0;
751 /* send http header */
752 post = h->flags & AVIO_FLAG_WRITE;
755 /* force POST method and disable chunked encoding when
756 * custom HTTP post data is set */
764 method = post ? "POST" : "GET";
766 authstr = ff_http_auth_create_response(&s->auth_state, auth,
768 proxyauthstr = ff_http_auth_create_response(&s->proxy_auth_state, proxyauth,
770 if (post && !s->post_data) {
771 send_expect_100 = s->send_expect_100;
772 /* The user has supplied authentication but we don't know the auth type,
773 * send Expect: 100-continue to get the 401 response including the
774 * WWW-Authenticate header, or an 100 continue if no auth actually
777 s->auth_state.auth_type == HTTP_AUTH_NONE &&
782 /* set default headers if needed */
783 if (!has_header(s->headers, "\r\nUser-Agent: "))
784 len += av_strlcatf(headers + len, sizeof(headers) - len,
785 "User-Agent: %s\r\n", s->user_agent);
786 if (!has_header(s->headers, "\r\nAccept: "))
787 len += av_strlcpy(headers + len, "Accept: */*\r\n",
788 sizeof(headers) - len);
789 // Note: we send this on purpose even when s->off is 0 when we're probing,
790 // since it allows us to detect more reliably if a (non-conforming)
791 // server supports seeking by analysing the reply headers.
792 if (!has_header(s->headers, "\r\nRange: ") && !post && (s->off > 0 || s->end_off || s->seekable == -1)) {
793 len += av_strlcatf(headers + len, sizeof(headers) - len,
794 "Range: bytes=%"PRId64"-", s->off);
796 len += av_strlcatf(headers + len, sizeof(headers) - len,
797 "%"PRId64, s->end_off - 1);
798 len += av_strlcpy(headers + len, "\r\n",
799 sizeof(headers) - len);
801 if (send_expect_100 && !has_header(s->headers, "\r\nExpect: "))
802 len += av_strlcatf(headers + len, sizeof(headers) - len,
803 "Expect: 100-continue\r\n");
805 if (!has_header(s->headers, "\r\nConnection: ")) {
806 if (s->multiple_requests)
807 len += av_strlcpy(headers + len, "Connection: keep-alive\r\n",
808 sizeof(headers) - len);
810 len += av_strlcpy(headers + len, "Connection: close\r\n",
811 sizeof(headers) - len);
814 if (!has_header(s->headers, "\r\nHost: "))
815 len += av_strlcatf(headers + len, sizeof(headers) - len,
816 "Host: %s\r\n", hoststr);
817 if (!has_header(s->headers, "\r\nContent-Length: ") && s->post_data)
818 len += av_strlcatf(headers + len, sizeof(headers) - len,
819 "Content-Length: %d\r\n", s->post_datalen);
821 if (!has_header(s->headers, "\r\nContent-Type: ") && s->content_type)
822 len += av_strlcatf(headers + len, sizeof(headers) - len,
823 "Content-Type: %s\r\n", s->content_type);
824 if (!has_header(s->headers, "\r\nCookie: ") && s->cookies) {
825 char *cookies = NULL;
826 if (!get_cookies(s, &cookies, path, hoststr) && cookies) {
827 len += av_strlcatf(headers + len, sizeof(headers) - len,
828 "Cookie: %s\r\n", cookies);
832 if (!has_header(s->headers, "\r\nIcy-MetaData: ") && s->icy)
833 len += av_strlcatf(headers + len, sizeof(headers) - len,
834 "Icy-MetaData: %d\r\n", 1);
836 /* now add in custom headers */
838 av_strlcpy(headers + len, s->headers, sizeof(headers) - len);
840 snprintf(s->buffer, sizeof(s->buffer),
849 post && s->chunked_post ? "Transfer-Encoding: chunked\r\n" : "",
851 authstr ? authstr : "",
852 proxyauthstr ? "Proxy-" : "", proxyauthstr ? proxyauthstr : "");
854 av_log(h, AV_LOG_DEBUG, "request: %s\n", s->buffer);
856 if ((err = ffurl_write(s->hd, s->buffer, strlen(s->buffer))) < 0)
860 if ((err = ffurl_write(s->hd, s->post_data, s->post_datalen)) < 0)
863 /* init input buffer */
864 s->buf_ptr = s->buffer;
865 s->buf_end = s->buffer;
868 s->icy_data_read = 0;
871 s->end_chunked_post = 0;
873 if (post && !s->post_data && !send_expect_100) {
874 /* Pretend that it did work. We didn't read any header yet, since
875 * we've still to send the POST data, but the code calling this
876 * function will check http_code after we return. */
882 /* wait for header */
883 err = http_read_header(h, new_location);
887 err = (off == s->off) ? 0 : -1;
890 av_freep(&proxyauthstr);
894 static int http_buf_read(URLContext *h, uint8_t *buf, int size)
896 HTTPContext *s = h->priv_data;
898 /* read bytes from input buffer first */
899 len = s->buf_end - s->buf_ptr;
903 memcpy(buf, s->buf_ptr, len);
906 if ((!s->willclose || s->chunksize < 0) &&
907 s->filesize >= 0 && s->off >= s->filesize)
909 len = ffurl_read(s->hd, buf, size);
913 if (s->chunksize > 0)
920 #define DECOMPRESS_BUF_SIZE (256 * 1024)
921 static int http_buf_read_compressed(URLContext *h, uint8_t *buf, int size)
923 HTTPContext *s = h->priv_data;
926 if (!s->inflate_buffer) {
927 s->inflate_buffer = av_malloc(DECOMPRESS_BUF_SIZE);
928 if (!s->inflate_buffer)
929 return AVERROR(ENOMEM);
932 if (s->inflate_stream.avail_in == 0) {
933 int read = http_buf_read(h, s->inflate_buffer, DECOMPRESS_BUF_SIZE);
936 s->inflate_stream.next_in = s->inflate_buffer;
937 s->inflate_stream.avail_in = read;
940 s->inflate_stream.avail_out = size;
941 s->inflate_stream.next_out = buf;
943 ret = inflate(&s->inflate_stream, Z_SYNC_FLUSH);
944 if (ret != Z_OK && ret != Z_STREAM_END)
945 av_log(h, AV_LOG_WARNING, "inflate return value: %d, %s\n",
946 ret, s->inflate_stream.msg);
948 return size - s->inflate_stream.avail_out;
950 #endif /* CONFIG_ZLIB */
952 static int64_t http_seek_internal(URLContext *h, int64_t off, int whence, int force_reconnect);
954 static int http_read_stream(URLContext *h, uint8_t *buf, int size)
956 HTTPContext *s = h->priv_data;
957 int err, new_location, read_ret, seek_ret;
962 if (s->end_chunked_post && !s->end_header) {
963 err = http_read_header(h, &new_location);
968 if (s->chunksize >= 0) {
973 if ((err = http_get_line(s, line, sizeof(line))) < 0)
975 } while (!*line); /* skip CR LF from last chunk */
977 s->chunksize = strtoll(line, NULL, 16);
979 av_dlog(NULL, "Chunked encoding data size: %"PRId64"'\n",
985 size = FFMIN(size, s->chunksize);
989 return http_buf_read_compressed(h, buf, size);
990 #endif /* CONFIG_ZLIB */
991 read_ret = http_buf_read(h, buf, size);
992 if (read_ret < 0 && s->reconnect && !h->is_streamed && s->filesize > 0 && s->off < s->filesize) {
993 av_log(h, AV_LOG_INFO, "Will reconnect at %"PRId64".\n", s->off);
994 seek_ret = http_seek_internal(h, s->off, SEEK_SET, 1);
995 if (seek_ret != s->off) {
996 av_log(h, AV_LOG_ERROR, "Failed to reconnect at %"PRId64".\n", s->off);
1000 read_ret = http_buf_read(h, buf, size);
1006 // Like http_read_stream(), but no short reads.
1007 // Assumes partial reads are an error.
1008 static int http_read_stream_all(URLContext *h, uint8_t *buf, int size)
1011 while (pos < size) {
1012 int len = http_read_stream(h, buf + pos, size - pos);
1020 static void update_metadata(HTTPContext *s, char *data)
1029 val = strstr(key, "='");
1032 end = strstr(val, "';");
1040 av_dict_set(&s->metadata, key, val, 0);
1046 static int store_icy(URLContext *h, int size)
1048 HTTPContext *s = h->priv_data;
1049 /* until next metadata packet */
1050 int remaining = s->icy_metaint - s->icy_data_read;
1053 return AVERROR_INVALIDDATA;
1056 /* The metadata packet is variable sized. It has a 1 byte header
1057 * which sets the length of the packet (divided by 16). If it's 0,
1058 * the metadata doesn't change. After the packet, icy_metaint bytes
1059 * of normal data follows. */
1061 int len = http_read_stream_all(h, &ch, 1);
1065 char data[255 * 16 + 1];
1068 ret = http_read_stream_all(h, data, len);
1072 if ((ret = av_opt_set(s, "icy_metadata_packet", data, 0)) < 0)
1074 update_metadata(s, data);
1076 s->icy_data_read = 0;
1077 remaining = s->icy_metaint;
1080 return FFMIN(size, remaining);
1083 static int http_read(URLContext *h, uint8_t *buf, int size)
1085 HTTPContext *s = h->priv_data;
1087 if (s->icy_metaint > 0) {
1088 size = store_icy(h, size);
1093 size = http_read_stream(h, buf, size);
1095 s->icy_data_read += size;
1099 /* used only when posting data */
1100 static int http_write(URLContext *h, const uint8_t *buf, int size)
1102 char temp[11] = ""; /* 32-bit hex + CRLF + nul */
1104 char crlf[] = "\r\n";
1105 HTTPContext *s = h->priv_data;
1107 if (!s->chunked_post) {
1108 /* non-chunked data is sent without any special encoding */
1109 return ffurl_write(s->hd, buf, size);
1112 /* silently ignore zero-size data since chunk encoding that would
1115 /* upload data using chunked encoding */
1116 snprintf(temp, sizeof(temp), "%x\r\n", size);
1118 if ((ret = ffurl_write(s->hd, temp, strlen(temp))) < 0 ||
1119 (ret = ffurl_write(s->hd, buf, size)) < 0 ||
1120 (ret = ffurl_write(s->hd, crlf, sizeof(crlf) - 1)) < 0)
1126 static int http_shutdown(URLContext *h, int flags)
1129 char footer[] = "0\r\n\r\n";
1130 HTTPContext *s = h->priv_data;
1132 /* signal end of chunked encoding if used */
1133 if ((flags & AVIO_FLAG_WRITE) && s->chunked_post) {
1134 ret = ffurl_write(s->hd, footer, sizeof(footer) - 1);
1135 ret = ret > 0 ? 0 : ret;
1136 s->end_chunked_post = 1;
1142 static int http_close(URLContext *h)
1145 HTTPContext *s = h->priv_data;
1148 inflateEnd(&s->inflate_stream);
1149 av_freep(&s->inflate_buffer);
1150 #endif /* CONFIG_ZLIB */
1152 if (!s->end_chunked_post)
1153 /* Close the write direction by sending the end of chunked encoding. */
1154 ret = http_shutdown(h, h->flags);
1157 ffurl_closep(&s->hd);
1158 av_dict_free(&s->chained_options);
1162 static int64_t http_seek_internal(URLContext *h, int64_t off, int whence, int force_reconnect)
1164 HTTPContext *s = h->priv_data;
1165 URLContext *old_hd = s->hd;
1166 int64_t old_off = s->off;
1167 uint8_t old_buf[BUFFER_SIZE];
1168 int old_buf_size, ret;
1169 AVDictionary *options = NULL;
1171 if (whence == AVSEEK_SIZE)
1173 else if (!force_reconnect &&
1174 ((whence == SEEK_CUR && off == 0) ||
1175 (whence == SEEK_SET && off == s->off)))
1177 else if ((s->filesize == -1 && whence == SEEK_END) || h->is_streamed)
1178 return AVERROR(ENOSYS);
1180 if (whence == SEEK_CUR)
1182 else if (whence == SEEK_END)
1184 else if (whence != SEEK_SET)
1185 return AVERROR(EINVAL);
1187 return AVERROR(EINVAL);
1190 /* we save the old context in case the seek fails */
1191 old_buf_size = s->buf_end - s->buf_ptr;
1192 memcpy(old_buf, s->buf_ptr, old_buf_size);
1195 /* if it fails, continue on old connection */
1196 if ((ret = http_open_cnx(h, &options)) < 0) {
1197 av_dict_free(&options);
1198 memcpy(s->buffer, old_buf, old_buf_size);
1199 s->buf_ptr = s->buffer;
1200 s->buf_end = s->buffer + old_buf_size;
1205 av_dict_free(&options);
1206 ffurl_close(old_hd);
1210 static int64_t http_seek(URLContext *h, int64_t off, int whence)
1212 return http_seek_internal(h, off, whence, 0);
1215 static int http_get_file_handle(URLContext *h)
1217 HTTPContext *s = h->priv_data;
1218 return ffurl_get_file_handle(s->hd);
1221 #define HTTP_CLASS(flavor) \
1222 static const AVClass flavor ## _context_class = { \
1223 .class_name = # flavor, \
1224 .item_name = av_default_item_name, \
1225 .option = options, \
1226 .version = LIBAVUTIL_VERSION_INT, \
1229 #if CONFIG_HTTP_PROTOCOL
1232 URLProtocol ff_http_protocol = {
1234 .url_open2 = http_open,
1235 .url_read = http_read,
1236 .url_write = http_write,
1237 .url_seek = http_seek,
1238 .url_close = http_close,
1239 .url_get_file_handle = http_get_file_handle,
1240 .url_shutdown = http_shutdown,
1241 .priv_data_size = sizeof(HTTPContext),
1242 .priv_data_class = &http_context_class,
1243 .flags = URL_PROTOCOL_FLAG_NETWORK,
1245 #endif /* CONFIG_HTTP_PROTOCOL */
1247 #if CONFIG_HTTPS_PROTOCOL
1250 URLProtocol ff_https_protocol = {
1252 .url_open2 = http_open,
1253 .url_read = http_read,
1254 .url_write = http_write,
1255 .url_seek = http_seek,
1256 .url_close = http_close,
1257 .url_get_file_handle = http_get_file_handle,
1258 .url_shutdown = http_shutdown,
1259 .priv_data_size = sizeof(HTTPContext),
1260 .priv_data_class = &https_context_class,
1261 .flags = URL_PROTOCOL_FLAG_NETWORK,
1263 #endif /* CONFIG_HTTPS_PROTOCOL */
1265 #if CONFIG_HTTPPROXY_PROTOCOL
1266 static int http_proxy_close(URLContext *h)
1268 HTTPContext *s = h->priv_data;
1270 ffurl_closep(&s->hd);
1274 static int http_proxy_open(URLContext *h, const char *uri, int flags)
1276 HTTPContext *s = h->priv_data;
1277 char hostname[1024], hoststr[1024];
1278 char auth[1024], pathbuf[1024], *path;
1279 char lower_url[100];
1280 int port, ret = 0, attempts = 0;
1281 HTTPAuthType cur_auth_type;
1285 if( s->seekable == 1 )
1290 av_url_split(NULL, 0, auth, sizeof(auth), hostname, sizeof(hostname), &port,
1291 pathbuf, sizeof(pathbuf), uri);
1292 ff_url_join(hoststr, sizeof(hoststr), NULL, NULL, hostname, port, NULL);
1297 ff_url_join(lower_url, sizeof(lower_url), "tcp", NULL, hostname, port,
1300 ret = ffurl_open(&s->hd, lower_url, AVIO_FLAG_READ_WRITE,
1301 &h->interrupt_callback, NULL);
1305 authstr = ff_http_auth_create_response(&s->proxy_auth_state, auth,
1307 snprintf(s->buffer, sizeof(s->buffer),
1308 "CONNECT %s HTTP/1.1\r\n"
1310 "Connection: close\r\n"
1315 authstr ? "Proxy-" : "", authstr ? authstr : "");
1318 if ((ret = ffurl_write(s->hd, s->buffer, strlen(s->buffer))) < 0)
1321 s->buf_ptr = s->buffer;
1322 s->buf_end = s->buffer;
1325 cur_auth_type = s->proxy_auth_state.auth_type;
1327 /* Note: This uses buffering, potentially reading more than the
1328 * HTTP header. If tunneling a protocol where the server starts
1329 * the conversation, we might buffer part of that here, too.
1330 * Reading that requires using the proper ffurl_read() function
1331 * on this URLContext, not using the fd directly (as the tls
1332 * protocol does). This shouldn't be an issue for tls though,
1333 * since the client starts the conversation there, so there
1334 * is no extra data that we might buffer up here.
1336 ret = http_read_header(h, &new_loc);
1341 if (s->http_code == 407 &&
1342 (cur_auth_type == HTTP_AUTH_NONE || s->proxy_auth_state.stale) &&
1343 s->proxy_auth_state.auth_type != HTTP_AUTH_NONE && attempts < 2) {
1344 ffurl_closep(&s->hd);
1348 if (s->http_code < 400)
1350 ret = ff_http_averror(s->http_code, AVERROR(EIO));
1353 http_proxy_close(h);
1357 static int http_proxy_write(URLContext *h, const uint8_t *buf, int size)
1359 HTTPContext *s = h->priv_data;
1360 return ffurl_write(s->hd, buf, size);
1363 URLProtocol ff_httpproxy_protocol = {
1364 .name = "httpproxy",
1365 .url_open = http_proxy_open,
1366 .url_read = http_buf_read,
1367 .url_write = http_proxy_write,
1368 .url_close = http_proxy_close,
1369 .url_get_file_handle = http_get_file_handle,
1370 .priv_data_size = sizeof(HTTPContext),
1371 .flags = URL_PROTOCOL_FLAG_NETWORK,
1373 #endif /* CONFIG_HTTPPROXY_PROTOCOL */