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
26 #endif /* CONFIG_ZLIB */
28 #include "libavutil/avstring.h"
29 #include "libavutil/opt.h"
36 #include "os_support.h"
39 /* XXX: POST protocol is not completely implemented because avconv uses
40 * only a subset of it. */
42 /* The IO buffer size is unrelated to the max URL size in itself, but needs
43 * to be large enough to fit the full request headers (including long
45 #define BUFFER_SIZE MAX_URL_SIZE
46 #define MAX_REDIRECTS 8
51 unsigned char buffer[BUFFER_SIZE], *buf_ptr, *buf_end;
54 /* Used if "Transfer-Encoding: chunked" otherwise -1. */
56 int64_t off, end_off, filesize;
58 HTTPAuthState auth_state;
59 HTTPAuthState proxy_auth_state;
64 /* Set if the server correctly handles Connection: close and will close
65 * the connection after feeding us the content. */
68 /* A flag which indicates if the end of chunked encoding has been sent. */
70 /* A flag which indicates we have finished to read POST reply. */
72 /* A flag which indicates if we use persistent connections. */
73 int multiple_requests;
77 /* how much data was read since the last ICY metadata packet */
79 /* after how many bytes of read data a new metadata packet will be found */
81 char *icy_metadata_headers;
82 char *icy_metadata_packet;
83 AVDictionary *metadata;
86 z_stream inflate_stream;
87 uint8_t *inflate_buffer;
88 #endif /* CONFIG_ZLIB */
89 AVDictionary *chained_options;
94 #define OFFSET(x) offsetof(HTTPContext, x)
95 #define D AV_OPT_FLAG_DECODING_PARAM
96 #define E AV_OPT_FLAG_ENCODING_PARAM
97 #define DEFAULT_USER_AGENT "Lavf/" AV_STRINGIFY(LIBAVFORMAT_VERSION)
99 static const AVOption options[] = {
100 { "chunked_post", "use chunked transfer-encoding for posts", OFFSET(chunked_post), AV_OPT_TYPE_INT, { .i64 = 1 }, 0, 1, E },
101 { "headers", "set custom HTTP headers, can override built in default headers", OFFSET(headers), AV_OPT_TYPE_STRING, { 0 }, 0, 0, D | E },
102 { "content_type", "set a specific content type for the POST messages", OFFSET(content_type), AV_OPT_TYPE_STRING, { 0 }, 0, 0, D | E },
103 { "user_agent", "override User-Agent header", OFFSET(user_agent), AV_OPT_TYPE_STRING, { .str = DEFAULT_USER_AGENT }, 0, 0, D },
104 { "user-agent", "override User-Agent header, for compatibility with ffmpeg", OFFSET(user_agent), AV_OPT_TYPE_STRING, { .str = DEFAULT_USER_AGENT }, 0, 0, D },
105 { "multiple_requests", "use persistent connections", OFFSET(multiple_requests), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 1, D | E },
106 { "post_data", "set custom HTTP post data", OFFSET(post_data), AV_OPT_TYPE_BINARY, .flags = D | E },
107 { "mime_type", "export the MIME type", OFFSET(mime_type), AV_OPT_TYPE_STRING, { 0 }, 0, 0, AV_OPT_FLAG_EXPORT | AV_OPT_FLAG_READONLY },
108 { "icy", "request ICY metadata", OFFSET(icy), AV_OPT_TYPE_INT, { .i64 = 1 }, 0, 1, D },
109 { "icy_metadata_headers", "return ICY metadata headers", OFFSET(icy_metadata_headers), AV_OPT_TYPE_STRING, { 0 }, 0, 0, AV_OPT_FLAG_EXPORT },
110 { "icy_metadata_packet", "return current ICY metadata packet", OFFSET(icy_metadata_packet), AV_OPT_TYPE_STRING, { 0 }, 0, 0, AV_OPT_FLAG_EXPORT },
111 { "metadata", "metadata read from the bitstream", OFFSET(metadata), AV_OPT_TYPE_DICT, {0}, 0, 0, AV_OPT_FLAG_EXPORT },
112 { "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"},
113 { "none", "No auth method set, autodetect", 0, AV_OPT_TYPE_CONST, { .i64 = HTTP_AUTH_NONE }, 0, 0, D | E, "auth_type"},
114 { "basic", "HTTP basic authentication", 0, AV_OPT_TYPE_CONST, { .i64 = HTTP_AUTH_BASIC }, 0, 0, D | E, "auth_type"},
115 { "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 },
116 { "location", "The actual location of the data received", OFFSET(location), AV_OPT_TYPE_STRING, { 0 }, 0, 0, D | E },
117 { "offset", "initial byte offset", OFFSET(off), AV_OPT_TYPE_INT64, { .i64 = 0 }, 0, INT64_MAX, D },
118 { "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 },
119 { "method", "Override the HTTP method", OFFSET(method), AV_OPT_TYPE_STRING, { .str = NULL }, 0, 0, E },
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,
131 sizeof(HTTPAuthState));
132 memcpy(&((HTTPContext *)dest->priv_data)->proxy_auth_state,
133 &((HTTPContext *)src->priv_data)->proxy_auth_state,
134 sizeof(HTTPAuthState));
137 static int http_open_cnx_internal(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;
145 HTTPContext *s = h->priv_data;
147 av_url_split(proto, sizeof(proto), auth, sizeof(auth),
148 hostname, sizeof(hostname), &port,
149 path1, sizeof(path1), s->location);
150 ff_url_join(hoststr, sizeof(hoststr), NULL, NULL, hostname, port, NULL);
152 proxy_path = getenv("http_proxy");
153 use_proxy = !ff_http_match_no_proxy(getenv("no_proxy"), hostname) &&
154 proxy_path && av_strstart(proxy_path, "http://", NULL);
156 if (!strcmp(proto, "https")) {
165 if (path1[0] == '\0')
171 /* Reassemble the request URL without auth string - we don't
172 * want to leak the auth to the proxy. */
173 ff_url_join(urlbuf, sizeof(urlbuf), proto, NULL, hostname, port, "%s",
176 av_url_split(NULL, 0, proxyauth, sizeof(proxyauth),
177 hostname, sizeof(hostname), &port, NULL, 0, proxy_path);
180 ff_url_join(buf, sizeof(buf), lower_proto, NULL, hostname, port, NULL);
183 err = ffurl_open(&s->hd, buf, AVIO_FLAG_READ_WRITE,
184 &h->interrupt_callback, options);
189 err = http_connect(h, path, local_path, hoststr,
190 auth, proxyauth, &location_changed);
194 return location_changed;
197 /* return non zero if error */
198 static int http_open_cnx(URLContext *h, AVDictionary **options)
200 HTTPAuthType cur_auth_type, cur_proxy_auth_type;
201 HTTPContext *s = h->priv_data;
202 int location_changed, attempts = 0, redirects = 0;
204 cur_auth_type = s->auth_state.auth_type;
205 cur_proxy_auth_type = s->auth_state.auth_type;
207 location_changed = http_open_cnx_internal(h, options);
208 if (location_changed < 0)
212 if (s->http_code == 401) {
213 if ((cur_auth_type == HTTP_AUTH_NONE || s->auth_state.stale) &&
214 s->auth_state.auth_type != HTTP_AUTH_NONE && attempts < 4) {
221 if (s->http_code == 407) {
222 if ((cur_proxy_auth_type == HTTP_AUTH_NONE || s->proxy_auth_state.stale) &&
223 s->proxy_auth_state.auth_type != HTTP_AUTH_NONE && attempts < 4) {
230 if ((s->http_code == 301 || s->http_code == 302 ||
231 s->http_code == 303 || s->http_code == 307) &&
232 location_changed == 1) {
233 /* url moved, get next */
236 if (redirects++ >= MAX_REDIRECTS)
238 /* Restart the authentication process with the new target, which
239 * might use a different auth mechanism. */
240 memset(&s->auth_state, 0, sizeof(s->auth_state));
242 location_changed = 0;
254 int ff_http_do_new_request(URLContext *h, const char *uri)
256 HTTPContext *s = h->priv_data;
257 AVDictionary *options = NULL;
261 s->icy_data_read = 0;
262 av_free(s->location);
263 s->location = av_strdup(uri);
265 return AVERROR(ENOMEM);
267 av_dict_copy(&options, s->chained_options, 0);
268 ret = http_open_cnx(h, &options);
269 av_dict_free(&options);
273 static int http_open(URLContext *h, const char *uri, int flags,
274 AVDictionary **options)
276 HTTPContext *s = h->priv_data;
282 s->location = av_strdup(uri);
284 return AVERROR(ENOMEM);
286 av_dict_copy(&s->chained_options, *options, 0);
289 int len = strlen(s->headers);
290 if (len < 2 || strcmp("\r\n", s->headers + len - 2))
291 av_log(h, AV_LOG_WARNING,
292 "No trailing CRLF found in HTTP header.\n");
295 ret = http_open_cnx(h, options);
297 av_dict_free(&s->chained_options);
301 static int http_getc(HTTPContext *s)
304 if (s->buf_ptr >= s->buf_end) {
305 len = ffurl_read(s->hd, s->buffer, BUFFER_SIZE);
308 } else if (len == 0) {
311 s->buf_ptr = s->buffer;
312 s->buf_end = s->buffer + len;
315 return *s->buf_ptr++;
318 static int http_get_line(HTTPContext *s, char *line, int line_size)
330 if (q > line && q[-1] == '\r')
336 if ((q - line) < line_size - 1)
342 static int check_http_code(URLContext *h, int http_code, const char *end)
344 HTTPContext *s = h->priv_data;
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 (http_code >= 400 && http_code < 600 &&
348 (http_code != 401 || s->auth_state.auth_type != HTTP_AUTH_NONE) &&
349 (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", http_code, end);
357 static int parse_location(HTTPContext *s, const char *p)
359 char redirected_location[MAX_URL_SIZE], *new_loc;
360 ff_make_absolute_url(redirected_location, sizeof(redirected_location),
362 new_loc = av_strdup(redirected_location);
364 return AVERROR(ENOMEM);
365 av_free(s->location);
366 s->location = new_loc;
370 /* "bytes $from-$to/$document_size" */
371 static void parse_content_range(URLContext *h, const char *p)
373 HTTPContext *s = h->priv_data;
376 if (!strncmp(p, "bytes ", 6)) {
378 s->off = strtoll(p, NULL, 10);
379 if ((slash = strchr(p, '/')) && strlen(slash) > 0)
380 s->filesize = strtoll(slash + 1, NULL, 10);
382 h->is_streamed = 0; /* we _can_ in fact seek */
385 static int parse_content_encoding(URLContext *h, const char *p)
387 if (!av_strncasecmp(p, "gzip", 4) ||
388 !av_strncasecmp(p, "deflate", 7)) {
390 HTTPContext *s = h->priv_data;
393 inflateEnd(&s->inflate_stream);
394 if (inflateInit2(&s->inflate_stream, 32 + 15) != Z_OK) {
395 av_log(h, AV_LOG_WARNING, "Error during zlib initialisation: %s\n",
396 s->inflate_stream.msg);
397 return AVERROR(ENOSYS);
399 if (zlibCompileFlags() & (1 << 17)) {
400 av_log(h, AV_LOG_WARNING,
401 "Your zlib was compiled without gzip support.\n");
402 return AVERROR(ENOSYS);
405 av_log(h, AV_LOG_WARNING,
406 "Compressed (%s) content, need zlib with gzip support\n", p);
407 return AVERROR(ENOSYS);
408 #endif /* CONFIG_ZLIB */
409 } else if (!av_strncasecmp(p, "identity", 8)) {
410 // The normal, no-encoding case (although servers shouldn't include
411 // the header at all if this is the case).
413 av_log(h, AV_LOG_WARNING, "Unknown content coding: %s\n", p);
414 return AVERROR(ENOSYS);
419 // Concat all Icy- header lines
420 static int parse_icy(HTTPContext *s, const char *tag, const char *p)
422 int len = 4 + strlen(p) + strlen(tag);
423 int is_first = !s->icy_metadata_headers;
426 av_dict_set(&s->metadata, tag, p, 0);
428 if (s->icy_metadata_headers)
429 len += strlen(s->icy_metadata_headers);
431 if ((ret = av_reallocp(&s->icy_metadata_headers, len)) < 0)
435 *s->icy_metadata_headers = '\0';
437 av_strlcatf(s->icy_metadata_headers, len, "%s: %s\n", tag, p);
442 static int process_line(URLContext *h, char *line, int line_count,
445 HTTPContext *s = h->priv_data;
450 if (line[0] == '\0') {
456 if (line_count == 0) {
457 while (!av_isspace(*p) && *p != '\0')
459 while (av_isspace(*p))
461 s->http_code = strtol(p, &end, 10);
463 av_dlog(NULL, "http_code=%d\n", s->http_code);
465 if ((ret = check_http_code(h, s->http_code, end)) < 0)
468 while (*p != '\0' && *p != ':')
476 while (av_isspace(*p))
478 if (!av_strcasecmp(tag, "Location")) {
479 if ((ret = parse_location(s, p)) < 0)
482 } else if (!av_strcasecmp(tag, "Content-Length") && s->filesize == -1) {
483 s->filesize = strtoll(p, NULL, 10);
484 } else if (!av_strcasecmp(tag, "Content-Range")) {
485 parse_content_range(h, p);
486 } else if (!av_strcasecmp(tag, "Accept-Ranges") &&
487 !strncmp(p, "bytes", 5)) {
489 } else if (!av_strcasecmp(tag, "Transfer-Encoding") &&
490 !av_strncasecmp(p, "chunked", 7)) {
493 } else if (!av_strcasecmp(tag, "WWW-Authenticate")) {
494 ff_http_auth_handle_header(&s->auth_state, tag, p);
495 } else if (!av_strcasecmp(tag, "Authentication-Info")) {
496 ff_http_auth_handle_header(&s->auth_state, tag, p);
497 } else if (!av_strcasecmp(tag, "Proxy-Authenticate")) {
498 ff_http_auth_handle_header(&s->proxy_auth_state, tag, p);
499 } else if (!av_strcasecmp(tag, "Connection")) {
500 if (!strcmp(p, "close"))
502 } else if (!av_strcasecmp(tag, "Content-Type")) {
503 av_free(s->mime_type);
504 s->mime_type = av_strdup(p);
505 } else if (!av_strcasecmp(tag, "Icy-MetaInt")) {
506 s->icy_metaint = strtoll(p, NULL, 10);
507 } else if (!av_strncasecmp(tag, "Icy-", 4)) {
508 if ((ret = parse_icy(s, tag, p)) < 0)
510 } else if (!av_strcasecmp(tag, "Content-Encoding")) {
511 if ((ret = parse_content_encoding(h, p)) < 0)
518 static inline int has_header(const char *str, const char *header)
520 /* header + 2 to skip over CRLF prefix. (make sure you have one!) */
523 return av_stristart(str, header + 2, NULL) || av_stristr(str, header);
526 static int http_read_header(URLContext *h, int *new_location)
528 HTTPContext *s = h->priv_data;
529 char line[MAX_URL_SIZE];
535 if ((err = http_get_line(s, line, sizeof(line))) < 0)
538 av_dlog(NULL, "header='%s'\n", line);
540 err = process_line(h, line, s->line_count, new_location);
551 static int http_connect(URLContext *h, const char *path, const char *local_path,
552 const char *hoststr, const char *auth,
553 const char *proxyauth, int *new_location)
555 HTTPContext *s = h->priv_data;
557 char headers[HTTP_HEADERS_SIZE] = "";
558 char *authstr = NULL, *proxyauthstr = NULL;
559 int64_t off = s->off;
562 int send_expect_100 = 0;
564 /* send http header */
565 post = h->flags & AVIO_FLAG_WRITE;
568 /* force POST method and disable chunked encoding when
569 * custom HTTP post data is set */
577 method = post ? "POST" : "GET";
579 authstr = ff_http_auth_create_response(&s->auth_state, auth,
581 proxyauthstr = ff_http_auth_create_response(&s->proxy_auth_state, proxyauth,
583 if (post && !s->post_data) {
584 send_expect_100 = s->send_expect_100;
585 /* The user has supplied authentication but we don't know the auth type,
586 * send Expect: 100-continue to get the 401 response including the
587 * WWW-Authenticate header, or an 100 continue if no auth actually
590 s->auth_state.auth_type == HTTP_AUTH_NONE &&
595 /* set default headers if needed */
596 if (!has_header(s->headers, "\r\nUser-Agent: "))
597 len += av_strlcatf(headers + len, sizeof(headers) - len,
598 "User-Agent: %s\r\n", s->user_agent);
599 if (!has_header(s->headers, "\r\nAccept: "))
600 len += av_strlcpy(headers + len, "Accept: */*\r\n",
601 sizeof(headers) - len);
602 // Note: we send this on purpose even when s->off is 0 when we're probing,
603 // since it allows us to detect more reliably if a (non-conforming)
604 // server supports seeking by analysing the reply headers.
605 if (!has_header(s->headers, "\r\nRange: ") && !post) {
606 len += av_strlcatf(headers + len, sizeof(headers) - len,
607 "Range: bytes=%"PRId64"-", s->off);
609 len += av_strlcatf(headers + len, sizeof(headers) - len,
610 "%"PRId64, s->end_off - 1);
611 len += av_strlcpy(headers + len, "\r\n",
612 sizeof(headers) - len);
614 if (send_expect_100 && !has_header(s->headers, "\r\nExpect: "))
615 len += av_strlcatf(headers + len, sizeof(headers) - len,
616 "Expect: 100-continue\r\n");
618 if (!has_header(s->headers, "\r\nConnection: ")) {
619 if (s->multiple_requests)
620 len += av_strlcpy(headers + len, "Connection: keep-alive\r\n",
621 sizeof(headers) - len);
623 len += av_strlcpy(headers + len, "Connection: close\r\n",
624 sizeof(headers) - len);
627 if (!has_header(s->headers, "\r\nHost: "))
628 len += av_strlcatf(headers + len, sizeof(headers) - len,
629 "Host: %s\r\n", hoststr);
630 if (!has_header(s->headers, "\r\nContent-Length: ") && s->post_data)
631 len += av_strlcatf(headers + len, sizeof(headers) - len,
632 "Content-Length: %d\r\n", s->post_datalen);
634 if (!has_header(s->headers, "\r\nContent-Type: ") && s->content_type)
635 len += av_strlcatf(headers + len, sizeof(headers) - len,
636 "Content-Type: %s\r\n", s->content_type);
637 if (!has_header(s->headers, "\r\nIcy-MetaData: ") && s->icy)
638 len += av_strlcatf(headers + len, sizeof(headers) - len,
639 "Icy-MetaData: %d\r\n", 1);
641 /* now add in custom headers */
643 av_strlcpy(headers + len, s->headers, sizeof(headers) - len);
645 snprintf(s->buffer, sizeof(s->buffer),
654 post && s->chunked_post ? "Transfer-Encoding: chunked\r\n" : "",
656 authstr ? authstr : "",
657 proxyauthstr ? "Proxy-" : "", proxyauthstr ? proxyauthstr : "");
660 av_freep(&proxyauthstr);
661 if ((err = ffurl_write(s->hd, s->buffer, strlen(s->buffer))) < 0)
665 if ((err = ffurl_write(s->hd, s->post_data, s->post_datalen)) < 0)
668 /* init input buffer */
669 s->buf_ptr = s->buffer;
670 s->buf_end = s->buffer;
673 s->icy_data_read = 0;
676 s->end_chunked_post = 0;
678 if (post && !s->post_data && !send_expect_100) {
679 /* Pretend that it did work. We didn't read any header yet, since
680 * we've still to send the POST data, but the code calling this
681 * function will check http_code after we return. */
686 /* wait for header */
687 err = http_read_header(h, new_location);
691 return (off == s->off) ? 0 : -1;
694 static int http_buf_read(URLContext *h, uint8_t *buf, int size)
696 HTTPContext *s = h->priv_data;
698 /* read bytes from input buffer first */
699 len = s->buf_end - s->buf_ptr;
703 memcpy(buf, s->buf_ptr, len);
706 if ((!s->willclose || s->chunksize < 0) &&
707 s->filesize >= 0 && s->off >= s->filesize)
709 len = ffurl_read(s->hd, buf, size);
713 if (s->chunksize > 0)
720 #define DECOMPRESS_BUF_SIZE (256 * 1024)
721 static int http_buf_read_compressed(URLContext *h, uint8_t *buf, int size)
723 HTTPContext *s = h->priv_data;
726 if (!s->inflate_buffer) {
727 s->inflate_buffer = av_malloc(DECOMPRESS_BUF_SIZE);
728 if (!s->inflate_buffer)
729 return AVERROR(ENOMEM);
732 if (s->inflate_stream.avail_in == 0) {
733 int read = http_buf_read(h, s->inflate_buffer, DECOMPRESS_BUF_SIZE);
736 s->inflate_stream.next_in = s->inflate_buffer;
737 s->inflate_stream.avail_in = read;
740 s->inflate_stream.avail_out = size;
741 s->inflate_stream.next_out = buf;
743 ret = inflate(&s->inflate_stream, Z_SYNC_FLUSH);
744 if (ret != Z_OK && ret != Z_STREAM_END)
745 av_log(h, AV_LOG_WARNING, "inflate return value: %d, %s\n",
746 ret, s->inflate_stream.msg);
748 return size - s->inflate_stream.avail_out;
750 #endif /* CONFIG_ZLIB */
752 static int http_read_stream(URLContext *h, uint8_t *buf, int size)
754 HTTPContext *s = h->priv_data;
755 int err, new_location;
760 if (s->end_chunked_post && !s->end_header) {
761 err = http_read_header(h, &new_location);
766 if (s->chunksize >= 0) {
772 if ((err = http_get_line(s, line, sizeof(line))) < 0)
774 } while (!*line); /* skip CR LF from last chunk */
776 s->chunksize = strtoll(line, NULL, 16);
778 av_dlog(NULL, "Chunked encoding data size: %"PRId64"'\n",
786 size = FFMIN(size, s->chunksize);
790 return http_buf_read_compressed(h, buf, size);
791 #endif /* CONFIG_ZLIB */
792 return http_buf_read(h, buf, size);
795 static int http_read_stream_all(URLContext *h, uint8_t *buf, int size)
799 int len = http_read_stream(h, buf + pos, size - pos);
807 static void update_metadata(HTTPContext *s, char *data)
816 val = strstr(key, "='");
819 end = strstr(val, "';");
827 av_dict_set(&s->metadata, key, val, 0);
833 static int store_icy(URLContext *h, int size)
835 HTTPContext *s = h->priv_data;
836 /* until next metadata packet */
837 int remaining = s->icy_metaint - s->icy_data_read;
840 return AVERROR_INVALIDDATA;
843 /* The metadata packet is variable sized. It has a 1 byte header
844 * which sets the length of the packet (divided by 16). If it's 0,
845 * the metadata doesn't change. After the packet, icy_metaint bytes
846 * of normal data follows. */
848 int len = http_read_stream_all(h, &ch, 1);
852 char data[255 * 16 + 1];
855 ret = http_read_stream_all(h, data, len);
859 if ((ret = av_opt_set(s, "icy_metadata_packet", data, 0)) < 0)
861 update_metadata(s, data);
863 s->icy_data_read = 0;
864 remaining = s->icy_metaint;
867 return FFMIN(size, remaining);
870 static int http_read(URLContext *h, uint8_t *buf, int size)
872 HTTPContext *s = h->priv_data;
874 if (s->icy_metaint > 0) {
875 size = store_icy(h, size);
880 size = http_read_stream(h, buf, size);
882 s->icy_data_read += size;
886 /* used only when posting data */
887 static int http_write(URLContext *h, const uint8_t *buf, int size)
889 char temp[11] = ""; /* 32-bit hex + CRLF + nul */
891 char crlf[] = "\r\n";
892 HTTPContext *s = h->priv_data;
894 if (!s->chunked_post) {
895 /* non-chunked data is sent without any special encoding */
896 return ffurl_write(s->hd, buf, size);
899 /* silently ignore zero-size data since chunk encoding that would
902 /* upload data using chunked encoding */
903 snprintf(temp, sizeof(temp), "%x\r\n", size);
905 if ((ret = ffurl_write(s->hd, temp, strlen(temp))) < 0 ||
906 (ret = ffurl_write(s->hd, buf, size)) < 0 ||
907 (ret = ffurl_write(s->hd, crlf, sizeof(crlf) - 1)) < 0)
913 static int http_shutdown(URLContext *h, int flags)
916 char footer[] = "0\r\n\r\n";
917 HTTPContext *s = h->priv_data;
919 /* signal end of chunked encoding if used */
920 if ((flags & AVIO_FLAG_WRITE) && s->chunked_post) {
921 ret = ffurl_write(s->hd, footer, sizeof(footer) - 1);
922 ret = ret > 0 ? 0 : ret;
923 s->end_chunked_post = 1;
929 static int http_close(URLContext *h)
932 HTTPContext *s = h->priv_data;
935 inflateEnd(&s->inflate_stream);
936 av_freep(&s->inflate_buffer);
937 #endif /* CONFIG_ZLIB */
939 if (!s->end_chunked_post)
940 /* Close the write direction by sending the end of chunked encoding. */
941 ret = http_shutdown(h, h->flags);
945 av_dict_free(&s->chained_options);
949 static int64_t http_seek(URLContext *h, int64_t off, int whence)
951 HTTPContext *s = h->priv_data;
952 URLContext *old_hd = s->hd;
953 int64_t old_off = s->off;
954 uint8_t old_buf[BUFFER_SIZE];
955 int old_buf_size, ret;
956 AVDictionary *options = NULL;
958 if (whence == AVSEEK_SIZE)
960 else if ((whence == SEEK_CUR && off == 0) ||
961 (whence == SEEK_SET && off == s->off))
963 else if ((s->filesize == -1 && whence == SEEK_END) || h->is_streamed)
964 return AVERROR(ENOSYS);
966 /* we save the old context in case the seek fails */
967 old_buf_size = s->buf_end - s->buf_ptr;
968 memcpy(old_buf, s->buf_ptr, old_buf_size);
970 if (whence == SEEK_CUR)
972 else if (whence == SEEK_END)
976 /* if it fails, continue on old connection */
977 av_dict_copy(&options, s->chained_options, 0);
978 if ((ret = http_open_cnx(h, &options)) < 0) {
979 av_dict_free(&options);
980 memcpy(s->buffer, old_buf, old_buf_size);
981 s->buf_ptr = s->buffer;
982 s->buf_end = s->buffer + old_buf_size;
987 av_dict_free(&options);
992 static int http_get_file_handle(URLContext *h)
994 HTTPContext *s = h->priv_data;
995 return ffurl_get_file_handle(s->hd);
998 #define HTTP_CLASS(flavor) \
999 static const AVClass flavor ## _context_class = { \
1000 .class_name = # flavor, \
1001 .item_name = av_default_item_name, \
1002 .option = options, \
1003 .version = LIBAVUTIL_VERSION_INT, \
1006 #if CONFIG_HTTP_PROTOCOL
1009 URLProtocol ff_http_protocol = {
1011 .url_open2 = http_open,
1012 .url_read = http_read,
1013 .url_write = http_write,
1014 .url_seek = http_seek,
1015 .url_close = http_close,
1016 .url_get_file_handle = http_get_file_handle,
1017 .url_shutdown = http_shutdown,
1018 .priv_data_size = sizeof(HTTPContext),
1019 .priv_data_class = &http_context_class,
1020 .flags = URL_PROTOCOL_FLAG_NETWORK,
1022 #endif /* CONFIG_HTTP_PROTOCOL */
1024 #if CONFIG_HTTPS_PROTOCOL
1027 URLProtocol ff_https_protocol = {
1029 .url_open2 = http_open,
1030 .url_read = http_read,
1031 .url_write = http_write,
1032 .url_seek = http_seek,
1033 .url_close = http_close,
1034 .url_get_file_handle = http_get_file_handle,
1035 .url_shutdown = http_shutdown,
1036 .priv_data_size = sizeof(HTTPContext),
1037 .priv_data_class = &https_context_class,
1038 .flags = URL_PROTOCOL_FLAG_NETWORK,
1040 #endif /* CONFIG_HTTPS_PROTOCOL */
1042 #if CONFIG_HTTPPROXY_PROTOCOL
1043 static int http_proxy_close(URLContext *h)
1045 HTTPContext *s = h->priv_data;
1051 static int http_proxy_open(URLContext *h, const char *uri, int flags)
1053 HTTPContext *s = h->priv_data;
1054 char hostname[1024], hoststr[1024];
1055 char auth[1024], pathbuf[1024], *path;
1056 char lower_url[100];
1057 int port, ret = 0, attempts = 0;
1058 HTTPAuthType cur_auth_type;
1064 av_url_split(NULL, 0, auth, sizeof(auth), hostname, sizeof(hostname), &port,
1065 pathbuf, sizeof(pathbuf), uri);
1066 ff_url_join(hoststr, sizeof(hoststr), NULL, NULL, hostname, port, NULL);
1071 ff_url_join(lower_url, sizeof(lower_url), "tcp", NULL, hostname, port,
1074 ret = ffurl_open(&s->hd, lower_url, AVIO_FLAG_READ_WRITE,
1075 &h->interrupt_callback, NULL);
1079 authstr = ff_http_auth_create_response(&s->proxy_auth_state, auth,
1081 snprintf(s->buffer, sizeof(s->buffer),
1082 "CONNECT %s HTTP/1.1\r\n"
1084 "Connection: close\r\n"
1089 authstr ? "Proxy-" : "", authstr ? authstr : "");
1092 if ((ret = ffurl_write(s->hd, s->buffer, strlen(s->buffer))) < 0)
1095 s->buf_ptr = s->buffer;
1096 s->buf_end = s->buffer;
1099 cur_auth_type = s->proxy_auth_state.auth_type;
1101 /* Note: This uses buffering, potentially reading more than the
1102 * HTTP header. If tunneling a protocol where the server starts
1103 * the conversation, we might buffer part of that here, too.
1104 * Reading that requires using the proper ffurl_read() function
1105 * on this URLContext, not using the fd directly (as the tls
1106 * protocol does). This shouldn't be an issue for tls though,
1107 * since the client starts the conversation there, so there
1108 * is no extra data that we might buffer up here.
1110 ret = http_read_header(h, &new_loc);
1115 if (s->http_code == 407 &&
1116 (cur_auth_type == HTTP_AUTH_NONE || s->proxy_auth_state.stale) &&
1117 s->proxy_auth_state.auth_type != HTTP_AUTH_NONE && attempts < 2) {
1123 if (s->http_code < 400)
1128 http_proxy_close(h);
1132 static int http_proxy_write(URLContext *h, const uint8_t *buf, int size)
1134 HTTPContext *s = h->priv_data;
1135 return ffurl_write(s->hd, buf, size);
1138 URLProtocol ff_httpproxy_protocol = {
1139 .name = "httpproxy",
1140 .url_open = http_proxy_open,
1141 .url_read = http_buf_read,
1142 .url_write = http_proxy_write,
1143 .url_close = http_proxy_close,
1144 .url_get_file_handle = http_get_file_handle,
1145 .priv_data_size = sizeof(HTTPContext),
1146 .flags = URL_PROTOCOL_FLAG_NETWORK,
1148 #endif /* CONFIG_HTTPPROXY_PROTOCOL */