2 * HTTP protocol for avconv client
3 * Copyright (c) 2000, 2001 Fabrice Bellard
5 * This file is part of Libav.
7 * Libav 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 * Libav 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 Libav; 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 avconv 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 /* Used if "Transfer-Encoding: chunked" otherwise -1. */
54 int64_t off, end_off, filesize;
56 HTTPAuthState auth_state;
57 HTTPAuthState proxy_auth_state;
62 /* Set if the server correctly handles Connection: close and will close
63 * the connection after feeding us the content. */
66 /* A flag which indicates if the end of chunked encoding has been sent. */
68 /* A flag which indicates we have finished to read POST reply. */
70 /* A flag which indicates if we use persistent connections. */
71 int multiple_requests;
75 /* how much data was read since the last ICY metadata packet */
77 /* after how many bytes of read data a new metadata packet will be found */
79 char *icy_metadata_headers;
80 char *icy_metadata_packet;
83 z_stream inflate_stream;
84 uint8_t *inflate_buffer;
86 AVDictionary *chained_options;
90 #define OFFSET(x) offsetof(HTTPContext, x)
91 #define D AV_OPT_FLAG_DECODING_PARAM
92 #define E AV_OPT_FLAG_ENCODING_PARAM
93 #define DEFAULT_USER_AGENT "Lavf/" AV_STRINGIFY(LIBAVFORMAT_VERSION)
94 static const AVOption options[] = {
95 {"chunked_post", "use chunked transfer-encoding for posts", OFFSET(chunked_post), AV_OPT_TYPE_INT, {.i64 = 1}, 0, 1, E },
96 {"headers", "set custom HTTP headers, can override built in default headers", OFFSET(headers), AV_OPT_TYPE_STRING, { 0 }, 0, 0, D|E },
97 {"content_type", "set a specific content type for the POST messages", OFFSET(content_type), AV_OPT_TYPE_STRING, { 0 }, 0, 0, D|E },
98 {"user_agent", "override User-Agent header", OFFSET(user_agent), AV_OPT_TYPE_STRING, {.str = DEFAULT_USER_AGENT}, 0, 0, D },
99 {"user-agent", "override User-Agent header, for compatibility with ffmpeg", OFFSET(user_agent), AV_OPT_TYPE_STRING, {.str = DEFAULT_USER_AGENT}, 0, 0, D },
100 {"multiple_requests", "use persistent connections", OFFSET(multiple_requests), AV_OPT_TYPE_INT, {.i64 = 0}, 0, 1, D|E },
101 {"post_data", "set custom HTTP post data", OFFSET(post_data), AV_OPT_TYPE_BINARY, .flags = D|E },
102 {"mime_type", "export the MIME type", OFFSET(mime_type), AV_OPT_TYPE_STRING, {0}, 0, 0, AV_OPT_FLAG_EXPORT | AV_OPT_FLAG_READONLY },
103 {"icy", "request ICY metadata", OFFSET(icy), AV_OPT_TYPE_INT, {.i64 = 0}, 0, 1, D },
104 {"icy_metadata_headers", "return ICY metadata headers", OFFSET(icy_metadata_headers), AV_OPT_TYPE_STRING, {0}, 0, 0, AV_OPT_FLAG_EXPORT },
105 {"icy_metadata_packet", "return current ICY metadata packet", OFFSET(icy_metadata_packet), AV_OPT_TYPE_STRING, {0}, 0, 0, AV_OPT_FLAG_EXPORT },
106 {"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" },
107 {"none", "No auth method set, autodetect", 0, AV_OPT_TYPE_CONST, {.i64 = HTTP_AUTH_NONE}, 0, 0, D|E, "auth_type" },
108 {"basic", "HTTP basic authentication", 0, AV_OPT_TYPE_CONST, {.i64 = HTTP_AUTH_BASIC}, 0, 0, D|E, "auth_type" },
109 {"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 },
110 {"location", "The actual location of the data received", OFFSET(location), AV_OPT_TYPE_STRING, { 0 }, 0, 0, D|E },
111 {"offset", "initial byte offset", OFFSET(off), AV_OPT_TYPE_INT64, {.i64 = 0}, 0, INT64_MAX, D },
112 {"end_offset", "try to limit the request to bytes preceding this offset", OFFSET(end_off), AV_OPT_TYPE_INT64, {.i64 = 0}, 0, INT64_MAX, D },
115 #define HTTP_CLASS(flavor)\
116 static const AVClass flavor ## _context_class = {\
117 .class_name = #flavor,\
118 .item_name = av_default_item_name,\
120 .version = LIBAVUTIL_VERSION_INT,\
126 static int http_connect(URLContext *h, const char *path, const char *local_path,
127 const char *hoststr, const char *auth,
128 const char *proxyauth, int *new_location);
130 void ff_http_init_auth_state(URLContext *dest, const URLContext *src)
132 memcpy(&((HTTPContext*)dest->priv_data)->auth_state,
133 &((HTTPContext*)src->priv_data)->auth_state, sizeof(HTTPAuthState));
134 memcpy(&((HTTPContext*)dest->priv_data)->proxy_auth_state,
135 &((HTTPContext*)src->priv_data)->proxy_auth_state,
136 sizeof(HTTPAuthState));
139 /* return non zero if error */
140 static int http_open_cnx(URLContext *h, AVDictionary **options)
142 const char *path, *proxy_path, *lower_proto = "tcp", *local_path;
143 char hostname[1024], hoststr[1024], proto[10];
144 char auth[1024], proxyauth[1024] = "";
145 char path1[MAX_URL_SIZE];
146 char buf[1024], urlbuf[MAX_URL_SIZE];
147 int port, use_proxy, err, location_changed = 0, redirects = 0, attempts = 0;
148 HTTPAuthType cur_auth_type, cur_proxy_auth_type;
149 HTTPContext *s = h->priv_data;
151 /* fill the dest addr */
153 /* needed in any case to build the host string */
154 av_url_split(proto, sizeof(proto), auth, sizeof(auth),
155 hostname, sizeof(hostname), &port,
156 path1, sizeof(path1), s->location);
157 ff_url_join(hoststr, sizeof(hoststr), NULL, NULL, hostname, port, NULL);
159 proxy_path = getenv("http_proxy");
160 use_proxy = !ff_http_match_no_proxy(getenv("no_proxy"), hostname) &&
161 proxy_path != NULL && av_strstart(proxy_path, "http://", NULL);
163 if (!strcmp(proto, "https")) {
172 if (path1[0] == '\0')
178 /* Reassemble the request URL without auth string - we don't
179 * want to leak the auth to the proxy. */
180 ff_url_join(urlbuf, sizeof(urlbuf), proto, NULL, hostname, port, "%s",
183 av_url_split(NULL, 0, proxyauth, sizeof(proxyauth),
184 hostname, sizeof(hostname), &port, NULL, 0, proxy_path);
187 ff_url_join(buf, sizeof(buf), lower_proto, NULL, hostname, port, NULL);
190 err = ffurl_open(&s->hd, buf, AVIO_FLAG_READ_WRITE,
191 &h->interrupt_callback, options);
196 cur_auth_type = s->auth_state.auth_type;
197 cur_proxy_auth_type = s->auth_state.auth_type;
198 if (http_connect(h, path, local_path, hoststr, auth, proxyauth, &location_changed) < 0)
201 if (s->http_code == 401) {
202 if ((cur_auth_type == HTTP_AUTH_NONE || s->auth_state.stale) &&
203 s->auth_state.auth_type != HTTP_AUTH_NONE && attempts < 4) {
210 if (s->http_code == 407) {
211 if ((cur_proxy_auth_type == HTTP_AUTH_NONE || s->proxy_auth_state.stale) &&
212 s->proxy_auth_state.auth_type != HTTP_AUTH_NONE && attempts < 4) {
219 if ((s->http_code == 301 || s->http_code == 302 || s->http_code == 303 || s->http_code == 307)
220 && location_changed == 1) {
221 /* url moved, get next */
224 if (redirects++ >= MAX_REDIRECTS)
226 /* Restart the authentication process with the new target, which
227 * might use a different auth mechanism. */
228 memset(&s->auth_state, 0, sizeof(s->auth_state));
230 location_changed = 0;
241 int ff_http_do_new_request(URLContext *h, const char *uri)
243 HTTPContext *s = h->priv_data;
244 AVDictionary *options = NULL;
248 s->icy_data_read = 0;
249 av_free(s->location);
250 s->location = av_strdup(uri);
252 return AVERROR(ENOMEM);
254 av_dict_copy(&options, s->chained_options, 0);
255 ret = http_open_cnx(h, &options);
256 av_dict_free(&options);
260 static int http_open(URLContext *h, const char *uri, int flags,
261 AVDictionary **options)
263 HTTPContext *s = h->priv_data;
269 s->location = av_strdup(uri);
271 return AVERROR(ENOMEM);
273 av_dict_copy(&s->chained_options, *options, 0);
276 int len = strlen(s->headers);
277 if (len < 2 || strcmp("\r\n", s->headers + len - 2))
278 av_log(h, AV_LOG_WARNING, "No trailing CRLF found in HTTP header.\n");
281 ret = http_open_cnx(h, options);
283 av_dict_free(&s->chained_options);
286 static int http_getc(HTTPContext *s)
289 if (s->buf_ptr >= s->buf_end) {
290 len = ffurl_read(s->hd, s->buffer, BUFFER_SIZE);
293 } else if (len == 0) {
296 s->buf_ptr = s->buffer;
297 s->buf_end = s->buffer + len;
300 return *s->buf_ptr++;
303 static int http_get_line(HTTPContext *s, char *line, int line_size)
315 if (q > line && q[-1] == '\r')
321 if ((q - line) < line_size - 1)
327 static int check_http_code(URLContext *h, int http_code, const char *end)
329 HTTPContext *s = h->priv_data;
330 /* error codes are 4xx and 5xx, but regard 401 as a success, so we
331 * don't abort until all headers have been parsed. */
332 if (http_code >= 400 && http_code < 600 &&
333 (http_code != 401 || s->auth_state.auth_type != HTTP_AUTH_NONE) &&
334 (http_code != 407 || s->proxy_auth_state.auth_type != HTTP_AUTH_NONE)) {
335 end += strspn(end, SPACE_CHARS);
336 av_log(h, AV_LOG_WARNING, "HTTP error %d %s\n", http_code, end);
342 static int parse_location(HTTPContext *s, const char *p)
344 char redirected_location[MAX_URL_SIZE], *new_loc;
345 ff_make_absolute_url(redirected_location, sizeof(redirected_location),
347 new_loc = av_strdup(redirected_location);
349 return AVERROR(ENOMEM);
350 av_free(s->location);
351 s->location = new_loc;
355 /* "bytes $from-$to/$document_size" */
356 static void parse_content_range(URLContext *h, const char *p)
358 HTTPContext *s = h->priv_data;
361 if (!strncmp(p, "bytes ", 6)) {
363 s->off = strtoll(p, NULL, 10);
364 if ((slash = strchr(p, '/')) && strlen(slash) > 0)
365 s->filesize = strtoll(slash+1, NULL, 10);
367 h->is_streamed = 0; /* we _can_ in fact seek */
370 static int parse_content_encoding(URLContext *h, const char *p)
372 HTTPContext *s = h->priv_data;
374 if (!av_strncasecmp(p, "gzip", 4) ||
375 !av_strncasecmp(p, "deflate", 7)) {
378 inflateEnd(&s->inflate_stream);
379 if (inflateInit2(&s->inflate_stream, 32 + 15) != Z_OK) {
380 av_log(h, AV_LOG_WARNING, "Error during zlib initialisation: %s\n",
381 s->inflate_stream.msg);
382 return AVERROR(ENOSYS);
384 if (zlibCompileFlags() & (1 << 17)) {
385 av_log(h, AV_LOG_WARNING,
386 "Your zlib was compiled without gzip support.\n");
387 return AVERROR(ENOSYS);
390 av_log(h, AV_LOG_WARNING,
391 "Compressed (%s) content, need zlib with gzip support\n", p);
392 return AVERROR(ENOSYS);
394 } else if (!av_strncasecmp(p, "identity", 8)) {
395 // The normal, no-encoding case (although servers shouldn't include
396 // the header at all if this is the case).
398 av_log(h, AV_LOG_WARNING, "Unknown content coding: %s\n", p);
399 return AVERROR(ENOSYS);
404 // Concat all Icy- header lines
405 static int parse_icy(HTTPContext *s, const char *tag, const char *p)
407 int len = 4 + strlen(p) + strlen(tag);
408 int is_first = !s->icy_metadata_headers;
411 if (s->icy_metadata_headers)
412 len += strlen(s->icy_metadata_headers);
414 if ((ret = av_reallocp(&s->icy_metadata_headers, len)) < 0)
418 *s->icy_metadata_headers = '\0';
420 av_strlcatf(s->icy_metadata_headers, len, "%s: %s\n", tag, p);
425 static int process_line(URLContext *h, char *line, int line_count,
428 HTTPContext *s = h->priv_data;
433 if (line[0] == '\0') {
439 if (line_count == 0) {
440 while (!av_isspace(*p) && *p != '\0')
442 while (av_isspace(*p))
444 s->http_code = strtol(p, &end, 10);
446 av_dlog(NULL, "http_code=%d\n", s->http_code);
448 if ((ret = check_http_code(h, s->http_code, end)) < 0)
451 while (*p != '\0' && *p != ':')
459 while (av_isspace(*p))
461 if (!av_strcasecmp(tag, "Location")) {
462 if ((ret = parse_location(s, p)) < 0)
465 } else if (!av_strcasecmp(tag, "Content-Length") && s->filesize == -1) {
466 s->filesize = strtoll(p, NULL, 10);
467 } else if (!av_strcasecmp(tag, "Content-Range")) {
468 parse_content_range(h, p);
469 } else if (!av_strcasecmp(tag, "Accept-Ranges") &&
470 !strncmp(p, "bytes", 5)) {
472 } else if (!av_strcasecmp(tag, "Transfer-Encoding") &&
473 !av_strncasecmp(p, "chunked", 7)) {
476 } else if (!av_strcasecmp(tag, "WWW-Authenticate")) {
477 ff_http_auth_handle_header(&s->auth_state, tag, p);
478 } else if (!av_strcasecmp(tag, "Authentication-Info")) {
479 ff_http_auth_handle_header(&s->auth_state, tag, p);
480 } else if (!av_strcasecmp(tag, "Proxy-Authenticate")) {
481 ff_http_auth_handle_header(&s->proxy_auth_state, tag, p);
482 } else if (!av_strcasecmp(tag, "Connection")) {
483 if (!strcmp(p, "close"))
485 } else if (!av_strcasecmp (tag, "Content-Type")) {
486 av_free(s->mime_type);
487 s->mime_type = av_strdup(p);
488 } else if (!av_strcasecmp (tag, "Icy-MetaInt")) {
489 s->icy_metaint = strtoll(p, NULL, 10);
490 } else if (!av_strncasecmp(tag, "Icy-", 4)) {
491 if ((ret = parse_icy(s, tag, p)) < 0)
493 } else if (!av_strcasecmp(tag, "Content-Encoding")) {
494 if ((ret = parse_content_encoding(h, p)) < 0)
501 static inline int has_header(const char *str, const char *header)
503 /* header + 2 to skip over CRLF prefix. (make sure you have one!) */
506 return av_stristart(str, header + 2, NULL) || av_stristr(str, header);
509 static int http_read_header(URLContext *h, int *new_location)
511 HTTPContext *s = h->priv_data;
512 char line[MAX_URL_SIZE];
518 if ((err = http_get_line(s, line, sizeof(line))) < 0)
521 av_dlog(NULL, "header='%s'\n", line);
523 err = process_line(h, line, s->line_count, new_location);
534 static int http_connect(URLContext *h, const char *path, const char *local_path,
535 const char *hoststr, const char *auth,
536 const char *proxyauth, int *new_location)
538 HTTPContext *s = h->priv_data;
540 char headers[1024] = "";
541 char *authstr = NULL, *proxyauthstr = NULL;
542 int64_t off = s->off;
545 int send_expect_100 = 0;
548 /* send http header */
549 post = h->flags & AVIO_FLAG_WRITE;
552 /* force POST method and disable chunked encoding when
553 * custom HTTP post data is set */
558 method = post ? "POST" : "GET";
559 authstr = ff_http_auth_create_response(&s->auth_state, auth, local_path,
561 proxyauthstr = ff_http_auth_create_response(&s->proxy_auth_state, proxyauth,
563 if (post && !s->post_data) {
564 send_expect_100 = s->send_expect_100;
565 /* The user has supplied authentication but we don't know the auth type,
566 * send Expect: 100-continue to get the 401 response including the
567 * WWW-Authenticate header, or an 100 continue if no auth actually
570 s->auth_state.auth_type == HTTP_AUTH_NONE &&
575 /* set default headers if needed */
576 if (!has_header(s->headers, "\r\nUser-Agent: "))
577 len += av_strlcatf(headers + len, sizeof(headers) - len,
578 "User-Agent: %s\r\n", s->user_agent);
579 if (!has_header(s->headers, "\r\nAccept: "))
580 len += av_strlcpy(headers + len, "Accept: */*\r\n",
581 sizeof(headers) - len);
582 // Note: we send this on purpose even when s->off is 0 when we're probing,
583 // since it allows us to detect more reliably if a (non-conforming)
584 // server supports seeking by analysing the reply headers.
585 if (!has_header(s->headers, "\r\nRange: ") && !post) {
586 len += av_strlcatf(headers + len, sizeof(headers) - len,
587 "Range: bytes=%"PRId64"-", s->off);
589 len += av_strlcatf(headers + len, sizeof(headers) - len,
590 "%"PRId64, s->end_off - 1);
591 len += av_strlcpy(headers + len, "\r\n",
592 sizeof(headers) - len);
594 if (send_expect_100 && !has_header(s->headers, "\r\nExpect: "))
595 len += av_strlcatf(headers + len, sizeof(headers) - len,
596 "Expect: 100-continue\r\n");
598 if (!has_header(s->headers, "\r\nConnection: ")) {
599 if (s->multiple_requests) {
600 len += av_strlcpy(headers + len, "Connection: keep-alive\r\n",
601 sizeof(headers) - len);
603 len += av_strlcpy(headers + len, "Connection: close\r\n",
604 sizeof(headers) - len);
608 if (!has_header(s->headers, "\r\nHost: "))
609 len += av_strlcatf(headers + len, sizeof(headers) - len,
610 "Host: %s\r\n", hoststr);
611 if (!has_header(s->headers, "\r\nContent-Length: ") && s->post_data)
612 len += av_strlcatf(headers + len, sizeof(headers) - len,
613 "Content-Length: %d\r\n", s->post_datalen);
615 if (!has_header(s->headers, "\r\nContent-Type: ") && s->content_type)
616 len += av_strlcatf(headers + len, sizeof(headers) - len,
617 "Content-Type: %s\r\n", s->content_type);
618 if (!has_header(s->headers, "\r\nIcy-MetaData: ") && s->icy) {
619 len += av_strlcatf(headers + len, sizeof(headers) - len,
620 "Icy-MetaData: %d\r\n", 1);
623 /* now add in custom headers */
625 av_strlcpy(headers + len, s->headers, sizeof(headers) - len);
627 snprintf(s->buffer, sizeof(s->buffer),
636 post && s->chunked_post ? "Transfer-Encoding: chunked\r\n" : "",
638 authstr ? authstr : "",
639 proxyauthstr ? "Proxy-" : "", proxyauthstr ? proxyauthstr : "");
642 av_freep(&proxyauthstr);
643 if ((err = ffurl_write(s->hd, s->buffer, strlen(s->buffer))) < 0)
647 if ((err = ffurl_write(s->hd, s->post_data, s->post_datalen)) < 0)
650 /* init input buffer */
651 s->buf_ptr = s->buffer;
652 s->buf_end = s->buffer;
655 s->icy_data_read = 0;
658 s->end_chunked_post = 0;
660 if (post && !s->post_data && !send_expect_100) {
661 /* Pretend that it did work. We didn't read any header yet, since
662 * we've still to send the POST data, but the code calling this
663 * function will check http_code after we return. */
668 /* wait for header */
669 err = http_read_header(h, new_location);
673 return (off == s->off) ? 0 : -1;
677 static int http_buf_read(URLContext *h, uint8_t *buf, int size)
679 HTTPContext *s = h->priv_data;
681 /* read bytes from input buffer first */
682 len = s->buf_end - s->buf_ptr;
686 memcpy(buf, s->buf_ptr, len);
689 if (!s->willclose && s->filesize >= 0 && s->off >= s->filesize)
691 len = ffurl_read(s->hd, buf, size);
695 if (s->chunksize > 0)
702 #define DECOMPRESS_BUF_SIZE (256 * 1024)
703 static int http_buf_read_compressed(URLContext *h, uint8_t *buf, int size)
705 HTTPContext *s = h->priv_data;
708 if (!s->inflate_buffer) {
709 s->inflate_buffer = av_malloc(DECOMPRESS_BUF_SIZE);
710 if (!s->inflate_buffer)
711 return AVERROR(ENOMEM);
714 if (s->inflate_stream.avail_in == 0) {
715 int read = http_buf_read(h, s->inflate_buffer, DECOMPRESS_BUF_SIZE);
718 s->inflate_stream.next_in = s->inflate_buffer;
719 s->inflate_stream.avail_in = read;
722 s->inflate_stream.avail_out = size;
723 s->inflate_stream.next_out = buf;
725 ret = inflate(&s->inflate_stream, Z_SYNC_FLUSH);
726 if (ret != Z_OK && ret != Z_STREAM_END)
727 av_log(h, AV_LOG_WARNING, "inflate return value: %d, %s\n", ret, s->inflate_stream.msg);
729 return size - s->inflate_stream.avail_out;
733 static int http_read_stream(URLContext *h, uint8_t *buf, int size)
735 HTTPContext *s = h->priv_data;
736 int err, new_location;
741 if (s->end_chunked_post && !s->end_header) {
742 err = http_read_header(h, &new_location);
747 if (s->chunksize >= 0) {
753 if ((err = http_get_line(s, line, sizeof(line))) < 0)
755 } while (!*line); /* skip CR LF from last chunk */
757 s->chunksize = strtoll(line, NULL, 16);
759 av_dlog(NULL, "Chunked encoding data size: %"PRId64"'\n", s->chunksize);
766 size = FFMIN(size, s->chunksize);
770 return http_buf_read_compressed(h, buf, size);
772 return http_buf_read(h, buf, size);
775 static int http_read_stream_all(URLContext *h, uint8_t *buf, int size)
779 int len = http_read_stream(h, buf + pos, size - pos);
787 static int store_icy(URLContext *h, int size)
789 HTTPContext *s = h->priv_data;
790 /* until next metadata packet */
791 int remaining = s->icy_metaint - s->icy_data_read;
794 return AVERROR_INVALIDDATA;
797 // The metadata packet is variable sized. It has a 1 byte header
798 // which sets the length of the packet (divided by 16). If it's 0,
799 // the metadata doesn't change. After the packet, icy_metaint bytes
800 // of normal data follow.
802 int len = http_read_stream_all(h, &ch, 1);
806 char data[255 * 16 + 1];
809 ret = http_read_stream_all(h, data, len);
813 if ((ret = av_opt_set(s, "icy_metadata_packet", data, 0)) < 0)
816 s->icy_data_read = 0;
817 remaining = s->icy_metaint;
820 return FFMIN(size, remaining);
823 static int http_read(URLContext *h, uint8_t *buf, int size)
825 HTTPContext *s = h->priv_data;
827 if (s->icy_metaint > 0) {
828 size = store_icy(h, size);
833 size = http_read_stream(h, buf, size);
835 s->icy_data_read += size;
839 /* used only when posting data */
840 static int http_write(URLContext *h, const uint8_t *buf, int size)
842 char temp[11] = ""; /* 32-bit hex + CRLF + nul */
844 char crlf[] = "\r\n";
845 HTTPContext *s = h->priv_data;
847 if (!s->chunked_post) {
848 /* non-chunked data is sent without any special encoding */
849 return ffurl_write(s->hd, buf, size);
852 /* silently ignore zero-size data since chunk encoding that would
855 /* upload data using chunked encoding */
856 snprintf(temp, sizeof(temp), "%x\r\n", size);
858 if ((ret = ffurl_write(s->hd, temp, strlen(temp))) < 0 ||
859 (ret = ffurl_write(s->hd, buf, size)) < 0 ||
860 (ret = ffurl_write(s->hd, crlf, sizeof(crlf) - 1)) < 0)
866 static int http_shutdown(URLContext *h, int flags)
869 char footer[] = "0\r\n\r\n";
870 HTTPContext *s = h->priv_data;
872 /* signal end of chunked encoding if used */
873 if ((flags & AVIO_FLAG_WRITE) && s->chunked_post) {
874 ret = ffurl_write(s->hd, footer, sizeof(footer) - 1);
875 ret = ret > 0 ? 0 : ret;
876 s->end_chunked_post = 1;
882 static int http_close(URLContext *h)
885 HTTPContext *s = h->priv_data;
888 inflateEnd(&s->inflate_stream);
889 av_freep(&s->inflate_buffer);
892 if (!s->end_chunked_post) {
893 /* Close the write direction by sending the end of chunked encoding. */
894 ret = http_shutdown(h, h->flags);
899 av_dict_free(&s->chained_options);
903 static int64_t http_seek(URLContext *h, int64_t off, int whence)
905 HTTPContext *s = h->priv_data;
906 URLContext *old_hd = s->hd;
907 int64_t old_off = s->off;
908 uint8_t old_buf[BUFFER_SIZE];
909 int old_buf_size, ret;
910 AVDictionary *options = NULL;
912 if (whence == AVSEEK_SIZE)
914 else if ((whence == SEEK_CUR && off == 0) ||
915 (whence == SEEK_SET && off == s->off))
917 else if ((s->filesize == -1 && whence == SEEK_END) || h->is_streamed)
918 return AVERROR(ENOSYS);
920 /* we save the old context in case the seek fails */
921 old_buf_size = s->buf_end - s->buf_ptr;
922 memcpy(old_buf, s->buf_ptr, old_buf_size);
924 if (whence == SEEK_CUR)
926 else if (whence == SEEK_END)
930 /* if it fails, continue on old connection */
931 av_dict_copy(&options, s->chained_options, 0);
932 if ((ret = http_open_cnx(h, &options)) < 0) {
933 av_dict_free(&options);
934 memcpy(s->buffer, old_buf, old_buf_size);
935 s->buf_ptr = s->buffer;
936 s->buf_end = s->buffer + old_buf_size;
941 av_dict_free(&options);
947 http_get_file_handle(URLContext *h)
949 HTTPContext *s = h->priv_data;
950 return ffurl_get_file_handle(s->hd);
953 #if CONFIG_HTTP_PROTOCOL
954 URLProtocol ff_http_protocol = {
956 .url_open2 = http_open,
957 .url_read = http_read,
958 .url_write = http_write,
959 .url_seek = http_seek,
960 .url_close = http_close,
961 .url_get_file_handle = http_get_file_handle,
962 .url_shutdown = http_shutdown,
963 .priv_data_size = sizeof(HTTPContext),
964 .priv_data_class = &http_context_class,
965 .flags = URL_PROTOCOL_FLAG_NETWORK,
968 #if CONFIG_HTTPS_PROTOCOL
969 URLProtocol ff_https_protocol = {
971 .url_open2 = http_open,
972 .url_read = http_read,
973 .url_write = http_write,
974 .url_seek = http_seek,
975 .url_close = http_close,
976 .url_get_file_handle = http_get_file_handle,
977 .url_shutdown = http_shutdown,
978 .priv_data_size = sizeof(HTTPContext),
979 .priv_data_class = &https_context_class,
980 .flags = URL_PROTOCOL_FLAG_NETWORK,
984 #if CONFIG_HTTPPROXY_PROTOCOL
985 static int http_proxy_close(URLContext *h)
987 HTTPContext *s = h->priv_data;
993 static int http_proxy_open(URLContext *h, const char *uri, int flags)
995 HTTPContext *s = h->priv_data;
996 char hostname[1024], hoststr[1024];
997 char auth[1024], pathbuf[1024], *path;
999 int port, ret = 0, attempts = 0;
1000 HTTPAuthType cur_auth_type;
1006 av_url_split(NULL, 0, auth, sizeof(auth), hostname, sizeof(hostname), &port,
1007 pathbuf, sizeof(pathbuf), uri);
1008 ff_url_join(hoststr, sizeof(hoststr), NULL, NULL, hostname, port, NULL);
1013 ff_url_join(lower_url, sizeof(lower_url), "tcp", NULL, hostname, port,
1016 ret = ffurl_open(&s->hd, lower_url, AVIO_FLAG_READ_WRITE,
1017 &h->interrupt_callback, NULL);
1021 authstr = ff_http_auth_create_response(&s->proxy_auth_state, auth,
1023 snprintf(s->buffer, sizeof(s->buffer),
1024 "CONNECT %s HTTP/1.1\r\n"
1026 "Connection: close\r\n"
1031 authstr ? "Proxy-" : "", authstr ? authstr : "");
1034 if ((ret = ffurl_write(s->hd, s->buffer, strlen(s->buffer))) < 0)
1037 s->buf_ptr = s->buffer;
1038 s->buf_end = s->buffer;
1041 cur_auth_type = s->proxy_auth_state.auth_type;
1043 /* Note: This uses buffering, potentially reading more than the
1044 * HTTP header. If tunneling a protocol where the server starts
1045 * the conversation, we might buffer part of that here, too.
1046 * Reading that requires using the proper ffurl_read() function
1047 * on this URLContext, not using the fd directly (as the tls
1048 * protocol does). This shouldn't be an issue for tls though,
1049 * since the client starts the conversation there, so there
1050 * is no extra data that we might buffer up here.
1052 ret = http_read_header(h, &new_loc);
1057 if (s->http_code == 407 &&
1058 (cur_auth_type == HTTP_AUTH_NONE || s->proxy_auth_state.stale) &&
1059 s->proxy_auth_state.auth_type != HTTP_AUTH_NONE && attempts < 2) {
1065 if (s->http_code < 400)
1070 http_proxy_close(h);
1074 static int http_proxy_write(URLContext *h, const uint8_t *buf, int size)
1076 HTTPContext *s = h->priv_data;
1077 return ffurl_write(s->hd, buf, size);
1080 URLProtocol ff_httpproxy_protocol = {
1081 .name = "httpproxy",
1082 .url_open = http_proxy_open,
1083 .url_read = http_buf_read,
1084 .url_write = http_proxy_write,
1085 .url_close = http_proxy_close,
1086 .url_get_file_handle = http_get_file_handle,
1087 .priv_data_size = sizeof(HTTPContext),
1088 .flags = URL_PROTOCOL_FLAG_NETWORK,