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)) {
494 cdomain = av_strdup(¶m[7]);
495 } else if (!av_strncasecmp("secure", param, 6) ||
496 !av_strncasecmp("comment", param, 7) ||
497 !av_strncasecmp("max-age", param, 7) ||
498 !av_strncasecmp("version", param, 7)) {
499 // ignore Comment, Max-Age, Secure and Version
502 cvalue = av_strdup(param);
506 cdomain = av_strdup(domain);
508 // ensure all of the necessary values are valid
509 if (!cdomain || !cpath || !cvalue) {
510 av_log(s, AV_LOG_WARNING,
511 "Invalid cookie found, no value, path or domain specified\n");
515 // check if the request path matches the cookie path
516 if (av_strncasecmp(path, cpath, strlen(cpath)))
519 // the domain should be at least the size of our cookie domain
520 domain_offset = strlen(domain) - strlen(cdomain);
521 if (domain_offset < 0)
524 // match the cookie domain
525 if (av_strcasecmp(&domain[domain_offset], cdomain))
528 // cookie parameters match, so copy the value
530 if (!(*cookies = av_strdup(cvalue))) {
531 ret = AVERROR(ENOMEM);
535 char *tmp = *cookies;
536 size_t str_size = strlen(cvalue) + strlen(*cookies) + 3;
537 if (!(*cookies = av_malloc(str_size))) {
538 ret = AVERROR(ENOMEM);
541 snprintf(*cookies, str_size, "%s; %s", tmp, cvalue);
550 if (*cookies) av_freep(cookies);
551 av_free(cset_cookies);
556 av_free(cset_cookies);
561 static inline int has_header(const char *str, const char *header)
563 /* header + 2 to skip over CRLF prefix. (make sure you have one!) */
566 return av_stristart(str, header + 2, NULL) || av_stristr(str, header);
569 static int http_read_header(URLContext *h, int *new_location)
571 HTTPContext *s = h->priv_data;
572 char line[MAX_URL_SIZE];
578 if ((err = http_get_line(s, line, sizeof(line))) < 0)
581 av_log(h, AV_LOG_DEBUG, "header='%s'\n", line);
583 err = process_line(h, line, s->line_count, new_location);
591 if (s->seekable == -1 && s->is_mediagateway && s->filesize == 2000000000)
592 h->is_streamed = 1; /* we can in fact _not_ seek */
597 static int http_connect(URLContext *h, const char *path, const char *local_path,
598 const char *hoststr, const char *auth,
599 const char *proxyauth, int *new_location)
601 HTTPContext *s = h->priv_data;
603 char headers[4096] = "";
604 char *authstr = NULL, *proxyauthstr = NULL;
605 int64_t off = s->off;
608 int send_expect_100 = 0;
611 /* send http header */
612 post = h->flags & AVIO_FLAG_WRITE;
615 /* force POST method and disable chunked encoding when
616 * custom HTTP post data is set */
621 method = post ? "POST" : "GET";
622 authstr = ff_http_auth_create_response(&s->auth_state, auth, local_path,
624 proxyauthstr = ff_http_auth_create_response(&s->proxy_auth_state, proxyauth,
626 if (post && !s->post_data) {
627 send_expect_100 = s->send_expect_100;
628 /* The user has supplied authentication but we don't know the auth type,
629 * send Expect: 100-continue to get the 401 response including the
630 * WWW-Authenticate header, or an 100 continue if no auth actually
633 s->auth_state.auth_type == HTTP_AUTH_NONE &&
638 /* set default headers if needed */
639 if (!has_header(s->headers, "\r\nUser-Agent: "))
640 len += av_strlcatf(headers + len, sizeof(headers) - len,
641 "User-Agent: %s\r\n", s->user_agent);
642 if (!has_header(s->headers, "\r\nAccept: "))
643 len += av_strlcpy(headers + len, "Accept: */*\r\n",
644 sizeof(headers) - len);
645 // Note: we send this on purpose even when s->off is 0 when we're probing,
646 // since it allows us to detect more reliably if a (non-conforming)
647 // server supports seeking by analysing the reply headers.
648 if (!has_header(s->headers, "\r\nRange: ") && !post && (s->off > 0 || s->req_end_offset || s->seekable == -1)) {
649 len += av_strlcatf(headers + len, sizeof(headers) - len,
650 "Range: bytes=%"PRId64"-", s->off);
651 if (s->req_end_offset)
652 len += av_strlcatf(headers + len, sizeof(headers) - len,
653 "%"PRId64, s->req_end_offset - 1);
654 len += av_strlcpy(headers + len, "\r\n",
655 sizeof(headers) - len);
657 if (send_expect_100 && !has_header(s->headers, "\r\nExpect: "))
658 len += av_strlcatf(headers + len, sizeof(headers) - len,
659 "Expect: 100-continue\r\n");
661 if (!has_header(s->headers, "\r\nConnection: ")) {
662 if (s->multiple_requests) {
663 len += av_strlcpy(headers + len, "Connection: keep-alive\r\n",
664 sizeof(headers) - len);
666 len += av_strlcpy(headers + len, "Connection: close\r\n",
667 sizeof(headers) - len);
671 if (!has_header(s->headers, "\r\nHost: "))
672 len += av_strlcatf(headers + len, sizeof(headers) - len,
673 "Host: %s\r\n", hoststr);
674 if (!has_header(s->headers, "\r\nContent-Length: ") && s->post_data)
675 len += av_strlcatf(headers + len, sizeof(headers) - len,
676 "Content-Length: %d\r\n", s->post_datalen);
677 if (!has_header(s->headers, "\r\nContent-Type: ") && s->content_type)
678 len += av_strlcatf(headers + len, sizeof(headers) - len,
679 "Content-Type: %s\r\n", s->content_type);
680 if (!has_header(s->headers, "\r\nCookie: ") && s->cookies) {
681 char *cookies = NULL;
682 if (!get_cookies(s, &cookies, path, hoststr)) {
683 len += av_strlcatf(headers + len, sizeof(headers) - len,
684 "Cookie: %s\r\n", cookies);
688 if (!has_header(s->headers, "\r\nIcy-MetaData: ") && s->icy) {
689 len += av_strlcatf(headers + len, sizeof(headers) - len,
690 "Icy-MetaData: %d\r\n", 1);
693 /* now add in custom headers */
695 av_strlcpy(headers + len, s->headers, sizeof(headers) - len);
697 snprintf(s->buffer, sizeof(s->buffer),
706 post && s->chunked_post ? "Transfer-Encoding: chunked\r\n" : "",
708 authstr ? authstr : "",
709 proxyauthstr ? "Proxy-" : "", proxyauthstr ? proxyauthstr : "");
712 av_freep(&proxyauthstr);
714 av_log(h, AV_LOG_DEBUG, "request: %s\n", s->buffer);
716 if ((err = ffurl_write(s->hd, s->buffer, strlen(s->buffer))) < 0)
720 if ((err = ffurl_write(s->hd, s->post_data, s->post_datalen)) < 0)
723 /* init input buffer */
724 s->buf_ptr = s->buffer;
725 s->buf_end = s->buffer;
728 s->icy_data_read = 0;
731 s->end_chunked_post = 0;
733 if (post && !s->post_data && !send_expect_100) {
734 /* Pretend that it did work. We didn't read any header yet, since
735 * we've still to send the POST data, but the code calling this
736 * function will check http_code after we return. */
741 /* wait for header */
742 err = http_read_header(h, new_location);
746 return (off == s->off) ? 0 : -1;
750 static int http_buf_read(URLContext *h, uint8_t *buf, int size)
752 HTTPContext *s = h->priv_data;
754 /* read bytes from input buffer first */
755 len = s->buf_end - s->buf_ptr;
759 memcpy(buf, s->buf_ptr, len);
762 if (!s->willclose && s->filesize >= 0 && s->off >= s->filesize)
764 len = ffurl_read(s->hd, buf, size);
768 s->icy_data_read += len;
769 if (s->chunksize > 0)
776 #define DECOMPRESS_BUF_SIZE (256 * 1024)
777 static int http_buf_read_compressed(URLContext *h, uint8_t *buf, int size)
779 HTTPContext *s = h->priv_data;
782 if (!s->inflate_buffer) {
783 s->inflate_buffer = av_malloc(DECOMPRESS_BUF_SIZE);
784 if (!s->inflate_buffer)
785 return AVERROR(ENOMEM);
788 if (s->inflate_stream.avail_in == 0) {
789 int read = http_buf_read(h, s->inflate_buffer, DECOMPRESS_BUF_SIZE);
792 s->inflate_stream.next_in = s->inflate_buffer;
793 s->inflate_stream.avail_in = read;
796 s->inflate_stream.avail_out = size;
797 s->inflate_stream.next_out = buf;
799 ret = inflate(&s->inflate_stream, Z_SYNC_FLUSH);
800 if (ret != Z_OK && ret != Z_STREAM_END)
801 av_log(h, AV_LOG_WARNING, "inflate return value: %d, %s\n", ret, s->inflate_stream.msg);
803 return size - s->inflate_stream.avail_out;
807 static int http_read(URLContext *h, uint8_t *buf, int size)
809 HTTPContext *s = h->priv_data;
810 int err, new_location;
815 if (s->end_chunked_post && !s->end_header) {
816 err = http_read_header(h, &new_location);
821 if (s->chunksize >= 0) {
827 if ((err = http_get_line(s, line, sizeof(line))) < 0)
829 } while (!*line); /* skip CR LF from last chunk */
831 s->chunksize = strtoll(line, NULL, 16);
833 av_dlog(NULL, "Chunked encoding data size: %"PRId64"'\n", s->chunksize);
840 size = FFMIN(size, s->chunksize);
842 if (s->icy_metaint > 0) {
843 int remaining = s->icy_metaint - s->icy_data_read; /* until next metadata packet */
845 // The metadata packet is variable sized. It has a 1 byte header
846 // which sets the length of the packet (divided by 16). If it's 0,
847 // the metadata doesn't change. After the packet, icy_metaint bytes
848 // of normal data follow.
849 int ch = http_getc(s);
853 char data[255 * 16 + 1];
857 for (n = 0; n < ch; n++)
858 data[n] = http_getc(s);
860 if ((ret = av_opt_set(s, "icy_metadata_packet", data, 0)) < 0)
863 s->icy_data_read = 0;
864 remaining = s->icy_metaint;
866 size = FFMIN(size, remaining);
870 return http_buf_read_compressed(h, buf, size);
872 return http_buf_read(h, buf, size);
875 /* used only when posting data */
876 static int http_write(URLContext *h, const uint8_t *buf, int size)
878 char temp[11] = ""; /* 32-bit hex + CRLF + nul */
880 char crlf[] = "\r\n";
881 HTTPContext *s = h->priv_data;
883 if (!s->chunked_post) {
884 /* non-chunked data is sent without any special encoding */
885 return ffurl_write(s->hd, buf, size);
888 /* silently ignore zero-size data since chunk encoding that would
891 /* upload data using chunked encoding */
892 snprintf(temp, sizeof(temp), "%x\r\n", size);
894 if ((ret = ffurl_write(s->hd, temp, strlen(temp))) < 0 ||
895 (ret = ffurl_write(s->hd, buf, size)) < 0 ||
896 (ret = ffurl_write(s->hd, crlf, sizeof(crlf) - 1)) < 0)
902 static int http_shutdown(URLContext *h, int flags)
905 char footer[] = "0\r\n\r\n";
906 HTTPContext *s = h->priv_data;
908 /* signal end of chunked encoding if used */
909 if ((flags & AVIO_FLAG_WRITE) && s->chunked_post) {
910 ret = ffurl_write(s->hd, footer, sizeof(footer) - 1);
911 ret = ret > 0 ? 0 : ret;
912 s->end_chunked_post = 1;
918 static int http_close(URLContext *h)
921 HTTPContext *s = h->priv_data;
924 inflateEnd(&s->inflate_stream);
925 av_freep(&s->inflate_buffer);
928 if (!s->end_chunked_post) {
929 /* Close the write direction by sending the end of chunked encoding. */
930 ret = http_shutdown(h, h->flags);
934 ffurl_closep(&s->hd);
935 av_dict_free(&s->chained_options);
939 static int64_t http_seek(URLContext *h, int64_t off, int whence)
941 HTTPContext *s = h->priv_data;
942 URLContext *old_hd = s->hd;
943 int64_t old_off = s->off;
944 uint8_t old_buf[BUFFER_SIZE];
946 AVDictionary *options = NULL;
948 if (whence == AVSEEK_SIZE)
950 else if ((whence == SEEK_CUR && off == 0) || (whence == SEEK_SET && off == s->off))
952 else if ((s->filesize == -1 && whence == SEEK_END) || h->is_streamed)
955 /* we save the old context in case the seek fails */
956 old_buf_size = s->buf_end - s->buf_ptr;
957 memcpy(old_buf, s->buf_ptr, old_buf_size);
959 if (whence == SEEK_CUR)
961 else if (whence == SEEK_END)
965 /* if it fails, continue on old connection */
966 av_dict_copy(&options, s->chained_options, 0);
967 if (http_open_cnx(h, &options) < 0) {
968 av_dict_free(&options);
969 memcpy(s->buffer, old_buf, old_buf_size);
970 s->buf_ptr = s->buffer;
971 s->buf_end = s->buffer + old_buf_size;
976 av_dict_free(&options);
982 http_get_file_handle(URLContext *h)
984 HTTPContext *s = h->priv_data;
985 return ffurl_get_file_handle(s->hd);
988 #if CONFIG_HTTP_PROTOCOL
989 URLProtocol ff_http_protocol = {
991 .url_open2 = http_open,
992 .url_read = http_read,
993 .url_write = http_write,
994 .url_seek = http_seek,
995 .url_close = http_close,
996 .url_get_file_handle = http_get_file_handle,
997 .url_shutdown = http_shutdown,
998 .priv_data_size = sizeof(HTTPContext),
999 .priv_data_class = &http_context_class,
1000 .flags = URL_PROTOCOL_FLAG_NETWORK,
1003 #if CONFIG_HTTPS_PROTOCOL
1004 URLProtocol ff_https_protocol = {
1006 .url_open2 = http_open,
1007 .url_read = http_read,
1008 .url_write = http_write,
1009 .url_seek = http_seek,
1010 .url_close = http_close,
1011 .url_get_file_handle = http_get_file_handle,
1012 .url_shutdown = http_shutdown,
1013 .priv_data_size = sizeof(HTTPContext),
1014 .priv_data_class = &https_context_class,
1015 .flags = URL_PROTOCOL_FLAG_NETWORK,
1019 #if CONFIG_HTTPPROXY_PROTOCOL
1020 static int http_proxy_close(URLContext *h)
1022 HTTPContext *s = h->priv_data;
1024 ffurl_closep(&s->hd);
1028 static int http_proxy_open(URLContext *h, const char *uri, int flags)
1030 HTTPContext *s = h->priv_data;
1031 char hostname[1024], hoststr[1024];
1032 char auth[1024], pathbuf[1024], *path;
1033 char lower_url[100];
1034 int port, ret = 0, attempts = 0;
1035 HTTPAuthType cur_auth_type;
1039 if( s->seekable == 1 )
1044 av_url_split(NULL, 0, auth, sizeof(auth), hostname, sizeof(hostname), &port,
1045 pathbuf, sizeof(pathbuf), uri);
1046 ff_url_join(hoststr, sizeof(hoststr), NULL, NULL, hostname, port, NULL);
1051 ff_url_join(lower_url, sizeof(lower_url), "tcp", NULL, hostname, port,
1054 ret = ffurl_open(&s->hd, lower_url, AVIO_FLAG_READ_WRITE,
1055 &h->interrupt_callback, NULL);
1059 authstr = ff_http_auth_create_response(&s->proxy_auth_state, auth,
1061 snprintf(s->buffer, sizeof(s->buffer),
1062 "CONNECT %s HTTP/1.1\r\n"
1064 "Connection: close\r\n"
1069 authstr ? "Proxy-" : "", authstr ? authstr : "");
1072 if ((ret = ffurl_write(s->hd, s->buffer, strlen(s->buffer))) < 0)
1075 s->buf_ptr = s->buffer;
1076 s->buf_end = s->buffer;
1079 cur_auth_type = s->proxy_auth_state.auth_type;
1081 /* Note: This uses buffering, potentially reading more than the
1082 * HTTP header. If tunneling a protocol where the server starts
1083 * the conversation, we might buffer part of that here, too.
1084 * Reading that requires using the proper ffurl_read() function
1085 * on this URLContext, not using the fd directly (as the tls
1086 * protocol does). This shouldn't be an issue for tls though,
1087 * since the client starts the conversation there, so there
1088 * is no extra data that we might buffer up here.
1090 ret = http_read_header(h, &new_loc);
1095 if (s->http_code == 407 &&
1096 (cur_auth_type == HTTP_AUTH_NONE || s->proxy_auth_state.stale) &&
1097 s->proxy_auth_state.auth_type != HTTP_AUTH_NONE && attempts < 2) {
1098 ffurl_closep(&s->hd);
1102 if (s->http_code < 400)
1107 http_proxy_close(h);
1111 static int http_proxy_write(URLContext *h, const uint8_t *buf, int size)
1113 HTTPContext *s = h->priv_data;
1114 return ffurl_write(s->hd, buf, size);
1117 URLProtocol ff_httpproxy_protocol = {
1118 .name = "httpproxy",
1119 .url_open = http_proxy_open,
1120 .url_read = http_buf_read,
1121 .url_write = http_proxy_write,
1122 .url_close = http_proxy_close,
1123 .url_get_file_handle = http_get_file_handle,
1124 .priv_data_size = sizeof(HTTPContext),
1125 .flags = URL_PROTOCOL_FLAG_NETWORK,