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;
81 #if FF_API_HTTP_USER_AGENT
82 char *user_agent_deprecated;
85 /* Set if the server correctly handles Connection: close and will close
86 * the connection after feeding us the content. */
88 int seekable; /**< Control seekability, 0 = disable, 1 = enable, -1 = probe. */
90 /* A flag which indicates if the end of chunked encoding has been sent. */
92 /* A flag which indicates we have finished to read POST reply. */
94 /* A flag which indicates if we use persistent connections. */
95 int multiple_requests;
100 char *cookies; ///< holds newline (\n) delimited Set-Cookie header field values (without the "Set-Cookie: " field name)
101 /* A dictionary containing cookies keyed by cookie name */
102 AVDictionary *cookie_dict;
104 /* how much data was read since the last ICY metadata packet */
105 uint64_t icy_data_read;
106 /* after how many bytes of read data a new metadata packet will be found */
107 uint64_t icy_metaint;
108 char *icy_metadata_headers;
109 char *icy_metadata_packet;
110 AVDictionary *metadata;
113 z_stream inflate_stream;
114 uint8_t *inflate_buffer;
115 #endif /* CONFIG_ZLIB */
116 AVDictionary *chained_options;
117 /* -1 = try to send if applicable, 0 = always disabled, 1 = always enabled */
121 int reconnect_at_eof;
122 int reconnect_on_network_error;
123 int reconnect_streamed;
124 int reconnect_delay_max;
125 char *reconnect_on_http_error;
130 HandshakeState handshake_step;
131 int is_connected_server;
134 #define OFFSET(x) offsetof(HTTPContext, x)
135 #define D AV_OPT_FLAG_DECODING_PARAM
136 #define E AV_OPT_FLAG_ENCODING_PARAM
137 #define DEFAULT_USER_AGENT "Lavf/" AV_STRINGIFY(LIBAVFORMAT_VERSION)
139 static const AVOption options[] = {
140 { "seekable", "control seekability of connection", OFFSET(seekable), AV_OPT_TYPE_BOOL, { .i64 = -1 }, -1, 1, D },
141 { "chunked_post", "use chunked transfer-encoding for posts", OFFSET(chunked_post), AV_OPT_TYPE_BOOL, { .i64 = 1 }, 0, 1, E },
142 { "http_proxy", "set HTTP proxy to tunnel through", OFFSET(http_proxy), AV_OPT_TYPE_STRING, { .str = NULL }, 0, 0, D | E },
143 { "headers", "set custom HTTP headers, can override built in default headers", OFFSET(headers), AV_OPT_TYPE_STRING, { .str = NULL }, 0, 0, D | E },
144 { "content_type", "set a specific content type for the POST messages", OFFSET(content_type), AV_OPT_TYPE_STRING, { .str = NULL }, 0, 0, D | E },
145 { "user_agent", "override User-Agent header", OFFSET(user_agent), AV_OPT_TYPE_STRING, { .str = DEFAULT_USER_AGENT }, 0, 0, D },
146 { "referer", "override referer header", OFFSET(referer), AV_OPT_TYPE_STRING, { .str = NULL }, 0, 0, D },
147 #if FF_API_HTTP_USER_AGENT
148 { "user-agent", "use the \"user_agent\" option instead", OFFSET(user_agent_deprecated), AV_OPT_TYPE_STRING, { .str = DEFAULT_USER_AGENT }, 0, 0, D|AV_OPT_FLAG_DEPRECATED },
150 { "multiple_requests", "use persistent connections", OFFSET(multiple_requests), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, D | E },
151 { "post_data", "set custom HTTP post data", OFFSET(post_data), AV_OPT_TYPE_BINARY, .flags = D | E },
152 { "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 },
153 { "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 },
154 { "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 },
155 { "icy", "request ICY metadata", OFFSET(icy), AV_OPT_TYPE_BOOL, { .i64 = 1 }, 0, 1, D },
156 { "icy_metadata_headers", "return ICY metadata headers", OFFSET(icy_metadata_headers), AV_OPT_TYPE_STRING, { .str = NULL }, 0, 0, AV_OPT_FLAG_EXPORT },
157 { "icy_metadata_packet", "return current ICY metadata packet", OFFSET(icy_metadata_packet), AV_OPT_TYPE_STRING, { .str = NULL }, 0, 0, AV_OPT_FLAG_EXPORT },
158 { "metadata", "metadata read from the bitstream", OFFSET(metadata), AV_OPT_TYPE_DICT, {0}, 0, 0, AV_OPT_FLAG_EXPORT },
159 { "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"},
160 { "none", "No auth method set, autodetect", 0, AV_OPT_TYPE_CONST, { .i64 = HTTP_AUTH_NONE }, 0, 0, D | E, "auth_type"},
161 { "basic", "HTTP basic authentication", 0, AV_OPT_TYPE_CONST, { .i64 = HTTP_AUTH_BASIC }, 0, 0, D | E, "auth_type"},
162 { "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 },
163 { "location", "The actual location of the data received", OFFSET(location), AV_OPT_TYPE_STRING, { .str = NULL }, 0, 0, D | E },
164 { "offset", "initial byte offset", OFFSET(off), AV_OPT_TYPE_INT64, { .i64 = 0 }, 0, INT64_MAX, D },
165 { "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 },
166 { "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 },
167 { "reconnect", "auto reconnect after disconnect before EOF", OFFSET(reconnect), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, D },
168 { "reconnect_at_eof", "auto reconnect at EOF", OFFSET(reconnect_at_eof), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, D },
169 { "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 },
170 { "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 },
171 { "reconnect_streamed", "auto reconnect streamed / non seekable streams", OFFSET(reconnect_streamed), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, D },
172 { "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 },
173 { "listen", "listen on HTTP", OFFSET(listen), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 2, D | E },
174 { "resource", "The resource requested by a client", OFFSET(resource), AV_OPT_TYPE_STRING, { .str = NULL }, 0, 0, E },
175 { "reply_code", "The http status code to return to a client", OFFSET(reply_code), AV_OPT_TYPE_INT, { .i64 = 200}, INT_MIN, 599, E},
179 static int http_connect(URLContext *h, const char *path, const char *local_path,
180 const char *hoststr, const char *auth,
181 const char *proxyauth, int *new_location);
182 static int http_read_header(URLContext *h, int *new_location);
183 static int http_shutdown(URLContext *h, int flags);
185 void ff_http_init_auth_state(URLContext *dest, const URLContext *src)
187 memcpy(&((HTTPContext *)dest->priv_data)->auth_state,
188 &((HTTPContext *)src->priv_data)->auth_state,
189 sizeof(HTTPAuthState));
190 memcpy(&((HTTPContext *)dest->priv_data)->proxy_auth_state,
191 &((HTTPContext *)src->priv_data)->proxy_auth_state,
192 sizeof(HTTPAuthState));
195 static int http_open_cnx_internal(URLContext *h, AVDictionary **options)
197 const char *path, *proxy_path, *lower_proto = "tcp", *local_path;
199 char hostname[1024], hoststr[1024], proto[10];
200 char auth[1024], proxyauth[1024] = "";
201 char path1[MAX_URL_SIZE], sanitized_path[MAX_URL_SIZE];
202 char buf[1024], urlbuf[MAX_URL_SIZE];
203 int port, use_proxy, err, location_changed = 0;
204 HTTPContext *s = h->priv_data;
206 av_url_split(proto, sizeof(proto), auth, sizeof(auth),
207 hostname, sizeof(hostname), &port,
208 path1, sizeof(path1), s->location);
209 ff_url_join(hoststr, sizeof(hoststr), NULL, NULL, hostname, port, NULL);
211 proxy_path = s->http_proxy ? s->http_proxy : getenv("http_proxy");
212 use_proxy = !ff_http_match_no_proxy(getenv("no_proxy"), hostname) &&
213 proxy_path && av_strstart(proxy_path, "http://", NULL);
215 if (!strcmp(proto, "https")) {
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 #if FF_API_HTTP_USER_AGENT
1325 if (strcmp(s->user_agent_deprecated, DEFAULT_USER_AGENT)) {
1326 s->user_agent = av_strdup(s->user_agent_deprecated);
1330 av_bprintf(&request, "%s ", method);
1331 bprint_escaped_path(&request, path);
1332 av_bprintf(&request, " HTTP/1.1\r\n");
1334 if (post && s->chunked_post)
1335 av_bprintf(&request, "Transfer-Encoding: chunked\r\n");
1336 /* set default headers if needed */
1337 if (!has_header(s->headers, "\r\nUser-Agent: "))
1338 av_bprintf(&request, "User-Agent: %s\r\n", s->user_agent);
1340 /* set default headers if needed */
1341 if (!has_header(s->headers, "\r\nReferer: "))
1342 av_bprintf(&request, "Referer: %s\r\n", s->referer);
1344 if (!has_header(s->headers, "\r\nAccept: "))
1345 av_bprintf(&request, "Accept: */*\r\n");
1346 // Note: we send this on purpose even when s->off is 0 when we're probing,
1347 // since it allows us to detect more reliably if a (non-conforming)
1348 // server supports seeking by analysing the reply headers.
1349 if (!has_header(s->headers, "\r\nRange: ") && !post && (s->off > 0 || s->end_off || s->seekable == -1)) {
1350 av_bprintf(&request, "Range: bytes=%"PRIu64"-", s->off);
1352 av_bprintf(&request, "%"PRId64, s->end_off - 1);
1353 av_bprintf(&request, "\r\n");
1355 if (send_expect_100 && !has_header(s->headers, "\r\nExpect: "))
1356 av_bprintf(&request, "Expect: 100-continue\r\n");
1358 if (!has_header(s->headers, "\r\nConnection: "))
1359 av_bprintf(&request, "Connection: %s\r\n", s->multiple_requests ? "keep-alive" : "close");
1361 if (!has_header(s->headers, "\r\nHost: "))
1362 av_bprintf(&request, "Host: %s\r\n", hoststr);
1363 if (!has_header(s->headers, "\r\nContent-Length: ") && s->post_data)
1364 av_bprintf(&request, "Content-Length: %d\r\n", s->post_datalen);
1366 if (!has_header(s->headers, "\r\nContent-Type: ") && s->content_type)
1367 av_bprintf(&request, "Content-Type: %s\r\n", s->content_type);
1368 if (!has_header(s->headers, "\r\nCookie: ") && s->cookies) {
1369 char *cookies = NULL;
1370 if (!get_cookies(s, &cookies, path, hoststr) && cookies) {
1371 av_bprintf(&request, "Cookie: %s\r\n", cookies);
1375 if (!has_header(s->headers, "\r\nIcy-MetaData: ") && s->icy)
1376 av_bprintf(&request, "Icy-MetaData: 1\r\n");
1378 /* now add in custom headers */
1380 av_bprintf(&request, "%s", s->headers);
1383 av_bprintf(&request, "%s", authstr);
1385 av_bprintf(&request, "Proxy-%s", proxyauthstr);
1386 av_bprintf(&request, "\r\n");
1388 av_log(h, AV_LOG_DEBUG, "request: %s\n", request.str);
1390 if (!av_bprint_is_complete(&request)) {
1391 av_log(h, AV_LOG_ERROR, "overlong headers\n");
1392 err = AVERROR(EINVAL);
1396 if ((err = ffurl_write(s->hd, request.str, request.len)) < 0)
1400 if ((err = ffurl_write(s->hd, s->post_data, s->post_datalen)) < 0)
1403 /* init input buffer */
1404 s->buf_ptr = s->buffer;
1405 s->buf_end = s->buffer;
1408 s->icy_data_read = 0;
1409 s->filesize = UINT64_MAX;
1411 s->end_chunked_post = 0;
1416 if (post && !s->post_data && !send_expect_100) {
1417 /* Pretend that it did work. We didn't read any header yet, since
1418 * we've still to send the POST data, but the code calling this
1419 * function will check http_code after we return. */
1425 /* wait for header */
1426 err = http_read_header(h, new_location);
1433 err = (off == s->off) ? 0 : -1;
1436 av_freep(&proxyauthstr);
1440 static int http_buf_read(URLContext *h, uint8_t *buf, int size)
1442 HTTPContext *s = h->priv_data;
1445 if (s->chunksize != UINT64_MAX) {
1449 if (!s->chunksize) {
1454 if ((err = http_get_line(s, line, sizeof(line))) < 0)
1456 } while (!*line); /* skip CR LF from last chunk */
1458 s->chunksize = strtoull(line, NULL, 16);
1460 av_log(h, AV_LOG_TRACE,
1461 "Chunked encoding data size: %"PRIu64"\n",
1464 if (!s->chunksize && s->multiple_requests) {
1465 http_get_line(s, line, sizeof(line)); // read empty chunk
1469 else if (!s->chunksize) {
1470 av_log(h, AV_LOG_DEBUG, "Last chunk received, closing conn\n");
1471 ffurl_closep(&s->hd);
1474 else if (s->chunksize == UINT64_MAX) {
1475 av_log(h, AV_LOG_ERROR, "Invalid chunk size %"PRIu64"\n",
1477 return AVERROR(EINVAL);
1480 size = FFMIN(size, s->chunksize);
1483 /* read bytes from input buffer first */
1484 len = s->buf_end - s->buf_ptr;
1488 memcpy(buf, s->buf_ptr, len);
1491 uint64_t target_end = s->end_off ? s->end_off : s->filesize;
1492 if ((!s->willclose || s->chunksize == UINT64_MAX) && s->off >= target_end)
1494 len = ffurl_read(s->hd, buf, size);
1495 if ((!len || len == AVERROR_EOF) &&
1496 (!s->willclose || s->chunksize == UINT64_MAX) && s->off < target_end) {
1497 av_log(h, AV_LOG_ERROR,
1498 "Stream ends prematurely at %"PRIu64", should be %"PRIu64"\n",
1501 return AVERROR(EIO);
1506 if (s->chunksize > 0 && s->chunksize != UINT64_MAX) {
1507 av_assert0(s->chunksize >= len);
1508 s->chunksize -= len;
1515 #define DECOMPRESS_BUF_SIZE (256 * 1024)
1516 static int http_buf_read_compressed(URLContext *h, uint8_t *buf, int size)
1518 HTTPContext *s = h->priv_data;
1521 if (!s->inflate_buffer) {
1522 s->inflate_buffer = av_malloc(DECOMPRESS_BUF_SIZE);
1523 if (!s->inflate_buffer)
1524 return AVERROR(ENOMEM);
1527 if (s->inflate_stream.avail_in == 0) {
1528 int read = http_buf_read(h, s->inflate_buffer, DECOMPRESS_BUF_SIZE);
1531 s->inflate_stream.next_in = s->inflate_buffer;
1532 s->inflate_stream.avail_in = read;
1535 s->inflate_stream.avail_out = size;
1536 s->inflate_stream.next_out = buf;
1538 ret = inflate(&s->inflate_stream, Z_SYNC_FLUSH);
1539 if (ret != Z_OK && ret != Z_STREAM_END)
1540 av_log(h, AV_LOG_WARNING, "inflate return value: %d, %s\n",
1541 ret, s->inflate_stream.msg);
1543 return size - s->inflate_stream.avail_out;
1545 #endif /* CONFIG_ZLIB */
1547 static int64_t http_seek_internal(URLContext *h, int64_t off, int whence, int force_reconnect);
1549 static int http_read_stream(URLContext *h, uint8_t *buf, int size)
1551 HTTPContext *s = h->priv_data;
1552 int err, new_location, read_ret;
1554 int reconnect_delay = 0;
1559 if (s->end_chunked_post && !s->end_header) {
1560 err = http_read_header(h, &new_location);
1567 return http_buf_read_compressed(h, buf, size);
1568 #endif /* CONFIG_ZLIB */
1569 read_ret = http_buf_read(h, buf, size);
1570 while (read_ret < 0) {
1571 uint64_t target = h->is_streamed ? 0 : s->off;
1573 if (read_ret == AVERROR_EXIT)
1576 if (h->is_streamed && !s->reconnect_streamed)
1579 if (!(s->reconnect && s->filesize > 0 && s->off < s->filesize) &&
1580 !(s->reconnect_at_eof && read_ret == AVERROR_EOF))
1583 if (reconnect_delay > s->reconnect_delay_max)
1584 return AVERROR(EIO);
1586 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));
1587 err = ff_network_sleep_interruptible(1000U*1000*reconnect_delay, &h->interrupt_callback);
1588 if (err != AVERROR(ETIMEDOUT))
1590 reconnect_delay = 1 + 2*reconnect_delay;
1591 seek_ret = http_seek_internal(h, target, SEEK_SET, 1);
1592 if (seek_ret >= 0 && seek_ret != target) {
1593 av_log(h, AV_LOG_ERROR, "Failed to reconnect at %"PRIu64".\n", target);
1597 read_ret = http_buf_read(h, buf, size);
1603 // Like http_read_stream(), but no short reads.
1604 // Assumes partial reads are an error.
1605 static int http_read_stream_all(URLContext *h, uint8_t *buf, int size)
1608 while (pos < size) {
1609 int len = http_read_stream(h, buf + pos, size - pos);
1617 static void update_metadata(URLContext *h, char *data)
1623 HTTPContext *s = h->priv_data;
1627 val = strstr(key, "='");
1630 end = strstr(val, "';");
1638 av_dict_set(&s->metadata, key, val, 0);
1639 av_log(h, AV_LOG_VERBOSE, "Metadata update for %s: %s\n", key, val);
1645 static int store_icy(URLContext *h, int size)
1647 HTTPContext *s = h->priv_data;
1648 /* until next metadata packet */
1651 if (s->icy_metaint < s->icy_data_read)
1652 return AVERROR_INVALIDDATA;
1653 remaining = s->icy_metaint - s->icy_data_read;
1656 /* The metadata packet is variable sized. It has a 1 byte header
1657 * which sets the length of the packet (divided by 16). If it's 0,
1658 * the metadata doesn't change. After the packet, icy_metaint bytes
1659 * of normal data follows. */
1661 int len = http_read_stream_all(h, &ch, 1);
1665 char data[255 * 16 + 1];
1668 ret = http_read_stream_all(h, data, len);
1672 if ((ret = av_opt_set(s, "icy_metadata_packet", data, 0)) < 0)
1674 update_metadata(h, data);
1676 s->icy_data_read = 0;
1677 remaining = s->icy_metaint;
1680 return FFMIN(size, remaining);
1683 static int http_read(URLContext *h, uint8_t *buf, int size)
1685 HTTPContext *s = h->priv_data;
1687 if (s->icy_metaint > 0) {
1688 size = store_icy(h, size);
1693 size = http_read_stream(h, buf, size);
1695 s->icy_data_read += size;
1699 /* used only when posting data */
1700 static int http_write(URLContext *h, const uint8_t *buf, int size)
1702 char temp[11] = ""; /* 32-bit hex + CRLF + nul */
1704 char crlf[] = "\r\n";
1705 HTTPContext *s = h->priv_data;
1707 if (!s->chunked_post) {
1708 /* non-chunked data is sent without any special encoding */
1709 return ffurl_write(s->hd, buf, size);
1712 /* silently ignore zero-size data since chunk encoding that would
1715 /* upload data using chunked encoding */
1716 snprintf(temp, sizeof(temp), "%x\r\n", size);
1718 if ((ret = ffurl_write(s->hd, temp, strlen(temp))) < 0 ||
1719 (ret = ffurl_write(s->hd, buf, size)) < 0 ||
1720 (ret = ffurl_write(s->hd, crlf, sizeof(crlf) - 1)) < 0)
1726 static int http_shutdown(URLContext *h, int flags)
1729 char footer[] = "0\r\n\r\n";
1730 HTTPContext *s = h->priv_data;
1732 /* signal end of chunked encoding if used */
1733 if (((flags & AVIO_FLAG_WRITE) && s->chunked_post) ||
1734 ((flags & AVIO_FLAG_READ) && s->chunked_post && s->listen)) {
1735 ret = ffurl_write(s->hd, footer, sizeof(footer) - 1);
1736 ret = ret > 0 ? 0 : ret;
1737 /* flush the receive buffer when it is write only mode */
1738 if (!(flags & AVIO_FLAG_READ)) {
1741 s->hd->flags |= AVIO_FLAG_NONBLOCK;
1742 read_ret = ffurl_read(s->hd, buf, sizeof(buf));
1743 s->hd->flags &= ~AVIO_FLAG_NONBLOCK;
1744 if (read_ret < 0 && read_ret != AVERROR(EAGAIN)) {
1745 av_log(h, AV_LOG_ERROR, "URL read error: %s\n", av_err2str(read_ret));
1749 s->end_chunked_post = 1;
1755 static int http_close(URLContext *h)
1758 HTTPContext *s = h->priv_data;
1761 inflateEnd(&s->inflate_stream);
1762 av_freep(&s->inflate_buffer);
1763 #endif /* CONFIG_ZLIB */
1765 if (s->hd && !s->end_chunked_post)
1766 /* Close the write direction by sending the end of chunked encoding. */
1767 ret = http_shutdown(h, h->flags);
1770 ffurl_closep(&s->hd);
1771 av_dict_free(&s->chained_options);
1775 static int64_t http_seek_internal(URLContext *h, int64_t off, int whence, int force_reconnect)
1777 HTTPContext *s = h->priv_data;
1778 URLContext *old_hd = s->hd;
1779 uint64_t old_off = s->off;
1780 uint8_t old_buf[BUFFER_SIZE];
1781 int old_buf_size, ret;
1782 AVDictionary *options = NULL;
1784 if (whence == AVSEEK_SIZE)
1786 else if (!force_reconnect &&
1787 ((whence == SEEK_CUR && off == 0) ||
1788 (whence == SEEK_SET && off == s->off)))
1790 else if ((s->filesize == UINT64_MAX && whence == SEEK_END))
1791 return AVERROR(ENOSYS);
1793 if (whence == SEEK_CUR)
1795 else if (whence == SEEK_END)
1797 else if (whence != SEEK_SET)
1798 return AVERROR(EINVAL);
1800 return AVERROR(EINVAL);
1803 if (s->off && h->is_streamed)
1804 return AVERROR(ENOSYS);
1806 /* do not try to make a new connection if seeking past the end of the file */
1807 if (s->end_off || s->filesize != UINT64_MAX) {
1808 uint64_t end_pos = s->end_off ? s->end_off : s->filesize;
1809 if (s->off >= end_pos)
1813 /* we save the old context in case the seek fails */
1814 old_buf_size = s->buf_end - s->buf_ptr;
1815 memcpy(old_buf, s->buf_ptr, old_buf_size);
1818 /* if it fails, continue on old connection */
1819 if ((ret = http_open_cnx(h, &options)) < 0) {
1820 av_dict_free(&options);
1821 memcpy(s->buffer, old_buf, old_buf_size);
1822 s->buf_ptr = s->buffer;
1823 s->buf_end = s->buffer + old_buf_size;
1828 av_dict_free(&options);
1829 ffurl_close(old_hd);
1833 static int64_t http_seek(URLContext *h, int64_t off, int whence)
1835 return http_seek_internal(h, off, whence, 0);
1838 static int http_get_file_handle(URLContext *h)
1840 HTTPContext *s = h->priv_data;
1841 return ffurl_get_file_handle(s->hd);
1844 static int http_get_short_seek(URLContext *h)
1846 HTTPContext *s = h->priv_data;
1847 return ffurl_get_short_seek(s->hd);
1850 #define HTTP_CLASS(flavor) \
1851 static const AVClass flavor ## _context_class = { \
1852 .class_name = # flavor, \
1853 .item_name = av_default_item_name, \
1854 .option = options, \
1855 .version = LIBAVUTIL_VERSION_INT, \
1858 #if CONFIG_HTTP_PROTOCOL
1861 const URLProtocol ff_http_protocol = {
1863 .url_open2 = http_open,
1864 .url_accept = http_accept,
1865 .url_handshake = http_handshake,
1866 .url_read = http_read,
1867 .url_write = http_write,
1868 .url_seek = http_seek,
1869 .url_close = http_close,
1870 .url_get_file_handle = http_get_file_handle,
1871 .url_get_short_seek = http_get_short_seek,
1872 .url_shutdown = http_shutdown,
1873 .priv_data_size = sizeof(HTTPContext),
1874 .priv_data_class = &http_context_class,
1875 .flags = URL_PROTOCOL_FLAG_NETWORK,
1876 .default_whitelist = "http,https,tls,rtp,tcp,udp,crypto,httpproxy,data"
1878 #endif /* CONFIG_HTTP_PROTOCOL */
1880 #if CONFIG_HTTPS_PROTOCOL
1883 const URLProtocol ff_https_protocol = {
1885 .url_open2 = http_open,
1886 .url_read = http_read,
1887 .url_write = http_write,
1888 .url_seek = http_seek,
1889 .url_close = http_close,
1890 .url_get_file_handle = http_get_file_handle,
1891 .url_get_short_seek = http_get_short_seek,
1892 .url_shutdown = http_shutdown,
1893 .priv_data_size = sizeof(HTTPContext),
1894 .priv_data_class = &https_context_class,
1895 .flags = URL_PROTOCOL_FLAG_NETWORK,
1896 .default_whitelist = "http,https,tls,rtp,tcp,udp,crypto,httpproxy"
1898 #endif /* CONFIG_HTTPS_PROTOCOL */
1900 #if CONFIG_HTTPPROXY_PROTOCOL
1901 static int http_proxy_close(URLContext *h)
1903 HTTPContext *s = h->priv_data;
1905 ffurl_closep(&s->hd);
1909 static int http_proxy_open(URLContext *h, const char *uri, int flags)
1911 HTTPContext *s = h->priv_data;
1912 char hostname[1024], hoststr[1024];
1913 char auth[1024], pathbuf[1024], *path;
1914 char lower_url[100];
1915 int port, ret = 0, attempts = 0;
1916 HTTPAuthType cur_auth_type;
1920 if( s->seekable == 1 )
1925 av_url_split(NULL, 0, auth, sizeof(auth), hostname, sizeof(hostname), &port,
1926 pathbuf, sizeof(pathbuf), uri);
1927 ff_url_join(hoststr, sizeof(hoststr), NULL, NULL, hostname, port, NULL);
1932 ff_url_join(lower_url, sizeof(lower_url), "tcp", NULL, hostname, port,
1935 ret = ffurl_open_whitelist(&s->hd, lower_url, AVIO_FLAG_READ_WRITE,
1936 &h->interrupt_callback, NULL,
1937 h->protocol_whitelist, h->protocol_blacklist, h);
1941 authstr = ff_http_auth_create_response(&s->proxy_auth_state, auth,
1943 snprintf(s->buffer, sizeof(s->buffer),
1944 "CONNECT %s HTTP/1.1\r\n"
1946 "Connection: close\r\n"
1951 authstr ? "Proxy-" : "", authstr ? authstr : "");
1954 if ((ret = ffurl_write(s->hd, s->buffer, strlen(s->buffer))) < 0)
1957 s->buf_ptr = s->buffer;
1958 s->buf_end = s->buffer;
1960 s->filesize = UINT64_MAX;
1961 cur_auth_type = s->proxy_auth_state.auth_type;
1963 /* Note: This uses buffering, potentially reading more than the
1964 * HTTP header. If tunneling a protocol where the server starts
1965 * the conversation, we might buffer part of that here, too.
1966 * Reading that requires using the proper ffurl_read() function
1967 * on this URLContext, not using the fd directly (as the tls
1968 * protocol does). This shouldn't be an issue for tls though,
1969 * since the client starts the conversation there, so there
1970 * is no extra data that we might buffer up here.
1972 ret = http_read_header(h, &new_loc);
1977 if (s->http_code == 407 &&
1978 (cur_auth_type == HTTP_AUTH_NONE || s->proxy_auth_state.stale) &&
1979 s->proxy_auth_state.auth_type != HTTP_AUTH_NONE && attempts < 2) {
1980 ffurl_closep(&s->hd);
1984 if (s->http_code < 400)
1986 ret = ff_http_averror(s->http_code, AVERROR(EIO));
1989 http_proxy_close(h);
1993 static int http_proxy_write(URLContext *h, const uint8_t *buf, int size)
1995 HTTPContext *s = h->priv_data;
1996 return ffurl_write(s->hd, buf, size);
1999 const URLProtocol ff_httpproxy_protocol = {
2000 .name = "httpproxy",
2001 .url_open = http_proxy_open,
2002 .url_read = http_buf_read,
2003 .url_write = http_proxy_write,
2004 .url_close = http_proxy_close,
2005 .url_get_file_handle = http_get_file_handle,
2006 .priv_data_size = sizeof(HTTPContext),
2007 .flags = URL_PROTOCOL_FLAG_NETWORK,
2009 #endif /* CONFIG_HTTPPROXY_PROTOCOL */