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
58 char location[MAX_URL_SIZE];
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. */
72 char *cookies; ///< holds newline (\n) delimited Set-Cookie header field values (without the "Set-Cookie: " field name)
74 char *icy_metadata_headers;
75 char *icy_metadata_packet;
78 z_stream inflate_stream;
79 uint8_t *inflate_buffer;
81 AVDictionary *chained_options;
84 #define OFFSET(x) offsetof(HTTPContext, x)
85 #define D AV_OPT_FLAG_DECODING_PARAM
86 #define E AV_OPT_FLAG_ENCODING_PARAM
87 #define DEFAULT_USER_AGENT "Lavf/" AV_STRINGIFY(LIBAVFORMAT_VERSION)
88 static const AVOption options[] = {
89 {"seekable", "control seekability of connection", OFFSET(seekable), AV_OPT_TYPE_INT, {.i64 = -1}, -1, 1, D },
90 {"chunked_post", "use chunked transfer-encoding for posts", OFFSET(chunked_post), AV_OPT_TYPE_INT, {.i64 = 1}, 0, 1, E },
91 {"headers", "set custom HTTP headers, can override built in default headers", OFFSET(headers), AV_OPT_TYPE_STRING, { 0 }, 0, 0, D|E },
92 {"content_type", "force a content type", OFFSET(content_type), AV_OPT_TYPE_STRING, { 0 }, 0, 0, D|E },
93 {"user-agent", "override User-Agent header", OFFSET(user_agent), AV_OPT_TYPE_STRING, {.str = DEFAULT_USER_AGENT}, 0, 0, D },
94 {"multiple_requests", "use persistent connections", OFFSET(multiple_requests), AV_OPT_TYPE_INT, {.i64 = 0}, 0, 1, D|E },
95 {"post_data", "set custom HTTP post data", OFFSET(post_data), AV_OPT_TYPE_BINARY, .flags = D|E },
96 {"mime_type", "set MIME type", OFFSET(mime_type), AV_OPT_TYPE_STRING, {0}, 0, 0, 0 },
97 {"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, 0 },
98 {"icy", "request ICY metadata", OFFSET(icy), AV_OPT_TYPE_INT, {.i64 = 0}, 0, 1, D },
99 {"icy_metadata_headers", "return ICY metadata headers", OFFSET(icy_metadata_headers), AV_OPT_TYPE_STRING, {0}, 0, 0, 0 },
100 {"icy_metadata_packet", "return current ICY metadata packet", OFFSET(icy_metadata_packet), AV_OPT_TYPE_STRING, {0}, 0, 0, 0 },
103 #define HTTP_CLASS(flavor)\
104 static const AVClass flavor ## _context_class = {\
105 .class_name = #flavor,\
106 .item_name = av_default_item_name,\
108 .version = LIBAVUTIL_VERSION_INT,\
114 static int http_connect(URLContext *h, const char *path, const char *local_path,
115 const char *hoststr, const char *auth,
116 const char *proxyauth, int *new_location);
118 void ff_http_init_auth_state(URLContext *dest, const URLContext *src)
120 memcpy(&((HTTPContext*)dest->priv_data)->auth_state,
121 &((HTTPContext*)src->priv_data)->auth_state, sizeof(HTTPAuthState));
122 memcpy(&((HTTPContext*)dest->priv_data)->proxy_auth_state,
123 &((HTTPContext*)src->priv_data)->proxy_auth_state,
124 sizeof(HTTPAuthState));
127 /* return non zero if error */
128 static int http_open_cnx(URLContext *h, AVDictionary **options)
130 const char *path, *proxy_path, *lower_proto = "tcp", *local_path;
131 char hostname[1024], hoststr[1024], proto[10];
132 char auth[1024], proxyauth[1024] = "";
133 char path1[MAX_URL_SIZE];
134 char buf[1024], urlbuf[MAX_URL_SIZE];
135 int port, use_proxy, err, location_changed = 0, redirects = 0, attempts = 0;
136 HTTPAuthType cur_auth_type, cur_proxy_auth_type;
137 HTTPContext *s = h->priv_data;
139 /* fill the dest addr */
141 /* needed in any case to build the host string */
142 av_url_split(proto, sizeof(proto), auth, sizeof(auth),
143 hostname, sizeof(hostname), &port,
144 path1, sizeof(path1), s->location);
145 ff_url_join(hoststr, sizeof(hoststr), NULL, NULL, hostname, port, NULL);
147 proxy_path = getenv("http_proxy");
148 use_proxy = !ff_http_match_no_proxy(getenv("no_proxy"), hostname) &&
149 proxy_path != NULL && av_strstart(proxy_path, "http://", NULL);
151 if (!strcmp(proto, "https")) {
160 if (path1[0] == '\0')
166 /* Reassemble the request URL without auth string - we don't
167 * want to leak the auth to the proxy. */
168 ff_url_join(urlbuf, sizeof(urlbuf), proto, NULL, hostname, port, "%s",
171 av_url_split(NULL, 0, proxyauth, sizeof(proxyauth),
172 hostname, sizeof(hostname), &port, NULL, 0, proxy_path);
175 ff_url_join(buf, sizeof(buf), lower_proto, NULL, hostname, port, NULL);
178 err = ffurl_open(&s->hd, buf, AVIO_FLAG_READ_WRITE,
179 &h->interrupt_callback, options);
184 cur_auth_type = s->auth_state.auth_type;
185 cur_proxy_auth_type = s->auth_state.auth_type;
186 if (http_connect(h, path, local_path, hoststr, auth, proxyauth, &location_changed) < 0)
189 if (s->http_code == 401) {
190 if ((cur_auth_type == HTTP_AUTH_NONE || s->auth_state.stale) &&
191 s->auth_state.auth_type != HTTP_AUTH_NONE && attempts < 4) {
192 ffurl_closep(&s->hd);
197 if (s->http_code == 407) {
198 if ((cur_proxy_auth_type == HTTP_AUTH_NONE || s->proxy_auth_state.stale) &&
199 s->proxy_auth_state.auth_type != HTTP_AUTH_NONE && attempts < 4) {
200 ffurl_closep(&s->hd);
205 if ((s->http_code == 301 || s->http_code == 302 || s->http_code == 303 || s->http_code == 307)
206 && location_changed == 1) {
207 /* url moved, get next */
208 ffurl_closep(&s->hd);
209 if (redirects++ >= MAX_REDIRECTS)
211 /* Restart the authentication process with the new target, which
212 * might use a different auth mechanism. */
213 memset(&s->auth_state, 0, sizeof(s->auth_state));
215 location_changed = 0;
221 ffurl_closep(&s->hd);
225 int ff_http_do_new_request(URLContext *h, const char *uri)
227 HTTPContext *s = h->priv_data;
228 AVDictionary *options = NULL;
232 s->icy_data_read = 0;
233 av_strlcpy(s->location, uri, sizeof(s->location));
235 av_dict_copy(&options, s->chained_options, 0);
236 ret = http_open_cnx(h, &options);
237 av_dict_free(&options);
241 static int http_open(URLContext *h, const char *uri, int flags,
242 AVDictionary **options)
244 HTTPContext *s = h->priv_data;
247 if( s->seekable == 1 )
253 av_strlcpy(s->location, uri, sizeof(s->location));
255 av_dict_copy(&s->chained_options, *options, 0);
258 int len = strlen(s->headers);
259 if (len < 2 || strcmp("\r\n", s->headers + len - 2))
260 av_log(h, AV_LOG_WARNING, "No trailing CRLF found in HTTP header.\n");
263 ret = http_open_cnx(h, options);
265 av_dict_free(&s->chained_options);
268 static int http_getc(HTTPContext *s)
271 if (s->buf_ptr >= s->buf_end) {
272 len = ffurl_read(s->hd, s->buffer, BUFFER_SIZE);
275 } else if (len == 0) {
278 s->buf_ptr = s->buffer;
279 s->buf_end = s->buffer + len;
282 return *s->buf_ptr++;
285 static int http_get_line(HTTPContext *s, char *line, int line_size)
297 if (q > line && q[-1] == '\r')
303 if ((q - line) < line_size - 1)
309 static int process_line(URLContext *h, char *line, int line_count,
312 HTTPContext *s = h->priv_data;
314 char redirected_location[MAX_URL_SIZE];
317 if (line[0] == '\0') {
323 if (line_count == 0) {
324 while (!av_isspace(*p) && *p != '\0')
326 while (av_isspace(*p))
328 s->http_code = strtol(p, &end, 10);
330 av_dlog(NULL, "http_code=%d\n", s->http_code);
332 /* error codes are 4xx and 5xx, but regard 401 as a success, so we
333 * don't abort until all headers have been parsed. */
334 if (s->http_code >= 400 && s->http_code < 600 && (s->http_code != 401
335 || s->auth_state.auth_type != HTTP_AUTH_NONE) &&
336 (s->http_code != 407 || s->proxy_auth_state.auth_type != HTTP_AUTH_NONE)) {
337 end += strspn(end, SPACE_CHARS);
338 av_log(h, AV_LOG_WARNING, "HTTP error %d %s\n",
343 while (*p != '\0' && *p != ':')
351 while (av_isspace(*p))
353 if (!av_strcasecmp(tag, "Location")) {
354 ff_make_absolute_url(redirected_location, sizeof(redirected_location), s->location, p);
355 av_strlcpy(s->location, redirected_location, sizeof(s->location));
357 } else if (!av_strcasecmp (tag, "Content-Length") && s->filesize == -1) {
358 s->filesize = strtoll(p, NULL, 10);
359 } else if (!av_strcasecmp (tag, "Content-Range")) {
360 /* "bytes $from-$to/$document_size" */
362 if (!strncmp (p, "bytes ", 6)) {
364 s->off = strtoll(p, NULL, 10);
365 if ((slash = strchr(p, '/')) && strlen(slash) > 0)
366 s->filesize = strtoll(slash+1, NULL, 10);
368 if (s->seekable == -1 && (!s->is_akamai || s->filesize != 2147483647))
369 h->is_streamed = 0; /* we _can_ in fact seek */
370 } else if (!av_strcasecmp(tag, "Accept-Ranges") && !strncmp(p, "bytes", 5) && s->seekable == -1) {
372 } else if (!av_strcasecmp (tag, "Transfer-Encoding") && !av_strncasecmp(p, "chunked", 7)) {
375 } else if (!av_strcasecmp (tag, "WWW-Authenticate")) {
376 ff_http_auth_handle_header(&s->auth_state, tag, p);
377 } else if (!av_strcasecmp (tag, "Authentication-Info")) {
378 ff_http_auth_handle_header(&s->auth_state, tag, p);
379 } else if (!av_strcasecmp (tag, "Proxy-Authenticate")) {
380 ff_http_auth_handle_header(&s->proxy_auth_state, tag, p);
381 } else if (!av_strcasecmp (tag, "Connection")) {
382 if (!strcmp(p, "close"))
384 } else if (!av_strcasecmp (tag, "Server") && !av_strcasecmp (p, "AkamaiGHost")) {
386 } else if (!av_strcasecmp (tag, "Content-Type")) {
387 av_free(s->mime_type); s->mime_type = av_strdup(p);
388 } else if (!av_strcasecmp (tag, "Set-Cookie")) {
390 if (!(s->cookies = av_strdup(p)))
391 return AVERROR(ENOMEM);
393 char *tmp = s->cookies;
394 size_t str_size = strlen(tmp) + strlen(p) + 2;
395 if (!(s->cookies = av_malloc(str_size))) {
397 return AVERROR(ENOMEM);
399 snprintf(s->cookies, str_size, "%s\n%s", tmp, p);
402 } else if (!av_strcasecmp (tag, "Icy-MetaInt")) {
403 s->icy_metaint = strtoll(p, NULL, 10);
404 } else if (!av_strncasecmp(tag, "Icy-", 4)) {
405 // Concat all Icy- header lines
406 char *buf = av_asprintf("%s%s: %s\n",
407 s->icy_metadata_headers ? s->icy_metadata_headers : "", tag, p);
409 return AVERROR(ENOMEM);
410 av_freep(&s->icy_metadata_headers);
411 s->icy_metadata_headers = buf;
412 } else if (!av_strcasecmp (tag, "Content-Encoding")) {
413 if (!av_strncasecmp(p, "gzip", 4) || !av_strncasecmp(p, "deflate", 7)) {
416 inflateEnd(&s->inflate_stream);
417 if (inflateInit2(&s->inflate_stream, 32 + 15) != Z_OK) {
418 av_log(h, AV_LOG_WARNING, "Error during zlib initialisation: %s\n",
419 s->inflate_stream.msg);
420 return AVERROR(ENOSYS);
422 if (zlibCompileFlags() & (1 << 17)) {
423 av_log(h, AV_LOG_WARNING, "Your zlib was compiled without gzip support.\n");
424 return AVERROR(ENOSYS);
427 av_log(h, AV_LOG_WARNING, "Compressed (%s) content, need zlib with gzip support\n", p);
428 return AVERROR(ENOSYS);
430 } else if (!av_strncasecmp(p, "identity", 8)) {
431 // The normal, no-encoding case (although servers shouldn't include
432 // the header at all if this is the case).
434 av_log(h, AV_LOG_WARNING, "Unknown content coding: %s\n", p);
435 return AVERROR(ENOSYS);
443 * Create a string containing cookie values for use as a HTTP cookie header
444 * field value for a particular path and domain from the cookie values stored in
445 * the HTTP protocol context. The cookie string is stored in *cookies.
447 * @return a negative value if an error condition occurred, 0 otherwise
449 static int get_cookies(HTTPContext *s, char **cookies, const char *path,
452 // cookie strings will look like Set-Cookie header field values. Multiple
453 // Set-Cookie fields will result in multiple values delimited by a newline
455 char *next, *cookie, *set_cookies = av_strdup(s->cookies), *cset_cookies = set_cookies;
457 if (!set_cookies) return AVERROR(EINVAL);
460 while ((cookie = av_strtok(set_cookies, "\n", &next))) {
461 int domain_offset = 0;
462 char *param, *next_param, *cdomain = NULL, *cpath = NULL, *cvalue = NULL;
465 while ((param = av_strtok(cookie, "; ", &next_param))) {
467 if (!av_strncasecmp("path=", param, 5)) {
469 cpath = av_strdup(¶m[5]);
470 } else if (!av_strncasecmp("domain=", param, 7)) {
472 cdomain = av_strdup(¶m[7]);
473 } else if (!av_strncasecmp("secure", param, 6) ||
474 !av_strncasecmp("comment", param, 7) ||
475 !av_strncasecmp("max-age", param, 7) ||
476 !av_strncasecmp("version", param, 7)) {
477 // ignore Comment, Max-Age, Secure and Version
480 cvalue = av_strdup(param);
484 cdomain = av_strdup(domain);
486 // ensure all of the necessary values are valid
487 if (!cdomain || !cpath || !cvalue) {
488 av_log(s, AV_LOG_WARNING,
489 "Invalid cookie found, no value, path or domain specified\n");
493 // check if the request path matches the cookie path
494 if (av_strncasecmp(path, cpath, strlen(cpath)))
497 // the domain should be at least the size of our cookie domain
498 domain_offset = strlen(domain) - strlen(cdomain);
499 if (domain_offset < 0)
502 // match the cookie domain
503 if (av_strcasecmp(&domain[domain_offset], cdomain))
506 // cookie parameters match, so copy the value
508 if (!(*cookies = av_strdup(cvalue))) {
509 ret = AVERROR(ENOMEM);
513 char *tmp = *cookies;
514 size_t str_size = strlen(cvalue) + strlen(*cookies) + 3;
515 if (!(*cookies = av_malloc(str_size))) {
516 ret = AVERROR(ENOMEM);
519 snprintf(*cookies, str_size, "%s; %s", tmp, cvalue);
528 if (*cookies) av_freep(cookies);
529 av_free(cset_cookies);
534 av_free(cset_cookies);
539 static inline int has_header(const char *str, const char *header)
541 /* header + 2 to skip over CRLF prefix. (make sure you have one!) */
544 return av_stristart(str, header + 2, NULL) || av_stristr(str, header);
547 static int http_read_header(URLContext *h, int *new_location)
549 HTTPContext *s = h->priv_data;
550 char line[MAX_URL_SIZE];
556 if ((err = http_get_line(s, line, sizeof(line))) < 0)
559 av_dlog(NULL, "header='%s'\n", line);
561 err = process_line(h, line, s->line_count, new_location);
572 static int http_connect(URLContext *h, const char *path, const char *local_path,
573 const char *hoststr, const char *auth,
574 const char *proxyauth, int *new_location)
576 HTTPContext *s = h->priv_data;
578 char headers[4096] = "";
579 char *authstr = NULL, *proxyauthstr = NULL;
580 int64_t off = s->off;
585 /* send http header */
586 post = h->flags & AVIO_FLAG_WRITE;
589 /* force POST method and disable chunked encoding when
590 * custom HTTP post data is set */
595 method = post ? "POST" : "GET";
596 authstr = ff_http_auth_create_response(&s->auth_state, auth, local_path,
598 proxyauthstr = ff_http_auth_create_response(&s->proxy_auth_state, proxyauth,
601 /* set default headers if needed */
602 if (!has_header(s->headers, "\r\nUser-Agent: "))
603 len += av_strlcatf(headers + len, sizeof(headers) - len,
604 "User-Agent: %s\r\n", s->user_agent);
605 if (!has_header(s->headers, "\r\nAccept: "))
606 len += av_strlcpy(headers + len, "Accept: */*\r\n",
607 sizeof(headers) - len);
608 // Note: we send this on purpose even when s->off is 0 when we're probing,
609 // since it allows us to detect more reliably if a (non-conforming)
610 // server supports seeking by analysing the reply headers.
611 if (!has_header(s->headers, "\r\nRange: ") && !post && (s->off > 0 || s->seekable == -1))
612 len += av_strlcatf(headers + len, sizeof(headers) - len,
613 "Range: bytes=%"PRId64"-\r\n", s->off);
615 if (!has_header(s->headers, "\r\nConnection: ")) {
616 if (s->multiple_requests) {
617 len += av_strlcpy(headers + len, "Connection: keep-alive\r\n",
618 sizeof(headers) - len);
620 len += av_strlcpy(headers + len, "Connection: close\r\n",
621 sizeof(headers) - len);
625 if (!has_header(s->headers, "\r\nHost: "))
626 len += av_strlcatf(headers + len, sizeof(headers) - len,
627 "Host: %s\r\n", hoststr);
628 if (!has_header(s->headers, "\r\nContent-Length: ") && s->post_data)
629 len += av_strlcatf(headers + len, sizeof(headers) - len,
630 "Content-Length: %d\r\n", s->post_datalen);
631 if (!has_header(s->headers, "\r\nContent-Type: ") && s->content_type)
632 len += av_strlcatf(headers + len, sizeof(headers) - len,
633 "Content-Type: %s\r\n", s->content_type);
634 if (!has_header(s->headers, "\r\nCookie: ") && s->cookies) {
635 char *cookies = NULL;
636 if (!get_cookies(s, &cookies, path, hoststr)) {
637 len += av_strlcatf(headers + len, sizeof(headers) - len,
638 "Cookie: %s\r\n", cookies);
642 if (!has_header(s->headers, "\r\nIcy-MetaData: ") && s->icy) {
643 len += av_strlcatf(headers + len, sizeof(headers) - len,
644 "Icy-MetaData: %d\r\n", 1);
647 /* now add in custom headers */
649 av_strlcpy(headers + len, s->headers, sizeof(headers) - len);
651 snprintf(s->buffer, sizeof(s->buffer),
660 post && s->chunked_post ? "Transfer-Encoding: chunked\r\n" : "",
662 authstr ? authstr : "",
663 proxyauthstr ? "Proxy-" : "", proxyauthstr ? proxyauthstr : "");
666 av_freep(&proxyauthstr);
667 if ((err = ffurl_write(s->hd, s->buffer, strlen(s->buffer))) < 0)
671 if ((err = ffurl_write(s->hd, s->post_data, s->post_datalen)) < 0)
674 /* init input buffer */
675 s->buf_ptr = s->buffer;
676 s->buf_end = s->buffer;
679 s->icy_data_read = 0;
682 s->end_chunked_post = 0;
684 if (post && !s->post_data) {
685 /* Pretend that it did work. We didn't read any header yet, since
686 * we've still to send the POST data, but the code calling this
687 * function will check http_code after we return. */
692 /* wait for header */
693 err = http_read_header(h, new_location);
697 return (off == s->off) ? 0 : -1;
701 static int http_buf_read(URLContext *h, uint8_t *buf, int size)
703 HTTPContext *s = h->priv_data;
705 /* read bytes from input buffer first */
706 len = s->buf_end - s->buf_ptr;
710 memcpy(buf, s->buf_ptr, len);
713 if (!s->willclose && s->filesize >= 0 && s->off >= s->filesize)
715 len = ffurl_read(s->hd, buf, size);
719 s->icy_data_read += len;
720 if (s->chunksize > 0)
727 #define DECOMPRESS_BUF_SIZE (256 * 1024)
728 static int http_buf_read_compressed(URLContext *h, uint8_t *buf, int size)
730 HTTPContext *s = h->priv_data;
733 if (!s->inflate_buffer) {
734 s->inflate_buffer = av_malloc(DECOMPRESS_BUF_SIZE);
735 if (!s->inflate_buffer)
736 return AVERROR(ENOMEM);
739 if (s->inflate_stream.avail_in == 0) {
740 int read = http_buf_read(h, s->inflate_buffer, DECOMPRESS_BUF_SIZE);
743 s->inflate_stream.next_in = s->inflate_buffer;
744 s->inflate_stream.avail_in = read;
747 s->inflate_stream.avail_out = size;
748 s->inflate_stream.next_out = buf;
750 ret = inflate(&s->inflate_stream, Z_SYNC_FLUSH);
751 if (ret != Z_OK && ret != Z_STREAM_END)
752 av_log(h, AV_LOG_WARNING, "inflate return value: %d, %s\n", ret, s->inflate_stream.msg);
754 return size - s->inflate_stream.avail_out;
758 static int http_read(URLContext *h, uint8_t *buf, int size)
760 HTTPContext *s = h->priv_data;
761 int err, new_location;
766 if (s->end_chunked_post && !s->end_header) {
767 err = http_read_header(h, &new_location);
772 if (s->chunksize >= 0) {
778 if ((err = http_get_line(s, line, sizeof(line))) < 0)
780 } while (!*line); /* skip CR LF from last chunk */
782 s->chunksize = strtoll(line, NULL, 16);
784 av_dlog(NULL, "Chunked encoding data size: %"PRId64"'\n", s->chunksize);
791 size = FFMIN(size, s->chunksize);
793 if (s->icy_metaint > 0) {
794 int remaining = s->icy_metaint - s->icy_data_read; /* until next metadata packet */
796 // The metadata packet is variable sized. It has a 1 byte header
797 // which sets the length of the packet (divided by 16). If it's 0,
798 // the metadata doesn't change. After the packet, icy_metaint bytes
799 // of normal data follow.
800 int ch = http_getc(s);
804 char data[255 * 16 + 1];
808 for (n = 0; n < ch; n++)
809 data[n] = http_getc(s);
811 if ((ret = av_opt_set(s, "icy_metadata_packet", data, 0)) < 0)
814 s->icy_data_read = 0;
815 remaining = s->icy_metaint;
817 size = FFMIN(size, remaining);
821 return http_buf_read_compressed(h, buf, size);
823 return http_buf_read(h, buf, size);
826 /* used only when posting data */
827 static int http_write(URLContext *h, const uint8_t *buf, int size)
829 char temp[11] = ""; /* 32-bit hex + CRLF + nul */
831 char crlf[] = "\r\n";
832 HTTPContext *s = h->priv_data;
834 if (!s->chunked_post) {
835 /* non-chunked data is sent without any special encoding */
836 return ffurl_write(s->hd, buf, size);
839 /* silently ignore zero-size data since chunk encoding that would
842 /* upload data using chunked encoding */
843 snprintf(temp, sizeof(temp), "%x\r\n", size);
845 if ((ret = ffurl_write(s->hd, temp, strlen(temp))) < 0 ||
846 (ret = ffurl_write(s->hd, buf, size)) < 0 ||
847 (ret = ffurl_write(s->hd, crlf, sizeof(crlf) - 1)) < 0)
853 static int http_shutdown(URLContext *h, int flags)
856 char footer[] = "0\r\n\r\n";
857 HTTPContext *s = h->priv_data;
859 /* signal end of chunked encoding if used */
860 if ((flags & AVIO_FLAG_WRITE) && s->chunked_post) {
861 ret = ffurl_write(s->hd, footer, sizeof(footer) - 1);
862 ret = ret > 0 ? 0 : ret;
863 s->end_chunked_post = 1;
869 static int http_close(URLContext *h)
872 HTTPContext *s = h->priv_data;
875 inflateEnd(&s->inflate_stream);
876 av_freep(&s->inflate_buffer);
879 if (!s->end_chunked_post) {
880 /* Close the write direction by sending the end of chunked encoding. */
881 ret = http_shutdown(h, h->flags);
885 ffurl_closep(&s->hd);
886 av_dict_free(&s->chained_options);
890 static int64_t http_seek(URLContext *h, int64_t off, int whence)
892 HTTPContext *s = h->priv_data;
893 URLContext *old_hd = s->hd;
894 int64_t old_off = s->off;
895 uint8_t old_buf[BUFFER_SIZE];
897 AVDictionary *options = NULL;
899 if (whence == AVSEEK_SIZE)
901 else if ((s->filesize == -1 && whence == SEEK_END) || h->is_streamed)
904 /* we save the old context in case the seek fails */
905 old_buf_size = s->buf_end - s->buf_ptr;
906 memcpy(old_buf, s->buf_ptr, old_buf_size);
908 if (whence == SEEK_CUR)
910 else if (whence == SEEK_END)
914 /* if it fails, continue on old connection */
915 av_dict_copy(&options, s->chained_options, 0);
916 if (http_open_cnx(h, &options) < 0) {
917 av_dict_free(&options);
918 memcpy(s->buffer, old_buf, old_buf_size);
919 s->buf_ptr = s->buffer;
920 s->buf_end = s->buffer + old_buf_size;
925 av_dict_free(&options);
931 http_get_file_handle(URLContext *h)
933 HTTPContext *s = h->priv_data;
934 return ffurl_get_file_handle(s->hd);
937 #if CONFIG_HTTP_PROTOCOL
938 URLProtocol ff_http_protocol = {
940 .url_open2 = http_open,
941 .url_read = http_read,
942 .url_write = http_write,
943 .url_seek = http_seek,
944 .url_close = http_close,
945 .url_get_file_handle = http_get_file_handle,
946 .url_shutdown = http_shutdown,
947 .priv_data_size = sizeof(HTTPContext),
948 .priv_data_class = &http_context_class,
949 .flags = URL_PROTOCOL_FLAG_NETWORK,
952 #if CONFIG_HTTPS_PROTOCOL
953 URLProtocol ff_https_protocol = {
955 .url_open2 = http_open,
956 .url_read = http_read,
957 .url_write = http_write,
958 .url_seek = http_seek,
959 .url_close = http_close,
960 .url_get_file_handle = http_get_file_handle,
961 .url_shutdown = http_shutdown,
962 .priv_data_size = sizeof(HTTPContext),
963 .priv_data_class = &https_context_class,
964 .flags = URL_PROTOCOL_FLAG_NETWORK,
968 #if CONFIG_HTTPPROXY_PROTOCOL
969 static int http_proxy_close(URLContext *h)
971 HTTPContext *s = h->priv_data;
973 ffurl_closep(&s->hd);
977 static int http_proxy_open(URLContext *h, const char *uri, int flags)
979 HTTPContext *s = h->priv_data;
980 char hostname[1024], hoststr[1024];
981 char auth[1024], pathbuf[1024], *path;
983 int port, ret = 0, attempts = 0;
984 HTTPAuthType cur_auth_type;
988 if( s->seekable == 1 )
993 av_url_split(NULL, 0, auth, sizeof(auth), hostname, sizeof(hostname), &port,
994 pathbuf, sizeof(pathbuf), uri);
995 ff_url_join(hoststr, sizeof(hoststr), NULL, NULL, hostname, port, NULL);
1000 ff_url_join(lower_url, sizeof(lower_url), "tcp", NULL, hostname, port,
1003 ret = ffurl_open(&s->hd, lower_url, AVIO_FLAG_READ_WRITE,
1004 &h->interrupt_callback, NULL);
1008 authstr = ff_http_auth_create_response(&s->proxy_auth_state, auth,
1010 snprintf(s->buffer, sizeof(s->buffer),
1011 "CONNECT %s HTTP/1.1\r\n"
1013 "Connection: close\r\n"
1018 authstr ? "Proxy-" : "", authstr ? authstr : "");
1021 if ((ret = ffurl_write(s->hd, s->buffer, strlen(s->buffer))) < 0)
1024 s->buf_ptr = s->buffer;
1025 s->buf_end = s->buffer;
1028 cur_auth_type = s->proxy_auth_state.auth_type;
1030 /* Note: This uses buffering, potentially reading more than the
1031 * HTTP header. If tunneling a protocol where the server starts
1032 * the conversation, we might buffer part of that here, too.
1033 * Reading that requires using the proper ffurl_read() function
1034 * on this URLContext, not using the fd directly (as the tls
1035 * protocol does). This shouldn't be an issue for tls though,
1036 * since the client starts the conversation there, so there
1037 * is no extra data that we might buffer up here.
1039 ret = http_read_header(h, &new_loc);
1044 if (s->http_code == 407 &&
1045 (cur_auth_type == HTTP_AUTH_NONE || s->proxy_auth_state.stale) &&
1046 s->proxy_auth_state.auth_type != HTTP_AUTH_NONE && attempts < 2) {
1047 ffurl_closep(&s->hd);
1051 if (s->http_code < 400)
1056 http_proxy_close(h);
1060 static int http_proxy_write(URLContext *h, const uint8_t *buf, int size)
1062 HTTPContext *s = h->priv_data;
1063 return ffurl_write(s->hd, buf, size);
1066 URLProtocol ff_httpproxy_protocol = {
1067 .name = "httpproxy",
1068 .url_open = http_proxy_open,
1069 .url_read = http_buf_read,
1070 .url_write = http_proxy_write,
1071 .url_close = http_proxy_close,
1072 .url_get_file_handle = http_get_file_handle,
1073 .priv_data_size = sizeof(HTTPContext),
1074 .flags = URL_PROTOCOL_FLAG_NETWORK,