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. */
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, "auth_type" },
109 #define HTTP_CLASS(flavor)\
110 static const AVClass flavor ## _context_class = {\
111 .class_name = #flavor,\
112 .item_name = av_default_item_name,\
114 .version = LIBAVUTIL_VERSION_INT,\
120 static int http_connect(URLContext *h, const char *path, const char *local_path,
121 const char *hoststr, const char *auth,
122 const char *proxyauth, int *new_location);
124 void ff_http_init_auth_state(URLContext *dest, const URLContext *src)
126 memcpy(&((HTTPContext*)dest->priv_data)->auth_state,
127 &((HTTPContext*)src->priv_data)->auth_state, sizeof(HTTPAuthState));
128 memcpy(&((HTTPContext*)dest->priv_data)->proxy_auth_state,
129 &((HTTPContext*)src->priv_data)->proxy_auth_state,
130 sizeof(HTTPAuthState));
133 /* return non zero if error */
134 static int http_open_cnx(URLContext *h, AVDictionary **options)
136 const char *path, *proxy_path, *lower_proto = "tcp", *local_path;
137 char hostname[1024], hoststr[1024], proto[10];
138 char auth[1024], proxyauth[1024] = "";
139 char path1[MAX_URL_SIZE];
140 char buf[1024], urlbuf[MAX_URL_SIZE];
141 int port, use_proxy, err, location_changed = 0, redirects = 0, attempts = 0;
142 HTTPAuthType cur_auth_type, cur_proxy_auth_type;
143 HTTPContext *s = h->priv_data;
145 /* fill the dest addr */
147 /* needed in any case to build the host string */
148 av_url_split(proto, sizeof(proto), auth, sizeof(auth),
149 hostname, sizeof(hostname), &port,
150 path1, sizeof(path1), s->location);
151 ff_url_join(hoststr, sizeof(hoststr), NULL, NULL, hostname, port, NULL);
153 proxy_path = getenv("http_proxy");
154 use_proxy = !ff_http_match_no_proxy(getenv("no_proxy"), hostname) &&
155 proxy_path != NULL && av_strstart(proxy_path, "http://", NULL);
157 if (!strcmp(proto, "https")) {
166 if (path1[0] == '\0')
172 /* Reassemble the request URL without auth string - we don't
173 * want to leak the auth to the proxy. */
174 ff_url_join(urlbuf, sizeof(urlbuf), proto, NULL, hostname, port, "%s",
177 av_url_split(NULL, 0, proxyauth, sizeof(proxyauth),
178 hostname, sizeof(hostname), &port, NULL, 0, proxy_path);
181 ff_url_join(buf, sizeof(buf), lower_proto, NULL, hostname, port, NULL);
184 err = ffurl_open(&s->hd, buf, AVIO_FLAG_READ_WRITE,
185 &h->interrupt_callback, options);
190 cur_auth_type = s->auth_state.auth_type;
191 cur_proxy_auth_type = s->auth_state.auth_type;
192 if (http_connect(h, path, local_path, hoststr, auth, proxyauth, &location_changed) < 0)
195 if (s->http_code == 401) {
196 if ((cur_auth_type == HTTP_AUTH_NONE || s->auth_state.stale) &&
197 s->auth_state.auth_type != HTTP_AUTH_NONE && attempts < 4) {
198 ffurl_closep(&s->hd);
203 if (s->http_code == 407) {
204 if ((cur_proxy_auth_type == HTTP_AUTH_NONE || s->proxy_auth_state.stale) &&
205 s->proxy_auth_state.auth_type != HTTP_AUTH_NONE && attempts < 4) {
206 ffurl_closep(&s->hd);
211 if ((s->http_code == 301 || s->http_code == 302 || s->http_code == 303 || s->http_code == 307)
212 && location_changed == 1) {
213 /* url moved, get next */
214 ffurl_closep(&s->hd);
215 if (redirects++ >= MAX_REDIRECTS)
217 /* Restart the authentication process with the new target, which
218 * might use a different auth mechanism. */
219 memset(&s->auth_state, 0, sizeof(s->auth_state));
221 location_changed = 0;
227 ffurl_closep(&s->hd);
231 int ff_http_do_new_request(URLContext *h, const char *uri)
233 HTTPContext *s = h->priv_data;
234 AVDictionary *options = NULL;
238 s->icy_data_read = 0;
239 av_strlcpy(s->location, uri, sizeof(s->location));
241 av_dict_copy(&options, s->chained_options, 0);
242 ret = http_open_cnx(h, &options);
243 av_dict_free(&options);
247 static int http_open(URLContext *h, const char *uri, int flags,
248 AVDictionary **options)
250 HTTPContext *s = h->priv_data;
253 if( s->seekable == 1 )
259 av_strlcpy(s->location, uri, sizeof(s->location));
261 av_dict_copy(&s->chained_options, *options, 0);
264 int len = strlen(s->headers);
265 if (len < 2 || strcmp("\r\n", s->headers + len - 2))
266 av_log(h, AV_LOG_WARNING, "No trailing CRLF found in HTTP header.\n");
269 ret = http_open_cnx(h, options);
271 av_dict_free(&s->chained_options);
274 static int http_getc(HTTPContext *s)
277 if (s->buf_ptr >= s->buf_end) {
278 len = ffurl_read(s->hd, s->buffer, BUFFER_SIZE);
281 } else if (len == 0) {
284 s->buf_ptr = s->buffer;
285 s->buf_end = s->buffer + len;
288 return *s->buf_ptr++;
291 static int http_get_line(HTTPContext *s, char *line, int line_size)
303 if (q > line && q[-1] == '\r')
309 if ((q - line) < line_size - 1)
315 static int process_line(URLContext *h, char *line, int line_count,
318 HTTPContext *s = h->priv_data;
320 char redirected_location[MAX_URL_SIZE];
323 if (line[0] == '\0') {
329 if (line_count == 0) {
330 while (!av_isspace(*p) && *p != '\0')
332 while (av_isspace(*p))
334 s->http_code = strtol(p, &end, 10);
336 av_dlog(NULL, "http_code=%d\n", s->http_code);
338 /* error codes are 4xx and 5xx, but regard 401 as a success, so we
339 * don't abort until all headers have been parsed. */
340 if (s->http_code >= 400 && s->http_code < 600 && (s->http_code != 401
341 || s->auth_state.auth_type != HTTP_AUTH_NONE) &&
342 (s->http_code != 407 || s->proxy_auth_state.auth_type != HTTP_AUTH_NONE)) {
343 end += strspn(end, SPACE_CHARS);
344 av_log(h, AV_LOG_WARNING, "HTTP error %d %s\n",
349 while (*p != '\0' && *p != ':')
357 while (av_isspace(*p))
359 if (!av_strcasecmp(tag, "Location")) {
360 ff_make_absolute_url(redirected_location, sizeof(redirected_location), s->location, p);
361 av_strlcpy(s->location, redirected_location, sizeof(s->location));
363 } else if (!av_strcasecmp (tag, "Content-Length") && s->filesize == -1) {
364 s->filesize = strtoll(p, NULL, 10);
365 } else if (!av_strcasecmp (tag, "Content-Range")) {
366 /* "bytes $from-$to/$document_size" */
368 if (!strncmp (p, "bytes ", 6)) {
370 s->off = strtoll(p, NULL, 10);
371 if ((slash = strchr(p, '/')) && strlen(slash) > 0)
372 s->filesize = strtoll(slash+1, NULL, 10);
374 if (s->seekable == -1 && (!s->is_akamai || s->filesize != 2147483647))
375 h->is_streamed = 0; /* we _can_ in fact seek */
376 } else if (!av_strcasecmp(tag, "Accept-Ranges") && !strncmp(p, "bytes", 5) && s->seekable == -1) {
378 } else if (!av_strcasecmp (tag, "Transfer-Encoding") && !av_strncasecmp(p, "chunked", 7)) {
381 } else if (!av_strcasecmp (tag, "WWW-Authenticate")) {
382 ff_http_auth_handle_header(&s->auth_state, tag, p);
383 } else if (!av_strcasecmp (tag, "Authentication-Info")) {
384 ff_http_auth_handle_header(&s->auth_state, tag, p);
385 } else if (!av_strcasecmp (tag, "Proxy-Authenticate")) {
386 ff_http_auth_handle_header(&s->proxy_auth_state, tag, p);
387 } else if (!av_strcasecmp (tag, "Connection")) {
388 if (!strcmp(p, "close"))
390 } else if (!av_strcasecmp (tag, "Server")) {
391 if (!av_strcasecmp (p, "AkamaiGHost")) {
393 } else if (!av_strncasecmp (p, "MediaGateway", 12)) {
394 s->is_mediagateway = 1;
396 } else if (!av_strcasecmp (tag, "Content-Type")) {
397 av_free(s->mime_type); s->mime_type = av_strdup(p);
398 } else if (!av_strcasecmp (tag, "Set-Cookie")) {
400 if (!(s->cookies = av_strdup(p)))
401 return AVERROR(ENOMEM);
403 char *tmp = s->cookies;
404 size_t str_size = strlen(tmp) + strlen(p) + 2;
405 if (!(s->cookies = av_malloc(str_size))) {
407 return AVERROR(ENOMEM);
409 snprintf(s->cookies, str_size, "%s\n%s", tmp, p);
412 } else if (!av_strcasecmp (tag, "Icy-MetaInt")) {
413 s->icy_metaint = strtoll(p, NULL, 10);
414 } else if (!av_strncasecmp(tag, "Icy-", 4)) {
415 // Concat all Icy- header lines
416 char *buf = av_asprintf("%s%s: %s\n",
417 s->icy_metadata_headers ? s->icy_metadata_headers : "", tag, p);
419 return AVERROR(ENOMEM);
420 av_freep(&s->icy_metadata_headers);
421 s->icy_metadata_headers = buf;
422 } else if (!av_strcasecmp (tag, "Content-Encoding")) {
423 if (!av_strncasecmp(p, "gzip", 4) || !av_strncasecmp(p, "deflate", 7)) {
426 inflateEnd(&s->inflate_stream);
427 if (inflateInit2(&s->inflate_stream, 32 + 15) != Z_OK) {
428 av_log(h, AV_LOG_WARNING, "Error during zlib initialisation: %s\n",
429 s->inflate_stream.msg);
430 return AVERROR(ENOSYS);
432 if (zlibCompileFlags() & (1 << 17)) {
433 av_log(h, AV_LOG_WARNING, "Your zlib was compiled without gzip support.\n");
434 return AVERROR(ENOSYS);
437 av_log(h, AV_LOG_WARNING, "Compressed (%s) content, need zlib with gzip support\n", p);
438 return AVERROR(ENOSYS);
440 } else if (!av_strncasecmp(p, "identity", 8)) {
441 // The normal, no-encoding case (although servers shouldn't include
442 // the header at all if this is the case).
444 av_log(h, AV_LOG_WARNING, "Unknown content coding: %s\n", p);
452 * Create a string containing cookie values for use as a HTTP cookie header
453 * field value for a particular path and domain from the cookie values stored in
454 * the HTTP protocol context. The cookie string is stored in *cookies.
456 * @return a negative value if an error condition occurred, 0 otherwise
458 static int get_cookies(HTTPContext *s, char **cookies, const char *path,
461 // cookie strings will look like Set-Cookie header field values. Multiple
462 // Set-Cookie fields will result in multiple values delimited by a newline
464 char *next, *cookie, *set_cookies = av_strdup(s->cookies), *cset_cookies = set_cookies;
466 if (!set_cookies) return AVERROR(EINVAL);
469 while ((cookie = av_strtok(set_cookies, "\n", &next))) {
470 int domain_offset = 0;
471 char *param, *next_param, *cdomain = NULL, *cpath = NULL, *cvalue = NULL;
474 while ((param = av_strtok(cookie, "; ", &next_param))) {
476 if (!av_strncasecmp("path=", param, 5)) {
478 cpath = av_strdup(¶m[5]);
479 } else if (!av_strncasecmp("domain=", param, 7)) {
481 cdomain = av_strdup(¶m[7]);
482 } else if (!av_strncasecmp("secure", param, 6) ||
483 !av_strncasecmp("comment", param, 7) ||
484 !av_strncasecmp("max-age", param, 7) ||
485 !av_strncasecmp("version", param, 7)) {
486 // ignore Comment, Max-Age, Secure and Version
489 cvalue = av_strdup(param);
493 cdomain = av_strdup(domain);
495 // ensure all of the necessary values are valid
496 if (!cdomain || !cpath || !cvalue) {
497 av_log(s, AV_LOG_WARNING,
498 "Invalid cookie found, no value, path or domain specified\n");
502 // check if the request path matches the cookie path
503 if (av_strncasecmp(path, cpath, strlen(cpath)))
506 // the domain should be at least the size of our cookie domain
507 domain_offset = strlen(domain) - strlen(cdomain);
508 if (domain_offset < 0)
511 // match the cookie domain
512 if (av_strcasecmp(&domain[domain_offset], cdomain))
515 // cookie parameters match, so copy the value
517 if (!(*cookies = av_strdup(cvalue))) {
518 ret = AVERROR(ENOMEM);
522 char *tmp = *cookies;
523 size_t str_size = strlen(cvalue) + strlen(*cookies) + 3;
524 if (!(*cookies = av_malloc(str_size))) {
525 ret = AVERROR(ENOMEM);
528 snprintf(*cookies, str_size, "%s; %s", tmp, cvalue);
537 if (*cookies) av_freep(cookies);
538 av_free(cset_cookies);
543 av_free(cset_cookies);
548 static inline int has_header(const char *str, const char *header)
550 /* header + 2 to skip over CRLF prefix. (make sure you have one!) */
553 return av_stristart(str, header + 2, NULL) || av_stristr(str, header);
556 static int http_read_header(URLContext *h, int *new_location)
558 HTTPContext *s = h->priv_data;
559 char line[MAX_URL_SIZE];
565 if ((err = http_get_line(s, line, sizeof(line))) < 0)
568 av_dlog(NULL, "header='%s'\n", line);
570 err = process_line(h, line, s->line_count, new_location);
578 if (s->seekable == -1 && s->is_mediagateway && s->filesize == 2000000000)
579 h->is_streamed = 1; /* we can in fact _not_ seek */
584 static int http_connect(URLContext *h, const char *path, const char *local_path,
585 const char *hoststr, const char *auth,
586 const char *proxyauth, int *new_location)
588 HTTPContext *s = h->priv_data;
590 char headers[4096] = "";
591 char *authstr = NULL, *proxyauthstr = NULL;
592 int64_t off = s->off;
595 int send_expect_100 = 0;
598 /* send http header */
599 post = h->flags & AVIO_FLAG_WRITE;
602 /* force POST method and disable chunked encoding when
603 * custom HTTP post data is set */
608 method = post ? "POST" : "GET";
609 authstr = ff_http_auth_create_response(&s->auth_state, auth, local_path,
611 proxyauthstr = ff_http_auth_create_response(&s->proxy_auth_state, proxyauth,
613 if (post && !s->post_data) {
614 send_expect_100 = s->send_expect_100;
615 /* The user has supplied authentication but we don't know the auth type,
616 * send Expect: 100-continue to get the 401 response including the
617 * WWW-Authenticate header, or an 100 continue if no auth actually
620 s->auth_state.auth_type == HTTP_AUTH_NONE &&
625 /* set default headers if needed */
626 if (!has_header(s->headers, "\r\nUser-Agent: "))
627 len += av_strlcatf(headers + len, sizeof(headers) - len,
628 "User-Agent: %s\r\n", s->user_agent);
629 if (!has_header(s->headers, "\r\nAccept: "))
630 len += av_strlcpy(headers + len, "Accept: */*\r\n",
631 sizeof(headers) - len);
632 // Note: we send this on purpose even when s->off is 0 when we're probing,
633 // since it allows us to detect more reliably if a (non-conforming)
634 // server supports seeking by analysing the reply headers.
635 if (!has_header(s->headers, "\r\nRange: ") && !post && (s->off > 0 || s->seekable == -1))
636 len += av_strlcatf(headers + len, sizeof(headers) - len,
637 "Range: bytes=%"PRId64"-\r\n", s->off);
638 if (send_expect_100 && !has_header(s->headers, "\r\nExpect: "))
639 len += av_strlcatf(headers + len, sizeof(headers) - len,
640 "Expect: 100-continue\r\n");
642 if (!has_header(s->headers, "\r\nConnection: ")) {
643 if (s->multiple_requests) {
644 len += av_strlcpy(headers + len, "Connection: keep-alive\r\n",
645 sizeof(headers) - len);
647 len += av_strlcpy(headers + len, "Connection: close\r\n",
648 sizeof(headers) - len);
652 if (!has_header(s->headers, "\r\nHost: "))
653 len += av_strlcatf(headers + len, sizeof(headers) - len,
654 "Host: %s\r\n", hoststr);
655 if (!has_header(s->headers, "\r\nContent-Length: ") && s->post_data)
656 len += av_strlcatf(headers + len, sizeof(headers) - len,
657 "Content-Length: %d\r\n", s->post_datalen);
658 if (!has_header(s->headers, "\r\nContent-Type: ") && s->content_type)
659 len += av_strlcatf(headers + len, sizeof(headers) - len,
660 "Content-Type: %s\r\n", s->content_type);
661 if (!has_header(s->headers, "\r\nCookie: ") && s->cookies) {
662 char *cookies = NULL;
663 if (!get_cookies(s, &cookies, path, hoststr)) {
664 len += av_strlcatf(headers + len, sizeof(headers) - len,
665 "Cookie: %s\r\n", cookies);
669 if (!has_header(s->headers, "\r\nIcy-MetaData: ") && s->icy) {
670 len += av_strlcatf(headers + len, sizeof(headers) - len,
671 "Icy-MetaData: %d\r\n", 1);
674 /* now add in custom headers */
676 av_strlcpy(headers + len, s->headers, sizeof(headers) - len);
678 snprintf(s->buffer, sizeof(s->buffer),
687 post && s->chunked_post ? "Transfer-Encoding: chunked\r\n" : "",
689 authstr ? authstr : "",
690 proxyauthstr ? "Proxy-" : "", proxyauthstr ? proxyauthstr : "");
693 av_freep(&proxyauthstr);
694 if ((err = ffurl_write(s->hd, s->buffer, strlen(s->buffer))) < 0)
698 if ((err = ffurl_write(s->hd, s->post_data, s->post_datalen)) < 0)
701 /* init input buffer */
702 s->buf_ptr = s->buffer;
703 s->buf_end = s->buffer;
706 s->icy_data_read = 0;
709 s->end_chunked_post = 0;
711 if (post && !s->post_data && !send_expect_100) {
712 /* Pretend that it did work. We didn't read any header yet, since
713 * we've still to send the POST data, but the code calling this
714 * function will check http_code after we return. */
719 /* wait for header */
720 err = http_read_header(h, new_location);
724 return (off == s->off) ? 0 : -1;
728 static int http_buf_read(URLContext *h, uint8_t *buf, int size)
730 HTTPContext *s = h->priv_data;
732 /* read bytes from input buffer first */
733 len = s->buf_end - s->buf_ptr;
737 memcpy(buf, s->buf_ptr, len);
740 if (!s->willclose && s->filesize >= 0 && s->off >= s->filesize)
742 len = ffurl_read(s->hd, buf, size);
746 s->icy_data_read += len;
747 if (s->chunksize > 0)
754 #define DECOMPRESS_BUF_SIZE (256 * 1024)
755 static int http_buf_read_compressed(URLContext *h, uint8_t *buf, int size)
757 HTTPContext *s = h->priv_data;
760 if (!s->inflate_buffer) {
761 s->inflate_buffer = av_malloc(DECOMPRESS_BUF_SIZE);
762 if (!s->inflate_buffer)
763 return AVERROR(ENOMEM);
766 if (s->inflate_stream.avail_in == 0) {
767 int read = http_buf_read(h, s->inflate_buffer, DECOMPRESS_BUF_SIZE);
770 s->inflate_stream.next_in = s->inflate_buffer;
771 s->inflate_stream.avail_in = read;
774 s->inflate_stream.avail_out = size;
775 s->inflate_stream.next_out = buf;
777 ret = inflate(&s->inflate_stream, Z_SYNC_FLUSH);
778 if (ret != Z_OK && ret != Z_STREAM_END)
779 av_log(h, AV_LOG_WARNING, "inflate return value: %d, %s\n", ret, s->inflate_stream.msg);
781 return size - s->inflate_stream.avail_out;
785 static int http_read(URLContext *h, uint8_t *buf, int size)
787 HTTPContext *s = h->priv_data;
788 int err, new_location;
793 if (s->end_chunked_post && !s->end_header) {
794 err = http_read_header(h, &new_location);
799 if (s->chunksize >= 0) {
805 if ((err = http_get_line(s, line, sizeof(line))) < 0)
807 } while (!*line); /* skip CR LF from last chunk */
809 s->chunksize = strtoll(line, NULL, 16);
811 av_dlog(NULL, "Chunked encoding data size: %"PRId64"'\n", s->chunksize);
818 size = FFMIN(size, s->chunksize);
820 if (s->icy_metaint > 0) {
821 int remaining = s->icy_metaint - s->icy_data_read; /* until next metadata packet */
823 // The metadata packet is variable sized. It has a 1 byte header
824 // which sets the length of the packet (divided by 16). If it's 0,
825 // the metadata doesn't change. After the packet, icy_metaint bytes
826 // of normal data follow.
827 int ch = http_getc(s);
831 char data[255 * 16 + 1];
835 for (n = 0; n < ch; n++)
836 data[n] = http_getc(s);
838 if ((ret = av_opt_set(s, "icy_metadata_packet", data, 0)) < 0)
841 s->icy_data_read = 0;
842 remaining = s->icy_metaint;
844 size = FFMIN(size, remaining);
848 return http_buf_read_compressed(h, buf, size);
850 return http_buf_read(h, buf, size);
853 /* used only when posting data */
854 static int http_write(URLContext *h, const uint8_t *buf, int size)
856 char temp[11] = ""; /* 32-bit hex + CRLF + nul */
858 char crlf[] = "\r\n";
859 HTTPContext *s = h->priv_data;
861 if (!s->chunked_post) {
862 /* non-chunked data is sent without any special encoding */
863 return ffurl_write(s->hd, buf, size);
866 /* silently ignore zero-size data since chunk encoding that would
869 /* upload data using chunked encoding */
870 snprintf(temp, sizeof(temp), "%x\r\n", size);
872 if ((ret = ffurl_write(s->hd, temp, strlen(temp))) < 0 ||
873 (ret = ffurl_write(s->hd, buf, size)) < 0 ||
874 (ret = ffurl_write(s->hd, crlf, sizeof(crlf) - 1)) < 0)
880 static int http_shutdown(URLContext *h, int flags)
883 char footer[] = "0\r\n\r\n";
884 HTTPContext *s = h->priv_data;
886 /* signal end of chunked encoding if used */
887 if ((flags & AVIO_FLAG_WRITE) && s->chunked_post) {
888 ret = ffurl_write(s->hd, footer, sizeof(footer) - 1);
889 ret = ret > 0 ? 0 : ret;
890 s->end_chunked_post = 1;
896 static int http_close(URLContext *h)
899 HTTPContext *s = h->priv_data;
902 inflateEnd(&s->inflate_stream);
903 av_freep(&s->inflate_buffer);
906 if (!s->end_chunked_post) {
907 /* Close the write direction by sending the end of chunked encoding. */
908 ret = http_shutdown(h, h->flags);
912 ffurl_closep(&s->hd);
913 av_dict_free(&s->chained_options);
917 static int64_t http_seek(URLContext *h, int64_t off, int whence)
919 HTTPContext *s = h->priv_data;
920 URLContext *old_hd = s->hd;
921 int64_t old_off = s->off;
922 uint8_t old_buf[BUFFER_SIZE];
924 AVDictionary *options = NULL;
926 if (whence == AVSEEK_SIZE)
928 else if ((s->filesize == -1 && whence == SEEK_END) || h->is_streamed)
931 /* we save the old context in case the seek fails */
932 old_buf_size = s->buf_end - s->buf_ptr;
933 memcpy(old_buf, s->buf_ptr, old_buf_size);
935 if (whence == SEEK_CUR)
937 else if (whence == SEEK_END)
941 /* if it fails, continue on old connection */
942 av_dict_copy(&options, s->chained_options, 0);
943 if (http_open_cnx(h, &options) < 0) {
944 av_dict_free(&options);
945 memcpy(s->buffer, old_buf, old_buf_size);
946 s->buf_ptr = s->buffer;
947 s->buf_end = s->buffer + old_buf_size;
952 av_dict_free(&options);
958 http_get_file_handle(URLContext *h)
960 HTTPContext *s = h->priv_data;
961 return ffurl_get_file_handle(s->hd);
964 #if CONFIG_HTTP_PROTOCOL
965 URLProtocol ff_http_protocol = {
967 .url_open2 = http_open,
968 .url_read = http_read,
969 .url_write = http_write,
970 .url_seek = http_seek,
971 .url_close = http_close,
972 .url_get_file_handle = http_get_file_handle,
973 .url_shutdown = http_shutdown,
974 .priv_data_size = sizeof(HTTPContext),
975 .priv_data_class = &http_context_class,
976 .flags = URL_PROTOCOL_FLAG_NETWORK,
979 #if CONFIG_HTTPS_PROTOCOL
980 URLProtocol ff_https_protocol = {
982 .url_open2 = http_open,
983 .url_read = http_read,
984 .url_write = http_write,
985 .url_seek = http_seek,
986 .url_close = http_close,
987 .url_get_file_handle = http_get_file_handle,
988 .url_shutdown = http_shutdown,
989 .priv_data_size = sizeof(HTTPContext),
990 .priv_data_class = &https_context_class,
991 .flags = URL_PROTOCOL_FLAG_NETWORK,
995 #if CONFIG_HTTPPROXY_PROTOCOL
996 static int http_proxy_close(URLContext *h)
998 HTTPContext *s = h->priv_data;
1000 ffurl_closep(&s->hd);
1004 static int http_proxy_open(URLContext *h, const char *uri, int flags)
1006 HTTPContext *s = h->priv_data;
1007 char hostname[1024], hoststr[1024];
1008 char auth[1024], pathbuf[1024], *path;
1009 char lower_url[100];
1010 int port, ret = 0, attempts = 0;
1011 HTTPAuthType cur_auth_type;
1015 if( s->seekable == 1 )
1020 av_url_split(NULL, 0, auth, sizeof(auth), hostname, sizeof(hostname), &port,
1021 pathbuf, sizeof(pathbuf), uri);
1022 ff_url_join(hoststr, sizeof(hoststr), NULL, NULL, hostname, port, NULL);
1027 ff_url_join(lower_url, sizeof(lower_url), "tcp", NULL, hostname, port,
1030 ret = ffurl_open(&s->hd, lower_url, AVIO_FLAG_READ_WRITE,
1031 &h->interrupt_callback, NULL);
1035 authstr = ff_http_auth_create_response(&s->proxy_auth_state, auth,
1037 snprintf(s->buffer, sizeof(s->buffer),
1038 "CONNECT %s HTTP/1.1\r\n"
1040 "Connection: close\r\n"
1045 authstr ? "Proxy-" : "", authstr ? authstr : "");
1048 if ((ret = ffurl_write(s->hd, s->buffer, strlen(s->buffer))) < 0)
1051 s->buf_ptr = s->buffer;
1052 s->buf_end = s->buffer;
1055 cur_auth_type = s->proxy_auth_state.auth_type;
1057 /* Note: This uses buffering, potentially reading more than the
1058 * HTTP header. If tunneling a protocol where the server starts
1059 * the conversation, we might buffer part of that here, too.
1060 * Reading that requires using the proper ffurl_read() function
1061 * on this URLContext, not using the fd directly (as the tls
1062 * protocol does). This shouldn't be an issue for tls though,
1063 * since the client starts the conversation there, so there
1064 * is no extra data that we might buffer up here.
1066 ret = http_read_header(h, &new_loc);
1071 if (s->http_code == 407 &&
1072 (cur_auth_type == HTTP_AUTH_NONE || s->proxy_auth_state.stale) &&
1073 s->proxy_auth_state.auth_type != HTTP_AUTH_NONE && attempts < 2) {
1074 ffurl_closep(&s->hd);
1078 if (s->http_code < 400)
1083 http_proxy_close(h);
1087 static int http_proxy_write(URLContext *h, const uint8_t *buf, int size)
1089 HTTPContext *s = h->priv_data;
1090 return ffurl_write(s->hd, buf, size);
1093 URLProtocol ff_httpproxy_protocol = {
1094 .name = "httpproxy",
1095 .url_open = http_proxy_open,
1096 .url_read = http_buf_read,
1097 .url_write = http_proxy_write,
1098 .url_close = http_proxy_close,
1099 .url_get_file_handle = http_get_file_handle,
1100 .priv_data_size = sizeof(HTTPContext),
1101 .flags = URL_PROTOCOL_FLAG_NETWORK,