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;
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 {"timeout", "set timeout of socket I/O operations", OFFSET(rw_timeout), AV_OPT_TYPE_INT, {.i64 = -1}, -1, INT_MAX, D|E },
97 {"mime_type", "set MIME type", OFFSET(mime_type), AV_OPT_TYPE_STRING, {0}, 0, 0, 0 },
98 {"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 },
99 {"icy", "request ICY metadata", OFFSET(icy), AV_OPT_TYPE_INT, {.i64 = 0}, 0, 1, D },
100 {"icy_metadata_headers", "return ICY metadata headers", OFFSET(icy_metadata_headers), AV_OPT_TYPE_STRING, {0}, 0, 0, 0 },
101 {"icy_metadata_packet", "return current ICY metadata packet", OFFSET(icy_metadata_packet), AV_OPT_TYPE_STRING, {0}, 0, 0, 0 },
104 #define HTTP_CLASS(flavor)\
105 static const AVClass flavor ## _context_class = {\
106 .class_name = #flavor,\
107 .item_name = av_default_item_name,\
109 .version = LIBAVUTIL_VERSION_INT,\
115 static int http_connect(URLContext *h, const char *path, const char *local_path,
116 const char *hoststr, const char *auth,
117 const char *proxyauth, int *new_location);
119 void ff_http_init_auth_state(URLContext *dest, const URLContext *src)
121 memcpy(&((HTTPContext*)dest->priv_data)->auth_state,
122 &((HTTPContext*)src->priv_data)->auth_state, sizeof(HTTPAuthState));
123 memcpy(&((HTTPContext*)dest->priv_data)->proxy_auth_state,
124 &((HTTPContext*)src->priv_data)->proxy_auth_state,
125 sizeof(HTTPAuthState));
128 /* return non zero if error */
129 static int http_open_cnx(URLContext *h)
131 const char *path, *proxy_path, *lower_proto = "tcp", *local_path;
132 char hostname[1024], hoststr[1024], proto[10];
133 char auth[1024], proxyauth[1024] = "";
134 char path1[MAX_URL_SIZE];
135 char buf[1024], urlbuf[MAX_URL_SIZE];
136 int port, use_proxy, err, location_changed = 0, redirects = 0, attempts = 0;
137 HTTPAuthType cur_auth_type, cur_proxy_auth_type;
138 HTTPContext *s = h->priv_data;
140 /* fill the dest addr */
142 /* needed in any case to build the host string */
143 av_url_split(proto, sizeof(proto), auth, sizeof(auth),
144 hostname, sizeof(hostname), &port,
145 path1, sizeof(path1), s->location);
146 ff_url_join(hoststr, sizeof(hoststr), NULL, NULL, hostname, port, NULL);
148 proxy_path = getenv("http_proxy");
149 use_proxy = !ff_http_match_no_proxy(getenv("no_proxy"), hostname) &&
150 proxy_path != NULL && av_strstart(proxy_path, "http://", NULL);
152 if (!strcmp(proto, "https")) {
161 if (path1[0] == '\0')
167 /* Reassemble the request URL without auth string - we don't
168 * want to leak the auth to the proxy. */
169 ff_url_join(urlbuf, sizeof(urlbuf), proto, NULL, hostname, port, "%s",
172 av_url_split(NULL, 0, proxyauth, sizeof(proxyauth),
173 hostname, sizeof(hostname), &port, NULL, 0, proxy_path);
176 ff_url_join(buf, sizeof(buf), lower_proto, NULL, hostname, port, NULL);
179 AVDictionary *opts = NULL;
180 char opts_format[20];
181 if (s->rw_timeout != -1) {
182 snprintf(opts_format, sizeof(opts_format), "%d", s->rw_timeout);
183 av_dict_set(&opts, "timeout", opts_format, 0);
184 } /* if option is not given, don't pass it and let tcp use its own default */
185 err = ffurl_open(&s->hd, buf, AVIO_FLAG_READ_WRITE,
186 &h->interrupt_callback, &opts);
192 cur_auth_type = s->auth_state.auth_type;
193 cur_proxy_auth_type = s->auth_state.auth_type;
194 if (http_connect(h, path, local_path, hoststr, auth, proxyauth, &location_changed) < 0)
197 if (s->http_code == 401) {
198 if ((cur_auth_type == HTTP_AUTH_NONE || s->auth_state.stale) &&
199 s->auth_state.auth_type != HTTP_AUTH_NONE && attempts < 4) {
200 ffurl_closep(&s->hd);
205 if (s->http_code == 407) {
206 if ((cur_proxy_auth_type == HTTP_AUTH_NONE || s->proxy_auth_state.stale) &&
207 s->proxy_auth_state.auth_type != HTTP_AUTH_NONE && attempts < 4) {
208 ffurl_closep(&s->hd);
213 if ((s->http_code == 301 || s->http_code == 302 || s->http_code == 303 || s->http_code == 307)
214 && location_changed == 1) {
215 /* url moved, get next */
216 ffurl_closep(&s->hd);
217 if (redirects++ >= MAX_REDIRECTS)
219 /* Restart the authentication process with the new target, which
220 * might use a different auth mechanism. */
221 memset(&s->auth_state, 0, sizeof(s->auth_state));
223 location_changed = 0;
229 ffurl_closep(&s->hd);
233 int ff_http_do_new_request(URLContext *h, const char *uri)
235 HTTPContext *s = h->priv_data;
238 s->icy_data_read = 0;
239 av_strlcpy(s->location, uri, sizeof(s->location));
241 return http_open_cnx(h);
244 static int http_open(URLContext *h, const char *uri, int flags)
246 HTTPContext *s = h->priv_data;
248 if( s->seekable == 1 )
254 av_strlcpy(s->location, uri, sizeof(s->location));
257 int len = strlen(s->headers);
258 if (len < 2 || strcmp("\r\n", s->headers + len - 2))
259 av_log(h, AV_LOG_WARNING, "No trailing CRLF found in HTTP header.\n");
262 return http_open_cnx(h);
264 static int http_getc(HTTPContext *s)
267 if (s->buf_ptr >= s->buf_end) {
268 len = ffurl_read(s->hd, s->buffer, BUFFER_SIZE);
271 } else if (len == 0) {
274 s->buf_ptr = s->buffer;
275 s->buf_end = s->buffer + len;
278 return *s->buf_ptr++;
281 static int http_get_line(HTTPContext *s, char *line, int line_size)
293 if (q > line && q[-1] == '\r')
299 if ((q - line) < line_size - 1)
305 static int process_line(URLContext *h, char *line, int line_count,
308 HTTPContext *s = h->priv_data;
310 char redirected_location[MAX_URL_SIZE];
313 if (line[0] == '\0') {
319 if (line_count == 0) {
320 while (!av_isspace(*p) && *p != '\0')
322 while (av_isspace(*p))
324 s->http_code = strtol(p, &end, 10);
326 av_dlog(NULL, "http_code=%d\n", s->http_code);
328 /* error codes are 4xx and 5xx, but regard 401 as a success, so we
329 * don't abort until all headers have been parsed. */
330 if (s->http_code >= 400 && s->http_code < 600 && (s->http_code != 401
331 || s->auth_state.auth_type != HTTP_AUTH_NONE) &&
332 (s->http_code != 407 || s->proxy_auth_state.auth_type != HTTP_AUTH_NONE)) {
333 end += strspn(end, SPACE_CHARS);
334 av_log(h, AV_LOG_WARNING, "HTTP error %d %s\n",
339 while (*p != '\0' && *p != ':')
347 while (av_isspace(*p))
349 if (!av_strcasecmp(tag, "Location")) {
350 ff_make_absolute_url(redirected_location, sizeof(redirected_location), s->location, p);
351 av_strlcpy(s->location, redirected_location, sizeof(s->location));
353 } else if (!av_strcasecmp (tag, "Content-Length") && s->filesize == -1) {
354 s->filesize = strtoll(p, NULL, 10);
355 } else if (!av_strcasecmp (tag, "Content-Range")) {
356 /* "bytes $from-$to/$document_size" */
358 if (!strncmp (p, "bytes ", 6)) {
360 s->off = strtoll(p, NULL, 10);
361 if ((slash = strchr(p, '/')) && strlen(slash) > 0)
362 s->filesize = strtoll(slash+1, NULL, 10);
364 if (s->seekable == -1 && (!s->is_akamai || s->filesize != 2147483647))
365 h->is_streamed = 0; /* we _can_ in fact seek */
366 } else if (!av_strcasecmp(tag, "Accept-Ranges") && !strncmp(p, "bytes", 5) && s->seekable == -1) {
368 } else if (!av_strcasecmp (tag, "Transfer-Encoding") && !av_strncasecmp(p, "chunked", 7)) {
371 } else if (!av_strcasecmp (tag, "WWW-Authenticate")) {
372 ff_http_auth_handle_header(&s->auth_state, tag, p);
373 } else if (!av_strcasecmp (tag, "Authentication-Info")) {
374 ff_http_auth_handle_header(&s->auth_state, tag, p);
375 } else if (!av_strcasecmp (tag, "Proxy-Authenticate")) {
376 ff_http_auth_handle_header(&s->proxy_auth_state, tag, p);
377 } else if (!av_strcasecmp (tag, "Connection")) {
378 if (!strcmp(p, "close"))
380 } else if (!av_strcasecmp (tag, "Server") && !av_strcasecmp (p, "AkamaiGHost")) {
382 } else if (!av_strcasecmp (tag, "Content-Type")) {
383 av_free(s->mime_type); s->mime_type = av_strdup(p);
384 } else if (!av_strcasecmp (tag, "Set-Cookie")) {
386 if (!(s->cookies = av_strdup(p)))
387 return AVERROR(ENOMEM);
389 char *tmp = s->cookies;
390 size_t str_size = strlen(tmp) + strlen(p) + 2;
391 if (!(s->cookies = av_malloc(str_size))) {
393 return AVERROR(ENOMEM);
395 snprintf(s->cookies, str_size, "%s\n%s", tmp, p);
398 } else if (!av_strcasecmp (tag, "Icy-MetaInt")) {
399 s->icy_metaint = strtoll(p, NULL, 10);
400 } else if (!av_strncasecmp(tag, "Icy-", 4)) {
401 // Concat all Icy- header lines
402 char *buf = av_asprintf("%s%s: %s\n",
403 s->icy_metadata_headers ? s->icy_metadata_headers : "", tag, p);
405 return AVERROR(ENOMEM);
406 av_freep(&s->icy_metadata_headers);
407 s->icy_metadata_headers = buf;
408 } else if (!av_strcasecmp (tag, "Content-Encoding")) {
409 if (!av_strncasecmp(p, "gzip", 4) || !av_strncasecmp(p, "deflate", 7)) {
412 inflateEnd(&s->inflate_stream);
413 if (inflateInit2(&s->inflate_stream, 32 + 15) != Z_OK) {
414 av_log(h, AV_LOG_WARNING, "Error during zlib initialisation: %s\n",
415 s->inflate_stream.msg);
416 return AVERROR(ENOSYS);
418 if (zlibCompileFlags() & (1 << 17)) {
419 av_log(h, AV_LOG_WARNING, "Your zlib was compiled without gzip support.\n");
420 return AVERROR(ENOSYS);
423 av_log(h, AV_LOG_WARNING, "Compressed (%s) content, need zlib with gzip support\n", p);
424 return AVERROR(ENOSYS);
426 } else if (!av_strncasecmp(p, "identity", 8)) {
427 // The normal, no-encoding case (although servers shouldn't include
428 // the header at all if this is the case).
430 av_log(h, AV_LOG_WARNING, "Unknown content coding: %s\n", p);
431 return AVERROR(ENOSYS);
439 * Create a string containing cookie values for use as a HTTP cookie header
440 * field value for a particular path and domain from the cookie values stored in
441 * the HTTP protocol context. The cookie string is stored in *cookies.
443 * @return a negative value if an error condition occurred, 0 otherwise
445 static int get_cookies(HTTPContext *s, char **cookies, const char *path,
448 // cookie strings will look like Set-Cookie header field values. Multiple
449 // Set-Cookie fields will result in multiple values delimited by a newline
451 char *next, *cookie, *set_cookies = av_strdup(s->cookies), *cset_cookies = set_cookies;
453 if (!set_cookies) return AVERROR(EINVAL);
456 while ((cookie = av_strtok(set_cookies, "\n", &next))) {
457 int domain_offset = 0;
458 char *param, *next_param, *cdomain = NULL, *cpath = NULL, *cvalue = NULL;
461 while ((param = av_strtok(cookie, "; ", &next_param))) {
463 if (!av_strncasecmp("path=", param, 5)) {
465 cpath = av_strdup(¶m[5]);
466 } else if (!av_strncasecmp("domain=", param, 7)) {
468 cdomain = av_strdup(¶m[7]);
469 } else if (!av_strncasecmp("secure", param, 6) ||
470 !av_strncasecmp("comment", param, 7) ||
471 !av_strncasecmp("max-age", param, 7) ||
472 !av_strncasecmp("version", param, 7)) {
473 // ignore Comment, Max-Age, Secure and Version
476 cvalue = av_strdup(param);
480 cdomain = av_strdup(domain);
482 // ensure all of the necessary values are valid
483 if (!cdomain || !cpath || !cvalue) {
484 av_log(s, AV_LOG_WARNING,
485 "Invalid cookie found, no value, path or domain specified\n");
489 // check if the request path matches the cookie path
490 if (av_strncasecmp(path, cpath, strlen(cpath)))
493 // the domain should be at least the size of our cookie domain
494 domain_offset = strlen(domain) - strlen(cdomain);
495 if (domain_offset < 0)
498 // match the cookie domain
499 if (av_strcasecmp(&domain[domain_offset], cdomain))
502 // cookie parameters match, so copy the value
504 if (!(*cookies = av_strdup(cvalue))) {
505 ret = AVERROR(ENOMEM);
509 char *tmp = *cookies;
510 size_t str_size = strlen(cvalue) + strlen(*cookies) + 3;
511 if (!(*cookies = av_malloc(str_size))) {
512 ret = AVERROR(ENOMEM);
515 snprintf(*cookies, str_size, "%s; %s", tmp, cvalue);
524 if (*cookies) av_freep(cookies);
525 av_free(cset_cookies);
530 av_free(cset_cookies);
535 static inline int has_header(const char *str, const char *header)
537 /* header + 2 to skip over CRLF prefix. (make sure you have one!) */
540 return av_stristart(str, header + 2, NULL) || av_stristr(str, header);
543 static int http_read_header(URLContext *h, int *new_location)
545 HTTPContext *s = h->priv_data;
546 char line[MAX_URL_SIZE];
552 if ((err = http_get_line(s, line, sizeof(line))) < 0)
555 av_dlog(NULL, "header='%s'\n", line);
557 err = process_line(h, line, s->line_count, new_location);
568 static int http_connect(URLContext *h, const char *path, const char *local_path,
569 const char *hoststr, const char *auth,
570 const char *proxyauth, int *new_location)
572 HTTPContext *s = h->priv_data;
574 char headers[4096] = "";
575 char *authstr = NULL, *proxyauthstr = NULL;
576 int64_t off = s->off;
581 /* send http header */
582 post = h->flags & AVIO_FLAG_WRITE;
585 /* force POST method and disable chunked encoding when
586 * custom HTTP post data is set */
591 method = post ? "POST" : "GET";
592 authstr = ff_http_auth_create_response(&s->auth_state, auth, local_path,
594 proxyauthstr = ff_http_auth_create_response(&s->proxy_auth_state, proxyauth,
597 /* set default headers if needed */
598 if (!has_header(s->headers, "\r\nUser-Agent: "))
599 len += av_strlcatf(headers + len, sizeof(headers) - len,
600 "User-Agent: %s\r\n", s->user_agent);
601 if (!has_header(s->headers, "\r\nAccept: "))
602 len += av_strlcpy(headers + len, "Accept: */*\r\n",
603 sizeof(headers) - len);
604 // Note: we send this on purpose even when s->off is 0 when we're probing,
605 // since it allows us to detect more reliably if a (non-conforming)
606 // server supports seeking by analysing the reply headers.
607 if (!has_header(s->headers, "\r\nRange: ") && !post && (s->off > 0 || s->seekable == -1))
608 len += av_strlcatf(headers + len, sizeof(headers) - len,
609 "Range: bytes=%"PRId64"-\r\n", s->off);
611 if (!has_header(s->headers, "\r\nConnection: ")) {
612 if (s->multiple_requests) {
613 len += av_strlcpy(headers + len, "Connection: keep-alive\r\n",
614 sizeof(headers) - len);
616 len += av_strlcpy(headers + len, "Connection: close\r\n",
617 sizeof(headers) - len);
621 if (!has_header(s->headers, "\r\nHost: "))
622 len += av_strlcatf(headers + len, sizeof(headers) - len,
623 "Host: %s\r\n", hoststr);
624 if (!has_header(s->headers, "\r\nContent-Length: ") && s->post_data)
625 len += av_strlcatf(headers + len, sizeof(headers) - len,
626 "Content-Length: %d\r\n", s->post_datalen);
627 if (!has_header(s->headers, "\r\nContent-Type: ") && s->content_type)
628 len += av_strlcatf(headers + len, sizeof(headers) - len,
629 "Content-Type: %s\r\n", s->content_type);
630 if (!has_header(s->headers, "\r\nCookie: ") && s->cookies) {
631 char *cookies = NULL;
632 if (!get_cookies(s, &cookies, path, hoststr)) {
633 len += av_strlcatf(headers + len, sizeof(headers) - len,
634 "Cookie: %s\r\n", cookies);
638 if (!has_header(s->headers, "\r\nIcy-MetaData: ") && s->icy) {
639 len += av_strlcatf(headers + len, sizeof(headers) - len,
640 "Icy-MetaData: %d\r\n", 1);
643 /* now add in custom headers */
645 av_strlcpy(headers + len, s->headers, sizeof(headers) - len);
647 snprintf(s->buffer, sizeof(s->buffer),
656 post && s->chunked_post ? "Transfer-Encoding: chunked\r\n" : "",
658 authstr ? authstr : "",
659 proxyauthstr ? "Proxy-" : "", proxyauthstr ? proxyauthstr : "");
662 av_freep(&proxyauthstr);
663 if ((err = ffurl_write(s->hd, s->buffer, strlen(s->buffer))) < 0)
667 if ((err = ffurl_write(s->hd, s->post_data, s->post_datalen)) < 0)
670 /* init input buffer */
671 s->buf_ptr = s->buffer;
672 s->buf_end = s->buffer;
675 s->icy_data_read = 0;
678 s->end_chunked_post = 0;
680 if (post && !s->post_data) {
681 /* Pretend that it did work. We didn't read any header yet, since
682 * we've still to send the POST data, but the code calling this
683 * function will check http_code after we return. */
688 /* wait for header */
689 err = http_read_header(h, new_location);
693 return (off == s->off) ? 0 : -1;
697 static int http_buf_read(URLContext *h, uint8_t *buf, int size)
699 HTTPContext *s = h->priv_data;
701 /* read bytes from input buffer first */
702 len = s->buf_end - s->buf_ptr;
706 memcpy(buf, s->buf_ptr, len);
709 if (!s->willclose && s->filesize >= 0 && s->off >= s->filesize)
711 len = ffurl_read(s->hd, buf, size);
715 s->icy_data_read += len;
716 if (s->chunksize > 0)
723 #define DECOMPRESS_BUF_SIZE (256 * 1024)
724 static int http_buf_read_compressed(URLContext *h, uint8_t *buf, int size)
726 HTTPContext *s = h->priv_data;
729 if (!s->inflate_buffer) {
730 s->inflate_buffer = av_malloc(DECOMPRESS_BUF_SIZE);
731 if (!s->inflate_buffer)
732 return AVERROR(ENOMEM);
735 if (s->inflate_stream.avail_in == 0) {
736 int read = http_buf_read(h, s->inflate_buffer, DECOMPRESS_BUF_SIZE);
739 s->inflate_stream.next_in = s->inflate_buffer;
740 s->inflate_stream.avail_in = read;
743 s->inflate_stream.avail_out = size;
744 s->inflate_stream.next_out = buf;
746 ret = inflate(&s->inflate_stream, Z_SYNC_FLUSH);
747 if (ret != Z_OK && ret != Z_STREAM_END)
748 av_log(h, AV_LOG_WARNING, "inflate return value: %d, %s\n", ret, s->inflate_stream.msg);
750 return size - s->inflate_stream.avail_out;
754 static int http_read(URLContext *h, uint8_t *buf, int size)
756 HTTPContext *s = h->priv_data;
757 int err, new_location;
762 if (s->end_chunked_post && !s->end_header) {
763 err = http_read_header(h, &new_location);
768 if (s->chunksize >= 0) {
774 if ((err = http_get_line(s, line, sizeof(line))) < 0)
776 } while (!*line); /* skip CR LF from last chunk */
778 s->chunksize = strtoll(line, NULL, 16);
780 av_dlog(NULL, "Chunked encoding data size: %"PRId64"'\n", s->chunksize);
787 size = FFMIN(size, s->chunksize);
789 if (s->icy_metaint > 0) {
790 int remaining = s->icy_metaint - s->icy_data_read; /* until next metadata packet */
792 // The metadata packet is variable sized. It has a 1 byte header
793 // which sets the length of the packet (divided by 16). If it's 0,
794 // the metadata doesn't change. After the packet, icy_metaint bytes
795 // of normal data follow.
796 int ch = http_getc(s);
800 char data[255 * 16 + 1];
804 for (n = 0; n < ch; n++)
805 data[n] = http_getc(s);
807 if ((ret = av_opt_set(s, "icy_metadata_packet", data, 0)) < 0)
810 s->icy_data_read = 0;
811 remaining = s->icy_metaint;
813 size = FFMIN(size, remaining);
817 return http_buf_read_compressed(h, buf, size);
819 return http_buf_read(h, buf, size);
822 /* used only when posting data */
823 static int http_write(URLContext *h, const uint8_t *buf, int size)
825 char temp[11] = ""; /* 32-bit hex + CRLF + nul */
827 char crlf[] = "\r\n";
828 HTTPContext *s = h->priv_data;
830 if (!s->chunked_post) {
831 /* non-chunked data is sent without any special encoding */
832 return ffurl_write(s->hd, buf, size);
835 /* silently ignore zero-size data since chunk encoding that would
838 /* upload data using chunked encoding */
839 snprintf(temp, sizeof(temp), "%x\r\n", size);
841 if ((ret = ffurl_write(s->hd, temp, strlen(temp))) < 0 ||
842 (ret = ffurl_write(s->hd, buf, size)) < 0 ||
843 (ret = ffurl_write(s->hd, crlf, sizeof(crlf) - 1)) < 0)
849 static int http_shutdown(URLContext *h, int flags)
852 char footer[] = "0\r\n\r\n";
853 HTTPContext *s = h->priv_data;
855 /* signal end of chunked encoding if used */
856 if ((flags & AVIO_FLAG_WRITE) && s->chunked_post) {
857 ret = ffurl_write(s->hd, footer, sizeof(footer) - 1);
858 ret = ret > 0 ? 0 : ret;
859 s->end_chunked_post = 1;
865 static int http_close(URLContext *h)
868 HTTPContext *s = h->priv_data;
871 inflateEnd(&s->inflate_stream);
872 av_freep(&s->inflate_buffer);
875 if (!s->end_chunked_post) {
876 /* Close the write direction by sending the end of chunked encoding. */
877 ret = http_shutdown(h, h->flags);
881 ffurl_closep(&s->hd);
885 static int64_t http_seek(URLContext *h, int64_t off, int whence)
887 HTTPContext *s = h->priv_data;
888 URLContext *old_hd = s->hd;
889 int64_t old_off = s->off;
890 uint8_t old_buf[BUFFER_SIZE];
893 if (whence == AVSEEK_SIZE)
895 else if ((s->filesize == -1 && whence == SEEK_END) || h->is_streamed)
898 /* we save the old context in case the seek fails */
899 old_buf_size = s->buf_end - s->buf_ptr;
900 memcpy(old_buf, s->buf_ptr, old_buf_size);
902 if (whence == SEEK_CUR)
904 else if (whence == SEEK_END)
908 /* if it fails, continue on old connection */
909 if (http_open_cnx(h) < 0) {
910 memcpy(s->buffer, old_buf, old_buf_size);
911 s->buf_ptr = s->buffer;
912 s->buf_end = s->buffer + old_buf_size;
922 http_get_file_handle(URLContext *h)
924 HTTPContext *s = h->priv_data;
925 return ffurl_get_file_handle(s->hd);
928 #if CONFIG_HTTP_PROTOCOL
929 URLProtocol ff_http_protocol = {
931 .url_open = http_open,
932 .url_read = http_read,
933 .url_write = http_write,
934 .url_seek = http_seek,
935 .url_close = http_close,
936 .url_get_file_handle = http_get_file_handle,
937 .url_shutdown = http_shutdown,
938 .priv_data_size = sizeof(HTTPContext),
939 .priv_data_class = &http_context_class,
940 .flags = URL_PROTOCOL_FLAG_NETWORK,
943 #if CONFIG_HTTPS_PROTOCOL
944 URLProtocol ff_https_protocol = {
946 .url_open = http_open,
947 .url_read = http_read,
948 .url_write = http_write,
949 .url_seek = http_seek,
950 .url_close = http_close,
951 .url_get_file_handle = http_get_file_handle,
952 .url_shutdown = http_shutdown,
953 .priv_data_size = sizeof(HTTPContext),
954 .priv_data_class = &https_context_class,
955 .flags = URL_PROTOCOL_FLAG_NETWORK,
959 #if CONFIG_HTTPPROXY_PROTOCOL
960 static int http_proxy_close(URLContext *h)
962 HTTPContext *s = h->priv_data;
964 ffurl_closep(&s->hd);
968 static int http_proxy_open(URLContext *h, const char *uri, int flags)
970 HTTPContext *s = h->priv_data;
971 char hostname[1024], hoststr[1024];
972 char auth[1024], pathbuf[1024], *path;
974 int port, ret = 0, attempts = 0;
975 HTTPAuthType cur_auth_type;
978 AVDictionary *opts = NULL;
979 char opts_format[20];
981 if( s->seekable == 1 )
986 av_url_split(NULL, 0, auth, sizeof(auth), hostname, sizeof(hostname), &port,
987 pathbuf, sizeof(pathbuf), uri);
988 ff_url_join(hoststr, sizeof(hoststr), NULL, NULL, hostname, port, NULL);
993 ff_url_join(lower_url, sizeof(lower_url), "tcp", NULL, hostname, port,
996 if (s->rw_timeout != -1) {
997 snprintf(opts_format, sizeof(opts_format), "%d", s->rw_timeout);
998 av_dict_set(&opts, "timeout", opts_format, 0);
999 } /* if option is not given, don't pass it and let tcp use its own default */
1000 ret = ffurl_open(&s->hd, lower_url, AVIO_FLAG_READ_WRITE,
1001 &h->interrupt_callback, &opts);
1002 av_dict_free(&opts);
1006 authstr = ff_http_auth_create_response(&s->proxy_auth_state, auth,
1008 snprintf(s->buffer, sizeof(s->buffer),
1009 "CONNECT %s HTTP/1.1\r\n"
1011 "Connection: close\r\n"
1016 authstr ? "Proxy-" : "", authstr ? authstr : "");
1019 if ((ret = ffurl_write(s->hd, s->buffer, strlen(s->buffer))) < 0)
1022 s->buf_ptr = s->buffer;
1023 s->buf_end = s->buffer;
1026 cur_auth_type = s->proxy_auth_state.auth_type;
1028 /* Note: This uses buffering, potentially reading more than the
1029 * HTTP header. If tunneling a protocol where the server starts
1030 * the conversation, we might buffer part of that here, too.
1031 * Reading that requires using the proper ffurl_read() function
1032 * on this URLContext, not using the fd directly (as the tls
1033 * protocol does). This shouldn't be an issue for tls though,
1034 * since the client starts the conversation there, so there
1035 * is no extra data that we might buffer up here.
1037 ret = http_read_header(h, &new_loc);
1042 if (s->http_code == 407 &&
1043 (cur_auth_type == HTTP_AUTH_NONE || s->proxy_auth_state.stale) &&
1044 s->proxy_auth_state.auth_type != HTTP_AUTH_NONE && attempts < 2) {
1045 ffurl_closep(&s->hd);
1049 if (s->http_code < 400)
1054 http_proxy_close(h);
1058 static int http_proxy_write(URLContext *h, const uint8_t *buf, int size)
1060 HTTPContext *s = h->priv_data;
1061 return ffurl_write(s->hd, buf, size);
1064 URLProtocol ff_httpproxy_protocol = {
1065 .name = "httpproxy",
1066 .url_open = http_proxy_open,
1067 .url_read = http_buf_read,
1068 .url_write = http_proxy_write,
1069 .url_close = http_proxy_close,
1070 .url_get_file_handle = http_get_file_handle,
1071 .priv_data_size = sizeof(HTTPContext),
1072 .flags = URL_PROTOCOL_FLAG_NETWORK,