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 { "multiple_requests", "use persistent connections", OFFSET(multiple_requests), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, D | E },
145 { "post_data", "set custom HTTP post data", OFFSET(post_data), AV_OPT_TYPE_BINARY, .flags = D | E },
146 { "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 },
147 { "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 },
148 { "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 },
149 { "icy", "request ICY metadata", OFFSET(icy), AV_OPT_TYPE_BOOL, { .i64 = 1 }, 0, 1, D },
150 { "icy_metadata_headers", "return ICY metadata headers", OFFSET(icy_metadata_headers), AV_OPT_TYPE_STRING, { .str = NULL }, 0, 0, AV_OPT_FLAG_EXPORT },
151 { "icy_metadata_packet", "return current ICY metadata packet", OFFSET(icy_metadata_packet), AV_OPT_TYPE_STRING, { .str = NULL }, 0, 0, AV_OPT_FLAG_EXPORT },
152 { "metadata", "metadata read from the bitstream", OFFSET(metadata), AV_OPT_TYPE_DICT, {0}, 0, 0, AV_OPT_FLAG_EXPORT },
153 { "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"},
154 { "none", "No auth method set, autodetect", 0, AV_OPT_TYPE_CONST, { .i64 = HTTP_AUTH_NONE }, 0, 0, D | E, "auth_type"},
155 { "basic", "HTTP basic authentication", 0, AV_OPT_TYPE_CONST, { .i64 = HTTP_AUTH_BASIC }, 0, 0, D | E, "auth_type"},
156 { "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 },
157 { "location", "The actual location of the data received", OFFSET(location), AV_OPT_TYPE_STRING, { .str = NULL }, 0, 0, D | E },
158 { "offset", "initial byte offset", OFFSET(off), AV_OPT_TYPE_INT64, { .i64 = 0 }, 0, INT64_MAX, D },
159 { "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 },
160 { "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 },
161 { "reconnect", "auto reconnect after disconnect before EOF", OFFSET(reconnect), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, D },
162 { "reconnect_at_eof", "auto reconnect at EOF", OFFSET(reconnect_at_eof), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, D },
163 { "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 },
164 { "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 },
165 { "reconnect_streamed", "auto reconnect streamed / non seekable streams", OFFSET(reconnect_streamed), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, D },
166 { "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 },
167 { "listen", "listen on HTTP", OFFSET(listen), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 2, D | E },
168 { "resource", "The resource requested by a client", OFFSET(resource), AV_OPT_TYPE_STRING, { .str = NULL }, 0, 0, E },
169 { "reply_code", "The http status code to return to a client", OFFSET(reply_code), AV_OPT_TYPE_INT, { .i64 = 200}, INT_MIN, 599, E},
173 static int http_connect(URLContext *h, const char *path, const char *local_path,
174 const char *hoststr, const char *auth,
175 const char *proxyauth, int *new_location);
176 static int http_read_header(URLContext *h, int *new_location);
177 static int http_shutdown(URLContext *h, int flags);
179 void ff_http_init_auth_state(URLContext *dest, const URLContext *src)
181 memcpy(&((HTTPContext *)dest->priv_data)->auth_state,
182 &((HTTPContext *)src->priv_data)->auth_state,
183 sizeof(HTTPAuthState));
184 memcpy(&((HTTPContext *)dest->priv_data)->proxy_auth_state,
185 &((HTTPContext *)src->priv_data)->proxy_auth_state,
186 sizeof(HTTPAuthState));
189 static int http_open_cnx_internal(URLContext *h, AVDictionary **options)
191 const char *path, *proxy_path, *lower_proto = "tcp", *local_path;
193 char hostname[1024], hoststr[1024], proto[10];
194 char auth[1024], proxyauth[1024] = "";
195 char path1[MAX_URL_SIZE], sanitized_path[MAX_URL_SIZE];
196 char buf[1024], urlbuf[MAX_URL_SIZE];
197 int port, use_proxy, err, location_changed = 0;
198 HTTPContext *s = h->priv_data;
200 av_url_split(proto, sizeof(proto), auth, sizeof(auth),
201 hostname, sizeof(hostname), &port,
202 path1, sizeof(path1), s->location);
203 ff_url_join(hoststr, sizeof(hoststr), NULL, NULL, hostname, port, NULL);
205 proxy_path = s->http_proxy ? s->http_proxy : getenv("http_proxy");
206 use_proxy = !ff_http_match_no_proxy(getenv("no_proxy"), hostname) &&
207 proxy_path && av_strstart(proxy_path, "http://", NULL);
209 if (!strcmp(proto, "https")) {
214 /* pass http_proxy to underlying protocol */
216 err = av_dict_set(options, "http_proxy", s->http_proxy, 0);
224 hashmark = strchr(path1, '#');
228 if (path1[0] == '\0') {
230 } else if (path1[0] == '?') {
231 snprintf(sanitized_path, sizeof(sanitized_path), "/%s", path1);
232 path = sanitized_path;
238 /* Reassemble the request URL without auth string - we don't
239 * want to leak the auth to the proxy. */
240 ff_url_join(urlbuf, sizeof(urlbuf), proto, NULL, hostname, port, "%s",
243 av_url_split(NULL, 0, proxyauth, sizeof(proxyauth),
244 hostname, sizeof(hostname), &port, NULL, 0, proxy_path);
247 ff_url_join(buf, sizeof(buf), lower_proto, NULL, hostname, port, NULL);
250 err = ffurl_open_whitelist(&s->hd, buf, AVIO_FLAG_READ_WRITE,
251 &h->interrupt_callback, options,
252 h->protocol_whitelist, h->protocol_blacklist, h);
257 err = http_connect(h, path, local_path, hoststr,
258 auth, proxyauth, &location_changed);
262 return location_changed;
265 static int http_should_reconnect(HTTPContext *s, int err)
267 const char *status_group;
271 case AVERROR_HTTP_BAD_REQUEST:
272 case AVERROR_HTTP_UNAUTHORIZED:
273 case AVERROR_HTTP_FORBIDDEN:
274 case AVERROR_HTTP_NOT_FOUND:
275 case AVERROR_HTTP_OTHER_4XX:
276 status_group = "4xx";
279 case AVERROR_HTTP_SERVER_ERROR:
280 status_group = "5xx";
284 return s->reconnect_on_network_error;
287 if (!s->reconnect_on_http_error)
290 if (av_match_list(status_group, s->reconnect_on_http_error, ',') > 0)
293 snprintf(http_code, sizeof(http_code), "%d", s->http_code);
295 return av_match_list(http_code, s->reconnect_on_http_error, ',') > 0;
298 /* return non zero if error */
299 static int http_open_cnx(URLContext *h, AVDictionary **options)
301 HTTPAuthType cur_auth_type, cur_proxy_auth_type;
302 HTTPContext *s = h->priv_data;
303 int location_changed, attempts = 0, redirects = 0;
304 int reconnect_delay = 0;
308 av_dict_copy(options, s->chained_options, 0);
310 cur_auth_type = s->auth_state.auth_type;
311 cur_proxy_auth_type = s->auth_state.auth_type;
314 location_changed = http_open_cnx_internal(h, options);
315 if (location_changed < 0) {
316 if (!http_should_reconnect(s, location_changed) ||
317 reconnect_delay > s->reconnect_delay_max)
320 av_log(h, AV_LOG_WARNING, "Will reconnect at %"PRIu64" in %d second(s).\n", off, reconnect_delay);
321 location_changed = ff_network_sleep_interruptible(1000U * 1000 * reconnect_delay, &h->interrupt_callback);
322 if (location_changed != AVERROR(ETIMEDOUT))
324 reconnect_delay = 1 + 2 * reconnect_delay;
326 /* restore the offset (http_connect resets it) */
329 ffurl_closep(&s->hd);
334 if (s->http_code == 401) {
335 if ((cur_auth_type == HTTP_AUTH_NONE || s->auth_state.stale) &&
336 s->auth_state.auth_type != HTTP_AUTH_NONE && attempts < 4) {
337 ffurl_closep(&s->hd);
342 if (s->http_code == 407) {
343 if ((cur_proxy_auth_type == HTTP_AUTH_NONE || s->proxy_auth_state.stale) &&
344 s->proxy_auth_state.auth_type != HTTP_AUTH_NONE && attempts < 4) {
345 ffurl_closep(&s->hd);
350 if ((s->http_code == 301 || s->http_code == 302 ||
351 s->http_code == 303 || s->http_code == 307 || s->http_code == 308) &&
352 location_changed == 1) {
353 /* url moved, get next */
354 ffurl_closep(&s->hd);
355 if (redirects++ >= MAX_REDIRECTS)
357 /* Restart the authentication process with the new target, which
358 * might use a different auth mechanism. */
359 memset(&s->auth_state, 0, sizeof(s->auth_state));
361 location_changed = 0;
368 ffurl_closep(&s->hd);
369 if (location_changed < 0)
370 return location_changed;
371 return ff_http_averror(s->http_code, AVERROR(EIO));
373 int ff_http_get_shutdown_status(URLContext *h)
376 HTTPContext *s = h->priv_data;
378 /* flush the receive buffer when it is write only mode */
381 read_ret = ffurl_read(s->hd, buf, sizeof(buf));
389 int ff_http_do_new_request(URLContext *h, const char *uri) {
390 return ff_http_do_new_request2(h, uri, NULL);
393 int ff_http_do_new_request2(URLContext *h, const char *uri, AVDictionary **opts)
395 HTTPContext *s = h->priv_data;
396 AVDictionary *options = NULL;
398 char hostname1[1024], hostname2[1024], proto1[10], proto2[10];
402 !(!strcmp(h->prot->name, "http") ||
403 !strcmp(h->prot->name, "https")))
404 return AVERROR(EINVAL);
406 av_url_split(proto1, sizeof(proto1), NULL, 0,
407 hostname1, sizeof(hostname1), &port1,
408 NULL, 0, s->location);
409 av_url_split(proto2, sizeof(proto2), NULL, 0,
410 hostname2, sizeof(hostname2), &port2,
412 if (port1 != port2 || strncmp(hostname1, hostname2, sizeof(hostname2)) != 0) {
413 av_log(h, AV_LOG_ERROR, "Cannot reuse HTTP connection for different host: %s:%d != %s:%d\n",
417 return AVERROR(EINVAL);
420 if (!s->end_chunked_post) {
421 ret = http_shutdown(h, h->flags);
429 s->end_chunked_post = 0;
432 s->icy_data_read = 0;
433 av_free(s->location);
434 s->location = av_strdup(uri);
436 return AVERROR(ENOMEM);
438 if ((ret = av_opt_set_dict(s, opts)) < 0)
441 av_log(s, AV_LOG_INFO, "Opening \'%s\' for %s\n", uri, h->flags & AVIO_FLAG_WRITE ? "writing" : "reading");
442 ret = http_open_cnx(h, &options);
443 av_dict_free(&options);
447 int ff_http_averror(int status_code, int default_averror)
449 switch (status_code) {
450 case 400: return AVERROR_HTTP_BAD_REQUEST;
451 case 401: return AVERROR_HTTP_UNAUTHORIZED;
452 case 403: return AVERROR_HTTP_FORBIDDEN;
453 case 404: return AVERROR_HTTP_NOT_FOUND;
456 if (status_code >= 400 && status_code <= 499)
457 return AVERROR_HTTP_OTHER_4XX;
458 else if (status_code >= 500)
459 return AVERROR_HTTP_SERVER_ERROR;
461 return default_averror;
464 static int http_write_reply(URLContext* h, int status_code)
466 int ret, body = 0, reply_code, message_len;
467 const char *reply_text, *content_type;
468 HTTPContext *s = h->priv_data;
469 char message[BUFFER_SIZE];
470 content_type = "text/plain";
474 switch (status_code) {
475 case AVERROR_HTTP_BAD_REQUEST:
478 reply_text = "Bad Request";
480 case AVERROR_HTTP_FORBIDDEN:
483 reply_text = "Forbidden";
485 case AVERROR_HTTP_NOT_FOUND:
488 reply_text = "Not Found";
493 content_type = s->content_type ? s->content_type : "application/octet-stream";
495 case AVERROR_HTTP_SERVER_ERROR:
498 reply_text = "Internal server error";
501 return AVERROR(EINVAL);
505 message_len = snprintf(message, sizeof(message),
506 "HTTP/1.1 %03d %s\r\n"
507 "Content-Type: %s\r\n"
508 "Content-Length: %"SIZE_SPECIFIER"\r\n"
515 strlen(reply_text) + 6, // 3 digit status code + space + \r\n
516 s->headers ? s->headers : "",
521 message_len = snprintf(message, sizeof(message),
522 "HTTP/1.1 %03d %s\r\n"
523 "Content-Type: %s\r\n"
524 "Transfer-Encoding: chunked\r\n"
530 s->headers ? s->headers : "");
532 av_log(h, AV_LOG_TRACE, "HTTP reply header: \n%s----\n", message);
533 if ((ret = ffurl_write(s->hd, message, message_len)) < 0)
538 static void handle_http_errors(URLContext *h, int error)
540 av_assert0(error < 0);
541 http_write_reply(h, error);
544 static int http_handshake(URLContext *c)
546 int ret, err, new_location;
547 HTTPContext *ch = c->priv_data;
548 URLContext *cl = ch->hd;
549 switch (ch->handshake_step) {
551 av_log(c, AV_LOG_TRACE, "Lower protocol\n");
552 if ((ret = ffurl_handshake(cl)) > 0)
556 ch->handshake_step = READ_HEADERS;
557 ch->is_connected_server = 1;
560 av_log(c, AV_LOG_TRACE, "Read headers\n");
561 if ((err = http_read_header(c, &new_location)) < 0) {
562 handle_http_errors(c, err);
565 ch->handshake_step = WRITE_REPLY_HEADERS;
567 case WRITE_REPLY_HEADERS:
568 av_log(c, AV_LOG_TRACE, "Reply code: %d\n", ch->reply_code);
569 if ((err = http_write_reply(c, ch->reply_code)) < 0)
571 ch->handshake_step = FINISH;
576 // this should never be reached.
577 return AVERROR(EINVAL);
580 static int http_listen(URLContext *h, const char *uri, int flags,
581 AVDictionary **options) {
582 HTTPContext *s = h->priv_data;
584 char hostname[1024], proto[10];
586 const char *lower_proto = "tcp";
588 av_url_split(proto, sizeof(proto), NULL, 0, hostname, sizeof(hostname), &port,
590 if (!strcmp(proto, "https"))
592 ff_url_join(lower_url, sizeof(lower_url), lower_proto, NULL, hostname, port,
594 if ((ret = av_dict_set_int(options, "listen", s->listen, 0)) < 0)
596 if ((ret = ffurl_open_whitelist(&s->hd, lower_url, AVIO_FLAG_READ_WRITE,
597 &h->interrupt_callback, options,
598 h->protocol_whitelist, h->protocol_blacklist, h
601 s->handshake_step = LOWER_PROTO;
602 if (s->listen == HTTP_SINGLE) { /* single client */
604 while ((ret = http_handshake(h)) > 0);
607 av_dict_free(&s->chained_options);
611 static int http_open(URLContext *h, const char *uri, int flags,
612 AVDictionary **options)
614 HTTPContext *s = h->priv_data;
617 if( s->seekable == 1 )
622 s->filesize = UINT64_MAX;
623 s->location = av_strdup(uri);
625 return AVERROR(ENOMEM);
627 av_dict_copy(&s->chained_options, *options, 0);
630 int len = strlen(s->headers);
631 if (len < 2 || strcmp("\r\n", s->headers + len - 2)) {
632 av_log(h, AV_LOG_WARNING,
633 "No trailing CRLF found in HTTP header. Adding it.\n");
634 ret = av_reallocp(&s->headers, len + 3);
637 s->headers[len] = '\r';
638 s->headers[len + 1] = '\n';
639 s->headers[len + 2] = '\0';
644 return http_listen(h, uri, flags, options);
646 ret = http_open_cnx(h, options);
649 av_dict_free(&s->chained_options);
653 static int http_accept(URLContext *s, URLContext **c)
656 HTTPContext *sc = s->priv_data;
658 URLContext *sl = sc->hd;
659 URLContext *cl = NULL;
661 av_assert0(sc->listen);
662 if ((ret = ffurl_alloc(c, s->filename, s->flags, &sl->interrupt_callback)) < 0)
664 cc = (*c)->priv_data;
665 if ((ret = ffurl_accept(sl, &cl)) < 0)
668 cc->is_multi_client = 1;
677 static int http_getc(HTTPContext *s)
680 if (s->buf_ptr >= s->buf_end) {
681 len = ffurl_read(s->hd, s->buffer, BUFFER_SIZE);
684 } else if (len == 0) {
687 s->buf_ptr = s->buffer;
688 s->buf_end = s->buffer + len;
691 return *s->buf_ptr++;
694 static int http_get_line(HTTPContext *s, char *line, int line_size)
706 if (q > line && q[-1] == '\r')
712 if ((q - line) < line_size - 1)
718 static int check_http_code(URLContext *h, int http_code, const char *end)
720 HTTPContext *s = h->priv_data;
721 /* error codes are 4xx and 5xx, but regard 401 as a success, so we
722 * don't abort until all headers have been parsed. */
723 if (http_code >= 400 && http_code < 600 &&
724 (http_code != 401 || s->auth_state.auth_type != HTTP_AUTH_NONE) &&
725 (http_code != 407 || s->proxy_auth_state.auth_type != HTTP_AUTH_NONE)) {
726 end += strspn(end, SPACE_CHARS);
727 av_log(h, AV_LOG_WARNING, "HTTP error %d %s\n", http_code, end);
728 return ff_http_averror(http_code, AVERROR(EIO));
733 static int parse_location(HTTPContext *s, const char *p)
735 char redirected_location[MAX_URL_SIZE], *new_loc;
736 ff_make_absolute_url(redirected_location, sizeof(redirected_location),
738 new_loc = av_strdup(redirected_location);
740 return AVERROR(ENOMEM);
741 av_free(s->location);
742 s->location = new_loc;
746 /* "bytes $from-$to/$document_size" */
747 static void parse_content_range(URLContext *h, const char *p)
749 HTTPContext *s = h->priv_data;
752 if (!strncmp(p, "bytes ", 6)) {
754 s->off = strtoull(p, NULL, 10);
755 if ((slash = strchr(p, '/')) && strlen(slash) > 0)
756 s->filesize = strtoull(slash + 1, NULL, 10);
758 if (s->seekable == -1 && (!s->is_akamai || s->filesize != 2147483647))
759 h->is_streamed = 0; /* we _can_ in fact seek */
762 static int parse_content_encoding(URLContext *h, const char *p)
764 if (!av_strncasecmp(p, "gzip", 4) ||
765 !av_strncasecmp(p, "deflate", 7)) {
767 HTTPContext *s = h->priv_data;
770 inflateEnd(&s->inflate_stream);
771 if (inflateInit2(&s->inflate_stream, 32 + 15) != Z_OK) {
772 av_log(h, AV_LOG_WARNING, "Error during zlib initialisation: %s\n",
773 s->inflate_stream.msg);
774 return AVERROR(ENOSYS);
776 if (zlibCompileFlags() & (1 << 17)) {
777 av_log(h, AV_LOG_WARNING,
778 "Your zlib was compiled without gzip support.\n");
779 return AVERROR(ENOSYS);
782 av_log(h, AV_LOG_WARNING,
783 "Compressed (%s) content, need zlib with gzip support\n", p);
784 return AVERROR(ENOSYS);
785 #endif /* CONFIG_ZLIB */
786 } else if (!av_strncasecmp(p, "identity", 8)) {
787 // The normal, no-encoding case (although servers shouldn't include
788 // the header at all if this is the case).
790 av_log(h, AV_LOG_WARNING, "Unknown content coding: %s\n", p);
795 // Concat all Icy- header lines
796 static int parse_icy(HTTPContext *s, const char *tag, const char *p)
798 int len = 4 + strlen(p) + strlen(tag);
799 int is_first = !s->icy_metadata_headers;
802 av_dict_set(&s->metadata, tag, p, 0);
804 if (s->icy_metadata_headers)
805 len += strlen(s->icy_metadata_headers);
807 if ((ret = av_reallocp(&s->icy_metadata_headers, len)) < 0)
811 *s->icy_metadata_headers = '\0';
813 av_strlcatf(s->icy_metadata_headers, len, "%s: %s\n", tag, p);
818 static int parse_set_cookie_expiry_time(const char *exp_str, struct tm *buf)
820 char exp_buf[MAX_EXPIRY];
821 int i, j, exp_buf_len = MAX_EXPIRY-1;
824 // strip off any punctuation or whitespace
825 for (i = 0, j = 0; exp_str[i] != '\0' && j < exp_buf_len; i++) {
826 if ((exp_str[i] >= '0' && exp_str[i] <= '9') ||
827 (exp_str[i] >= 'A' && exp_str[i] <= 'Z') ||
828 (exp_str[i] >= 'a' && exp_str[i] <= 'z')) {
829 exp_buf[j] = exp_str[i];
836 // move the string beyond the day of week
837 while ((*expiry < '0' || *expiry > '9') && *expiry != '\0')
840 return av_small_strptime(expiry, "%d%b%Y%H%M%S", buf) ? 0 : AVERROR(EINVAL);
843 static int parse_set_cookie(const char *set_cookie, AVDictionary **dict)
845 char *param, *next_param, *cstr, *back;
846 char *saveptr = NULL;
851 if (!(cstr = av_strdup(set_cookie)))
852 return AVERROR(EINVAL);
854 // strip any trailing whitespace
855 back = &cstr[strlen(cstr)-1];
856 while (strchr(WHITESPACES, *back)) {
864 while ((param = av_strtok(next_param, ";", &saveptr))) {
867 param += strspn(param, WHITESPACES);
868 if ((name = av_strtok(param, "=", &value))) {
869 if (av_dict_set(dict, name, value, 0) < 0) {
880 static int parse_cookie(HTTPContext *s, const char *p, AVDictionary **cookies)
882 AVDictionary *new_params = NULL;
883 AVDictionaryEntry *e, *cookie_entry;
886 // ensure the cookie is parsable
887 if (parse_set_cookie(p, &new_params))
890 // if there is no cookie value there is nothing to parse
891 cookie_entry = av_dict_get(new_params, "", NULL, AV_DICT_IGNORE_SUFFIX);
892 if (!cookie_entry || !cookie_entry->value) {
893 av_dict_free(&new_params);
897 // ensure the cookie is not expired or older than an existing value
898 if ((e = av_dict_get(new_params, "expires", NULL, 0)) && e->value) {
899 struct tm new_tm = {0};
900 if (!parse_set_cookie_expiry_time(e->value, &new_tm)) {
901 AVDictionaryEntry *e2;
903 // if the cookie has already expired ignore it
904 if (av_timegm(&new_tm) < av_gettime() / 1000000) {
905 av_dict_free(&new_params);
909 // only replace an older cookie with the same name
910 e2 = av_dict_get(*cookies, cookie_entry->key, NULL, 0);
911 if (e2 && e2->value) {
912 AVDictionary *old_params = NULL;
913 if (!parse_set_cookie(p, &old_params)) {
914 e2 = av_dict_get(old_params, "expires", NULL, 0);
915 if (e2 && e2->value) {
916 struct tm old_tm = {0};
917 if (!parse_set_cookie_expiry_time(e->value, &old_tm)) {
918 if (av_timegm(&new_tm) < av_timegm(&old_tm)) {
919 av_dict_free(&new_params);
920 av_dict_free(&old_params);
926 av_dict_free(&old_params);
930 av_dict_free(&new_params);
932 // duplicate the cookie name (dict will dupe the value)
933 if (!(eql = strchr(p, '='))) return AVERROR(EINVAL);
934 if (!(name = av_strndup(p, eql - p))) return AVERROR(ENOMEM);
936 // add the cookie to the dictionary
937 av_dict_set(cookies, name, eql, AV_DICT_DONT_STRDUP_KEY);
942 static int cookie_string(AVDictionary *dict, char **cookies)
944 AVDictionaryEntry *e = NULL;
947 // determine how much memory is needed for the cookies string
948 while (e = av_dict_get(dict, "", e, AV_DICT_IGNORE_SUFFIX))
949 len += strlen(e->key) + strlen(e->value) + 1;
951 // reallocate the cookies
953 if (*cookies) av_free(*cookies);
954 *cookies = av_malloc(len);
955 if (!*cookies) return AVERROR(ENOMEM);
958 // write out the cookies
959 while (e = av_dict_get(dict, "", e, AV_DICT_IGNORE_SUFFIX))
960 av_strlcatf(*cookies, len, "%s%s\n", e->key, e->value);
965 static int process_line(URLContext *h, char *line, int line_count,
968 HTTPContext *s = h->priv_data;
969 const char *auto_method = h->flags & AVIO_FLAG_READ ? "POST" : "GET";
970 char *tag, *p, *end, *method, *resource, *version;
974 if (line[0] == '\0') {
980 if (line_count == 0) {
981 if (s->is_connected_server) {
984 while (*p && !av_isspace(*p))
987 av_log(h, AV_LOG_TRACE, "Received method: %s\n", method);
989 if (av_strcasecmp(s->method, method)) {
990 av_log(h, AV_LOG_ERROR, "Received and expected HTTP method do not match. (%s expected, %s received)\n",
992 return ff_http_averror(400, AVERROR(EIO));
995 // use autodetected HTTP method to expect
996 av_log(h, AV_LOG_TRACE, "Autodetected %s HTTP method\n", auto_method);
997 if (av_strcasecmp(auto_method, method)) {
998 av_log(h, AV_LOG_ERROR, "Received and autodetected HTTP method did not match "
999 "(%s autodetected %s received)\n", auto_method, method);
1000 return ff_http_averror(400, AVERROR(EIO));
1002 if (!(s->method = av_strdup(method)))
1003 return AVERROR(ENOMEM);
1007 while (av_isspace(*p))
1010 while (*p && !av_isspace(*p))
1013 av_log(h, AV_LOG_TRACE, "Requested resource: %s\n", resource);
1014 if (!(s->resource = av_strdup(resource)))
1015 return AVERROR(ENOMEM);
1018 while (av_isspace(*p))
1021 while (*p && !av_isspace(*p))
1024 if (av_strncasecmp(version, "HTTP/", 5)) {
1025 av_log(h, AV_LOG_ERROR, "Malformed HTTP version string.\n");
1026 return ff_http_averror(400, AVERROR(EIO));
1028 av_log(h, AV_LOG_TRACE, "HTTP version string: %s\n", version);
1030 if (av_strncasecmp(p, "HTTP/1.0", 8) == 0)
1032 while (*p != '/' && *p != '\0')
1036 av_freep(&s->http_version);
1037 s->http_version = av_strndup(p, 3);
1038 while (!av_isspace(*p) && *p != '\0')
1040 while (av_isspace(*p))
1042 s->http_code = strtol(p, &end, 10);
1044 av_log(h, AV_LOG_TRACE, "http_code=%d\n", s->http_code);
1046 if ((ret = check_http_code(h, s->http_code, end)) < 0)
1050 while (*p != '\0' && *p != ':')
1058 while (av_isspace(*p))
1060 if (!av_strcasecmp(tag, "Location")) {
1061 if ((ret = parse_location(s, p)) < 0)
1064 } else if (!av_strcasecmp(tag, "Content-Length") &&
1065 s->filesize == UINT64_MAX) {
1066 s->filesize = strtoull(p, NULL, 10);
1067 } else if (!av_strcasecmp(tag, "Content-Range")) {
1068 parse_content_range(h, p);
1069 } else if (!av_strcasecmp(tag, "Accept-Ranges") &&
1070 !strncmp(p, "bytes", 5) &&
1071 s->seekable == -1) {
1073 } else if (!av_strcasecmp(tag, "Transfer-Encoding") &&
1074 !av_strncasecmp(p, "chunked", 7)) {
1075 s->filesize = UINT64_MAX;
1077 } else if (!av_strcasecmp(tag, "WWW-Authenticate")) {
1078 ff_http_auth_handle_header(&s->auth_state, tag, p);
1079 } else if (!av_strcasecmp(tag, "Authentication-Info")) {
1080 ff_http_auth_handle_header(&s->auth_state, tag, p);
1081 } else if (!av_strcasecmp(tag, "Proxy-Authenticate")) {
1082 ff_http_auth_handle_header(&s->proxy_auth_state, tag, p);
1083 } else if (!av_strcasecmp(tag, "Connection")) {
1084 if (!strcmp(p, "close"))
1086 } else if (!av_strcasecmp(tag, "Server")) {
1087 if (!av_strcasecmp(p, "AkamaiGHost")) {
1089 } else if (!av_strncasecmp(p, "MediaGateway", 12)) {
1090 s->is_mediagateway = 1;
1092 } else if (!av_strcasecmp(tag, "Content-Type")) {
1093 av_free(s->mime_type);
1094 s->mime_type = av_strdup(p);
1095 } else if (!av_strcasecmp(tag, "Set-Cookie")) {
1096 if (parse_cookie(s, p, &s->cookie_dict))
1097 av_log(h, AV_LOG_WARNING, "Unable to parse '%s'\n", p);
1098 } else if (!av_strcasecmp(tag, "Icy-MetaInt")) {
1099 s->icy_metaint = strtoull(p, NULL, 10);
1100 } else if (!av_strncasecmp(tag, "Icy-", 4)) {
1101 if ((ret = parse_icy(s, tag, p)) < 0)
1103 } else if (!av_strcasecmp(tag, "Content-Encoding")) {
1104 if ((ret = parse_content_encoding(h, p)) < 0)
1112 * Create a string containing cookie values for use as a HTTP cookie header
1113 * field value for a particular path and domain from the cookie values stored in
1114 * the HTTP protocol context. The cookie string is stored in *cookies, and may
1115 * be NULL if there are no valid cookies.
1117 * @return a negative value if an error condition occurred, 0 otherwise
1119 static int get_cookies(HTTPContext *s, char **cookies, const char *path,
1122 // cookie strings will look like Set-Cookie header field values. Multiple
1123 // Set-Cookie fields will result in multiple values delimited by a newline
1125 char *cookie, *set_cookies, *next;
1126 char *saveptr = NULL;
1128 // destroy any cookies in the dictionary.
1129 av_dict_free(&s->cookie_dict);
1134 next = set_cookies = av_strdup(s->cookies);
1136 return AVERROR(ENOMEM);
1139 while ((cookie = av_strtok(next, "\n", &saveptr)) && !ret) {
1140 AVDictionary *cookie_params = NULL;
1141 AVDictionaryEntry *cookie_entry, *e;
1144 // store the cookie in a dict in case it is updated in the response
1145 if (parse_cookie(s, cookie, &s->cookie_dict))
1146 av_log(s, AV_LOG_WARNING, "Unable to parse '%s'\n", cookie);
1148 // continue on to the next cookie if this one cannot be parsed
1149 if (parse_set_cookie(cookie, &cookie_params))
1152 // if the cookie has no value, skip it
1153 cookie_entry = av_dict_get(cookie_params, "", NULL, AV_DICT_IGNORE_SUFFIX);
1154 if (!cookie_entry || !cookie_entry->value)
1157 // if the cookie has expired, don't add it
1158 if ((e = av_dict_get(cookie_params, "expires", NULL, 0)) && e->value) {
1159 struct tm tm_buf = {0};
1160 if (!parse_set_cookie_expiry_time(e->value, &tm_buf)) {
1161 if (av_timegm(&tm_buf) < av_gettime() / 1000000)
1166 // if no domain in the cookie assume it appied to this request
1167 if ((e = av_dict_get(cookie_params, "domain", NULL, 0)) && e->value) {
1168 // find the offset comparison is on the min domain (b.com, not a.b.com)
1169 int domain_offset = strlen(domain) - strlen(e->value);
1170 if (domain_offset < 0)
1173 // match the cookie domain
1174 if (av_strcasecmp(&domain[domain_offset], e->value))
1178 // ensure this cookie matches the path
1179 e = av_dict_get(cookie_params, "path", NULL, 0);
1180 if (!e || av_strncasecmp(path, e->value, strlen(e->value)))
1183 // cookie parameters match, so copy the value
1185 *cookies = av_asprintf("%s=%s", cookie_entry->key, cookie_entry->value);
1187 char *tmp = *cookies;
1188 *cookies = av_asprintf("%s; %s=%s", tmp, cookie_entry->key, cookie_entry->value);
1192 ret = AVERROR(ENOMEM);
1195 av_dict_free(&cookie_params);
1198 av_free(set_cookies);
1203 static inline int has_header(const char *str, const char *header)
1205 /* header + 2 to skip over CRLF prefix. (make sure you have one!) */
1208 return av_stristart(str, header + 2, NULL) || av_stristr(str, header);
1211 static int http_read_header(URLContext *h, int *new_location)
1213 HTTPContext *s = h->priv_data;
1214 char line[MAX_URL_SIZE];
1217 s->chunksize = UINT64_MAX;
1220 if ((err = http_get_line(s, line, sizeof(line))) < 0)
1223 av_log(h, AV_LOG_TRACE, "header='%s'\n", line);
1225 err = process_line(h, line, s->line_count, new_location);
1233 if (s->seekable == -1 && s->is_mediagateway && s->filesize == 2000000000)
1234 h->is_streamed = 1; /* we can in fact _not_ seek */
1236 // add any new cookies into the existing cookie string
1237 cookie_string(s->cookie_dict, &s->cookies);
1238 av_dict_free(&s->cookie_dict);
1244 * Escape unsafe characters in path in order to pass them safely to the HTTP
1245 * request. Insipred by the algorithm in GNU wget:
1246 * - escape "%" characters not followed by two hex digits
1247 * - escape all "unsafe" characters except which are also "reserved"
1248 * - pass through everything else
1250 static void bprint_escaped_path(AVBPrint *bp, const char *path)
1252 #define NEEDS_ESCAPE(ch) \
1253 ((ch) <= ' ' || (ch) >= '\x7f' || \
1254 (ch) == '"' || (ch) == '%' || (ch) == '<' || (ch) == '>' || (ch) == '\\' || \
1255 (ch) == '^' || (ch) == '`' || (ch) == '{' || (ch) == '}' || (ch) == '|')
1259 while (*path && q - buf < sizeof(buf) - 4) {
1260 if (path[0] == '%' && av_isxdigit(path[1]) && av_isxdigit(path[2])) {
1264 } else if (NEEDS_ESCAPE(*path)) {
1265 q += snprintf(q, 4, "%%%02X", (uint8_t)*path++);
1270 av_bprint_append_data(bp, buf, q - buf);
1274 static int http_connect(URLContext *h, const char *path, const char *local_path,
1275 const char *hoststr, const char *auth,
1276 const char *proxyauth, int *new_location)
1278 HTTPContext *s = h->priv_data;
1281 char *authstr = NULL, *proxyauthstr = NULL;
1282 uint64_t off = s->off;
1284 int send_expect_100 = 0;
1286 av_bprint_init_for_buffer(&request, s->buffer, sizeof(s->buffer));
1288 /* send http header */
1289 post = h->flags & AVIO_FLAG_WRITE;
1292 /* force POST method and disable chunked encoding when
1293 * custom HTTP post data is set */
1295 s->chunked_post = 0;
1301 method = post ? "POST" : "GET";
1303 authstr = ff_http_auth_create_response(&s->auth_state, auth,
1304 local_path, method);
1305 proxyauthstr = ff_http_auth_create_response(&s->proxy_auth_state, proxyauth,
1306 local_path, method);
1308 if (post && !s->post_data) {
1309 if (s->send_expect_100 != -1) {
1310 send_expect_100 = s->send_expect_100;
1312 send_expect_100 = 0;
1313 /* The user has supplied authentication but we don't know the auth type,
1314 * send Expect: 100-continue to get the 401 response including the
1315 * WWW-Authenticate header, or an 100 continue if no auth actually
1317 if (auth && *auth &&
1318 s->auth_state.auth_type == HTTP_AUTH_NONE &&
1319 s->http_code != 401)
1320 send_expect_100 = 1;
1324 av_bprintf(&request, "%s ", method);
1325 bprint_escaped_path(&request, path);
1326 av_bprintf(&request, " HTTP/1.1\r\n");
1328 if (post && s->chunked_post)
1329 av_bprintf(&request, "Transfer-Encoding: chunked\r\n");
1330 /* set default headers if needed */
1331 if (!has_header(s->headers, "\r\nUser-Agent: "))
1332 av_bprintf(&request, "User-Agent: %s\r\n", s->user_agent);
1334 /* set default headers if needed */
1335 if (!has_header(s->headers, "\r\nReferer: "))
1336 av_bprintf(&request, "Referer: %s\r\n", s->referer);
1338 if (!has_header(s->headers, "\r\nAccept: "))
1339 av_bprintf(&request, "Accept: */*\r\n");
1340 // Note: we send this on purpose even when s->off is 0 when we're probing,
1341 // since it allows us to detect more reliably if a (non-conforming)
1342 // server supports seeking by analysing the reply headers.
1343 if (!has_header(s->headers, "\r\nRange: ") && !post && (s->off > 0 || s->end_off || s->seekable == -1)) {
1344 av_bprintf(&request, "Range: bytes=%"PRIu64"-", s->off);
1346 av_bprintf(&request, "%"PRId64, s->end_off - 1);
1347 av_bprintf(&request, "\r\n");
1349 if (send_expect_100 && !has_header(s->headers, "\r\nExpect: "))
1350 av_bprintf(&request, "Expect: 100-continue\r\n");
1352 if (!has_header(s->headers, "\r\nConnection: "))
1353 av_bprintf(&request, "Connection: %s\r\n", s->multiple_requests ? "keep-alive" : "close");
1355 if (!has_header(s->headers, "\r\nHost: "))
1356 av_bprintf(&request, "Host: %s\r\n", hoststr);
1357 if (!has_header(s->headers, "\r\nContent-Length: ") && s->post_data)
1358 av_bprintf(&request, "Content-Length: %d\r\n", s->post_datalen);
1360 if (!has_header(s->headers, "\r\nContent-Type: ") && s->content_type)
1361 av_bprintf(&request, "Content-Type: %s\r\n", s->content_type);
1362 if (!has_header(s->headers, "\r\nCookie: ") && s->cookies) {
1363 char *cookies = NULL;
1364 if (!get_cookies(s, &cookies, path, hoststr) && cookies) {
1365 av_bprintf(&request, "Cookie: %s\r\n", cookies);
1369 if (!has_header(s->headers, "\r\nIcy-MetaData: ") && s->icy)
1370 av_bprintf(&request, "Icy-MetaData: 1\r\n");
1372 /* now add in custom headers */
1374 av_bprintf(&request, "%s", s->headers);
1377 av_bprintf(&request, "%s", authstr);
1379 av_bprintf(&request, "Proxy-%s", proxyauthstr);
1380 av_bprintf(&request, "\r\n");
1382 av_log(h, AV_LOG_DEBUG, "request: %s\n", request.str);
1384 if (!av_bprint_is_complete(&request)) {
1385 av_log(h, AV_LOG_ERROR, "overlong headers\n");
1386 err = AVERROR(EINVAL);
1390 if ((err = ffurl_write(s->hd, request.str, request.len)) < 0)
1394 if ((err = ffurl_write(s->hd, s->post_data, s->post_datalen)) < 0)
1397 /* init input buffer */
1398 s->buf_ptr = s->buffer;
1399 s->buf_end = s->buffer;
1402 s->icy_data_read = 0;
1403 s->filesize = UINT64_MAX;
1405 s->end_chunked_post = 0;
1410 if (post && !s->post_data && !send_expect_100) {
1411 /* Pretend that it did work. We didn't read any header yet, since
1412 * we've still to send the POST data, but the code calling this
1413 * function will check http_code after we return. */
1419 /* wait for header */
1420 err = http_read_header(h, new_location);
1427 err = (off == s->off) ? 0 : -1;
1430 av_freep(&proxyauthstr);
1434 static int http_buf_read(URLContext *h, uint8_t *buf, int size)
1436 HTTPContext *s = h->priv_data;
1439 if (s->chunksize != UINT64_MAX) {
1443 if (!s->chunksize) {
1448 if ((err = http_get_line(s, line, sizeof(line))) < 0)
1450 } while (!*line); /* skip CR LF from last chunk */
1452 s->chunksize = strtoull(line, NULL, 16);
1454 av_log(h, AV_LOG_TRACE,
1455 "Chunked encoding data size: %"PRIu64"\n",
1458 if (!s->chunksize && s->multiple_requests) {
1459 http_get_line(s, line, sizeof(line)); // read empty chunk
1463 else if (!s->chunksize) {
1464 av_log(h, AV_LOG_DEBUG, "Last chunk received, closing conn\n");
1465 ffurl_closep(&s->hd);
1468 else if (s->chunksize == UINT64_MAX) {
1469 av_log(h, AV_LOG_ERROR, "Invalid chunk size %"PRIu64"\n",
1471 return AVERROR(EINVAL);
1474 size = FFMIN(size, s->chunksize);
1477 /* read bytes from input buffer first */
1478 len = s->buf_end - s->buf_ptr;
1482 memcpy(buf, s->buf_ptr, len);
1485 uint64_t target_end = s->end_off ? s->end_off : s->filesize;
1486 if ((!s->willclose || s->chunksize == UINT64_MAX) && s->off >= target_end)
1488 len = ffurl_read(s->hd, buf, size);
1489 if ((!len || len == AVERROR_EOF) &&
1490 (!s->willclose || s->chunksize == UINT64_MAX) && s->off < target_end) {
1491 av_log(h, AV_LOG_ERROR,
1492 "Stream ends prematurely at %"PRIu64", should be %"PRIu64"\n",
1495 return AVERROR(EIO);
1500 if (s->chunksize > 0 && s->chunksize != UINT64_MAX) {
1501 av_assert0(s->chunksize >= len);
1502 s->chunksize -= len;
1509 #define DECOMPRESS_BUF_SIZE (256 * 1024)
1510 static int http_buf_read_compressed(URLContext *h, uint8_t *buf, int size)
1512 HTTPContext *s = h->priv_data;
1515 if (!s->inflate_buffer) {
1516 s->inflate_buffer = av_malloc(DECOMPRESS_BUF_SIZE);
1517 if (!s->inflate_buffer)
1518 return AVERROR(ENOMEM);
1521 if (s->inflate_stream.avail_in == 0) {
1522 int read = http_buf_read(h, s->inflate_buffer, DECOMPRESS_BUF_SIZE);
1525 s->inflate_stream.next_in = s->inflate_buffer;
1526 s->inflate_stream.avail_in = read;
1529 s->inflate_stream.avail_out = size;
1530 s->inflate_stream.next_out = buf;
1532 ret = inflate(&s->inflate_stream, Z_SYNC_FLUSH);
1533 if (ret != Z_OK && ret != Z_STREAM_END)
1534 av_log(h, AV_LOG_WARNING, "inflate return value: %d, %s\n",
1535 ret, s->inflate_stream.msg);
1537 return size - s->inflate_stream.avail_out;
1539 #endif /* CONFIG_ZLIB */
1541 static int64_t http_seek_internal(URLContext *h, int64_t off, int whence, int force_reconnect);
1543 static int http_read_stream(URLContext *h, uint8_t *buf, int size)
1545 HTTPContext *s = h->priv_data;
1546 int err, new_location, read_ret;
1548 int reconnect_delay = 0;
1553 if (s->end_chunked_post && !s->end_header) {
1554 err = http_read_header(h, &new_location);
1561 return http_buf_read_compressed(h, buf, size);
1562 #endif /* CONFIG_ZLIB */
1563 read_ret = http_buf_read(h, buf, size);
1564 while (read_ret < 0) {
1565 uint64_t target = h->is_streamed ? 0 : s->off;
1567 if (read_ret == AVERROR_EXIT)
1570 if (h->is_streamed && !s->reconnect_streamed)
1573 if (!(s->reconnect && s->filesize > 0 && s->off < s->filesize) &&
1574 !(s->reconnect_at_eof && read_ret == AVERROR_EOF))
1577 if (reconnect_delay > s->reconnect_delay_max)
1578 return AVERROR(EIO);
1580 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));
1581 err = ff_network_sleep_interruptible(1000U*1000*reconnect_delay, &h->interrupt_callback);
1582 if (err != AVERROR(ETIMEDOUT))
1584 reconnect_delay = 1 + 2*reconnect_delay;
1585 seek_ret = http_seek_internal(h, target, SEEK_SET, 1);
1586 if (seek_ret >= 0 && seek_ret != target) {
1587 av_log(h, AV_LOG_ERROR, "Failed to reconnect at %"PRIu64".\n", target);
1591 read_ret = http_buf_read(h, buf, size);
1597 // Like http_read_stream(), but no short reads.
1598 // Assumes partial reads are an error.
1599 static int http_read_stream_all(URLContext *h, uint8_t *buf, int size)
1602 while (pos < size) {
1603 int len = http_read_stream(h, buf + pos, size - pos);
1611 static void update_metadata(URLContext *h, char *data)
1617 HTTPContext *s = h->priv_data;
1621 val = strstr(key, "='");
1624 end = strstr(val, "';");
1632 av_dict_set(&s->metadata, key, val, 0);
1633 av_log(h, AV_LOG_VERBOSE, "Metadata update for %s: %s\n", key, val);
1639 static int store_icy(URLContext *h, int size)
1641 HTTPContext *s = h->priv_data;
1642 /* until next metadata packet */
1645 if (s->icy_metaint < s->icy_data_read)
1646 return AVERROR_INVALIDDATA;
1647 remaining = s->icy_metaint - s->icy_data_read;
1650 /* The metadata packet is variable sized. It has a 1 byte header
1651 * which sets the length of the packet (divided by 16). If it's 0,
1652 * the metadata doesn't change. After the packet, icy_metaint bytes
1653 * of normal data follows. */
1655 int len = http_read_stream_all(h, &ch, 1);
1659 char data[255 * 16 + 1];
1662 ret = http_read_stream_all(h, data, len);
1666 if ((ret = av_opt_set(s, "icy_metadata_packet", data, 0)) < 0)
1668 update_metadata(h, data);
1670 s->icy_data_read = 0;
1671 remaining = s->icy_metaint;
1674 return FFMIN(size, remaining);
1677 static int http_read(URLContext *h, uint8_t *buf, int size)
1679 HTTPContext *s = h->priv_data;
1681 if (s->icy_metaint > 0) {
1682 size = store_icy(h, size);
1687 size = http_read_stream(h, buf, size);
1689 s->icy_data_read += size;
1693 /* used only when posting data */
1694 static int http_write(URLContext *h, const uint8_t *buf, int size)
1696 char temp[11] = ""; /* 32-bit hex + CRLF + nul */
1698 char crlf[] = "\r\n";
1699 HTTPContext *s = h->priv_data;
1701 if (!s->chunked_post) {
1702 /* non-chunked data is sent without any special encoding */
1703 return ffurl_write(s->hd, buf, size);
1706 /* silently ignore zero-size data since chunk encoding that would
1709 /* upload data using chunked encoding */
1710 snprintf(temp, sizeof(temp), "%x\r\n", size);
1712 if ((ret = ffurl_write(s->hd, temp, strlen(temp))) < 0 ||
1713 (ret = ffurl_write(s->hd, buf, size)) < 0 ||
1714 (ret = ffurl_write(s->hd, crlf, sizeof(crlf) - 1)) < 0)
1720 static int http_shutdown(URLContext *h, int flags)
1723 char footer[] = "0\r\n\r\n";
1724 HTTPContext *s = h->priv_data;
1726 /* signal end of chunked encoding if used */
1727 if (((flags & AVIO_FLAG_WRITE) && s->chunked_post) ||
1728 ((flags & AVIO_FLAG_READ) && s->chunked_post && s->listen)) {
1729 ret = ffurl_write(s->hd, footer, sizeof(footer) - 1);
1730 ret = ret > 0 ? 0 : ret;
1731 /* flush the receive buffer when it is write only mode */
1732 if (!(flags & AVIO_FLAG_READ)) {
1735 s->hd->flags |= AVIO_FLAG_NONBLOCK;
1736 read_ret = ffurl_read(s->hd, buf, sizeof(buf));
1737 s->hd->flags &= ~AVIO_FLAG_NONBLOCK;
1738 if (read_ret < 0 && read_ret != AVERROR(EAGAIN)) {
1739 av_log(h, AV_LOG_ERROR, "URL read error: %s\n", av_err2str(read_ret));
1743 s->end_chunked_post = 1;
1749 static int http_close(URLContext *h)
1752 HTTPContext *s = h->priv_data;
1755 inflateEnd(&s->inflate_stream);
1756 av_freep(&s->inflate_buffer);
1757 #endif /* CONFIG_ZLIB */
1759 if (s->hd && !s->end_chunked_post)
1760 /* Close the write direction by sending the end of chunked encoding. */
1761 ret = http_shutdown(h, h->flags);
1764 ffurl_closep(&s->hd);
1765 av_dict_free(&s->chained_options);
1769 static int64_t http_seek_internal(URLContext *h, int64_t off, int whence, int force_reconnect)
1771 HTTPContext *s = h->priv_data;
1772 URLContext *old_hd = s->hd;
1773 uint64_t old_off = s->off;
1774 uint8_t old_buf[BUFFER_SIZE];
1775 int old_buf_size, ret;
1776 AVDictionary *options = NULL;
1778 if (whence == AVSEEK_SIZE)
1780 else if (!force_reconnect &&
1781 ((whence == SEEK_CUR && off == 0) ||
1782 (whence == SEEK_SET && off == s->off)))
1784 else if ((s->filesize == UINT64_MAX && whence == SEEK_END))
1785 return AVERROR(ENOSYS);
1787 if (whence == SEEK_CUR)
1789 else if (whence == SEEK_END)
1791 else if (whence != SEEK_SET)
1792 return AVERROR(EINVAL);
1794 return AVERROR(EINVAL);
1797 if (s->off && h->is_streamed)
1798 return AVERROR(ENOSYS);
1800 /* do not try to make a new connection if seeking past the end of the file */
1801 if (s->end_off || s->filesize != UINT64_MAX) {
1802 uint64_t end_pos = s->end_off ? s->end_off : s->filesize;
1803 if (s->off >= end_pos)
1807 /* we save the old context in case the seek fails */
1808 old_buf_size = s->buf_end - s->buf_ptr;
1809 memcpy(old_buf, s->buf_ptr, old_buf_size);
1812 /* if it fails, continue on old connection */
1813 if ((ret = http_open_cnx(h, &options)) < 0) {
1814 av_dict_free(&options);
1815 memcpy(s->buffer, old_buf, old_buf_size);
1816 s->buf_ptr = s->buffer;
1817 s->buf_end = s->buffer + old_buf_size;
1822 av_dict_free(&options);
1823 ffurl_close(old_hd);
1827 static int64_t http_seek(URLContext *h, int64_t off, int whence)
1829 return http_seek_internal(h, off, whence, 0);
1832 static int http_get_file_handle(URLContext *h)
1834 HTTPContext *s = h->priv_data;
1835 return ffurl_get_file_handle(s->hd);
1838 static int http_get_short_seek(URLContext *h)
1840 HTTPContext *s = h->priv_data;
1841 return ffurl_get_short_seek(s->hd);
1844 #define HTTP_CLASS(flavor) \
1845 static const AVClass flavor ## _context_class = { \
1846 .class_name = # flavor, \
1847 .item_name = av_default_item_name, \
1848 .option = options, \
1849 .version = LIBAVUTIL_VERSION_INT, \
1852 #if CONFIG_HTTP_PROTOCOL
1855 const URLProtocol ff_http_protocol = {
1857 .url_open2 = http_open,
1858 .url_accept = http_accept,
1859 .url_handshake = http_handshake,
1860 .url_read = http_read,
1861 .url_write = http_write,
1862 .url_seek = http_seek,
1863 .url_close = http_close,
1864 .url_get_file_handle = http_get_file_handle,
1865 .url_get_short_seek = http_get_short_seek,
1866 .url_shutdown = http_shutdown,
1867 .priv_data_size = sizeof(HTTPContext),
1868 .priv_data_class = &http_context_class,
1869 .flags = URL_PROTOCOL_FLAG_NETWORK,
1870 .default_whitelist = "http,https,tls,rtp,tcp,udp,crypto,httpproxy,data"
1872 #endif /* CONFIG_HTTP_PROTOCOL */
1874 #if CONFIG_HTTPS_PROTOCOL
1877 const URLProtocol ff_https_protocol = {
1879 .url_open2 = http_open,
1880 .url_read = http_read,
1881 .url_write = http_write,
1882 .url_seek = http_seek,
1883 .url_close = http_close,
1884 .url_get_file_handle = http_get_file_handle,
1885 .url_get_short_seek = http_get_short_seek,
1886 .url_shutdown = http_shutdown,
1887 .priv_data_size = sizeof(HTTPContext),
1888 .priv_data_class = &https_context_class,
1889 .flags = URL_PROTOCOL_FLAG_NETWORK,
1890 .default_whitelist = "http,https,tls,rtp,tcp,udp,crypto,httpproxy"
1892 #endif /* CONFIG_HTTPS_PROTOCOL */
1894 #if CONFIG_HTTPPROXY_PROTOCOL
1895 static int http_proxy_close(URLContext *h)
1897 HTTPContext *s = h->priv_data;
1899 ffurl_closep(&s->hd);
1903 static int http_proxy_open(URLContext *h, const char *uri, int flags)
1905 HTTPContext *s = h->priv_data;
1906 char hostname[1024], hoststr[1024];
1907 char auth[1024], pathbuf[1024], *path;
1908 char lower_url[100];
1909 int port, ret = 0, attempts = 0;
1910 HTTPAuthType cur_auth_type;
1914 if( s->seekable == 1 )
1919 av_url_split(NULL, 0, auth, sizeof(auth), hostname, sizeof(hostname), &port,
1920 pathbuf, sizeof(pathbuf), uri);
1921 ff_url_join(hoststr, sizeof(hoststr), NULL, NULL, hostname, port, NULL);
1926 ff_url_join(lower_url, sizeof(lower_url), "tcp", NULL, hostname, port,
1929 ret = ffurl_open_whitelist(&s->hd, lower_url, AVIO_FLAG_READ_WRITE,
1930 &h->interrupt_callback, NULL,
1931 h->protocol_whitelist, h->protocol_blacklist, h);
1935 authstr = ff_http_auth_create_response(&s->proxy_auth_state, auth,
1937 snprintf(s->buffer, sizeof(s->buffer),
1938 "CONNECT %s HTTP/1.1\r\n"
1940 "Connection: close\r\n"
1945 authstr ? "Proxy-" : "", authstr ? authstr : "");
1948 if ((ret = ffurl_write(s->hd, s->buffer, strlen(s->buffer))) < 0)
1951 s->buf_ptr = s->buffer;
1952 s->buf_end = s->buffer;
1954 s->filesize = UINT64_MAX;
1955 cur_auth_type = s->proxy_auth_state.auth_type;
1957 /* Note: This uses buffering, potentially reading more than the
1958 * HTTP header. If tunneling a protocol where the server starts
1959 * the conversation, we might buffer part of that here, too.
1960 * Reading that requires using the proper ffurl_read() function
1961 * on this URLContext, not using the fd directly (as the tls
1962 * protocol does). This shouldn't be an issue for tls though,
1963 * since the client starts the conversation there, so there
1964 * is no extra data that we might buffer up here.
1966 ret = http_read_header(h, &new_loc);
1971 if (s->http_code == 407 &&
1972 (cur_auth_type == HTTP_AUTH_NONE || s->proxy_auth_state.stale) &&
1973 s->proxy_auth_state.auth_type != HTTP_AUTH_NONE && attempts < 2) {
1974 ffurl_closep(&s->hd);
1978 if (s->http_code < 400)
1980 ret = ff_http_averror(s->http_code, AVERROR(EIO));
1983 http_proxy_close(h);
1987 static int http_proxy_write(URLContext *h, const uint8_t *buf, int size)
1989 HTTPContext *s = h->priv_data;
1990 return ffurl_write(s->hd, buf, size);
1993 const URLProtocol ff_httpproxy_protocol = {
1994 .name = "httpproxy",
1995 .url_open = http_proxy_open,
1996 .url_read = http_buf_read,
1997 .url_write = http_proxy_write,
1998 .url_close = http_proxy_close,
1999 .url_get_file_handle = http_get_file_handle,
2000 .priv_data_size = sizeof(HTTPContext),
2001 .flags = URL_PROTOCOL_FLAG_NETWORK,
2003 #endif /* CONFIG_HTTPPROXY_PROTOCOL */