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;
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 },
110 #define HTTP_CLASS(flavor)\
111 static const AVClass flavor ## _context_class = {\
112 .class_name = #flavor,\
113 .item_name = av_default_item_name,\
115 .version = LIBAVUTIL_VERSION_INT,\
121 static int http_connect(URLContext *h, const char *path, const char *local_path,
122 const char *hoststr, const char *auth,
123 const char *proxyauth, int *new_location);
125 void ff_http_init_auth_state(URLContext *dest, const URLContext *src)
127 memcpy(&((HTTPContext*)dest->priv_data)->auth_state,
128 &((HTTPContext*)src->priv_data)->auth_state, sizeof(HTTPAuthState));
129 memcpy(&((HTTPContext*)dest->priv_data)->proxy_auth_state,
130 &((HTTPContext*)src->priv_data)->proxy_auth_state,
131 sizeof(HTTPAuthState));
134 /* return non zero if error */
135 static int http_open_cnx(URLContext *h, AVDictionary **options)
137 const char *path, *proxy_path, *lower_proto = "tcp", *local_path;
138 char hostname[1024], hoststr[1024], proto[10];
139 char auth[1024], proxyauth[1024] = "";
140 char path1[MAX_URL_SIZE];
141 char buf[1024], urlbuf[MAX_URL_SIZE];
142 int port, use_proxy, err, location_changed = 0, redirects = 0, attempts = 0;
143 HTTPAuthType cur_auth_type, cur_proxy_auth_type;
144 HTTPContext *s = h->priv_data;
146 /* fill the dest addr */
148 /* needed in any case to build the host string */
149 av_url_split(proto, sizeof(proto), auth, sizeof(auth),
150 hostname, sizeof(hostname), &port,
151 path1, sizeof(path1), s->location);
152 ff_url_join(hoststr, sizeof(hoststr), NULL, NULL, hostname, port, NULL);
154 proxy_path = getenv("http_proxy");
155 use_proxy = !ff_http_match_no_proxy(getenv("no_proxy"), hostname) &&
156 proxy_path != NULL && av_strstart(proxy_path, "http://", NULL);
158 if (!strcmp(proto, "https")) {
167 if (path1[0] == '\0')
173 /* Reassemble the request URL without auth string - we don't
174 * want to leak the auth to the proxy. */
175 ff_url_join(urlbuf, sizeof(urlbuf), proto, NULL, hostname, port, "%s",
178 av_url_split(NULL, 0, proxyauth, sizeof(proxyauth),
179 hostname, sizeof(hostname), &port, NULL, 0, proxy_path);
182 ff_url_join(buf, sizeof(buf), lower_proto, NULL, hostname, port, NULL);
185 err = ffurl_open(&s->hd, buf, AVIO_FLAG_READ_WRITE,
186 &h->interrupt_callback, options);
191 cur_auth_type = s->auth_state.auth_type;
192 cur_proxy_auth_type = s->auth_state.auth_type;
193 if (http_connect(h, path, local_path, hoststr, auth, proxyauth, &location_changed) < 0)
196 if (s->http_code == 401) {
197 if ((cur_auth_type == HTTP_AUTH_NONE || s->auth_state.stale) &&
198 s->auth_state.auth_type != HTTP_AUTH_NONE && attempts < 4) {
199 ffurl_closep(&s->hd);
204 if (s->http_code == 407) {
205 if ((cur_proxy_auth_type == HTTP_AUTH_NONE || s->proxy_auth_state.stale) &&
206 s->proxy_auth_state.auth_type != HTTP_AUTH_NONE && attempts < 4) {
207 ffurl_closep(&s->hd);
212 if ((s->http_code == 301 || s->http_code == 302 || s->http_code == 303 || s->http_code == 307)
213 && location_changed == 1) {
214 /* url moved, get next */
215 ffurl_closep(&s->hd);
216 if (redirects++ >= MAX_REDIRECTS)
218 /* Restart the authentication process with the new target, which
219 * might use a different auth mechanism. */
220 memset(&s->auth_state, 0, sizeof(s->auth_state));
222 location_changed = 0;
228 ffurl_closep(&s->hd);
232 int ff_http_do_new_request(URLContext *h, const char *uri)
234 HTTPContext *s = h->priv_data;
235 AVDictionary *options = NULL;
239 s->icy_data_read = 0;
240 av_free(s->location);
241 s->location = av_strdup(uri);
243 return AVERROR(ENOMEM);
245 av_dict_copy(&options, s->chained_options, 0);
246 ret = http_open_cnx(h, &options);
247 av_dict_free(&options);
251 static int http_open(URLContext *h, const char *uri, int flags,
252 AVDictionary **options)
254 HTTPContext *s = h->priv_data;
257 if( s->seekable == 1 )
263 s->location = av_strdup(uri);
265 return AVERROR(ENOMEM);
267 av_dict_copy(&s->chained_options, *options, 0);
270 int len = strlen(s->headers);
271 if (len < 2 || strcmp("\r\n", s->headers + len - 2))
272 av_log(h, AV_LOG_WARNING, "No trailing CRLF found in HTTP header.\n");
275 ret = http_open_cnx(h, options);
277 av_dict_free(&s->chained_options);
280 static int http_getc(HTTPContext *s)
283 if (s->buf_ptr >= s->buf_end) {
284 len = ffurl_read(s->hd, s->buffer, BUFFER_SIZE);
287 } else if (len == 0) {
290 s->buf_ptr = s->buffer;
291 s->buf_end = s->buffer + len;
294 return *s->buf_ptr++;
297 static int http_get_line(HTTPContext *s, char *line, int line_size)
309 if (q > line && q[-1] == '\r')
315 if ((q - line) < line_size - 1)
321 static int process_line(URLContext *h, char *line, int line_count,
324 HTTPContext *s = h->priv_data;
328 if (line[0] == '\0') {
334 if (line_count == 0) {
335 while (!av_isspace(*p) && *p != '\0')
337 while (av_isspace(*p))
339 s->http_code = strtol(p, &end, 10);
341 av_log(h, AV_LOG_DEBUG, "http_code=%d\n", s->http_code);
343 /* error codes are 4xx and 5xx, but regard 401 as a success, so we
344 * don't abort until all headers have been parsed. */
345 if (s->http_code >= 400 && s->http_code < 600 && (s->http_code != 401
346 || s->auth_state.auth_type != HTTP_AUTH_NONE) &&
347 (s->http_code != 407 || s->proxy_auth_state.auth_type != HTTP_AUTH_NONE)) {
348 end += strspn(end, SPACE_CHARS);
349 av_log(h, AV_LOG_WARNING, "HTTP error %d %s\n",
354 while (*p != '\0' && *p != ':')
362 while (av_isspace(*p))
364 if (!av_strcasecmp(tag, "Location")) {
365 char redirected_location[MAX_URL_SIZE], *new_loc;
366 ff_make_absolute_url(redirected_location, sizeof(redirected_location),
368 new_loc = av_strdup(redirected_location);
370 return AVERROR(ENOMEM);
371 av_free(s->location);
372 s->location = new_loc;
374 } else if (!av_strcasecmp (tag, "Content-Length") && s->filesize == -1) {
375 s->filesize = strtoll(p, NULL, 10);
376 } else if (!av_strcasecmp (tag, "Content-Range")) {
377 /* "bytes $from-$to/$document_size" */
379 if (!strncmp (p, "bytes ", 6)) {
381 s->off = strtoll(p, NULL, 10);
382 if ((slash = strchr(p, '/')) && strlen(slash) > 0)
383 s->filesize = strtoll(slash+1, NULL, 10);
385 if (s->seekable == -1 && (!s->is_akamai || s->filesize != 2147483647))
386 h->is_streamed = 0; /* we _can_ in fact seek */
387 } else if (!av_strcasecmp(tag, "Accept-Ranges") && !strncmp(p, "bytes", 5) && s->seekable == -1) {
389 } else if (!av_strcasecmp (tag, "Transfer-Encoding") && !av_strncasecmp(p, "chunked", 7)) {
392 } else if (!av_strcasecmp (tag, "WWW-Authenticate")) {
393 ff_http_auth_handle_header(&s->auth_state, tag, p);
394 } else if (!av_strcasecmp (tag, "Authentication-Info")) {
395 ff_http_auth_handle_header(&s->auth_state, tag, p);
396 } else if (!av_strcasecmp (tag, "Proxy-Authenticate")) {
397 ff_http_auth_handle_header(&s->proxy_auth_state, tag, p);
398 } else if (!av_strcasecmp (tag, "Connection")) {
399 if (!strcmp(p, "close"))
401 } else if (!av_strcasecmp (tag, "Server")) {
402 if (!av_strcasecmp (p, "AkamaiGHost")) {
404 } else if (!av_strncasecmp (p, "MediaGateway", 12)) {
405 s->is_mediagateway = 1;
407 } else if (!av_strcasecmp (tag, "Content-Type")) {
408 av_free(s->mime_type); s->mime_type = av_strdup(p);
409 } else if (!av_strcasecmp (tag, "Set-Cookie")) {
411 if (!(s->cookies = av_strdup(p)))
412 return AVERROR(ENOMEM);
414 char *tmp = s->cookies;
415 size_t str_size = strlen(tmp) + strlen(p) + 2;
416 if (!(s->cookies = av_malloc(str_size))) {
418 return AVERROR(ENOMEM);
420 snprintf(s->cookies, str_size, "%s\n%s", tmp, p);
423 } else if (!av_strcasecmp (tag, "Icy-MetaInt")) {
424 s->icy_metaint = strtoll(p, NULL, 10);
425 } else if (!av_strncasecmp(tag, "Icy-", 4)) {
426 // Concat all Icy- header lines
427 char *buf = av_asprintf("%s%s: %s\n",
428 s->icy_metadata_headers ? s->icy_metadata_headers : "", tag, p);
430 return AVERROR(ENOMEM);
431 av_freep(&s->icy_metadata_headers);
432 s->icy_metadata_headers = buf;
433 } else if (!av_strcasecmp (tag, "Content-Encoding")) {
434 if (!av_strncasecmp(p, "gzip", 4) || !av_strncasecmp(p, "deflate", 7)) {
437 inflateEnd(&s->inflate_stream);
438 if (inflateInit2(&s->inflate_stream, 32 + 15) != Z_OK) {
439 av_log(h, AV_LOG_WARNING, "Error during zlib initialisation: %s\n",
440 s->inflate_stream.msg);
441 return AVERROR(ENOSYS);
443 if (zlibCompileFlags() & (1 << 17)) {
444 av_log(h, AV_LOG_WARNING, "Your zlib was compiled without gzip support.\n");
445 return AVERROR(ENOSYS);
448 av_log(h, AV_LOG_WARNING, "Compressed (%s) content, need zlib with gzip support\n", p);
449 return AVERROR(ENOSYS);
451 } else if (!av_strncasecmp(p, "identity", 8)) {
452 // The normal, no-encoding case (although servers shouldn't include
453 // the header at all if this is the case).
455 av_log(h, AV_LOG_WARNING, "Unknown content coding: %s\n", p);
463 * Create a string containing cookie values for use as a HTTP cookie header
464 * field value for a particular path and domain from the cookie values stored in
465 * the HTTP protocol context. The cookie string is stored in *cookies.
467 * @return a negative value if an error condition occurred, 0 otherwise
469 static int get_cookies(HTTPContext *s, char **cookies, const char *path,
472 // cookie strings will look like Set-Cookie header field values. Multiple
473 // Set-Cookie fields will result in multiple values delimited by a newline
475 char *next, *cookie, *set_cookies = av_strdup(s->cookies), *cset_cookies = set_cookies;
477 if (!set_cookies) return AVERROR(EINVAL);
480 while ((cookie = av_strtok(set_cookies, "\n", &next))) {
481 int domain_offset = 0;
482 char *param, *next_param, *cdomain = NULL, *cpath = NULL, *cvalue = NULL;
485 while ((param = av_strtok(cookie, "; ", &next_param))) {
487 if (!av_strncasecmp("path=", param, 5)) {
489 cpath = av_strdup(¶m[5]);
490 } else if (!av_strncasecmp("domain=", param, 7)) {
492 cdomain = av_strdup(¶m[7]);
493 } else if (!av_strncasecmp("secure", param, 6) ||
494 !av_strncasecmp("comment", param, 7) ||
495 !av_strncasecmp("max-age", param, 7) ||
496 !av_strncasecmp("version", param, 7)) {
497 // ignore Comment, Max-Age, Secure and Version
500 cvalue = av_strdup(param);
504 cdomain = av_strdup(domain);
506 // ensure all of the necessary values are valid
507 if (!cdomain || !cpath || !cvalue) {
508 av_log(s, AV_LOG_WARNING,
509 "Invalid cookie found, no value, path or domain specified\n");
513 // check if the request path matches the cookie path
514 if (av_strncasecmp(path, cpath, strlen(cpath)))
517 // the domain should be at least the size of our cookie domain
518 domain_offset = strlen(domain) - strlen(cdomain);
519 if (domain_offset < 0)
522 // match the cookie domain
523 if (av_strcasecmp(&domain[domain_offset], cdomain))
526 // cookie parameters match, so copy the value
528 if (!(*cookies = av_strdup(cvalue))) {
529 ret = AVERROR(ENOMEM);
533 char *tmp = *cookies;
534 size_t str_size = strlen(cvalue) + strlen(*cookies) + 3;
535 if (!(*cookies = av_malloc(str_size))) {
536 ret = AVERROR(ENOMEM);
539 snprintf(*cookies, str_size, "%s; %s", tmp, cvalue);
548 if (*cookies) av_freep(cookies);
549 av_free(cset_cookies);
554 av_free(cset_cookies);
559 static inline int has_header(const char *str, const char *header)
561 /* header + 2 to skip over CRLF prefix. (make sure you have one!) */
564 return av_stristart(str, header + 2, NULL) || av_stristr(str, header);
567 static int http_read_header(URLContext *h, int *new_location)
569 HTTPContext *s = h->priv_data;
570 char line[MAX_URL_SIZE];
576 if ((err = http_get_line(s, line, sizeof(line))) < 0)
579 av_log(h, AV_LOG_DEBUG, "header='%s'\n", line);
581 err = process_line(h, line, s->line_count, new_location);
589 if (s->seekable == -1 && s->is_mediagateway && s->filesize == 2000000000)
590 h->is_streamed = 1; /* we can in fact _not_ seek */
595 static int http_connect(URLContext *h, const char *path, const char *local_path,
596 const char *hoststr, const char *auth,
597 const char *proxyauth, int *new_location)
599 HTTPContext *s = h->priv_data;
601 char headers[4096] = "";
602 char *authstr = NULL, *proxyauthstr = NULL;
603 int64_t off = s->off;
606 int send_expect_100 = 0;
609 /* send http header */
610 post = h->flags & AVIO_FLAG_WRITE;
613 /* force POST method and disable chunked encoding when
614 * custom HTTP post data is set */
619 method = post ? "POST" : "GET";
620 authstr = ff_http_auth_create_response(&s->auth_state, auth, local_path,
622 proxyauthstr = ff_http_auth_create_response(&s->proxy_auth_state, proxyauth,
624 if (post && !s->post_data) {
625 send_expect_100 = s->send_expect_100;
626 /* The user has supplied authentication but we don't know the auth type,
627 * send Expect: 100-continue to get the 401 response including the
628 * WWW-Authenticate header, or an 100 continue if no auth actually
631 s->auth_state.auth_type == HTTP_AUTH_NONE &&
636 /* set default headers if needed */
637 if (!has_header(s->headers, "\r\nUser-Agent: "))
638 len += av_strlcatf(headers + len, sizeof(headers) - len,
639 "User-Agent: %s\r\n", s->user_agent);
640 if (!has_header(s->headers, "\r\nAccept: "))
641 len += av_strlcpy(headers + len, "Accept: */*\r\n",
642 sizeof(headers) - len);
643 // Note: we send this on purpose even when s->off is 0 when we're probing,
644 // since it allows us to detect more reliably if a (non-conforming)
645 // server supports seeking by analysing the reply headers.
646 if (!has_header(s->headers, "\r\nRange: ") && !post && (s->off > 0 || s->seekable == -1))
647 len += av_strlcatf(headers + len, sizeof(headers) - len,
648 "Range: bytes=%"PRId64"-\r\n", s->off);
649 if (send_expect_100 && !has_header(s->headers, "\r\nExpect: "))
650 len += av_strlcatf(headers + len, sizeof(headers) - len,
651 "Expect: 100-continue\r\n");
653 if (!has_header(s->headers, "\r\nConnection: ")) {
654 if (s->multiple_requests) {
655 len += av_strlcpy(headers + len, "Connection: keep-alive\r\n",
656 sizeof(headers) - len);
658 len += av_strlcpy(headers + len, "Connection: close\r\n",
659 sizeof(headers) - len);
663 if (!has_header(s->headers, "\r\nHost: "))
664 len += av_strlcatf(headers + len, sizeof(headers) - len,
665 "Host: %s\r\n", hoststr);
666 if (!has_header(s->headers, "\r\nContent-Length: ") && s->post_data)
667 len += av_strlcatf(headers + len, sizeof(headers) - len,
668 "Content-Length: %d\r\n", s->post_datalen);
669 if (!has_header(s->headers, "\r\nContent-Type: ") && s->content_type)
670 len += av_strlcatf(headers + len, sizeof(headers) - len,
671 "Content-Type: %s\r\n", s->content_type);
672 if (!has_header(s->headers, "\r\nCookie: ") && s->cookies) {
673 char *cookies = NULL;
674 if (!get_cookies(s, &cookies, path, hoststr)) {
675 len += av_strlcatf(headers + len, sizeof(headers) - len,
676 "Cookie: %s\r\n", cookies);
680 if (!has_header(s->headers, "\r\nIcy-MetaData: ") && s->icy) {
681 len += av_strlcatf(headers + len, sizeof(headers) - len,
682 "Icy-MetaData: %d\r\n", 1);
685 /* now add in custom headers */
687 av_strlcpy(headers + len, s->headers, sizeof(headers) - len);
689 snprintf(s->buffer, sizeof(s->buffer),
698 post && s->chunked_post ? "Transfer-Encoding: chunked\r\n" : "",
700 authstr ? authstr : "",
701 proxyauthstr ? "Proxy-" : "", proxyauthstr ? proxyauthstr : "");
704 av_freep(&proxyauthstr);
706 av_log(h, AV_LOG_DEBUG, "request: %s\n", s->buffer);
708 if ((err = ffurl_write(s->hd, s->buffer, strlen(s->buffer))) < 0)
712 if ((err = ffurl_write(s->hd, s->post_data, s->post_datalen)) < 0)
715 /* init input buffer */
716 s->buf_ptr = s->buffer;
717 s->buf_end = s->buffer;
720 s->icy_data_read = 0;
723 s->end_chunked_post = 0;
725 if (post && !s->post_data && !send_expect_100) {
726 /* Pretend that it did work. We didn't read any header yet, since
727 * we've still to send the POST data, but the code calling this
728 * function will check http_code after we return. */
733 /* wait for header */
734 err = http_read_header(h, new_location);
738 return (off == s->off) ? 0 : -1;
742 static int http_buf_read(URLContext *h, uint8_t *buf, int size)
744 HTTPContext *s = h->priv_data;
746 /* read bytes from input buffer first */
747 len = s->buf_end - s->buf_ptr;
751 memcpy(buf, s->buf_ptr, len);
754 if (!s->willclose && s->filesize >= 0 && s->off >= s->filesize)
756 len = ffurl_read(s->hd, buf, size);
760 s->icy_data_read += len;
761 if (s->chunksize > 0)
768 #define DECOMPRESS_BUF_SIZE (256 * 1024)
769 static int http_buf_read_compressed(URLContext *h, uint8_t *buf, int size)
771 HTTPContext *s = h->priv_data;
774 if (!s->inflate_buffer) {
775 s->inflate_buffer = av_malloc(DECOMPRESS_BUF_SIZE);
776 if (!s->inflate_buffer)
777 return AVERROR(ENOMEM);
780 if (s->inflate_stream.avail_in == 0) {
781 int read = http_buf_read(h, s->inflate_buffer, DECOMPRESS_BUF_SIZE);
784 s->inflate_stream.next_in = s->inflate_buffer;
785 s->inflate_stream.avail_in = read;
788 s->inflate_stream.avail_out = size;
789 s->inflate_stream.next_out = buf;
791 ret = inflate(&s->inflate_stream, Z_SYNC_FLUSH);
792 if (ret != Z_OK && ret != Z_STREAM_END)
793 av_log(h, AV_LOG_WARNING, "inflate return value: %d, %s\n", ret, s->inflate_stream.msg);
795 return size - s->inflate_stream.avail_out;
799 static int http_read(URLContext *h, uint8_t *buf, int size)
801 HTTPContext *s = h->priv_data;
802 int err, new_location;
807 if (s->end_chunked_post && !s->end_header) {
808 err = http_read_header(h, &new_location);
813 if (s->chunksize >= 0) {
819 if ((err = http_get_line(s, line, sizeof(line))) < 0)
821 } while (!*line); /* skip CR LF from last chunk */
823 s->chunksize = strtoll(line, NULL, 16);
825 av_dlog(NULL, "Chunked encoding data size: %"PRId64"'\n", s->chunksize);
832 size = FFMIN(size, s->chunksize);
834 if (s->icy_metaint > 0) {
835 int remaining = s->icy_metaint - s->icy_data_read; /* until next metadata packet */
837 // The metadata packet is variable sized. It has a 1 byte header
838 // which sets the length of the packet (divided by 16). If it's 0,
839 // the metadata doesn't change. After the packet, icy_metaint bytes
840 // of normal data follow.
841 int ch = http_getc(s);
845 char data[255 * 16 + 1];
849 for (n = 0; n < ch; n++)
850 data[n] = http_getc(s);
852 if ((ret = av_opt_set(s, "icy_metadata_packet", data, 0)) < 0)
855 s->icy_data_read = 0;
856 remaining = s->icy_metaint;
858 size = FFMIN(size, remaining);
862 return http_buf_read_compressed(h, buf, size);
864 return http_buf_read(h, buf, size);
867 /* used only when posting data */
868 static int http_write(URLContext *h, const uint8_t *buf, int size)
870 char temp[11] = ""; /* 32-bit hex + CRLF + nul */
872 char crlf[] = "\r\n";
873 HTTPContext *s = h->priv_data;
875 if (!s->chunked_post) {
876 /* non-chunked data is sent without any special encoding */
877 return ffurl_write(s->hd, buf, size);
880 /* silently ignore zero-size data since chunk encoding that would
883 /* upload data using chunked encoding */
884 snprintf(temp, sizeof(temp), "%x\r\n", size);
886 if ((ret = ffurl_write(s->hd, temp, strlen(temp))) < 0 ||
887 (ret = ffurl_write(s->hd, buf, size)) < 0 ||
888 (ret = ffurl_write(s->hd, crlf, sizeof(crlf) - 1)) < 0)
894 static int http_shutdown(URLContext *h, int flags)
897 char footer[] = "0\r\n\r\n";
898 HTTPContext *s = h->priv_data;
900 /* signal end of chunked encoding if used */
901 if ((flags & AVIO_FLAG_WRITE) && s->chunked_post) {
902 ret = ffurl_write(s->hd, footer, sizeof(footer) - 1);
903 ret = ret > 0 ? 0 : ret;
904 s->end_chunked_post = 1;
910 static int http_close(URLContext *h)
913 HTTPContext *s = h->priv_data;
916 inflateEnd(&s->inflate_stream);
917 av_freep(&s->inflate_buffer);
920 if (!s->end_chunked_post) {
921 /* Close the write direction by sending the end of chunked encoding. */
922 ret = http_shutdown(h, h->flags);
926 ffurl_closep(&s->hd);
927 av_dict_free(&s->chained_options);
931 static int64_t http_seek(URLContext *h, int64_t off, int whence)
933 HTTPContext *s = h->priv_data;
934 URLContext *old_hd = s->hd;
935 int64_t old_off = s->off;
936 uint8_t old_buf[BUFFER_SIZE];
938 AVDictionary *options = NULL;
940 if (whence == AVSEEK_SIZE)
942 else if ((s->filesize == -1 && whence == SEEK_END) || h->is_streamed)
945 /* we save the old context in case the seek fails */
946 old_buf_size = s->buf_end - s->buf_ptr;
947 memcpy(old_buf, s->buf_ptr, old_buf_size);
949 if (whence == SEEK_CUR)
951 else if (whence == SEEK_END)
955 /* if it fails, continue on old connection */
956 av_dict_copy(&options, s->chained_options, 0);
957 if (http_open_cnx(h, &options) < 0) {
958 av_dict_free(&options);
959 memcpy(s->buffer, old_buf, old_buf_size);
960 s->buf_ptr = s->buffer;
961 s->buf_end = s->buffer + old_buf_size;
966 av_dict_free(&options);
972 http_get_file_handle(URLContext *h)
974 HTTPContext *s = h->priv_data;
975 return ffurl_get_file_handle(s->hd);
978 #if CONFIG_HTTP_PROTOCOL
979 URLProtocol ff_http_protocol = {
981 .url_open2 = http_open,
982 .url_read = http_read,
983 .url_write = http_write,
984 .url_seek = http_seek,
985 .url_close = http_close,
986 .url_get_file_handle = http_get_file_handle,
987 .url_shutdown = http_shutdown,
988 .priv_data_size = sizeof(HTTPContext),
989 .priv_data_class = &http_context_class,
990 .flags = URL_PROTOCOL_FLAG_NETWORK,
993 #if CONFIG_HTTPS_PROTOCOL
994 URLProtocol ff_https_protocol = {
996 .url_open2 = http_open,
997 .url_read = http_read,
998 .url_write = http_write,
999 .url_seek = http_seek,
1000 .url_close = http_close,
1001 .url_get_file_handle = http_get_file_handle,
1002 .url_shutdown = http_shutdown,
1003 .priv_data_size = sizeof(HTTPContext),
1004 .priv_data_class = &https_context_class,
1005 .flags = URL_PROTOCOL_FLAG_NETWORK,
1009 #if CONFIG_HTTPPROXY_PROTOCOL
1010 static int http_proxy_close(URLContext *h)
1012 HTTPContext *s = h->priv_data;
1014 ffurl_closep(&s->hd);
1018 static int http_proxy_open(URLContext *h, const char *uri, int flags)
1020 HTTPContext *s = h->priv_data;
1021 char hostname[1024], hoststr[1024];
1022 char auth[1024], pathbuf[1024], *path;
1023 char lower_url[100];
1024 int port, ret = 0, attempts = 0;
1025 HTTPAuthType cur_auth_type;
1029 if( s->seekable == 1 )
1034 av_url_split(NULL, 0, auth, sizeof(auth), hostname, sizeof(hostname), &port,
1035 pathbuf, sizeof(pathbuf), uri);
1036 ff_url_join(hoststr, sizeof(hoststr), NULL, NULL, hostname, port, NULL);
1041 ff_url_join(lower_url, sizeof(lower_url), "tcp", NULL, hostname, port,
1044 ret = ffurl_open(&s->hd, lower_url, AVIO_FLAG_READ_WRITE,
1045 &h->interrupt_callback, NULL);
1049 authstr = ff_http_auth_create_response(&s->proxy_auth_state, auth,
1051 snprintf(s->buffer, sizeof(s->buffer),
1052 "CONNECT %s HTTP/1.1\r\n"
1054 "Connection: close\r\n"
1059 authstr ? "Proxy-" : "", authstr ? authstr : "");
1062 if ((ret = ffurl_write(s->hd, s->buffer, strlen(s->buffer))) < 0)
1065 s->buf_ptr = s->buffer;
1066 s->buf_end = s->buffer;
1069 cur_auth_type = s->proxy_auth_state.auth_type;
1071 /* Note: This uses buffering, potentially reading more than the
1072 * HTTP header. If tunneling a protocol where the server starts
1073 * the conversation, we might buffer part of that here, too.
1074 * Reading that requires using the proper ffurl_read() function
1075 * on this URLContext, not using the fd directly (as the tls
1076 * protocol does). This shouldn't be an issue for tls though,
1077 * since the client starts the conversation there, so there
1078 * is no extra data that we might buffer up here.
1080 ret = http_read_header(h, &new_loc);
1085 if (s->http_code == 407 &&
1086 (cur_auth_type == HTTP_AUTH_NONE || s->proxy_auth_state.stale) &&
1087 s->proxy_auth_state.auth_type != HTTP_AUTH_NONE && attempts < 2) {
1088 ffurl_closep(&s->hd);
1092 if (s->http_code < 400)
1097 http_proxy_close(h);
1101 static int http_proxy_write(URLContext *h, const uint8_t *buf, int size)
1103 HTTPContext *s = h->priv_data;
1104 return ffurl_write(s->hd, buf, size);
1107 URLProtocol ff_httpproxy_protocol = {
1108 .name = "httpproxy",
1109 .url_open = http_proxy_open,
1110 .url_read = http_buf_read,
1111 .url_write = http_proxy_write,
1112 .url_close = http_proxy_close,
1113 .url_get_file_handle = http_get_file_handle,
1114 .priv_data_size = sizeof(HTTPContext),
1115 .flags = URL_PROTOCOL_FLAG_NETWORK,