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
26 #endif /* CONFIG_ZLIB */
28 #include "libavutil/avassert.h"
29 #include "libavutil/avstring.h"
30 #include "libavutil/bprint.h"
31 #include "libavutil/opt.h"
32 #include "libavutil/time.h"
33 #include "libavutil/parseutils.h"
40 #include "os_support.h"
43 /* XXX: POST protocol is not completely implemented because ffmpeg uses
44 * only a subset of it. */
46 /* The IO buffer size is unrelated to the max URL size in itself, but needs
47 * to be large enough to fit the full request headers (including long
49 #define BUFFER_SIZE (MAX_URL_SIZE + HTTP_HEADERS_SIZE)
50 #define MAX_REDIRECTS 8
54 #define WHITESPACES " \n\t\r"
62 typedef struct HTTPContext {
65 unsigned char buffer[BUFFER_SIZE], *buf_ptr, *buf_end;
68 /* Used if "Transfer-Encoding: chunked" otherwise -1. */
71 uint64_t off, end_off, filesize;
73 HTTPAuthState auth_state;
74 HTTPAuthState proxy_auth_state;
82 /* Set if the server correctly handles Connection: close and will close
83 * the connection after feeding us the content. */
85 int seekable; /**< Control seekability, 0 = disable, 1 = enable, -1 = probe. */
87 /* A flag which indicates if the end of chunked encoding has been sent. */
89 /* A flag which indicates we have finished to read POST reply. */
91 /* A flag which indicates if we use persistent connections. */
92 int multiple_requests;
97 char *cookies; ///< holds newline (\n) delimited Set-Cookie header field values (without the "Set-Cookie: " field name)
98 /* A dictionary containing cookies keyed by cookie name */
99 AVDictionary *cookie_dict;
101 /* how much data was read since the last ICY metadata packet */
102 uint64_t icy_data_read;
103 /* after how many bytes of read data a new metadata packet will be found */
104 uint64_t icy_metaint;
105 char *icy_metadata_headers;
106 char *icy_metadata_packet;
107 AVDictionary *metadata;
110 z_stream inflate_stream;
111 uint8_t *inflate_buffer;
112 #endif /* CONFIG_ZLIB */
113 AVDictionary *chained_options;
114 /* -1 = try to send if applicable, 0 = always disabled, 1 = always enabled */
118 int reconnect_at_eof;
119 int reconnect_on_network_error;
120 int reconnect_streamed;
121 int reconnect_delay_max;
122 char *reconnect_on_http_error;
127 HandshakeState handshake_step;
128 int is_connected_server;
131 #define OFFSET(x) offsetof(HTTPContext, x)
132 #define D AV_OPT_FLAG_DECODING_PARAM
133 #define E AV_OPT_FLAG_ENCODING_PARAM
134 #define DEFAULT_USER_AGENT "Lavf/" AV_STRINGIFY(LIBAVFORMAT_VERSION)
136 static const AVOption options[] = {
137 { "seekable", "control seekability of connection", OFFSET(seekable), AV_OPT_TYPE_BOOL, { .i64 = -1 }, -1, 1, D },
138 { "chunked_post", "use chunked transfer-encoding for posts", OFFSET(chunked_post), AV_OPT_TYPE_BOOL, { .i64 = 1 }, 0, 1, E },
139 { "http_proxy", "set HTTP proxy to tunnel through", OFFSET(http_proxy), AV_OPT_TYPE_STRING, { .str = NULL }, 0, 0, D | E },
140 { "headers", "set custom HTTP headers, can override built in default headers", OFFSET(headers), AV_OPT_TYPE_STRING, { .str = NULL }, 0, 0, D | E },
141 { "content_type", "set a specific content type for the POST messages", OFFSET(content_type), AV_OPT_TYPE_STRING, { .str = NULL }, 0, 0, D | E },
142 { "user_agent", "override User-Agent header", OFFSET(user_agent), AV_OPT_TYPE_STRING, { .str = DEFAULT_USER_AGENT }, 0, 0, D },
143 { "referer", "override referer header", OFFSET(referer), AV_OPT_TYPE_STRING, { .str = NULL }, 0, 0, D },
144 #if FF_API_HTTP_USER_AGENT
145 { "user-agent", "use the \"user_agent\" option instead", OFFSET(user_agent), AV_OPT_TYPE_STRING, { .str = DEFAULT_USER_AGENT }, 0, 0, D|AV_OPT_FLAG_DEPRECATED },
147 { "multiple_requests", "use persistent connections", OFFSET(multiple_requests), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, D | E },
148 { "post_data", "set custom HTTP post data", OFFSET(post_data), AV_OPT_TYPE_BINARY, .flags = D | E },
149 { "mime_type", "export the MIME type", OFFSET(mime_type), AV_OPT_TYPE_STRING, { .str = NULL }, 0, 0, AV_OPT_FLAG_EXPORT | AV_OPT_FLAG_READONLY },
150 { "http_version", "export the http response version", OFFSET(http_version), AV_OPT_TYPE_STRING, { .str = NULL }, 0, 0, AV_OPT_FLAG_EXPORT | AV_OPT_FLAG_READONLY },
151 { "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, { .str = NULL }, 0, 0, D },
152 { "icy", "request ICY metadata", OFFSET(icy), AV_OPT_TYPE_BOOL, { .i64 = 1 }, 0, 1, D },
153 { "icy_metadata_headers", "return ICY metadata headers", OFFSET(icy_metadata_headers), AV_OPT_TYPE_STRING, { .str = NULL }, 0, 0, AV_OPT_FLAG_EXPORT },
154 { "icy_metadata_packet", "return current ICY metadata packet", OFFSET(icy_metadata_packet), AV_OPT_TYPE_STRING, { .str = NULL }, 0, 0, AV_OPT_FLAG_EXPORT },
155 { "metadata", "metadata read from the bitstream", OFFSET(metadata), AV_OPT_TYPE_DICT, {0}, 0, 0, AV_OPT_FLAG_EXPORT },
156 { "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"},
157 { "none", "No auth method set, autodetect", 0, AV_OPT_TYPE_CONST, { .i64 = HTTP_AUTH_NONE }, 0, 0, D | E, "auth_type"},
158 { "basic", "HTTP basic authentication", 0, AV_OPT_TYPE_CONST, { .i64 = HTTP_AUTH_BASIC }, 0, 0, D | E, "auth_type"},
159 { "send_expect_100", "Force sending an Expect: 100-continue header for POST", OFFSET(send_expect_100), AV_OPT_TYPE_BOOL, { .i64 = -1 }, -1, 1, E },
160 { "location", "The actual location of the data received", OFFSET(location), AV_OPT_TYPE_STRING, { .str = NULL }, 0, 0, D | E },
161 { "offset", "initial byte offset", OFFSET(off), AV_OPT_TYPE_INT64, { .i64 = 0 }, 0, INT64_MAX, D },
162 { "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 },
163 { "method", "Override the HTTP method or set the expected HTTP method from a client", OFFSET(method), AV_OPT_TYPE_STRING, { .str = NULL }, 0, 0, D | E },
164 { "reconnect", "auto reconnect after disconnect before EOF", OFFSET(reconnect), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, D },
165 { "reconnect_at_eof", "auto reconnect at EOF", OFFSET(reconnect_at_eof), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, D },
166 { "reconnect_on_network_error", "auto reconnect in case of tcp/tls error during connect", OFFSET(reconnect_on_network_error), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, D },
167 { "reconnect_on_http_error", "list of http status codes to reconnect on", OFFSET(reconnect_on_http_error), AV_OPT_TYPE_STRING, { .str = NULL }, 0, 0, D },
168 { "reconnect_streamed", "auto reconnect streamed / non seekable streams", OFFSET(reconnect_streamed), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, D },
169 { "reconnect_delay_max", "max reconnect delay in seconds after which to give up", OFFSET(reconnect_delay_max), AV_OPT_TYPE_INT, { .i64 = 120 }, 0, UINT_MAX/1000/1000, D },
170 { "listen", "listen on HTTP", OFFSET(listen), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 2, D | E },
171 { "resource", "The resource requested by a client", OFFSET(resource), AV_OPT_TYPE_STRING, { .str = NULL }, 0, 0, E },
172 { "reply_code", "The http status code to return to a client", OFFSET(reply_code), AV_OPT_TYPE_INT, { .i64 = 200}, INT_MIN, 599, E},
176 static int http_connect(URLContext *h, const char *path, const char *local_path,
177 const char *hoststr, const char *auth,
178 const char *proxyauth, int *new_location);
179 static int http_read_header(URLContext *h, int *new_location);
180 static int http_shutdown(URLContext *h, int flags);
182 void ff_http_init_auth_state(URLContext *dest, const URLContext *src)
184 memcpy(&((HTTPContext *)dest->priv_data)->auth_state,
185 &((HTTPContext *)src->priv_data)->auth_state,
186 sizeof(HTTPAuthState));
187 memcpy(&((HTTPContext *)dest->priv_data)->proxy_auth_state,
188 &((HTTPContext *)src->priv_data)->proxy_auth_state,
189 sizeof(HTTPAuthState));
192 static int http_open_cnx_internal(URLContext *h, AVDictionary **options)
194 const char *path, *proxy_path, *lower_proto = "tcp", *local_path;
196 char hostname[1024], hoststr[1024], proto[10];
197 char auth[1024], proxyauth[1024] = "";
198 char path1[MAX_URL_SIZE], sanitized_path[MAX_URL_SIZE];
199 char buf[1024], urlbuf[MAX_URL_SIZE];
200 int port, use_proxy, err, location_changed = 0;
201 HTTPContext *s = h->priv_data;
203 av_url_split(proto, sizeof(proto), auth, sizeof(auth),
204 hostname, sizeof(hostname), &port,
205 path1, sizeof(path1), s->location);
206 ff_url_join(hoststr, sizeof(hoststr), NULL, NULL, hostname, port, NULL);
208 proxy_path = s->http_proxy ? s->http_proxy : getenv("http_proxy");
209 use_proxy = !ff_http_match_no_proxy(getenv("no_proxy"), hostname) &&
210 proxy_path && av_strstart(proxy_path, "http://", NULL);
212 if (!strcmp(proto, "https")) {
221 hashmark = strchr(path1, '#');
225 if (path1[0] == '\0') {
227 } else if (path1[0] == '?') {
228 snprintf(sanitized_path, sizeof(sanitized_path), "/%s", path1);
229 path = sanitized_path;
235 /* Reassemble the request URL without auth string - we don't
236 * want to leak the auth to the proxy. */
237 ff_url_join(urlbuf, sizeof(urlbuf), proto, NULL, hostname, port, "%s",
240 av_url_split(NULL, 0, proxyauth, sizeof(proxyauth),
241 hostname, sizeof(hostname), &port, NULL, 0, proxy_path);
244 ff_url_join(buf, sizeof(buf), lower_proto, NULL, hostname, port, NULL);
247 err = ffurl_open_whitelist(&s->hd, buf, AVIO_FLAG_READ_WRITE,
248 &h->interrupt_callback, options,
249 h->protocol_whitelist, h->protocol_blacklist, h);
254 err = http_connect(h, path, local_path, hoststr,
255 auth, proxyauth, &location_changed);
259 return location_changed;
262 static int http_should_reconnect(HTTPContext *s, int err)
264 const char *status_group;
268 case AVERROR_HTTP_BAD_REQUEST:
269 case AVERROR_HTTP_UNAUTHORIZED:
270 case AVERROR_HTTP_FORBIDDEN:
271 case AVERROR_HTTP_NOT_FOUND:
272 case AVERROR_HTTP_OTHER_4XX:
273 status_group = "4xx";
276 case AVERROR_HTTP_SERVER_ERROR:
277 status_group = "5xx";
281 return s->reconnect_on_network_error;
284 if (!s->reconnect_on_http_error)
287 if (av_match_list(status_group, s->reconnect_on_http_error, ',') > 0)
290 snprintf(http_code, sizeof(http_code), "%d", s->http_code);
292 return av_match_list(http_code, s->reconnect_on_http_error, ',') > 0;
295 /* return non zero if error */
296 static int http_open_cnx(URLContext *h, AVDictionary **options)
298 HTTPAuthType cur_auth_type, cur_proxy_auth_type;
299 HTTPContext *s = h->priv_data;
300 int location_changed, attempts = 0, redirects = 0;
301 int reconnect_delay = 0;
305 av_dict_copy(options, s->chained_options, 0);
307 cur_auth_type = s->auth_state.auth_type;
308 cur_proxy_auth_type = s->auth_state.auth_type;
311 location_changed = http_open_cnx_internal(h, options);
312 if (location_changed < 0) {
313 if (!http_should_reconnect(s, location_changed) ||
314 reconnect_delay > s->reconnect_delay_max)
317 av_log(h, AV_LOG_WARNING, "Will reconnect at %"PRIu64" in %d second(s).\n", off, reconnect_delay);
318 location_changed = ff_network_sleep_interruptible(1000U * 1000 * reconnect_delay, &h->interrupt_callback);
319 if (location_changed != AVERROR(ETIMEDOUT))
321 reconnect_delay = 1 + 2 * reconnect_delay;
323 /* restore the offset (http_connect resets it) */
326 ffurl_closep(&s->hd);
331 if (s->http_code == 401) {
332 if ((cur_auth_type == HTTP_AUTH_NONE || s->auth_state.stale) &&
333 s->auth_state.auth_type != HTTP_AUTH_NONE && attempts < 4) {
334 ffurl_closep(&s->hd);
339 if (s->http_code == 407) {
340 if ((cur_proxy_auth_type == HTTP_AUTH_NONE || s->proxy_auth_state.stale) &&
341 s->proxy_auth_state.auth_type != HTTP_AUTH_NONE && attempts < 4) {
342 ffurl_closep(&s->hd);
347 if ((s->http_code == 301 || s->http_code == 302 ||
348 s->http_code == 303 || s->http_code == 307 || s->http_code == 308) &&
349 location_changed == 1) {
350 /* url moved, get next */
351 ffurl_closep(&s->hd);
352 if (redirects++ >= MAX_REDIRECTS)
354 /* Restart the authentication process with the new target, which
355 * might use a different auth mechanism. */
356 memset(&s->auth_state, 0, sizeof(s->auth_state));
358 location_changed = 0;
365 ffurl_closep(&s->hd);
366 if (location_changed < 0)
367 return location_changed;
368 return ff_http_averror(s->http_code, AVERROR(EIO));
370 int ff_http_get_shutdown_status(URLContext *h)
373 HTTPContext *s = h->priv_data;
375 /* flush the receive buffer when it is write only mode */
378 read_ret = ffurl_read(s->hd, buf, sizeof(buf));
386 int ff_http_do_new_request(URLContext *h, const char *uri) {
387 return ff_http_do_new_request2(h, uri, NULL);
390 int ff_http_do_new_request2(URLContext *h, const char *uri, AVDictionary **opts)
392 HTTPContext *s = h->priv_data;
393 AVDictionary *options = NULL;
395 char hostname1[1024], hostname2[1024], proto1[10], proto2[10];
399 !(!strcmp(h->prot->name, "http") ||
400 !strcmp(h->prot->name, "https")))
401 return AVERROR(EINVAL);
403 av_url_split(proto1, sizeof(proto1), NULL, 0,
404 hostname1, sizeof(hostname1), &port1,
405 NULL, 0, s->location);
406 av_url_split(proto2, sizeof(proto2), NULL, 0,
407 hostname2, sizeof(hostname2), &port2,
409 if (port1 != port2 || strncmp(hostname1, hostname2, sizeof(hostname2)) != 0) {
410 av_log(h, AV_LOG_ERROR, "Cannot reuse HTTP connection for different host: %s:%d != %s:%d\n",
414 return AVERROR(EINVAL);
417 if (!s->end_chunked_post) {
418 ret = http_shutdown(h, h->flags);
426 s->end_chunked_post = 0;
429 s->icy_data_read = 0;
430 av_free(s->location);
431 s->location = av_strdup(uri);
433 return AVERROR(ENOMEM);
435 if ((ret = av_opt_set_dict(s, opts)) < 0)
438 av_log(s, AV_LOG_INFO, "Opening \'%s\' for %s\n", uri, h->flags & AVIO_FLAG_WRITE ? "writing" : "reading");
439 ret = http_open_cnx(h, &options);
440 av_dict_free(&options);
444 int ff_http_averror(int status_code, int default_averror)
446 switch (status_code) {
447 case 400: return AVERROR_HTTP_BAD_REQUEST;
448 case 401: return AVERROR_HTTP_UNAUTHORIZED;
449 case 403: return AVERROR_HTTP_FORBIDDEN;
450 case 404: return AVERROR_HTTP_NOT_FOUND;
453 if (status_code >= 400 && status_code <= 499)
454 return AVERROR_HTTP_OTHER_4XX;
455 else if (status_code >= 500)
456 return AVERROR_HTTP_SERVER_ERROR;
458 return default_averror;
461 static int http_write_reply(URLContext* h, int status_code)
463 int ret, body = 0, reply_code, message_len;
464 const char *reply_text, *content_type;
465 HTTPContext *s = h->priv_data;
466 char message[BUFFER_SIZE];
467 content_type = "text/plain";
471 switch (status_code) {
472 case AVERROR_HTTP_BAD_REQUEST:
475 reply_text = "Bad Request";
477 case AVERROR_HTTP_FORBIDDEN:
480 reply_text = "Forbidden";
482 case AVERROR_HTTP_NOT_FOUND:
485 reply_text = "Not Found";
490 content_type = s->content_type ? s->content_type : "application/octet-stream";
492 case AVERROR_HTTP_SERVER_ERROR:
495 reply_text = "Internal server error";
498 return AVERROR(EINVAL);
502 message_len = snprintf(message, sizeof(message),
503 "HTTP/1.1 %03d %s\r\n"
504 "Content-Type: %s\r\n"
505 "Content-Length: %"SIZE_SPECIFIER"\r\n"
512 strlen(reply_text) + 6, // 3 digit status code + space + \r\n
513 s->headers ? s->headers : "",
518 message_len = snprintf(message, sizeof(message),
519 "HTTP/1.1 %03d %s\r\n"
520 "Content-Type: %s\r\n"
521 "Transfer-Encoding: chunked\r\n"
527 s->headers ? s->headers : "");
529 av_log(h, AV_LOG_TRACE, "HTTP reply header: \n%s----\n", message);
530 if ((ret = ffurl_write(s->hd, message, message_len)) < 0)
535 static void handle_http_errors(URLContext *h, int error)
537 av_assert0(error < 0);
538 http_write_reply(h, error);
541 static int http_handshake(URLContext *c)
543 int ret, err, new_location;
544 HTTPContext *ch = c->priv_data;
545 URLContext *cl = ch->hd;
546 switch (ch->handshake_step) {
548 av_log(c, AV_LOG_TRACE, "Lower protocol\n");
549 if ((ret = ffurl_handshake(cl)) > 0)
553 ch->handshake_step = READ_HEADERS;
554 ch->is_connected_server = 1;
557 av_log(c, AV_LOG_TRACE, "Read headers\n");
558 if ((err = http_read_header(c, &new_location)) < 0) {
559 handle_http_errors(c, err);
562 ch->handshake_step = WRITE_REPLY_HEADERS;
564 case WRITE_REPLY_HEADERS:
565 av_log(c, AV_LOG_TRACE, "Reply code: %d\n", ch->reply_code);
566 if ((err = http_write_reply(c, ch->reply_code)) < 0)
568 ch->handshake_step = FINISH;
573 // this should never be reached.
574 return AVERROR(EINVAL);
577 static int http_listen(URLContext *h, const char *uri, int flags,
578 AVDictionary **options) {
579 HTTPContext *s = h->priv_data;
581 char hostname[1024], proto[10];
583 const char *lower_proto = "tcp";
585 av_url_split(proto, sizeof(proto), NULL, 0, hostname, sizeof(hostname), &port,
587 if (!strcmp(proto, "https"))
589 ff_url_join(lower_url, sizeof(lower_url), lower_proto, NULL, hostname, port,
591 if ((ret = av_dict_set_int(options, "listen", s->listen, 0)) < 0)
593 if ((ret = ffurl_open_whitelist(&s->hd, lower_url, AVIO_FLAG_READ_WRITE,
594 &h->interrupt_callback, options,
595 h->protocol_whitelist, h->protocol_blacklist, h
598 s->handshake_step = LOWER_PROTO;
599 if (s->listen == HTTP_SINGLE) { /* single client */
601 while ((ret = http_handshake(h)) > 0);
604 av_dict_free(&s->chained_options);
608 static int http_open(URLContext *h, const char *uri, int flags,
609 AVDictionary **options)
611 HTTPContext *s = h->priv_data;
614 if( s->seekable == 1 )
619 s->filesize = UINT64_MAX;
620 s->location = av_strdup(uri);
622 return AVERROR(ENOMEM);
624 av_dict_copy(&s->chained_options, *options, 0);
627 int len = strlen(s->headers);
628 if (len < 2 || strcmp("\r\n", s->headers + len - 2)) {
629 av_log(h, AV_LOG_WARNING,
630 "No trailing CRLF found in HTTP header. Adding it.\n");
631 ret = av_reallocp(&s->headers, len + 3);
634 s->headers[len] = '\r';
635 s->headers[len + 1] = '\n';
636 s->headers[len + 2] = '\0';
641 return http_listen(h, uri, flags, options);
643 ret = http_open_cnx(h, options);
646 av_dict_free(&s->chained_options);
650 static int http_accept(URLContext *s, URLContext **c)
653 HTTPContext *sc = s->priv_data;
655 URLContext *sl = sc->hd;
656 URLContext *cl = NULL;
658 av_assert0(sc->listen);
659 if ((ret = ffurl_alloc(c, s->filename, s->flags, &sl->interrupt_callback)) < 0)
661 cc = (*c)->priv_data;
662 if ((ret = ffurl_accept(sl, &cl)) < 0)
665 cc->is_multi_client = 1;
674 static int http_getc(HTTPContext *s)
677 if (s->buf_ptr >= s->buf_end) {
678 len = ffurl_read(s->hd, s->buffer, BUFFER_SIZE);
681 } else if (len == 0) {
684 s->buf_ptr = s->buffer;
685 s->buf_end = s->buffer + len;
688 return *s->buf_ptr++;
691 static int http_get_line(HTTPContext *s, char *line, int line_size)
703 if (q > line && q[-1] == '\r')
709 if ((q - line) < line_size - 1)
715 static int check_http_code(URLContext *h, int http_code, const char *end)
717 HTTPContext *s = h->priv_data;
718 /* error codes are 4xx and 5xx, but regard 401 as a success, so we
719 * don't abort until all headers have been parsed. */
720 if (http_code >= 400 && http_code < 600 &&
721 (http_code != 401 || s->auth_state.auth_type != HTTP_AUTH_NONE) &&
722 (http_code != 407 || s->proxy_auth_state.auth_type != HTTP_AUTH_NONE)) {
723 end += strspn(end, SPACE_CHARS);
724 av_log(h, AV_LOG_WARNING, "HTTP error %d %s\n", http_code, end);
725 return ff_http_averror(http_code, AVERROR(EIO));
730 static int parse_location(HTTPContext *s, const char *p)
732 char redirected_location[MAX_URL_SIZE], *new_loc;
733 ff_make_absolute_url(redirected_location, sizeof(redirected_location),
735 new_loc = av_strdup(redirected_location);
737 return AVERROR(ENOMEM);
738 av_free(s->location);
739 s->location = new_loc;
743 /* "bytes $from-$to/$document_size" */
744 static void parse_content_range(URLContext *h, const char *p)
746 HTTPContext *s = h->priv_data;
749 if (!strncmp(p, "bytes ", 6)) {
751 s->off = strtoull(p, NULL, 10);
752 if ((slash = strchr(p, '/')) && strlen(slash) > 0)
753 s->filesize = strtoull(slash + 1, NULL, 10);
755 if (s->seekable == -1 && (!s->is_akamai || s->filesize != 2147483647))
756 h->is_streamed = 0; /* we _can_ in fact seek */
759 static int parse_content_encoding(URLContext *h, const char *p)
761 if (!av_strncasecmp(p, "gzip", 4) ||
762 !av_strncasecmp(p, "deflate", 7)) {
764 HTTPContext *s = h->priv_data;
767 inflateEnd(&s->inflate_stream);
768 if (inflateInit2(&s->inflate_stream, 32 + 15) != Z_OK) {
769 av_log(h, AV_LOG_WARNING, "Error during zlib initialisation: %s\n",
770 s->inflate_stream.msg);
771 return AVERROR(ENOSYS);
773 if (zlibCompileFlags() & (1 << 17)) {
774 av_log(h, AV_LOG_WARNING,
775 "Your zlib was compiled without gzip support.\n");
776 return AVERROR(ENOSYS);
779 av_log(h, AV_LOG_WARNING,
780 "Compressed (%s) content, need zlib with gzip support\n", p);
781 return AVERROR(ENOSYS);
782 #endif /* CONFIG_ZLIB */
783 } else if (!av_strncasecmp(p, "identity", 8)) {
784 // The normal, no-encoding case (although servers shouldn't include
785 // the header at all if this is the case).
787 av_log(h, AV_LOG_WARNING, "Unknown content coding: %s\n", p);
792 // Concat all Icy- header lines
793 static int parse_icy(HTTPContext *s, const char *tag, const char *p)
795 int len = 4 + strlen(p) + strlen(tag);
796 int is_first = !s->icy_metadata_headers;
799 av_dict_set(&s->metadata, tag, p, 0);
801 if (s->icy_metadata_headers)
802 len += strlen(s->icy_metadata_headers);
804 if ((ret = av_reallocp(&s->icy_metadata_headers, len)) < 0)
808 *s->icy_metadata_headers = '\0';
810 av_strlcatf(s->icy_metadata_headers, len, "%s: %s\n", tag, p);
815 static int parse_set_cookie_expiry_time(const char *exp_str, struct tm *buf)
817 char exp_buf[MAX_EXPIRY];
818 int i, j, exp_buf_len = MAX_EXPIRY-1;
821 // strip off any punctuation or whitespace
822 for (i = 0, j = 0; exp_str[i] != '\0' && j < exp_buf_len; i++) {
823 if ((exp_str[i] >= '0' && exp_str[i] <= '9') ||
824 (exp_str[i] >= 'A' && exp_str[i] <= 'Z') ||
825 (exp_str[i] >= 'a' && exp_str[i] <= 'z')) {
826 exp_buf[j] = exp_str[i];
833 // move the string beyond the day of week
834 while ((*expiry < '0' || *expiry > '9') && *expiry != '\0')
837 return av_small_strptime(expiry, "%d%b%Y%H%M%S", buf) ? 0 : AVERROR(EINVAL);
840 static int parse_set_cookie(const char *set_cookie, AVDictionary **dict)
842 char *param, *next_param, *cstr, *back;
843 char *saveptr = NULL;
848 if (!(cstr = av_strdup(set_cookie)))
849 return AVERROR(EINVAL);
851 // strip any trailing whitespace
852 back = &cstr[strlen(cstr)-1];
853 while (strchr(WHITESPACES, *back)) {
861 while ((param = av_strtok(next_param, ";", &saveptr))) {
864 param += strspn(param, WHITESPACES);
865 if ((name = av_strtok(param, "=", &value))) {
866 if (av_dict_set(dict, name, value, 0) < 0) {
877 static int parse_cookie(HTTPContext *s, const char *p, AVDictionary **cookies)
879 AVDictionary *new_params = NULL;
880 AVDictionaryEntry *e, *cookie_entry;
883 // ensure the cookie is parsable
884 if (parse_set_cookie(p, &new_params))
887 // if there is no cookie value there is nothing to parse
888 cookie_entry = av_dict_get(new_params, "", NULL, AV_DICT_IGNORE_SUFFIX);
889 if (!cookie_entry || !cookie_entry->value) {
890 av_dict_free(&new_params);
894 // ensure the cookie is not expired or older than an existing value
895 if ((e = av_dict_get(new_params, "expires", NULL, 0)) && e->value) {
896 struct tm new_tm = {0};
897 if (!parse_set_cookie_expiry_time(e->value, &new_tm)) {
898 AVDictionaryEntry *e2;
900 // if the cookie has already expired ignore it
901 if (av_timegm(&new_tm) < av_gettime() / 1000000) {
902 av_dict_free(&new_params);
906 // only replace an older cookie with the same name
907 e2 = av_dict_get(*cookies, cookie_entry->key, NULL, 0);
908 if (e2 && e2->value) {
909 AVDictionary *old_params = NULL;
910 if (!parse_set_cookie(p, &old_params)) {
911 e2 = av_dict_get(old_params, "expires", NULL, 0);
912 if (e2 && e2->value) {
913 struct tm old_tm = {0};
914 if (!parse_set_cookie_expiry_time(e->value, &old_tm)) {
915 if (av_timegm(&new_tm) < av_timegm(&old_tm)) {
916 av_dict_free(&new_params);
917 av_dict_free(&old_params);
923 av_dict_free(&old_params);
927 av_dict_free(&new_params);
929 // duplicate the cookie name (dict will dupe the value)
930 if (!(eql = strchr(p, '='))) return AVERROR(EINVAL);
931 if (!(name = av_strndup(p, eql - p))) return AVERROR(ENOMEM);
933 // add the cookie to the dictionary
934 av_dict_set(cookies, name, eql, AV_DICT_DONT_STRDUP_KEY);
939 static int cookie_string(AVDictionary *dict, char **cookies)
941 AVDictionaryEntry *e = NULL;
944 // determine how much memory is needed for the cookies string
945 while (e = av_dict_get(dict, "", e, AV_DICT_IGNORE_SUFFIX))
946 len += strlen(e->key) + strlen(e->value) + 1;
948 // reallocate the cookies
950 if (*cookies) av_free(*cookies);
951 *cookies = av_malloc(len);
952 if (!*cookies) return AVERROR(ENOMEM);
955 // write out the cookies
956 while (e = av_dict_get(dict, "", e, AV_DICT_IGNORE_SUFFIX))
957 av_strlcatf(*cookies, len, "%s%s\n", e->key, e->value);
962 static int process_line(URLContext *h, char *line, int line_count,
965 HTTPContext *s = h->priv_data;
966 const char *auto_method = h->flags & AVIO_FLAG_READ ? "POST" : "GET";
967 char *tag, *p, *end, *method, *resource, *version;
971 if (line[0] == '\0') {
977 if (line_count == 0) {
978 if (s->is_connected_server) {
981 while (*p && !av_isspace(*p))
984 av_log(h, AV_LOG_TRACE, "Received method: %s\n", method);
986 if (av_strcasecmp(s->method, method)) {
987 av_log(h, AV_LOG_ERROR, "Received and expected HTTP method do not match. (%s expected, %s received)\n",
989 return ff_http_averror(400, AVERROR(EIO));
992 // use autodetected HTTP method to expect
993 av_log(h, AV_LOG_TRACE, "Autodetected %s HTTP method\n", auto_method);
994 if (av_strcasecmp(auto_method, method)) {
995 av_log(h, AV_LOG_ERROR, "Received and autodetected HTTP method did not match "
996 "(%s autodetected %s received)\n", auto_method, method);
997 return ff_http_averror(400, AVERROR(EIO));
999 if (!(s->method = av_strdup(method)))
1000 return AVERROR(ENOMEM);
1004 while (av_isspace(*p))
1007 while (*p && !av_isspace(*p))
1010 av_log(h, AV_LOG_TRACE, "Requested resource: %s\n", resource);
1011 if (!(s->resource = av_strdup(resource)))
1012 return AVERROR(ENOMEM);
1015 while (av_isspace(*p))
1018 while (*p && !av_isspace(*p))
1021 if (av_strncasecmp(version, "HTTP/", 5)) {
1022 av_log(h, AV_LOG_ERROR, "Malformed HTTP version string.\n");
1023 return ff_http_averror(400, AVERROR(EIO));
1025 av_log(h, AV_LOG_TRACE, "HTTP version string: %s\n", version);
1027 if (av_strncasecmp(p, "HTTP/1.0", 8) == 0)
1029 while (*p != '/' && *p != '\0')
1033 av_freep(&s->http_version);
1034 s->http_version = av_strndup(p, 3);
1035 while (!av_isspace(*p) && *p != '\0')
1037 while (av_isspace(*p))
1039 s->http_code = strtol(p, &end, 10);
1041 av_log(h, AV_LOG_TRACE, "http_code=%d\n", s->http_code);
1043 if ((ret = check_http_code(h, s->http_code, end)) < 0)
1047 while (*p != '\0' && *p != ':')
1055 while (av_isspace(*p))
1057 if (!av_strcasecmp(tag, "Location")) {
1058 if ((ret = parse_location(s, p)) < 0)
1061 } else if (!av_strcasecmp(tag, "Content-Length") &&
1062 s->filesize == UINT64_MAX) {
1063 s->filesize = strtoull(p, NULL, 10);
1064 } else if (!av_strcasecmp(tag, "Content-Range")) {
1065 parse_content_range(h, p);
1066 } else if (!av_strcasecmp(tag, "Accept-Ranges") &&
1067 !strncmp(p, "bytes", 5) &&
1068 s->seekable == -1) {
1070 } else if (!av_strcasecmp(tag, "Transfer-Encoding") &&
1071 !av_strncasecmp(p, "chunked", 7)) {
1072 s->filesize = UINT64_MAX;
1074 } else if (!av_strcasecmp(tag, "WWW-Authenticate")) {
1075 ff_http_auth_handle_header(&s->auth_state, tag, p);
1076 } else if (!av_strcasecmp(tag, "Authentication-Info")) {
1077 ff_http_auth_handle_header(&s->auth_state, tag, p);
1078 } else if (!av_strcasecmp(tag, "Proxy-Authenticate")) {
1079 ff_http_auth_handle_header(&s->proxy_auth_state, tag, p);
1080 } else if (!av_strcasecmp(tag, "Connection")) {
1081 if (!strcmp(p, "close"))
1083 } else if (!av_strcasecmp(tag, "Server")) {
1084 if (!av_strcasecmp(p, "AkamaiGHost")) {
1086 } else if (!av_strncasecmp(p, "MediaGateway", 12)) {
1087 s->is_mediagateway = 1;
1089 } else if (!av_strcasecmp(tag, "Content-Type")) {
1090 av_free(s->mime_type);
1091 s->mime_type = av_strdup(p);
1092 } else if (!av_strcasecmp(tag, "Set-Cookie")) {
1093 if (parse_cookie(s, p, &s->cookie_dict))
1094 av_log(h, AV_LOG_WARNING, "Unable to parse '%s'\n", p);
1095 } else if (!av_strcasecmp(tag, "Icy-MetaInt")) {
1096 s->icy_metaint = strtoull(p, NULL, 10);
1097 } else if (!av_strncasecmp(tag, "Icy-", 4)) {
1098 if ((ret = parse_icy(s, tag, p)) < 0)
1100 } else if (!av_strcasecmp(tag, "Content-Encoding")) {
1101 if ((ret = parse_content_encoding(h, p)) < 0)
1109 * Create a string containing cookie values for use as a HTTP cookie header
1110 * field value for a particular path and domain from the cookie values stored in
1111 * the HTTP protocol context. The cookie string is stored in *cookies, and may
1112 * be NULL if there are no valid cookies.
1114 * @return a negative value if an error condition occurred, 0 otherwise
1116 static int get_cookies(HTTPContext *s, char **cookies, const char *path,
1119 // cookie strings will look like Set-Cookie header field values. Multiple
1120 // Set-Cookie fields will result in multiple values delimited by a newline
1122 char *cookie, *set_cookies, *next;
1123 char *saveptr = NULL;
1125 // destroy any cookies in the dictionary.
1126 av_dict_free(&s->cookie_dict);
1131 next = set_cookies = av_strdup(s->cookies);
1133 return AVERROR(ENOMEM);
1136 while ((cookie = av_strtok(next, "\n", &saveptr)) && !ret) {
1137 AVDictionary *cookie_params = NULL;
1138 AVDictionaryEntry *cookie_entry, *e;
1141 // store the cookie in a dict in case it is updated in the response
1142 if (parse_cookie(s, cookie, &s->cookie_dict))
1143 av_log(s, AV_LOG_WARNING, "Unable to parse '%s'\n", cookie);
1145 // continue on to the next cookie if this one cannot be parsed
1146 if (parse_set_cookie(cookie, &cookie_params))
1149 // if the cookie has no value, skip it
1150 cookie_entry = av_dict_get(cookie_params, "", NULL, AV_DICT_IGNORE_SUFFIX);
1151 if (!cookie_entry || !cookie_entry->value)
1154 // if the cookie has expired, don't add it
1155 if ((e = av_dict_get(cookie_params, "expires", NULL, 0)) && e->value) {
1156 struct tm tm_buf = {0};
1157 if (!parse_set_cookie_expiry_time(e->value, &tm_buf)) {
1158 if (av_timegm(&tm_buf) < av_gettime() / 1000000)
1163 // if no domain in the cookie assume it appied to this request
1164 if ((e = av_dict_get(cookie_params, "domain", NULL, 0)) && e->value) {
1165 // find the offset comparison is on the min domain (b.com, not a.b.com)
1166 int domain_offset = strlen(domain) - strlen(e->value);
1167 if (domain_offset < 0)
1170 // match the cookie domain
1171 if (av_strcasecmp(&domain[domain_offset], e->value))
1175 // ensure this cookie matches the path
1176 e = av_dict_get(cookie_params, "path", NULL, 0);
1177 if (!e || av_strncasecmp(path, e->value, strlen(e->value)))
1180 // cookie parameters match, so copy the value
1182 *cookies = av_asprintf("%s=%s", cookie_entry->key, cookie_entry->value);
1184 char *tmp = *cookies;
1185 *cookies = av_asprintf("%s; %s=%s", tmp, cookie_entry->key, cookie_entry->value);
1189 ret = AVERROR(ENOMEM);
1192 av_dict_free(&cookie_params);
1195 av_free(set_cookies);
1200 static inline int has_header(const char *str, const char *header)
1202 /* header + 2 to skip over CRLF prefix. (make sure you have one!) */
1205 return av_stristart(str, header + 2, NULL) || av_stristr(str, header);
1208 static int http_read_header(URLContext *h, int *new_location)
1210 HTTPContext *s = h->priv_data;
1211 char line[MAX_URL_SIZE];
1214 s->chunksize = UINT64_MAX;
1217 if ((err = http_get_line(s, line, sizeof(line))) < 0)
1220 av_log(h, AV_LOG_TRACE, "header='%s'\n", line);
1222 err = process_line(h, line, s->line_count, new_location);
1230 if (s->seekable == -1 && s->is_mediagateway && s->filesize == 2000000000)
1231 h->is_streamed = 1; /* we can in fact _not_ seek */
1233 // add any new cookies into the existing cookie string
1234 cookie_string(s->cookie_dict, &s->cookies);
1235 av_dict_free(&s->cookie_dict);
1241 * Escape unsafe characters in path in order to pass them safely to the HTTP
1242 * request. Insipred by the algorithm in GNU wget:
1243 * - escape "%" characters not followed by two hex digits
1244 * - escape all "unsafe" characters except which are also "reserved"
1245 * - pass through everything else
1247 static void bprint_escaped_path(AVBPrint *bp, const char *path)
1249 #define NEEDS_ESCAPE(ch) \
1250 ((ch) <= ' ' || (ch) >= '\x7f' || \
1251 (ch) == '"' || (ch) == '%' || (ch) == '<' || (ch) == '>' || (ch) == '\\' || \
1252 (ch) == '^' || (ch) == '`' || (ch) == '{' || (ch) == '}' || (ch) == '|')
1256 while (*path && q - buf < sizeof(buf) - 4) {
1257 if (path[0] == '%' && av_isxdigit(path[1]) && av_isxdigit(path[2])) {
1261 } else if (NEEDS_ESCAPE(*path)) {
1262 q += snprintf(q, 4, "%%%02X", (uint8_t)*path++);
1267 av_bprint_append_data(bp, buf, q - buf);
1271 static int http_connect(URLContext *h, const char *path, const char *local_path,
1272 const char *hoststr, const char *auth,
1273 const char *proxyauth, int *new_location)
1275 HTTPContext *s = h->priv_data;
1278 char *authstr = NULL, *proxyauthstr = NULL;
1279 uint64_t off = s->off;
1281 int send_expect_100 = 0;
1283 av_bprint_init_for_buffer(&request, s->buffer, sizeof(s->buffer));
1285 /* send http header */
1286 post = h->flags & AVIO_FLAG_WRITE;
1289 /* force POST method and disable chunked encoding when
1290 * custom HTTP post data is set */
1292 s->chunked_post = 0;
1298 method = post ? "POST" : "GET";
1300 authstr = ff_http_auth_create_response(&s->auth_state, auth,
1301 local_path, method);
1302 proxyauthstr = ff_http_auth_create_response(&s->proxy_auth_state, proxyauth,
1303 local_path, method);
1305 if (post && !s->post_data) {
1306 if (s->send_expect_100 != -1) {
1307 send_expect_100 = s->send_expect_100;
1309 send_expect_100 = 0;
1310 /* The user has supplied authentication but we don't know the auth type,
1311 * send Expect: 100-continue to get the 401 response including the
1312 * WWW-Authenticate header, or an 100 continue if no auth actually
1314 if (auth && *auth &&
1315 s->auth_state.auth_type == HTTP_AUTH_NONE &&
1316 s->http_code != 401)
1317 send_expect_100 = 1;
1321 av_bprintf(&request, "%s ", method);
1322 bprint_escaped_path(&request, path);
1323 av_bprintf(&request, " HTTP/1.1\r\n");
1325 if (post && s->chunked_post)
1326 av_bprintf(&request, "Transfer-Encoding: chunked\r\n");
1327 /* set default headers if needed */
1328 if (!has_header(s->headers, "\r\nUser-Agent: "))
1329 av_bprintf(&request, "User-Agent: %s\r\n", s->user_agent);
1331 /* set default headers if needed */
1332 if (!has_header(s->headers, "\r\nReferer: "))
1333 av_bprintf(&request, "Referer: %s\r\n", s->referer);
1335 if (!has_header(s->headers, "\r\nAccept: "))
1336 av_bprintf(&request, "Accept: */*\r\n");
1337 // Note: we send this on purpose even when s->off is 0 when we're probing,
1338 // since it allows us to detect more reliably if a (non-conforming)
1339 // server supports seeking by analysing the reply headers.
1340 if (!has_header(s->headers, "\r\nRange: ") && !post && (s->off > 0 || s->end_off || s->seekable == -1)) {
1341 av_bprintf(&request, "Range: bytes=%"PRIu64"-", s->off);
1343 av_bprintf(&request, "%"PRId64, s->end_off - 1);
1344 av_bprintf(&request, "\r\n");
1346 if (send_expect_100 && !has_header(s->headers, "\r\nExpect: "))
1347 av_bprintf(&request, "Expect: 100-continue\r\n");
1349 if (!has_header(s->headers, "\r\nConnection: "))
1350 av_bprintf(&request, "Connection: %s\r\n", s->multiple_requests ? "keep-alive" : "close");
1352 if (!has_header(s->headers, "\r\nHost: "))
1353 av_bprintf(&request, "Host: %s\r\n", hoststr);
1354 if (!has_header(s->headers, "\r\nContent-Length: ") && s->post_data)
1355 av_bprintf(&request, "Content-Length: %d\r\n", s->post_datalen);
1357 if (!has_header(s->headers, "\r\nContent-Type: ") && s->content_type)
1358 av_bprintf(&request, "Content-Type: %s\r\n", s->content_type);
1359 if (!has_header(s->headers, "\r\nCookie: ") && s->cookies) {
1360 char *cookies = NULL;
1361 if (!get_cookies(s, &cookies, path, hoststr) && cookies) {
1362 av_bprintf(&request, "Cookie: %s\r\n", cookies);
1366 if (!has_header(s->headers, "\r\nIcy-MetaData: ") && s->icy)
1367 av_bprintf(&request, "Icy-MetaData: 1\r\n");
1369 /* now add in custom headers */
1371 av_bprintf(&request, "%s", s->headers);
1374 av_bprintf(&request, "%s", authstr);
1376 av_bprintf(&request, "Proxy-%s", proxyauthstr);
1377 av_bprintf(&request, "\r\n");
1379 av_log(h, AV_LOG_DEBUG, "request: %s\n", request.str);
1381 if (!av_bprint_is_complete(&request)) {
1382 av_log(h, AV_LOG_ERROR, "overlong headers\n");
1383 err = AVERROR(EINVAL);
1387 if ((err = ffurl_write(s->hd, request.str, request.len)) < 0)
1391 if ((err = ffurl_write(s->hd, s->post_data, s->post_datalen)) < 0)
1394 /* init input buffer */
1395 s->buf_ptr = s->buffer;
1396 s->buf_end = s->buffer;
1399 s->icy_data_read = 0;
1400 s->filesize = UINT64_MAX;
1402 s->end_chunked_post = 0;
1407 if (post && !s->post_data && !send_expect_100) {
1408 /* Pretend that it did work. We didn't read any header yet, since
1409 * we've still to send the POST data, but the code calling this
1410 * function will check http_code after we return. */
1416 /* wait for header */
1417 err = http_read_header(h, new_location);
1424 err = (off == s->off) ? 0 : -1;
1427 av_freep(&proxyauthstr);
1431 static int http_buf_read(URLContext *h, uint8_t *buf, int size)
1433 HTTPContext *s = h->priv_data;
1436 if (s->chunksize != UINT64_MAX) {
1440 if (!s->chunksize) {
1445 if ((err = http_get_line(s, line, sizeof(line))) < 0)
1447 } while (!*line); /* skip CR LF from last chunk */
1449 s->chunksize = strtoull(line, NULL, 16);
1451 av_log(h, AV_LOG_TRACE,
1452 "Chunked encoding data size: %"PRIu64"\n",
1455 if (!s->chunksize && s->multiple_requests) {
1456 http_get_line(s, line, sizeof(line)); // read empty chunk
1460 else if (!s->chunksize) {
1461 av_log(h, AV_LOG_DEBUG, "Last chunk received, closing conn\n");
1462 ffurl_closep(&s->hd);
1465 else if (s->chunksize == UINT64_MAX) {
1466 av_log(h, AV_LOG_ERROR, "Invalid chunk size %"PRIu64"\n",
1468 return AVERROR(EINVAL);
1471 size = FFMIN(size, s->chunksize);
1474 /* read bytes from input buffer first */
1475 len = s->buf_end - s->buf_ptr;
1479 memcpy(buf, s->buf_ptr, len);
1482 uint64_t target_end = s->end_off ? s->end_off : s->filesize;
1483 if ((!s->willclose || s->chunksize == UINT64_MAX) && s->off >= target_end)
1485 len = ffurl_read(s->hd, buf, size);
1486 if ((!len || len == AVERROR_EOF) &&
1487 (!s->willclose || s->chunksize == UINT64_MAX) && s->off < target_end) {
1488 av_log(h, AV_LOG_ERROR,
1489 "Stream ends prematurely at %"PRIu64", should be %"PRIu64"\n",
1492 return AVERROR(EIO);
1497 if (s->chunksize > 0 && s->chunksize != UINT64_MAX) {
1498 av_assert0(s->chunksize >= len);
1499 s->chunksize -= len;
1506 #define DECOMPRESS_BUF_SIZE (256 * 1024)
1507 static int http_buf_read_compressed(URLContext *h, uint8_t *buf, int size)
1509 HTTPContext *s = h->priv_data;
1512 if (!s->inflate_buffer) {
1513 s->inflate_buffer = av_malloc(DECOMPRESS_BUF_SIZE);
1514 if (!s->inflate_buffer)
1515 return AVERROR(ENOMEM);
1518 if (s->inflate_stream.avail_in == 0) {
1519 int read = http_buf_read(h, s->inflate_buffer, DECOMPRESS_BUF_SIZE);
1522 s->inflate_stream.next_in = s->inflate_buffer;
1523 s->inflate_stream.avail_in = read;
1526 s->inflate_stream.avail_out = size;
1527 s->inflate_stream.next_out = buf;
1529 ret = inflate(&s->inflate_stream, Z_SYNC_FLUSH);
1530 if (ret != Z_OK && ret != Z_STREAM_END)
1531 av_log(h, AV_LOG_WARNING, "inflate return value: %d, %s\n",
1532 ret, s->inflate_stream.msg);
1534 return size - s->inflate_stream.avail_out;
1536 #endif /* CONFIG_ZLIB */
1538 static int64_t http_seek_internal(URLContext *h, int64_t off, int whence, int force_reconnect);
1540 static int http_read_stream(URLContext *h, uint8_t *buf, int size)
1542 HTTPContext *s = h->priv_data;
1543 int err, new_location, read_ret;
1545 int reconnect_delay = 0;
1550 if (s->end_chunked_post && !s->end_header) {
1551 err = http_read_header(h, &new_location);
1558 return http_buf_read_compressed(h, buf, size);
1559 #endif /* CONFIG_ZLIB */
1560 read_ret = http_buf_read(h, buf, size);
1561 while (read_ret < 0) {
1562 uint64_t target = h->is_streamed ? 0 : s->off;
1564 if (read_ret == AVERROR_EXIT)
1567 if (h->is_streamed && !s->reconnect_streamed)
1570 if (!(s->reconnect && s->filesize > 0 && s->off < s->filesize) &&
1571 !(s->reconnect_at_eof && read_ret == AVERROR_EOF))
1574 if (reconnect_delay > s->reconnect_delay_max)
1575 return AVERROR(EIO);
1577 av_log(h, AV_LOG_WARNING, "Will reconnect at %"PRIu64" in %d second(s), error=%s.\n", s->off, reconnect_delay, av_err2str(read_ret));
1578 err = ff_network_sleep_interruptible(1000U*1000*reconnect_delay, &h->interrupt_callback);
1579 if (err != AVERROR(ETIMEDOUT))
1581 reconnect_delay = 1 + 2*reconnect_delay;
1582 seek_ret = http_seek_internal(h, target, SEEK_SET, 1);
1583 if (seek_ret >= 0 && seek_ret != target) {
1584 av_log(h, AV_LOG_ERROR, "Failed to reconnect at %"PRIu64".\n", target);
1588 read_ret = http_buf_read(h, buf, size);
1594 // Like http_read_stream(), but no short reads.
1595 // Assumes partial reads are an error.
1596 static int http_read_stream_all(URLContext *h, uint8_t *buf, int size)
1599 while (pos < size) {
1600 int len = http_read_stream(h, buf + pos, size - pos);
1608 static void update_metadata(URLContext *h, char *data)
1614 HTTPContext *s = h->priv_data;
1618 val = strstr(key, "='");
1621 end = strstr(val, "';");
1629 av_dict_set(&s->metadata, key, val, 0);
1630 av_log(h, AV_LOG_VERBOSE, "Metadata update for %s: %s\n", key, val);
1636 static int store_icy(URLContext *h, int size)
1638 HTTPContext *s = h->priv_data;
1639 /* until next metadata packet */
1642 if (s->icy_metaint < s->icy_data_read)
1643 return AVERROR_INVALIDDATA;
1644 remaining = s->icy_metaint - s->icy_data_read;
1647 /* The metadata packet is variable sized. It has a 1 byte header
1648 * which sets the length of the packet (divided by 16). If it's 0,
1649 * the metadata doesn't change. After the packet, icy_metaint bytes
1650 * of normal data follows. */
1652 int len = http_read_stream_all(h, &ch, 1);
1656 char data[255 * 16 + 1];
1659 ret = http_read_stream_all(h, data, len);
1663 if ((ret = av_opt_set(s, "icy_metadata_packet", data, 0)) < 0)
1665 update_metadata(h, data);
1667 s->icy_data_read = 0;
1668 remaining = s->icy_metaint;
1671 return FFMIN(size, remaining);
1674 static int http_read(URLContext *h, uint8_t *buf, int size)
1676 HTTPContext *s = h->priv_data;
1678 if (s->icy_metaint > 0) {
1679 size = store_icy(h, size);
1684 size = http_read_stream(h, buf, size);
1686 s->icy_data_read += size;
1690 /* used only when posting data */
1691 static int http_write(URLContext *h, const uint8_t *buf, int size)
1693 char temp[11] = ""; /* 32-bit hex + CRLF + nul */
1695 char crlf[] = "\r\n";
1696 HTTPContext *s = h->priv_data;
1698 if (!s->chunked_post) {
1699 /* non-chunked data is sent without any special encoding */
1700 return ffurl_write(s->hd, buf, size);
1703 /* silently ignore zero-size data since chunk encoding that would
1706 /* upload data using chunked encoding */
1707 snprintf(temp, sizeof(temp), "%x\r\n", size);
1709 if ((ret = ffurl_write(s->hd, temp, strlen(temp))) < 0 ||
1710 (ret = ffurl_write(s->hd, buf, size)) < 0 ||
1711 (ret = ffurl_write(s->hd, crlf, sizeof(crlf) - 1)) < 0)
1717 static int http_shutdown(URLContext *h, int flags)
1720 char footer[] = "0\r\n\r\n";
1721 HTTPContext *s = h->priv_data;
1723 /* signal end of chunked encoding if used */
1724 if (((flags & AVIO_FLAG_WRITE) && s->chunked_post) ||
1725 ((flags & AVIO_FLAG_READ) && s->chunked_post && s->listen)) {
1726 ret = ffurl_write(s->hd, footer, sizeof(footer) - 1);
1727 ret = ret > 0 ? 0 : ret;
1728 /* flush the receive buffer when it is write only mode */
1729 if (!(flags & AVIO_FLAG_READ)) {
1732 s->hd->flags |= AVIO_FLAG_NONBLOCK;
1733 read_ret = ffurl_read(s->hd, buf, sizeof(buf));
1734 s->hd->flags &= ~AVIO_FLAG_NONBLOCK;
1735 if (read_ret < 0 && read_ret != AVERROR(EAGAIN)) {
1736 av_log(h, AV_LOG_ERROR, "URL read error: %s\n", av_err2str(read_ret));
1740 s->end_chunked_post = 1;
1746 static int http_close(URLContext *h)
1749 HTTPContext *s = h->priv_data;
1752 inflateEnd(&s->inflate_stream);
1753 av_freep(&s->inflate_buffer);
1754 #endif /* CONFIG_ZLIB */
1756 if (s->hd && !s->end_chunked_post)
1757 /* Close the write direction by sending the end of chunked encoding. */
1758 ret = http_shutdown(h, h->flags);
1761 ffurl_closep(&s->hd);
1762 av_dict_free(&s->chained_options);
1766 static int64_t http_seek_internal(URLContext *h, int64_t off, int whence, int force_reconnect)
1768 HTTPContext *s = h->priv_data;
1769 URLContext *old_hd = s->hd;
1770 uint64_t old_off = s->off;
1771 uint8_t old_buf[BUFFER_SIZE];
1772 int old_buf_size, ret;
1773 AVDictionary *options = NULL;
1775 if (whence == AVSEEK_SIZE)
1777 else if (!force_reconnect &&
1778 ((whence == SEEK_CUR && off == 0) ||
1779 (whence == SEEK_SET && off == s->off)))
1781 else if ((s->filesize == UINT64_MAX && whence == SEEK_END))
1782 return AVERROR(ENOSYS);
1784 if (whence == SEEK_CUR)
1786 else if (whence == SEEK_END)
1788 else if (whence != SEEK_SET)
1789 return AVERROR(EINVAL);
1791 return AVERROR(EINVAL);
1794 if (s->off && h->is_streamed)
1795 return AVERROR(ENOSYS);
1797 /* do not try to make a new connection if seeking past the end of the file */
1798 if (s->end_off || s->filesize != UINT64_MAX) {
1799 uint64_t end_pos = s->end_off ? s->end_off : s->filesize;
1800 if (s->off >= end_pos)
1804 /* we save the old context in case the seek fails */
1805 old_buf_size = s->buf_end - s->buf_ptr;
1806 memcpy(old_buf, s->buf_ptr, old_buf_size);
1809 /* if it fails, continue on old connection */
1810 if ((ret = http_open_cnx(h, &options)) < 0) {
1811 av_dict_free(&options);
1812 memcpy(s->buffer, old_buf, old_buf_size);
1813 s->buf_ptr = s->buffer;
1814 s->buf_end = s->buffer + old_buf_size;
1819 av_dict_free(&options);
1820 ffurl_close(old_hd);
1824 static int64_t http_seek(URLContext *h, int64_t off, int whence)
1826 return http_seek_internal(h, off, whence, 0);
1829 static int http_get_file_handle(URLContext *h)
1831 HTTPContext *s = h->priv_data;
1832 return ffurl_get_file_handle(s->hd);
1835 static int http_get_short_seek(URLContext *h)
1837 HTTPContext *s = h->priv_data;
1838 return ffurl_get_short_seek(s->hd);
1841 #define HTTP_CLASS(flavor) \
1842 static const AVClass flavor ## _context_class = { \
1843 .class_name = # flavor, \
1844 .item_name = av_default_item_name, \
1845 .option = options, \
1846 .version = LIBAVUTIL_VERSION_INT, \
1849 #if CONFIG_HTTP_PROTOCOL
1852 const URLProtocol ff_http_protocol = {
1854 .url_open2 = http_open,
1855 .url_accept = http_accept,
1856 .url_handshake = http_handshake,
1857 .url_read = http_read,
1858 .url_write = http_write,
1859 .url_seek = http_seek,
1860 .url_close = http_close,
1861 .url_get_file_handle = http_get_file_handle,
1862 .url_get_short_seek = http_get_short_seek,
1863 .url_shutdown = http_shutdown,
1864 .priv_data_size = sizeof(HTTPContext),
1865 .priv_data_class = &http_context_class,
1866 .flags = URL_PROTOCOL_FLAG_NETWORK,
1867 .default_whitelist = "http,https,tls,rtp,tcp,udp,crypto,httpproxy,data"
1869 #endif /* CONFIG_HTTP_PROTOCOL */
1871 #if CONFIG_HTTPS_PROTOCOL
1874 const URLProtocol ff_https_protocol = {
1876 .url_open2 = http_open,
1877 .url_read = http_read,
1878 .url_write = http_write,
1879 .url_seek = http_seek,
1880 .url_close = http_close,
1881 .url_get_file_handle = http_get_file_handle,
1882 .url_get_short_seek = http_get_short_seek,
1883 .url_shutdown = http_shutdown,
1884 .priv_data_size = sizeof(HTTPContext),
1885 .priv_data_class = &https_context_class,
1886 .flags = URL_PROTOCOL_FLAG_NETWORK,
1887 .default_whitelist = "http,https,tls,rtp,tcp,udp,crypto,httpproxy"
1889 #endif /* CONFIG_HTTPS_PROTOCOL */
1891 #if CONFIG_HTTPPROXY_PROTOCOL
1892 static int http_proxy_close(URLContext *h)
1894 HTTPContext *s = h->priv_data;
1896 ffurl_closep(&s->hd);
1900 static int http_proxy_open(URLContext *h, const char *uri, int flags)
1902 HTTPContext *s = h->priv_data;
1903 char hostname[1024], hoststr[1024];
1904 char auth[1024], pathbuf[1024], *path;
1905 char lower_url[100];
1906 int port, ret = 0, attempts = 0;
1907 HTTPAuthType cur_auth_type;
1911 if( s->seekable == 1 )
1916 av_url_split(NULL, 0, auth, sizeof(auth), hostname, sizeof(hostname), &port,
1917 pathbuf, sizeof(pathbuf), uri);
1918 ff_url_join(hoststr, sizeof(hoststr), NULL, NULL, hostname, port, NULL);
1923 ff_url_join(lower_url, sizeof(lower_url), "tcp", NULL, hostname, port,
1926 ret = ffurl_open_whitelist(&s->hd, lower_url, AVIO_FLAG_READ_WRITE,
1927 &h->interrupt_callback, NULL,
1928 h->protocol_whitelist, h->protocol_blacklist, h);
1932 authstr = ff_http_auth_create_response(&s->proxy_auth_state, auth,
1934 snprintf(s->buffer, sizeof(s->buffer),
1935 "CONNECT %s HTTP/1.1\r\n"
1937 "Connection: close\r\n"
1942 authstr ? "Proxy-" : "", authstr ? authstr : "");
1945 if ((ret = ffurl_write(s->hd, s->buffer, strlen(s->buffer))) < 0)
1948 s->buf_ptr = s->buffer;
1949 s->buf_end = s->buffer;
1951 s->filesize = UINT64_MAX;
1952 cur_auth_type = s->proxy_auth_state.auth_type;
1954 /* Note: This uses buffering, potentially reading more than the
1955 * HTTP header. If tunneling a protocol where the server starts
1956 * the conversation, we might buffer part of that here, too.
1957 * Reading that requires using the proper ffurl_read() function
1958 * on this URLContext, not using the fd directly (as the tls
1959 * protocol does). This shouldn't be an issue for tls though,
1960 * since the client starts the conversation there, so there
1961 * is no extra data that we might buffer up here.
1963 ret = http_read_header(h, &new_loc);
1968 if (s->http_code == 407 &&
1969 (cur_auth_type == HTTP_AUTH_NONE || s->proxy_auth_state.stale) &&
1970 s->proxy_auth_state.auth_type != HTTP_AUTH_NONE && attempts < 2) {
1971 ffurl_closep(&s->hd);
1975 if (s->http_code < 400)
1977 ret = ff_http_averror(s->http_code, AVERROR(EIO));
1980 http_proxy_close(h);
1984 static int http_proxy_write(URLContext *h, const uint8_t *buf, int size)
1986 HTTPContext *s = h->priv_data;
1987 return ffurl_write(s->hd, buf, size);
1990 const URLProtocol ff_httpproxy_protocol = {
1991 .name = "httpproxy",
1992 .url_open = http_proxy_open,
1993 .url_read = http_buf_read,
1994 .url_write = http_proxy_write,
1995 .url_close = http_proxy_close,
1996 .url_get_file_handle = http_get_file_handle,
1997 .priv_data_size = sizeof(HTTPContext),
1998 .flags = URL_PROTOCOL_FLAG_NETWORK,
2000 #endif /* CONFIG_HTTPPROXY_PROTOCOL */