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
22 #include "libavutil/avstring.h"
27 #include "os_support.h"
30 #include "libavutil/opt.h"
36 /* XXX: POST protocol is not completely implemented because ffmpeg uses
37 only a subset of it. */
39 /* The IO buffer size is unrelated to the max URL size in itself, but needs
40 * to be large enough to fit the full request headers (including long
43 #define BUFFER_SIZE MAX_URL_SIZE
44 #define MAX_REDIRECTS 8
49 unsigned char buffer[BUFFER_SIZE], *buf_ptr, *buf_end;
52 int64_t chunksize; /**< Used if "Transfer-Encoding: chunked" otherwise -1. */
55 int64_t off, filesize, req_end_offset;
56 int icy_data_read; ///< how much data was read since last ICY metadata packet
57 int icy_metaint; ///< after how many bytes of read data a new metadata packet will be found
59 HTTPAuthState auth_state;
60 HTTPAuthState proxy_auth_state;
62 int willclose; /**< Set if the server correctly handles Connection: close and will close the connection after feeding us the content. */
63 int seekable; /**< Control seekability, 0 = disable, 1 = enable, -1 = probe. */
65 int end_chunked_post; /**< A flag which indicates if the end of chunked encoding has been sent. */
66 int end_header; /**< A flag which indicates we have finished to read POST reply. */
67 int multiple_requests; /**< A flag which indicates if we use persistent connections. */
73 char *cookies; ///< holds newline (\n) delimited Set-Cookie header field values (without the "Set-Cookie: " field name)
75 char *icy_metadata_headers;
76 char *icy_metadata_packet;
79 z_stream inflate_stream;
80 uint8_t *inflate_buffer;
82 AVDictionary *chained_options;
86 #define OFFSET(x) offsetof(HTTPContext, x)
87 #define D AV_OPT_FLAG_DECODING_PARAM
88 #define E AV_OPT_FLAG_ENCODING_PARAM
89 #define DEFAULT_USER_AGENT "Lavf/" AV_STRINGIFY(LIBAVFORMAT_VERSION)
90 static const AVOption options[] = {
91 {"seekable", "control seekability of connection", OFFSET(seekable), AV_OPT_TYPE_INT, {.i64 = -1}, -1, 1, D },
92 {"chunked_post", "use chunked transfer-encoding for posts", OFFSET(chunked_post), AV_OPT_TYPE_INT, {.i64 = 1}, 0, 1, E },
93 {"headers", "set custom HTTP headers, can override built in default headers", OFFSET(headers), AV_OPT_TYPE_STRING, { 0 }, 0, 0, D|E },
94 {"content_type", "force a content type", OFFSET(content_type), AV_OPT_TYPE_STRING, { 0 }, 0, 0, D|E },
95 {"user-agent", "override User-Agent header", OFFSET(user_agent), AV_OPT_TYPE_STRING, {.str = DEFAULT_USER_AGENT}, 0, 0, D },
96 {"multiple_requests", "use persistent connections", OFFSET(multiple_requests), AV_OPT_TYPE_INT, {.i64 = 0}, 0, 1, D|E },
97 {"post_data", "set custom HTTP post data", OFFSET(post_data), AV_OPT_TYPE_BINARY, .flags = D|E },
98 {"mime_type", "set MIME type", OFFSET(mime_type), AV_OPT_TYPE_STRING, {0}, 0, 0, 0 },
99 {"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 },
100 {"icy", "request ICY metadata", OFFSET(icy), AV_OPT_TYPE_INT, {.i64 = 0}, 0, 1, D },
101 {"icy_metadata_headers", "return ICY metadata headers", OFFSET(icy_metadata_headers), AV_OPT_TYPE_STRING, {0}, 0, 0, 0 },
102 {"icy_metadata_packet", "return current ICY metadata packet", OFFSET(icy_metadata_packet), AV_OPT_TYPE_STRING, {0}, 0, 0, 0 },
103 {"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" },
104 {"none", "No auth method set, autodetect", 0, AV_OPT_TYPE_CONST, {.i64 = HTTP_AUTH_NONE}, 0, 0, D|E, "auth_type" },
105 {"basic", "HTTP basic authentication", 0, AV_OPT_TYPE_CONST, {.i64 = HTTP_AUTH_BASIC}, 0, 0, D|E, "auth_type" },
106 {"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 },
107 {"location", "The actual location of the data received", OFFSET(location), AV_OPT_TYPE_STRING, { 0 }, 0, 0, D|E },
108 {"offset", "initial byte offset", OFFSET(off), AV_OPT_TYPE_INT64, {.i64 = 0}, 0, INT64_MAX, D },
109 {"end_offset", "try to limit the request to bytes preceding this offset", OFFSET(req_end_offset), AV_OPT_TYPE_INT64, {.i64 = 0}, 0, INT64_MAX, D },
112 #define HTTP_CLASS(flavor)\
113 static const AVClass flavor ## _context_class = {\
114 .class_name = #flavor,\
115 .item_name = av_default_item_name,\
117 .version = LIBAVUTIL_VERSION_INT,\
123 static int http_connect(URLContext *h, const char *path, const char *local_path,
124 const char *hoststr, const char *auth,
125 const char *proxyauth, int *new_location);
127 void ff_http_init_auth_state(URLContext *dest, const URLContext *src)
129 memcpy(&((HTTPContext*)dest->priv_data)->auth_state,
130 &((HTTPContext*)src->priv_data)->auth_state, sizeof(HTTPAuthState));
131 memcpy(&((HTTPContext*)dest->priv_data)->proxy_auth_state,
132 &((HTTPContext*)src->priv_data)->proxy_auth_state,
133 sizeof(HTTPAuthState));
136 /* return non zero if error */
137 static int http_open_cnx(URLContext *h, AVDictionary **options)
139 const char *path, *proxy_path, *lower_proto = "tcp", *local_path;
140 char hostname[1024], hoststr[1024], proto[10];
141 char auth[1024], proxyauth[1024] = "";
142 char path1[MAX_URL_SIZE];
143 char buf[1024], urlbuf[MAX_URL_SIZE];
144 int port, use_proxy, err, location_changed = 0, redirects = 0, attempts = 0;
145 HTTPAuthType cur_auth_type, cur_proxy_auth_type;
146 HTTPContext *s = h->priv_data;
148 /* fill the dest addr */
150 /* needed in any case to build the host string */
151 av_url_split(proto, sizeof(proto), auth, sizeof(auth),
152 hostname, sizeof(hostname), &port,
153 path1, sizeof(path1), s->location);
154 ff_url_join(hoststr, sizeof(hoststr), NULL, NULL, hostname, port, NULL);
156 proxy_path = getenv("http_proxy");
157 use_proxy = !ff_http_match_no_proxy(getenv("no_proxy"), hostname) &&
158 proxy_path != NULL && av_strstart(proxy_path, "http://", NULL);
160 if (!strcmp(proto, "https")) {
169 if (path1[0] == '\0')
175 /* Reassemble the request URL without auth string - we don't
176 * want to leak the auth to the proxy. */
177 ff_url_join(urlbuf, sizeof(urlbuf), proto, NULL, hostname, port, "%s",
180 av_url_split(NULL, 0, proxyauth, sizeof(proxyauth),
181 hostname, sizeof(hostname), &port, NULL, 0, proxy_path);
184 ff_url_join(buf, sizeof(buf), lower_proto, NULL, hostname, port, NULL);
187 err = ffurl_open(&s->hd, buf, AVIO_FLAG_READ_WRITE,
188 &h->interrupt_callback, options);
193 cur_auth_type = s->auth_state.auth_type;
194 cur_proxy_auth_type = s->auth_state.auth_type;
195 if (http_connect(h, path, local_path, hoststr, auth, proxyauth, &location_changed) < 0)
198 if (s->http_code == 401) {
199 if ((cur_auth_type == HTTP_AUTH_NONE || s->auth_state.stale) &&
200 s->auth_state.auth_type != HTTP_AUTH_NONE && attempts < 4) {
201 ffurl_closep(&s->hd);
206 if (s->http_code == 407) {
207 if ((cur_proxy_auth_type == HTTP_AUTH_NONE || s->proxy_auth_state.stale) &&
208 s->proxy_auth_state.auth_type != HTTP_AUTH_NONE && attempts < 4) {
209 ffurl_closep(&s->hd);
214 if ((s->http_code == 301 || s->http_code == 302 || s->http_code == 303 || s->http_code == 307)
215 && location_changed == 1) {
216 /* url moved, get next */
217 ffurl_closep(&s->hd);
218 if (redirects++ >= MAX_REDIRECTS)
220 /* Restart the authentication process with the new target, which
221 * might use a different auth mechanism. */
222 memset(&s->auth_state, 0, sizeof(s->auth_state));
224 location_changed = 0;
230 ffurl_closep(&s->hd);
234 int ff_http_do_new_request(URLContext *h, const char *uri)
236 HTTPContext *s = h->priv_data;
237 AVDictionary *options = NULL;
241 s->icy_data_read = 0;
242 av_free(s->location);
243 s->location = av_strdup(uri);
245 return AVERROR(ENOMEM);
247 av_dict_copy(&options, s->chained_options, 0);
248 ret = http_open_cnx(h, &options);
249 av_dict_free(&options);
253 static int http_open(URLContext *h, const char *uri, int flags,
254 AVDictionary **options)
256 HTTPContext *s = h->priv_data;
259 if( s->seekable == 1 )
265 s->location = av_strdup(uri);
267 return AVERROR(ENOMEM);
269 av_dict_copy(&s->chained_options, *options, 0);
272 int len = strlen(s->headers);
273 if (len < 2 || strcmp("\r\n", s->headers + len - 2))
274 av_log(h, AV_LOG_WARNING, "No trailing CRLF found in HTTP header.\n");
277 ret = http_open_cnx(h, options);
279 av_dict_free(&s->chained_options);
282 static int http_getc(HTTPContext *s)
285 if (s->buf_ptr >= s->buf_end) {
286 len = ffurl_read(s->hd, s->buffer, BUFFER_SIZE);
289 } else if (len == 0) {
292 s->buf_ptr = s->buffer;
293 s->buf_end = s->buffer + len;
296 return *s->buf_ptr++;
299 static int http_get_line(HTTPContext *s, char *line, int line_size)
311 if (q > line && q[-1] == '\r')
317 if ((q - line) < line_size - 1)
323 static int process_line(URLContext *h, char *line, int line_count,
326 HTTPContext *s = h->priv_data;
330 if (line[0] == '\0') {
336 if (line_count == 0) {
337 while (!av_isspace(*p) && *p != '\0')
339 while (av_isspace(*p))
341 s->http_code = strtol(p, &end, 10);
343 av_log(h, AV_LOG_DEBUG, "http_code=%d\n", s->http_code);
345 /* error codes are 4xx and 5xx, but regard 401 as a success, so we
346 * don't abort until all headers have been parsed. */
347 if (s->http_code >= 400 && s->http_code < 600 && (s->http_code != 401
348 || s->auth_state.auth_type != HTTP_AUTH_NONE) &&
349 (s->http_code != 407 || s->proxy_auth_state.auth_type != HTTP_AUTH_NONE)) {
350 end += strspn(end, SPACE_CHARS);
351 av_log(h, AV_LOG_WARNING, "HTTP error %d %s\n",
356 while (*p != '\0' && *p != ':')
364 while (av_isspace(*p))
366 if (!av_strcasecmp(tag, "Location")) {
367 char redirected_location[MAX_URL_SIZE], *new_loc;
368 ff_make_absolute_url(redirected_location, sizeof(redirected_location),
370 new_loc = av_strdup(redirected_location);
372 return AVERROR(ENOMEM);
373 av_free(s->location);
374 s->location = new_loc;
376 } else if (!av_strcasecmp (tag, "Content-Length") && s->filesize == -1) {
377 s->filesize = strtoll(p, NULL, 10);
378 } else if (!av_strcasecmp (tag, "Content-Range")) {
379 /* "bytes $from-$to/$document_size" */
381 if (!strncmp (p, "bytes ", 6)) {
383 s->off = strtoll(p, NULL, 10);
384 if ((slash = strchr(p, '/')) && strlen(slash) > 0)
385 s->filesize = strtoll(slash+1, NULL, 10);
387 if (s->seekable == -1 && (!s->is_akamai || s->filesize != 2147483647))
388 h->is_streamed = 0; /* we _can_ in fact seek */
389 } else if (!av_strcasecmp(tag, "Accept-Ranges") && !strncmp(p, "bytes", 5) && s->seekable == -1) {
391 } else if (!av_strcasecmp (tag, "Transfer-Encoding") && !av_strncasecmp(p, "chunked", 7)) {
394 } else if (!av_strcasecmp (tag, "WWW-Authenticate")) {
395 ff_http_auth_handle_header(&s->auth_state, tag, p);
396 } else if (!av_strcasecmp (tag, "Authentication-Info")) {
397 ff_http_auth_handle_header(&s->auth_state, tag, p);
398 } else if (!av_strcasecmp (tag, "Proxy-Authenticate")) {
399 ff_http_auth_handle_header(&s->proxy_auth_state, tag, p);
400 } else if (!av_strcasecmp (tag, "Connection")) {
401 if (!strcmp(p, "close"))
403 } else if (!av_strcasecmp (tag, "Server")) {
404 if (!av_strcasecmp (p, "AkamaiGHost")) {
406 } else if (!av_strncasecmp (p, "MediaGateway", 12)) {
407 s->is_mediagateway = 1;
409 } else if (!av_strcasecmp (tag, "Content-Type")) {
410 av_free(s->mime_type); s->mime_type = av_strdup(p);
411 } else if (!av_strcasecmp (tag, "Set-Cookie")) {
413 if (!(s->cookies = av_strdup(p)))
414 return AVERROR(ENOMEM);
416 char *tmp = s->cookies;
417 size_t str_size = strlen(tmp) + strlen(p) + 2;
418 if (!(s->cookies = av_malloc(str_size))) {
420 return AVERROR(ENOMEM);
422 snprintf(s->cookies, str_size, "%s\n%s", tmp, p);
425 } else if (!av_strcasecmp (tag, "Icy-MetaInt")) {
426 s->icy_metaint = strtoll(p, NULL, 10);
427 } else if (!av_strncasecmp(tag, "Icy-", 4)) {
428 // Concat all Icy- header lines
429 char *buf = av_asprintf("%s%s: %s\n",
430 s->icy_metadata_headers ? s->icy_metadata_headers : "", tag, p);
432 return AVERROR(ENOMEM);
433 av_freep(&s->icy_metadata_headers);
434 s->icy_metadata_headers = buf;
435 } else if (!av_strcasecmp (tag, "Content-Encoding")) {
436 if (!av_strncasecmp(p, "gzip", 4) || !av_strncasecmp(p, "deflate", 7)) {
439 inflateEnd(&s->inflate_stream);
440 if (inflateInit2(&s->inflate_stream, 32 + 15) != Z_OK) {
441 av_log(h, AV_LOG_WARNING, "Error during zlib initialisation: %s\n",
442 s->inflate_stream.msg);
443 return AVERROR(ENOSYS);
445 if (zlibCompileFlags() & (1 << 17)) {
446 av_log(h, AV_LOG_WARNING, "Your zlib was compiled without gzip support.\n");
447 return AVERROR(ENOSYS);
450 av_log(h, AV_LOG_WARNING, "Compressed (%s) content, need zlib with gzip support\n", p);
451 return AVERROR(ENOSYS);
453 } else if (!av_strncasecmp(p, "identity", 8)) {
454 // The normal, no-encoding case (although servers shouldn't include
455 // the header at all if this is the case).
457 av_log(h, AV_LOG_WARNING, "Unknown content coding: %s\n", p);
465 * Create a string containing cookie values for use as a HTTP cookie header
466 * field value for a particular path and domain from the cookie values stored in
467 * the HTTP protocol context. The cookie string is stored in *cookies.
469 * @return a negative value if an error condition occurred, 0 otherwise
471 static int get_cookies(HTTPContext *s, char **cookies, const char *path,
474 // cookie strings will look like Set-Cookie header field values. Multiple
475 // Set-Cookie fields will result in multiple values delimited by a newline
477 char *next, *cookie, *set_cookies = av_strdup(s->cookies), *cset_cookies = set_cookies;
479 if (!set_cookies) return AVERROR(EINVAL);
482 while ((cookie = av_strtok(set_cookies, "\n", &next))) {
483 int domain_offset = 0;
484 char *param, *next_param, *cdomain = NULL, *cpath = NULL, *cvalue = NULL;
487 while ((param = av_strtok(cookie, "; ", &next_param))) {
489 if (!av_strncasecmp("path=", param, 5)) {
491 cpath = av_strdup(¶m[5]);
492 } else if (!av_strncasecmp("domain=", param, 7)) {
493 // if the cookie specifies a sub-domain, skip the leading dot thereby
494 // supporting URLs that point to sub-domains and the master domain
495 int leading_dot = (param[7] == '.');
497 cdomain = av_strdup(¶m[7+leading_dot]);
498 } else if (!av_strncasecmp("secure", param, 6) ||
499 !av_strncasecmp("comment", param, 7) ||
500 !av_strncasecmp("max-age", param, 7) ||
501 !av_strncasecmp("version", param, 7)) {
502 // ignore Comment, Max-Age, Secure and Version
505 cvalue = av_strdup(param);
509 cdomain = av_strdup(domain);
511 // ensure all of the necessary values are valid
512 if (!cdomain || !cpath || !cvalue) {
513 av_log(s, AV_LOG_WARNING,
514 "Invalid cookie found, no value, path or domain specified\n");
518 // check if the request path matches the cookie path
519 if (av_strncasecmp(path, cpath, strlen(cpath)))
522 // the domain should be at least the size of our cookie domain
523 domain_offset = strlen(domain) - strlen(cdomain);
524 if (domain_offset < 0)
527 // match the cookie domain
528 if (av_strcasecmp(&domain[domain_offset], cdomain))
531 // cookie parameters match, so copy the value
533 if (!(*cookies = av_strdup(cvalue))) {
534 ret = AVERROR(ENOMEM);
538 char *tmp = *cookies;
539 size_t str_size = strlen(cvalue) + strlen(*cookies) + 3;
540 if (!(*cookies = av_malloc(str_size))) {
541 ret = AVERROR(ENOMEM);
544 snprintf(*cookies, str_size, "%s; %s", tmp, cvalue);
553 if (*cookies) av_freep(cookies);
554 av_free(cset_cookies);
559 av_free(cset_cookies);
564 static inline int has_header(const char *str, const char *header)
566 /* header + 2 to skip over CRLF prefix. (make sure you have one!) */
569 return av_stristart(str, header + 2, NULL) || av_stristr(str, header);
572 static int http_read_header(URLContext *h, int *new_location)
574 HTTPContext *s = h->priv_data;
575 char line[MAX_URL_SIZE];
581 if ((err = http_get_line(s, line, sizeof(line))) < 0)
584 av_log(h, AV_LOG_DEBUG, "header='%s'\n", line);
586 err = process_line(h, line, s->line_count, new_location);
594 if (s->seekable == -1 && s->is_mediagateway && s->filesize == 2000000000)
595 h->is_streamed = 1; /* we can in fact _not_ seek */
600 static int http_connect(URLContext *h, const char *path, const char *local_path,
601 const char *hoststr, const char *auth,
602 const char *proxyauth, int *new_location)
604 HTTPContext *s = h->priv_data;
606 char headers[4096] = "";
607 char *authstr = NULL, *proxyauthstr = NULL;
608 int64_t off = s->off;
611 int send_expect_100 = 0;
614 /* send http header */
615 post = h->flags & AVIO_FLAG_WRITE;
618 /* force POST method and disable chunked encoding when
619 * custom HTTP post data is set */
624 method = post ? "POST" : "GET";
625 authstr = ff_http_auth_create_response(&s->auth_state, auth, local_path,
627 proxyauthstr = ff_http_auth_create_response(&s->proxy_auth_state, proxyauth,
629 if (post && !s->post_data) {
630 send_expect_100 = s->send_expect_100;
631 /* The user has supplied authentication but we don't know the auth type,
632 * send Expect: 100-continue to get the 401 response including the
633 * WWW-Authenticate header, or an 100 continue if no auth actually
636 s->auth_state.auth_type == HTTP_AUTH_NONE &&
641 /* set default headers if needed */
642 if (!has_header(s->headers, "\r\nUser-Agent: "))
643 len += av_strlcatf(headers + len, sizeof(headers) - len,
644 "User-Agent: %s\r\n", s->user_agent);
645 if (!has_header(s->headers, "\r\nAccept: "))
646 len += av_strlcpy(headers + len, "Accept: */*\r\n",
647 sizeof(headers) - len);
648 // Note: we send this on purpose even when s->off is 0 when we're probing,
649 // since it allows us to detect more reliably if a (non-conforming)
650 // server supports seeking by analysing the reply headers.
651 if (!has_header(s->headers, "\r\nRange: ") && !post && (s->off > 0 || s->req_end_offset || s->seekable == -1)) {
652 len += av_strlcatf(headers + len, sizeof(headers) - len,
653 "Range: bytes=%"PRId64"-", s->off);
654 if (s->req_end_offset)
655 len += av_strlcatf(headers + len, sizeof(headers) - len,
656 "%"PRId64, s->req_end_offset - 1);
657 len += av_strlcpy(headers + len, "\r\n",
658 sizeof(headers) - len);
660 if (send_expect_100 && !has_header(s->headers, "\r\nExpect: "))
661 len += av_strlcatf(headers + len, sizeof(headers) - len,
662 "Expect: 100-continue\r\n");
664 if (!has_header(s->headers, "\r\nConnection: ")) {
665 if (s->multiple_requests) {
666 len += av_strlcpy(headers + len, "Connection: keep-alive\r\n",
667 sizeof(headers) - len);
669 len += av_strlcpy(headers + len, "Connection: close\r\n",
670 sizeof(headers) - len);
674 if (!has_header(s->headers, "\r\nHost: "))
675 len += av_strlcatf(headers + len, sizeof(headers) - len,
676 "Host: %s\r\n", hoststr);
677 if (!has_header(s->headers, "\r\nContent-Length: ") && s->post_data)
678 len += av_strlcatf(headers + len, sizeof(headers) - len,
679 "Content-Length: %d\r\n", s->post_datalen);
680 if (!has_header(s->headers, "\r\nContent-Type: ") && s->content_type)
681 len += av_strlcatf(headers + len, sizeof(headers) - len,
682 "Content-Type: %s\r\n", s->content_type);
683 if (!has_header(s->headers, "\r\nCookie: ") && s->cookies) {
684 char *cookies = NULL;
685 if (!get_cookies(s, &cookies, path, hoststr)) {
686 len += av_strlcatf(headers + len, sizeof(headers) - len,
687 "Cookie: %s\r\n", cookies);
691 if (!has_header(s->headers, "\r\nIcy-MetaData: ") && s->icy) {
692 len += av_strlcatf(headers + len, sizeof(headers) - len,
693 "Icy-MetaData: %d\r\n", 1);
696 /* now add in custom headers */
698 av_strlcpy(headers + len, s->headers, sizeof(headers) - len);
700 snprintf(s->buffer, sizeof(s->buffer),
709 post && s->chunked_post ? "Transfer-Encoding: chunked\r\n" : "",
711 authstr ? authstr : "",
712 proxyauthstr ? "Proxy-" : "", proxyauthstr ? proxyauthstr : "");
715 av_freep(&proxyauthstr);
717 av_log(h, AV_LOG_DEBUG, "request: %s\n", s->buffer);
719 if ((err = ffurl_write(s->hd, s->buffer, strlen(s->buffer))) < 0)
723 if ((err = ffurl_write(s->hd, s->post_data, s->post_datalen)) < 0)
726 /* init input buffer */
727 s->buf_ptr = s->buffer;
728 s->buf_end = s->buffer;
731 s->icy_data_read = 0;
734 s->end_chunked_post = 0;
736 if (post && !s->post_data && !send_expect_100) {
737 /* Pretend that it did work. We didn't read any header yet, since
738 * we've still to send the POST data, but the code calling this
739 * function will check http_code after we return. */
744 /* wait for header */
745 err = http_read_header(h, new_location);
749 return (off == s->off) ? 0 : -1;
753 static int http_buf_read(URLContext *h, uint8_t *buf, int size)
755 HTTPContext *s = h->priv_data;
757 /* read bytes from input buffer first */
758 len = s->buf_end - s->buf_ptr;
762 memcpy(buf, s->buf_ptr, len);
765 if (!s->willclose && s->filesize >= 0 && s->off >= s->filesize)
767 len = ffurl_read(s->hd, buf, size);
771 s->icy_data_read += len;
772 if (s->chunksize > 0)
779 #define DECOMPRESS_BUF_SIZE (256 * 1024)
780 static int http_buf_read_compressed(URLContext *h, uint8_t *buf, int size)
782 HTTPContext *s = h->priv_data;
785 if (!s->inflate_buffer) {
786 s->inflate_buffer = av_malloc(DECOMPRESS_BUF_SIZE);
787 if (!s->inflate_buffer)
788 return AVERROR(ENOMEM);
791 if (s->inflate_stream.avail_in == 0) {
792 int read = http_buf_read(h, s->inflate_buffer, DECOMPRESS_BUF_SIZE);
795 s->inflate_stream.next_in = s->inflate_buffer;
796 s->inflate_stream.avail_in = read;
799 s->inflate_stream.avail_out = size;
800 s->inflate_stream.next_out = buf;
802 ret = inflate(&s->inflate_stream, Z_SYNC_FLUSH);
803 if (ret != Z_OK && ret != Z_STREAM_END)
804 av_log(h, AV_LOG_WARNING, "inflate return value: %d, %s\n", ret, s->inflate_stream.msg);
806 return size - s->inflate_stream.avail_out;
810 static int http_read(URLContext *h, uint8_t *buf, int size)
812 HTTPContext *s = h->priv_data;
813 int err, new_location;
818 if (s->end_chunked_post && !s->end_header) {
819 err = http_read_header(h, &new_location);
824 if (s->chunksize >= 0) {
830 if ((err = http_get_line(s, line, sizeof(line))) < 0)
832 } while (!*line); /* skip CR LF from last chunk */
834 s->chunksize = strtoll(line, NULL, 16);
836 av_dlog(NULL, "Chunked encoding data size: %"PRId64"'\n", s->chunksize);
843 size = FFMIN(size, s->chunksize);
845 if (s->icy_metaint > 0) {
846 int remaining = s->icy_metaint - s->icy_data_read; /* until next metadata packet */
848 // The metadata packet is variable sized. It has a 1 byte header
849 // which sets the length of the packet (divided by 16). If it's 0,
850 // the metadata doesn't change. After the packet, icy_metaint bytes
851 // of normal data follow.
852 int ch = http_getc(s);
856 char data[255 * 16 + 1];
860 for (n = 0; n < ch; n++)
861 data[n] = http_getc(s);
863 if ((ret = av_opt_set(s, "icy_metadata_packet", data, 0)) < 0)
866 s->icy_data_read = 0;
867 remaining = s->icy_metaint;
869 size = FFMIN(size, remaining);
873 return http_buf_read_compressed(h, buf, size);
875 return http_buf_read(h, buf, size);
878 /* used only when posting data */
879 static int http_write(URLContext *h, const uint8_t *buf, int size)
881 char temp[11] = ""; /* 32-bit hex + CRLF + nul */
883 char crlf[] = "\r\n";
884 HTTPContext *s = h->priv_data;
886 if (!s->chunked_post) {
887 /* non-chunked data is sent without any special encoding */
888 return ffurl_write(s->hd, buf, size);
891 /* silently ignore zero-size data since chunk encoding that would
894 /* upload data using chunked encoding */
895 snprintf(temp, sizeof(temp), "%x\r\n", size);
897 if ((ret = ffurl_write(s->hd, temp, strlen(temp))) < 0 ||
898 (ret = ffurl_write(s->hd, buf, size)) < 0 ||
899 (ret = ffurl_write(s->hd, crlf, sizeof(crlf) - 1)) < 0)
905 static int http_shutdown(URLContext *h, int flags)
908 char footer[] = "0\r\n\r\n";
909 HTTPContext *s = h->priv_data;
911 /* signal end of chunked encoding if used */
912 if ((flags & AVIO_FLAG_WRITE) && s->chunked_post) {
913 ret = ffurl_write(s->hd, footer, sizeof(footer) - 1);
914 ret = ret > 0 ? 0 : ret;
915 s->end_chunked_post = 1;
921 static int http_close(URLContext *h)
924 HTTPContext *s = h->priv_data;
927 inflateEnd(&s->inflate_stream);
928 av_freep(&s->inflate_buffer);
931 if (!s->end_chunked_post) {
932 /* Close the write direction by sending the end of chunked encoding. */
933 ret = http_shutdown(h, h->flags);
937 ffurl_closep(&s->hd);
938 av_dict_free(&s->chained_options);
942 static int64_t http_seek(URLContext *h, int64_t off, int whence)
944 HTTPContext *s = h->priv_data;
945 URLContext *old_hd = s->hd;
946 int64_t old_off = s->off;
947 uint8_t old_buf[BUFFER_SIZE];
949 AVDictionary *options = NULL;
951 if (whence == AVSEEK_SIZE)
953 else if ((whence == SEEK_CUR && off == 0) || (whence == SEEK_SET && off == s->off))
955 else if ((s->filesize == -1 && whence == SEEK_END) || h->is_streamed)
958 /* we save the old context in case the seek fails */
959 old_buf_size = s->buf_end - s->buf_ptr;
960 memcpy(old_buf, s->buf_ptr, old_buf_size);
962 if (whence == SEEK_CUR)
964 else if (whence == SEEK_END)
968 /* if it fails, continue on old connection */
969 av_dict_copy(&options, s->chained_options, 0);
970 if (http_open_cnx(h, &options) < 0) {
971 av_dict_free(&options);
972 memcpy(s->buffer, old_buf, old_buf_size);
973 s->buf_ptr = s->buffer;
974 s->buf_end = s->buffer + old_buf_size;
979 av_dict_free(&options);
985 http_get_file_handle(URLContext *h)
987 HTTPContext *s = h->priv_data;
988 return ffurl_get_file_handle(s->hd);
991 #if CONFIG_HTTP_PROTOCOL
992 URLProtocol ff_http_protocol = {
994 .url_open2 = http_open,
995 .url_read = http_read,
996 .url_write = http_write,
997 .url_seek = http_seek,
998 .url_close = http_close,
999 .url_get_file_handle = http_get_file_handle,
1000 .url_shutdown = http_shutdown,
1001 .priv_data_size = sizeof(HTTPContext),
1002 .priv_data_class = &http_context_class,
1003 .flags = URL_PROTOCOL_FLAG_NETWORK,
1006 #if CONFIG_HTTPS_PROTOCOL
1007 URLProtocol ff_https_protocol = {
1009 .url_open2 = http_open,
1010 .url_read = http_read,
1011 .url_write = http_write,
1012 .url_seek = http_seek,
1013 .url_close = http_close,
1014 .url_get_file_handle = http_get_file_handle,
1015 .url_shutdown = http_shutdown,
1016 .priv_data_size = sizeof(HTTPContext),
1017 .priv_data_class = &https_context_class,
1018 .flags = URL_PROTOCOL_FLAG_NETWORK,
1022 #if CONFIG_HTTPPROXY_PROTOCOL
1023 static int http_proxy_close(URLContext *h)
1025 HTTPContext *s = h->priv_data;
1027 ffurl_closep(&s->hd);
1031 static int http_proxy_open(URLContext *h, const char *uri, int flags)
1033 HTTPContext *s = h->priv_data;
1034 char hostname[1024], hoststr[1024];
1035 char auth[1024], pathbuf[1024], *path;
1036 char lower_url[100];
1037 int port, ret = 0, attempts = 0;
1038 HTTPAuthType cur_auth_type;
1042 if( s->seekable == 1 )
1047 av_url_split(NULL, 0, auth, sizeof(auth), hostname, sizeof(hostname), &port,
1048 pathbuf, sizeof(pathbuf), uri);
1049 ff_url_join(hoststr, sizeof(hoststr), NULL, NULL, hostname, port, NULL);
1054 ff_url_join(lower_url, sizeof(lower_url), "tcp", NULL, hostname, port,
1057 ret = ffurl_open(&s->hd, lower_url, AVIO_FLAG_READ_WRITE,
1058 &h->interrupt_callback, NULL);
1062 authstr = ff_http_auth_create_response(&s->proxy_auth_state, auth,
1064 snprintf(s->buffer, sizeof(s->buffer),
1065 "CONNECT %s HTTP/1.1\r\n"
1067 "Connection: close\r\n"
1072 authstr ? "Proxy-" : "", authstr ? authstr : "");
1075 if ((ret = ffurl_write(s->hd, s->buffer, strlen(s->buffer))) < 0)
1078 s->buf_ptr = s->buffer;
1079 s->buf_end = s->buffer;
1082 cur_auth_type = s->proxy_auth_state.auth_type;
1084 /* Note: This uses buffering, potentially reading more than the
1085 * HTTP header. If tunneling a protocol where the server starts
1086 * the conversation, we might buffer part of that here, too.
1087 * Reading that requires using the proper ffurl_read() function
1088 * on this URLContext, not using the fd directly (as the tls
1089 * protocol does). This shouldn't be an issue for tls though,
1090 * since the client starts the conversation there, so there
1091 * is no extra data that we might buffer up here.
1093 ret = http_read_header(h, &new_loc);
1098 if (s->http_code == 407 &&
1099 (cur_auth_type == HTTP_AUTH_NONE || s->proxy_auth_state.stale) &&
1100 s->proxy_auth_state.auth_type != HTTP_AUTH_NONE && attempts < 2) {
1101 ffurl_closep(&s->hd);
1105 if (s->http_code < 400)
1110 http_proxy_close(h);
1114 static int http_proxy_write(URLContext *h, const uint8_t *buf, int size)
1116 HTTPContext *s = h->priv_data;
1117 return ffurl_write(s->hd, buf, size);
1120 URLProtocol ff_httpproxy_protocol = {
1121 .name = "httpproxy",
1122 .url_open = http_proxy_open,
1123 .url_read = http_buf_read,
1124 .url_write = http_proxy_write,
1125 .url_close = http_proxy_close,
1126 .url_get_file_handle = http_get_file_handle,
1127 .priv_data_size = sizeof(HTTPContext),
1128 .flags = URL_PROTOCOL_FLAG_NETWORK,