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
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_streamed;
123 int reconnect_delay_max;
128 HandshakeState handshake_step;
129 int is_connected_server;
132 #define OFFSET(x) offsetof(HTTPContext, x)
133 #define D AV_OPT_FLAG_DECODING_PARAM
134 #define E AV_OPT_FLAG_ENCODING_PARAM
135 #define DEFAULT_USER_AGENT "Lavf/" AV_STRINGIFY(LIBAVFORMAT_VERSION)
137 static const AVOption options[] = {
138 { "seekable", "control seekability of connection", OFFSET(seekable), AV_OPT_TYPE_BOOL, { .i64 = -1 }, -1, 1, D },
139 { "chunked_post", "use chunked transfer-encoding for posts", OFFSET(chunked_post), AV_OPT_TYPE_BOOL, { .i64 = 1 }, 0, 1, E },
140 { "http_proxy", "set HTTP proxy to tunnel through", OFFSET(http_proxy), AV_OPT_TYPE_STRING, { .str = NULL }, 0, 0, D | E },
141 { "headers", "set custom HTTP headers, can override built in default headers", OFFSET(headers), AV_OPT_TYPE_STRING, { .str = NULL }, 0, 0, D | E },
142 { "content_type", "set a specific content type for the POST messages", OFFSET(content_type), AV_OPT_TYPE_STRING, { .str = NULL }, 0, 0, D | E },
143 { "user_agent", "override User-Agent header", OFFSET(user_agent), AV_OPT_TYPE_STRING, { .str = DEFAULT_USER_AGENT }, 0, 0, D },
144 { "referer", "override referer header", OFFSET(referer), AV_OPT_TYPE_STRING, { .str = NULL }, 0, 0, D },
145 #if FF_API_HTTP_USER_AGENT
146 { "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 },
148 { "multiple_requests", "use persistent connections", OFFSET(multiple_requests), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, D | E },
149 { "post_data", "set custom HTTP post data", OFFSET(post_data), AV_OPT_TYPE_BINARY, .flags = D | E },
150 { "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 },
151 { "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 },
152 { "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 },
153 { "icy", "request ICY metadata", OFFSET(icy), AV_OPT_TYPE_BOOL, { .i64 = 1 }, 0, 1, D },
154 { "icy_metadata_headers", "return ICY metadata headers", OFFSET(icy_metadata_headers), AV_OPT_TYPE_STRING, { .str = NULL }, 0, 0, AV_OPT_FLAG_EXPORT },
155 { "icy_metadata_packet", "return current ICY metadata packet", OFFSET(icy_metadata_packet), AV_OPT_TYPE_STRING, { .str = NULL }, 0, 0, AV_OPT_FLAG_EXPORT },
156 { "metadata", "metadata read from the bitstream", OFFSET(metadata), AV_OPT_TYPE_DICT, {0}, 0, 0, AV_OPT_FLAG_EXPORT },
157 { "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"},
158 { "none", "No auth method set, autodetect", 0, AV_OPT_TYPE_CONST, { .i64 = HTTP_AUTH_NONE }, 0, 0, D | E, "auth_type"},
159 { "basic", "HTTP basic authentication", 0, AV_OPT_TYPE_CONST, { .i64 = HTTP_AUTH_BASIC }, 0, 0, D | E, "auth_type"},
160 { "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 },
161 { "location", "The actual location of the data received", OFFSET(location), AV_OPT_TYPE_STRING, { .str = NULL }, 0, 0, D | E },
162 { "offset", "initial byte offset", OFFSET(off), AV_OPT_TYPE_INT64, { .i64 = 0 }, 0, INT64_MAX, D },
163 { "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 },
164 { "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 },
165 { "reconnect", "auto reconnect after disconnect before EOF", OFFSET(reconnect), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, D },
166 { "reconnect_at_eof", "auto reconnect at EOF", OFFSET(reconnect_at_eof), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, D },
167 { "reconnect_streamed", "auto reconnect streamed / non seekable streams", OFFSET(reconnect_streamed), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, D },
168 { "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 },
169 { "listen", "listen on HTTP", OFFSET(listen), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 2, D | E },
170 { "resource", "The resource requested by a client", OFFSET(resource), AV_OPT_TYPE_STRING, { .str = NULL }, 0, 0, E },
171 { "reply_code", "The http status code to return to a client", OFFSET(reply_code), AV_OPT_TYPE_INT, { .i64 = 200}, INT_MIN, 599, E},
175 static int http_connect(URLContext *h, const char *path, const char *local_path,
176 const char *hoststr, const char *auth,
177 const char *proxyauth, int *new_location);
178 static int http_read_header(URLContext *h, int *new_location);
179 static int http_shutdown(URLContext *h, int flags);
181 void ff_http_init_auth_state(URLContext *dest, const URLContext *src)
183 memcpy(&((HTTPContext *)dest->priv_data)->auth_state,
184 &((HTTPContext *)src->priv_data)->auth_state,
185 sizeof(HTTPAuthState));
186 memcpy(&((HTTPContext *)dest->priv_data)->proxy_auth_state,
187 &((HTTPContext *)src->priv_data)->proxy_auth_state,
188 sizeof(HTTPAuthState));
191 static int http_open_cnx_internal(URLContext *h, AVDictionary **options)
193 const char *path, *proxy_path, *lower_proto = "tcp", *local_path;
195 char hostname[1024], hoststr[1024], proto[10];
196 char auth[1024], proxyauth[1024] = "";
197 char path1[MAX_URL_SIZE], sanitized_path[MAX_URL_SIZE];
198 char buf[1024], urlbuf[MAX_URL_SIZE];
199 int port, use_proxy, err, location_changed = 0;
200 HTTPContext *s = h->priv_data;
202 av_url_split(proto, sizeof(proto), auth, sizeof(auth),
203 hostname, sizeof(hostname), &port,
204 path1, sizeof(path1), s->location);
205 ff_url_join(hoststr, sizeof(hoststr), NULL, NULL, hostname, port, NULL);
207 proxy_path = s->http_proxy ? s->http_proxy : getenv("http_proxy");
208 use_proxy = !ff_http_match_no_proxy(getenv("no_proxy"), hostname) &&
209 proxy_path && av_strstart(proxy_path, "http://", NULL);
211 if (!strcmp(proto, "https")) {
220 hashmark = strchr(path1, '#');
224 if (path1[0] == '\0') {
226 } else if (path1[0] == '?') {
227 snprintf(sanitized_path, sizeof(sanitized_path), "/%s", path1);
228 path = sanitized_path;
234 /* Reassemble the request URL without auth string - we don't
235 * want to leak the auth to the proxy. */
236 ff_url_join(urlbuf, sizeof(urlbuf), proto, NULL, hostname, port, "%s",
239 av_url_split(NULL, 0, proxyauth, sizeof(proxyauth),
240 hostname, sizeof(hostname), &port, NULL, 0, proxy_path);
243 ff_url_join(buf, sizeof(buf), lower_proto, NULL, hostname, port, NULL);
246 err = ffurl_open_whitelist(&s->hd, buf, AVIO_FLAG_READ_WRITE,
247 &h->interrupt_callback, options,
248 h->protocol_whitelist, h->protocol_blacklist, h);
253 err = http_connect(h, path, local_path, hoststr,
254 auth, proxyauth, &location_changed);
258 return location_changed;
261 /* return non zero if error */
262 static int http_open_cnx(URLContext *h, AVDictionary **options)
264 HTTPAuthType cur_auth_type, cur_proxy_auth_type;
265 HTTPContext *s = h->priv_data;
266 int location_changed, attempts = 0, redirects = 0;
268 av_dict_copy(options, s->chained_options, 0);
270 cur_auth_type = s->auth_state.auth_type;
271 cur_proxy_auth_type = s->auth_state.auth_type;
273 location_changed = http_open_cnx_internal(h, options);
274 if (location_changed < 0)
278 if (s->http_code == 401) {
279 if ((cur_auth_type == HTTP_AUTH_NONE || s->auth_state.stale) &&
280 s->auth_state.auth_type != HTTP_AUTH_NONE && attempts < 4) {
281 ffurl_closep(&s->hd);
286 if (s->http_code == 407) {
287 if ((cur_proxy_auth_type == HTTP_AUTH_NONE || s->proxy_auth_state.stale) &&
288 s->proxy_auth_state.auth_type != HTTP_AUTH_NONE && attempts < 4) {
289 ffurl_closep(&s->hd);
294 if ((s->http_code == 301 || s->http_code == 302 ||
295 s->http_code == 303 || s->http_code == 307) &&
296 location_changed == 1) {
297 /* url moved, get next */
298 ffurl_closep(&s->hd);
299 if (redirects++ >= MAX_REDIRECTS)
301 /* Restart the authentication process with the new target, which
302 * might use a different auth mechanism. */
303 memset(&s->auth_state, 0, sizeof(s->auth_state));
305 location_changed = 0;
312 ffurl_closep(&s->hd);
313 if (location_changed < 0)
314 return location_changed;
315 return ff_http_averror(s->http_code, AVERROR(EIO));
317 int ff_http_get_shutdown_status(URLContext *h)
320 HTTPContext *s = h->priv_data;
322 /* flush the receive buffer when it is write only mode */
325 read_ret = ffurl_read(s->hd, buf, sizeof(buf));
333 int ff_http_do_new_request(URLContext *h, const char *uri) {
334 return ff_http_do_new_request2(h, uri, NULL);
337 int ff_http_do_new_request2(URLContext *h, const char *uri, AVDictionary **opts)
339 HTTPContext *s = h->priv_data;
340 AVDictionary *options = NULL;
342 char hostname1[1024], hostname2[1024], proto1[10], proto2[10];
346 !(!strcmp(h->prot->name, "http") ||
347 !strcmp(h->prot->name, "https")))
348 return AVERROR(EINVAL);
350 av_url_split(proto1, sizeof(proto1), NULL, 0,
351 hostname1, sizeof(hostname1), &port1,
352 NULL, 0, s->location);
353 av_url_split(proto2, sizeof(proto2), NULL, 0,
354 hostname2, sizeof(hostname2), &port2,
356 if (port1 != port2 || strncmp(hostname1, hostname2, sizeof(hostname2)) != 0) {
357 av_log(h, AV_LOG_ERROR, "Cannot reuse HTTP connection for different host: %s:%d != %s:%d\n",
361 return AVERROR(EINVAL);
364 if (!s->end_chunked_post) {
365 ret = http_shutdown(h, h->flags);
373 s->end_chunked_post = 0;
376 s->icy_data_read = 0;
377 av_free(s->location);
378 s->location = av_strdup(uri);
380 return AVERROR(ENOMEM);
382 if ((ret = av_opt_set_dict(s, opts)) < 0)
385 av_log(s, AV_LOG_INFO, "Opening \'%s\' for %s\n", uri, h->flags & AVIO_FLAG_WRITE ? "writing" : "reading");
386 ret = http_open_cnx(h, &options);
387 av_dict_free(&options);
391 int ff_http_averror(int status_code, int default_averror)
393 switch (status_code) {
394 case 400: return AVERROR_HTTP_BAD_REQUEST;
395 case 401: return AVERROR_HTTP_UNAUTHORIZED;
396 case 403: return AVERROR_HTTP_FORBIDDEN;
397 case 404: return AVERROR_HTTP_NOT_FOUND;
400 if (status_code >= 400 && status_code <= 499)
401 return AVERROR_HTTP_OTHER_4XX;
402 else if (status_code >= 500)
403 return AVERROR_HTTP_SERVER_ERROR;
405 return default_averror;
408 static int http_write_reply(URLContext* h, int status_code)
410 int ret, body = 0, reply_code, message_len;
411 const char *reply_text, *content_type;
412 HTTPContext *s = h->priv_data;
413 char message[BUFFER_SIZE];
414 content_type = "text/plain";
418 switch (status_code) {
419 case AVERROR_HTTP_BAD_REQUEST:
422 reply_text = "Bad Request";
424 case AVERROR_HTTP_FORBIDDEN:
427 reply_text = "Forbidden";
429 case AVERROR_HTTP_NOT_FOUND:
432 reply_text = "Not Found";
437 content_type = s->content_type ? s->content_type : "application/octet-stream";
439 case AVERROR_HTTP_SERVER_ERROR:
442 reply_text = "Internal server error";
445 return AVERROR(EINVAL);
449 message_len = snprintf(message, sizeof(message),
450 "HTTP/1.1 %03d %s\r\n"
451 "Content-Type: %s\r\n"
452 "Content-Length: %"SIZE_SPECIFIER"\r\n"
459 strlen(reply_text) + 6, // 3 digit status code + space + \r\n
460 s->headers ? s->headers : "",
465 message_len = snprintf(message, sizeof(message),
466 "HTTP/1.1 %03d %s\r\n"
467 "Content-Type: %s\r\n"
468 "Transfer-Encoding: chunked\r\n"
474 s->headers ? s->headers : "");
476 av_log(h, AV_LOG_TRACE, "HTTP reply header: \n%s----\n", message);
477 if ((ret = ffurl_write(s->hd, message, message_len)) < 0)
482 static void handle_http_errors(URLContext *h, int error)
484 av_assert0(error < 0);
485 http_write_reply(h, error);
488 static int http_handshake(URLContext *c)
490 int ret, err, new_location;
491 HTTPContext *ch = c->priv_data;
492 URLContext *cl = ch->hd;
493 switch (ch->handshake_step) {
495 av_log(c, AV_LOG_TRACE, "Lower protocol\n");
496 if ((ret = ffurl_handshake(cl)) > 0)
500 ch->handshake_step = READ_HEADERS;
501 ch->is_connected_server = 1;
504 av_log(c, AV_LOG_TRACE, "Read headers\n");
505 if ((err = http_read_header(c, &new_location)) < 0) {
506 handle_http_errors(c, err);
509 ch->handshake_step = WRITE_REPLY_HEADERS;
511 case WRITE_REPLY_HEADERS:
512 av_log(c, AV_LOG_TRACE, "Reply code: %d\n", ch->reply_code);
513 if ((err = http_write_reply(c, ch->reply_code)) < 0)
515 ch->handshake_step = FINISH;
520 // this should never be reached.
521 return AVERROR(EINVAL);
524 static int http_listen(URLContext *h, const char *uri, int flags,
525 AVDictionary **options) {
526 HTTPContext *s = h->priv_data;
528 char hostname[1024], proto[10];
530 const char *lower_proto = "tcp";
532 av_url_split(proto, sizeof(proto), NULL, 0, hostname, sizeof(hostname), &port,
534 if (!strcmp(proto, "https"))
536 ff_url_join(lower_url, sizeof(lower_url), lower_proto, NULL, hostname, port,
538 if ((ret = av_dict_set_int(options, "listen", s->listen, 0)) < 0)
540 if ((ret = ffurl_open_whitelist(&s->hd, lower_url, AVIO_FLAG_READ_WRITE,
541 &h->interrupt_callback, options,
542 h->protocol_whitelist, h->protocol_blacklist, h
545 s->handshake_step = LOWER_PROTO;
546 if (s->listen == HTTP_SINGLE) { /* single client */
548 while ((ret = http_handshake(h)) > 0);
551 av_dict_free(&s->chained_options);
555 static int http_open(URLContext *h, const char *uri, int flags,
556 AVDictionary **options)
558 HTTPContext *s = h->priv_data;
561 if( s->seekable == 1 )
566 s->filesize = UINT64_MAX;
567 s->location = av_strdup(uri);
569 return AVERROR(ENOMEM);
571 av_dict_copy(&s->chained_options, *options, 0);
574 int len = strlen(s->headers);
575 if (len < 2 || strcmp("\r\n", s->headers + len - 2)) {
576 av_log(h, AV_LOG_WARNING,
577 "No trailing CRLF found in HTTP header. Adding it.\n");
578 ret = av_reallocp(&s->headers, len + 3);
581 s->headers[len] = '\r';
582 s->headers[len + 1] = '\n';
583 s->headers[len + 2] = '\0';
588 return http_listen(h, uri, flags, options);
590 ret = http_open_cnx(h, options);
592 av_dict_free(&s->chained_options);
596 static int http_accept(URLContext *s, URLContext **c)
599 HTTPContext *sc = s->priv_data;
601 URLContext *sl = sc->hd;
602 URLContext *cl = NULL;
604 av_assert0(sc->listen);
605 if ((ret = ffurl_alloc(c, s->filename, s->flags, &sl->interrupt_callback)) < 0)
607 cc = (*c)->priv_data;
608 if ((ret = ffurl_accept(sl, &cl)) < 0)
611 cc->is_multi_client = 1;
620 static int http_getc(HTTPContext *s)
623 if (s->buf_ptr >= s->buf_end) {
624 len = ffurl_read(s->hd, s->buffer, BUFFER_SIZE);
627 } else if (len == 0) {
630 s->buf_ptr = s->buffer;
631 s->buf_end = s->buffer + len;
634 return *s->buf_ptr++;
637 static int http_get_line(HTTPContext *s, char *line, int line_size)
649 if (q > line && q[-1] == '\r')
655 if ((q - line) < line_size - 1)
661 static int check_http_code(URLContext *h, int http_code, const char *end)
663 HTTPContext *s = h->priv_data;
664 /* error codes are 4xx and 5xx, but regard 401 as a success, so we
665 * don't abort until all headers have been parsed. */
666 if (http_code >= 400 && http_code < 600 &&
667 (http_code != 401 || s->auth_state.auth_type != HTTP_AUTH_NONE) &&
668 (http_code != 407 || s->proxy_auth_state.auth_type != HTTP_AUTH_NONE)) {
669 end += strspn(end, SPACE_CHARS);
670 av_log(h, AV_LOG_WARNING, "HTTP error %d %s\n", http_code, end);
671 return ff_http_averror(http_code, AVERROR(EIO));
676 static int parse_location(HTTPContext *s, const char *p)
678 char redirected_location[MAX_URL_SIZE], *new_loc;
679 ff_make_absolute_url(redirected_location, sizeof(redirected_location),
681 new_loc = av_strdup(redirected_location);
683 return AVERROR(ENOMEM);
684 av_free(s->location);
685 s->location = new_loc;
689 /* "bytes $from-$to/$document_size" */
690 static void parse_content_range(URLContext *h, const char *p)
692 HTTPContext *s = h->priv_data;
695 if (!strncmp(p, "bytes ", 6)) {
697 s->off = strtoull(p, NULL, 10);
698 if ((slash = strchr(p, '/')) && strlen(slash) > 0)
699 s->filesize = strtoull(slash + 1, NULL, 10);
701 if (s->seekable == -1 && (!s->is_akamai || s->filesize != 2147483647))
702 h->is_streamed = 0; /* we _can_ in fact seek */
705 static int parse_content_encoding(URLContext *h, const char *p)
707 if (!av_strncasecmp(p, "gzip", 4) ||
708 !av_strncasecmp(p, "deflate", 7)) {
710 HTTPContext *s = h->priv_data;
713 inflateEnd(&s->inflate_stream);
714 if (inflateInit2(&s->inflate_stream, 32 + 15) != Z_OK) {
715 av_log(h, AV_LOG_WARNING, "Error during zlib initialisation: %s\n",
716 s->inflate_stream.msg);
717 return AVERROR(ENOSYS);
719 if (zlibCompileFlags() & (1 << 17)) {
720 av_log(h, AV_LOG_WARNING,
721 "Your zlib was compiled without gzip support.\n");
722 return AVERROR(ENOSYS);
725 av_log(h, AV_LOG_WARNING,
726 "Compressed (%s) content, need zlib with gzip support\n", p);
727 return AVERROR(ENOSYS);
728 #endif /* CONFIG_ZLIB */
729 } else if (!av_strncasecmp(p, "identity", 8)) {
730 // The normal, no-encoding case (although servers shouldn't include
731 // the header at all if this is the case).
733 av_log(h, AV_LOG_WARNING, "Unknown content coding: %s\n", p);
738 // Concat all Icy- header lines
739 static int parse_icy(HTTPContext *s, const char *tag, const char *p)
741 int len = 4 + strlen(p) + strlen(tag);
742 int is_first = !s->icy_metadata_headers;
745 av_dict_set(&s->metadata, tag, p, 0);
747 if (s->icy_metadata_headers)
748 len += strlen(s->icy_metadata_headers);
750 if ((ret = av_reallocp(&s->icy_metadata_headers, len)) < 0)
754 *s->icy_metadata_headers = '\0';
756 av_strlcatf(s->icy_metadata_headers, len, "%s: %s\n", tag, p);
761 static int parse_set_cookie_expiry_time(const char *exp_str, struct tm *buf)
763 char exp_buf[MAX_EXPIRY];
764 int i, j, exp_buf_len = MAX_EXPIRY-1;
767 // strip off any punctuation or whitespace
768 for (i = 0, j = 0; exp_str[i] != '\0' && j < exp_buf_len; i++) {
769 if ((exp_str[i] >= '0' && exp_str[i] <= '9') ||
770 (exp_str[i] >= 'A' && exp_str[i] <= 'Z') ||
771 (exp_str[i] >= 'a' && exp_str[i] <= 'z')) {
772 exp_buf[j] = exp_str[i];
779 // move the string beyond the day of week
780 while ((*expiry < '0' || *expiry > '9') && *expiry != '\0')
783 return av_small_strptime(expiry, "%d%b%Y%H%M%S", buf) ? 0 : AVERROR(EINVAL);
786 static int parse_set_cookie(const char *set_cookie, AVDictionary **dict)
788 char *param, *next_param, *cstr, *back;
793 if (!(cstr = av_strdup(set_cookie)))
794 return AVERROR(EINVAL);
796 // strip any trailing whitespace
797 back = &cstr[strlen(cstr)-1];
798 while (strchr(WHITESPACES, *back)) {
806 while ((param = av_strtok(next_param, ";", &next_param))) {
808 param += strspn(param, WHITESPACES);
809 if ((name = av_strtok(param, "=", &value))) {
810 if (av_dict_set(dict, name, value, 0) < 0) {
821 static int parse_cookie(HTTPContext *s, const char *p, AVDictionary **cookies)
823 AVDictionary *new_params = NULL;
824 AVDictionaryEntry *e, *cookie_entry;
827 // ensure the cookie is parsable
828 if (parse_set_cookie(p, &new_params))
831 // if there is no cookie value there is nothing to parse
832 cookie_entry = av_dict_get(new_params, "", NULL, AV_DICT_IGNORE_SUFFIX);
833 if (!cookie_entry || !cookie_entry->value) {
834 av_dict_free(&new_params);
838 // ensure the cookie is not expired or older than an existing value
839 if ((e = av_dict_get(new_params, "expires", NULL, 0)) && e->value) {
840 struct tm new_tm = {0};
841 if (!parse_set_cookie_expiry_time(e->value, &new_tm)) {
842 AVDictionaryEntry *e2;
844 // if the cookie has already expired ignore it
845 if (av_timegm(&new_tm) < av_gettime() / 1000000) {
846 av_dict_free(&new_params);
850 // only replace an older cookie with the same name
851 e2 = av_dict_get(*cookies, cookie_entry->key, NULL, 0);
852 if (e2 && e2->value) {
853 AVDictionary *old_params = NULL;
854 if (!parse_set_cookie(p, &old_params)) {
855 e2 = av_dict_get(old_params, "expires", NULL, 0);
856 if (e2 && e2->value) {
857 struct tm old_tm = {0};
858 if (!parse_set_cookie_expiry_time(e->value, &old_tm)) {
859 if (av_timegm(&new_tm) < av_timegm(&old_tm)) {
860 av_dict_free(&new_params);
861 av_dict_free(&old_params);
867 av_dict_free(&old_params);
871 av_dict_free(&new_params);
873 // duplicate the cookie name (dict will dupe the value)
874 if (!(eql = strchr(p, '='))) return AVERROR(EINVAL);
875 if (!(name = av_strndup(p, eql - p))) return AVERROR(ENOMEM);
877 // add the cookie to the dictionary
878 av_dict_set(cookies, name, eql, AV_DICT_DONT_STRDUP_KEY);
883 static int cookie_string(AVDictionary *dict, char **cookies)
885 AVDictionaryEntry *e = NULL;
888 // determine how much memory is needed for the cookies string
889 while (e = av_dict_get(dict, "", e, AV_DICT_IGNORE_SUFFIX))
890 len += strlen(e->key) + strlen(e->value) + 1;
892 // reallocate the cookies
894 if (*cookies) av_free(*cookies);
895 *cookies = av_malloc(len);
896 if (!*cookies) return AVERROR(ENOMEM);
899 // write out the cookies
900 while (e = av_dict_get(dict, "", e, AV_DICT_IGNORE_SUFFIX))
901 av_strlcatf(*cookies, len, "%s%s\n", e->key, e->value);
906 static int process_line(URLContext *h, char *line, int line_count,
909 HTTPContext *s = h->priv_data;
910 const char *auto_method = h->flags & AVIO_FLAG_READ ? "POST" : "GET";
911 char *tag, *p, *end, *method, *resource, *version;
915 if (line[0] == '\0') {
921 if (line_count == 0) {
922 if (s->is_connected_server) {
925 while (*p && !av_isspace(*p))
928 av_log(h, AV_LOG_TRACE, "Received method: %s\n", method);
930 if (av_strcasecmp(s->method, method)) {
931 av_log(h, AV_LOG_ERROR, "Received and expected HTTP method do not match. (%s expected, %s received)\n",
933 return ff_http_averror(400, AVERROR(EIO));
936 // use autodetected HTTP method to expect
937 av_log(h, AV_LOG_TRACE, "Autodetected %s HTTP method\n", auto_method);
938 if (av_strcasecmp(auto_method, method)) {
939 av_log(h, AV_LOG_ERROR, "Received and autodetected HTTP method did not match "
940 "(%s autodetected %s received)\n", auto_method, method);
941 return ff_http_averror(400, AVERROR(EIO));
943 if (!(s->method = av_strdup(method)))
944 return AVERROR(ENOMEM);
948 while (av_isspace(*p))
951 while (*p && !av_isspace(*p))
954 av_log(h, AV_LOG_TRACE, "Requested resource: %s\n", resource);
955 if (!(s->resource = av_strdup(resource)))
956 return AVERROR(ENOMEM);
959 while (av_isspace(*p))
962 while (*p && !av_isspace(*p))
965 if (av_strncasecmp(version, "HTTP/", 5)) {
966 av_log(h, AV_LOG_ERROR, "Malformed HTTP version string.\n");
967 return ff_http_averror(400, AVERROR(EIO));
969 av_log(h, AV_LOG_TRACE, "HTTP version string: %s\n", version);
971 if (av_strncasecmp(p, "HTTP/1.0", 8) == 0)
973 while (*p != '/' && *p != '\0')
977 av_freep(&s->http_version);
978 s->http_version = av_strndup(p, 3);
979 while (!av_isspace(*p) && *p != '\0')
981 while (av_isspace(*p))
983 s->http_code = strtol(p, &end, 10);
985 av_log(h, AV_LOG_TRACE, "http_code=%d\n", s->http_code);
987 if ((ret = check_http_code(h, s->http_code, end)) < 0)
991 while (*p != '\0' && *p != ':')
999 while (av_isspace(*p))
1001 if (!av_strcasecmp(tag, "Location")) {
1002 if ((ret = parse_location(s, p)) < 0)
1005 } else if (!av_strcasecmp(tag, "Content-Length") &&
1006 s->filesize == UINT64_MAX) {
1007 s->filesize = strtoull(p, NULL, 10);
1008 } else if (!av_strcasecmp(tag, "Content-Range")) {
1009 parse_content_range(h, p);
1010 } else if (!av_strcasecmp(tag, "Accept-Ranges") &&
1011 !strncmp(p, "bytes", 5) &&
1012 s->seekable == -1) {
1014 } else if (!av_strcasecmp(tag, "Transfer-Encoding") &&
1015 !av_strncasecmp(p, "chunked", 7)) {
1016 s->filesize = UINT64_MAX;
1018 } else if (!av_strcasecmp(tag, "WWW-Authenticate")) {
1019 ff_http_auth_handle_header(&s->auth_state, tag, p);
1020 } else if (!av_strcasecmp(tag, "Authentication-Info")) {
1021 ff_http_auth_handle_header(&s->auth_state, tag, p);
1022 } else if (!av_strcasecmp(tag, "Proxy-Authenticate")) {
1023 ff_http_auth_handle_header(&s->proxy_auth_state, tag, p);
1024 } else if (!av_strcasecmp(tag, "Connection")) {
1025 if (!strcmp(p, "close"))
1027 } else if (!av_strcasecmp(tag, "Server")) {
1028 if (!av_strcasecmp(p, "AkamaiGHost")) {
1030 } else if (!av_strncasecmp(p, "MediaGateway", 12)) {
1031 s->is_mediagateway = 1;
1033 } else if (!av_strcasecmp(tag, "Content-Type")) {
1034 av_free(s->mime_type);
1035 s->mime_type = av_strdup(p);
1036 } else if (!av_strcasecmp(tag, "Set-Cookie")) {
1037 if (parse_cookie(s, p, &s->cookie_dict))
1038 av_log(h, AV_LOG_WARNING, "Unable to parse '%s'\n", p);
1039 } else if (!av_strcasecmp(tag, "Icy-MetaInt")) {
1040 s->icy_metaint = strtoull(p, NULL, 10);
1041 } else if (!av_strncasecmp(tag, "Icy-", 4)) {
1042 if ((ret = parse_icy(s, tag, p)) < 0)
1044 } else if (!av_strcasecmp(tag, "Content-Encoding")) {
1045 if ((ret = parse_content_encoding(h, p)) < 0)
1053 * Create a string containing cookie values for use as a HTTP cookie header
1054 * field value for a particular path and domain from the cookie values stored in
1055 * the HTTP protocol context. The cookie string is stored in *cookies, and may
1056 * be NULL if there are no valid cookies.
1058 * @return a negative value if an error condition occurred, 0 otherwise
1060 static int get_cookies(HTTPContext *s, char **cookies, const char *path,
1063 // cookie strings will look like Set-Cookie header field values. Multiple
1064 // Set-Cookie fields will result in multiple values delimited by a newline
1066 char *cookie, *set_cookies, *next;
1068 // destroy any cookies in the dictionary.
1069 av_dict_free(&s->cookie_dict);
1074 next = set_cookies = av_strdup(s->cookies);
1076 return AVERROR(ENOMEM);
1079 while ((cookie = av_strtok(next, "\n", &next)) && !ret) {
1080 AVDictionary *cookie_params = NULL;
1081 AVDictionaryEntry *cookie_entry, *e;
1083 // store the cookie in a dict in case it is updated in the response
1084 if (parse_cookie(s, cookie, &s->cookie_dict))
1085 av_log(s, AV_LOG_WARNING, "Unable to parse '%s'\n", cookie);
1087 // continue on to the next cookie if this one cannot be parsed
1088 if (parse_set_cookie(cookie, &cookie_params))
1091 // if the cookie has no value, skip it
1092 cookie_entry = av_dict_get(cookie_params, "", NULL, AV_DICT_IGNORE_SUFFIX);
1093 if (!cookie_entry || !cookie_entry->value)
1096 // if the cookie has expired, don't add it
1097 if ((e = av_dict_get(cookie_params, "expires", NULL, 0)) && e->value) {
1098 struct tm tm_buf = {0};
1099 if (!parse_set_cookie_expiry_time(e->value, &tm_buf)) {
1100 if (av_timegm(&tm_buf) < av_gettime() / 1000000)
1105 // if no domain in the cookie assume it appied to this request
1106 if ((e = av_dict_get(cookie_params, "domain", NULL, 0)) && e->value) {
1107 // find the offset comparison is on the min domain (b.com, not a.b.com)
1108 int domain_offset = strlen(domain) - strlen(e->value);
1109 if (domain_offset < 0)
1112 // match the cookie domain
1113 if (av_strcasecmp(&domain[domain_offset], e->value))
1117 // ensure this cookie matches the path
1118 e = av_dict_get(cookie_params, "path", NULL, 0);
1119 if (!e || av_strncasecmp(path, e->value, strlen(e->value)))
1122 // cookie parameters match, so copy the value
1124 *cookies = av_asprintf("%s=%s", cookie_entry->key, cookie_entry->value);
1126 char *tmp = *cookies;
1127 *cookies = av_asprintf("%s; %s=%s", tmp, cookie_entry->key, cookie_entry->value);
1131 ret = AVERROR(ENOMEM);
1134 av_dict_free(&cookie_params);
1137 av_free(set_cookies);
1142 static inline int has_header(const char *str, const char *header)
1144 /* header + 2 to skip over CRLF prefix. (make sure you have one!) */
1147 return av_stristart(str, header + 2, NULL) || av_stristr(str, header);
1150 static int http_read_header(URLContext *h, int *new_location)
1152 HTTPContext *s = h->priv_data;
1153 char line[MAX_URL_SIZE];
1156 s->chunksize = UINT64_MAX;
1159 if ((err = http_get_line(s, line, sizeof(line))) < 0)
1162 av_log(h, AV_LOG_TRACE, "header='%s'\n", line);
1164 err = process_line(h, line, s->line_count, new_location);
1172 if (s->seekable == -1 && s->is_mediagateway && s->filesize == 2000000000)
1173 h->is_streamed = 1; /* we can in fact _not_ seek */
1175 // add any new cookies into the existing cookie string
1176 cookie_string(s->cookie_dict, &s->cookies);
1177 av_dict_free(&s->cookie_dict);
1183 * Escape unsafe characters in path in order to pass them safely to the HTTP
1184 * request. Insipred by the algorithm in GNU wget:
1185 * - escape "%" characters not followed by two hex digits
1186 * - escape all "unsafe" characters except which are also "reserved"
1187 * - pass through everything else
1189 static void bprint_escaped_path(AVBPrint *bp, const char *path)
1191 #define NEEDS_ESCAPE(ch) \
1192 ((ch) <= ' ' || (ch) >= '\x7f' || \
1193 (ch) == '"' || (ch) == '%' || (ch) == '<' || (ch) == '>' || (ch) == '\\' || \
1194 (ch) == '^' || (ch) == '`' || (ch) == '{' || (ch) == '}' || (ch) == '|')
1198 while (*path && q - buf < sizeof(buf) - 4) {
1199 if (path[0] == '%' && av_isxdigit(path[1]) && av_isxdigit(path[2])) {
1203 } else if (NEEDS_ESCAPE(*path)) {
1204 q += snprintf(q, 4, "%%%02X", (uint8_t)*path++);
1209 av_bprint_append_data(bp, buf, q - buf);
1213 static int http_connect(URLContext *h, const char *path, const char *local_path,
1214 const char *hoststr, const char *auth,
1215 const char *proxyauth, int *new_location)
1217 HTTPContext *s = h->priv_data;
1220 char *authstr = NULL, *proxyauthstr = NULL;
1221 uint64_t off = s->off;
1223 int send_expect_100 = 0;
1225 av_bprint_init_for_buffer(&request, s->buffer, sizeof(s->buffer));
1227 /* send http header */
1228 post = h->flags & AVIO_FLAG_WRITE;
1231 /* force POST method and disable chunked encoding when
1232 * custom HTTP post data is set */
1234 s->chunked_post = 0;
1240 method = post ? "POST" : "GET";
1242 authstr = ff_http_auth_create_response(&s->auth_state, auth,
1243 local_path, method);
1244 proxyauthstr = ff_http_auth_create_response(&s->proxy_auth_state, proxyauth,
1245 local_path, method);
1247 if (post && !s->post_data) {
1248 if (s->send_expect_100 != -1) {
1249 send_expect_100 = s->send_expect_100;
1251 send_expect_100 = 0;
1252 /* The user has supplied authentication but we don't know the auth type,
1253 * send Expect: 100-continue to get the 401 response including the
1254 * WWW-Authenticate header, or an 100 continue if no auth actually
1256 if (auth && *auth &&
1257 s->auth_state.auth_type == HTTP_AUTH_NONE &&
1258 s->http_code != 401)
1259 send_expect_100 = 1;
1263 #if FF_API_HTTP_USER_AGENT
1264 if (strcmp(s->user_agent_deprecated, DEFAULT_USER_AGENT)) {
1265 s->user_agent = av_strdup(s->user_agent_deprecated);
1269 av_bprintf(&request, "%s ", method);
1270 bprint_escaped_path(&request, path);
1271 av_bprintf(&request, " HTTP/1.1\r\n");
1273 if (post && s->chunked_post)
1274 av_bprintf(&request, "Transfer-Encoding: chunked\r\n");
1275 /* set default headers if needed */
1276 if (!has_header(s->headers, "\r\nUser-Agent: "))
1277 av_bprintf(&request, "User-Agent: %s\r\n", s->user_agent);
1279 /* set default headers if needed */
1280 if (!has_header(s->headers, "\r\nReferer: "))
1281 av_bprintf(&request, "Referer: %s\r\n", s->referer);
1283 if (!has_header(s->headers, "\r\nAccept: "))
1284 av_bprintf(&request, "Accept: */*\r\n");
1285 // Note: we send this on purpose even when s->off is 0 when we're probing,
1286 // since it allows us to detect more reliably if a (non-conforming)
1287 // server supports seeking by analysing the reply headers.
1288 if (!has_header(s->headers, "\r\nRange: ") && !post && (s->off > 0 || s->end_off || s->seekable == -1)) {
1289 av_bprintf(&request, "Range: bytes=%"PRIu64"-", s->off);
1291 av_bprintf(&request, "%"PRId64, s->end_off - 1);
1292 av_bprintf(&request, "\r\n");
1294 if (send_expect_100 && !has_header(s->headers, "\r\nExpect: "))
1295 av_bprintf(&request, "Expect: 100-continue\r\n");
1297 if (!has_header(s->headers, "\r\nConnection: "))
1298 av_bprintf(&request, "Connection: %s\r\n", s->multiple_requests ? "keep-alive" : "close");
1300 if (!has_header(s->headers, "\r\nHost: "))
1301 av_bprintf(&request, "Host: %s\r\n", hoststr);
1302 if (!has_header(s->headers, "\r\nContent-Length: ") && s->post_data)
1303 av_bprintf(&request, "Content-Length: %d\r\n", s->post_datalen);
1305 if (!has_header(s->headers, "\r\nContent-Type: ") && s->content_type)
1306 av_bprintf(&request, "Content-Type: %s\r\n", s->content_type);
1307 if (!has_header(s->headers, "\r\nCookie: ") && s->cookies) {
1308 char *cookies = NULL;
1309 if (!get_cookies(s, &cookies, path, hoststr) && cookies) {
1310 av_bprintf(&request, "Cookie: %s\r\n", cookies);
1314 if (!has_header(s->headers, "\r\nIcy-MetaData: ") && s->icy)
1315 av_bprintf(&request, "Icy-MetaData: 1\r\n");
1317 /* now add in custom headers */
1319 av_bprintf(&request, "%s", s->headers);
1322 av_bprintf(&request, "%s", authstr);
1324 av_bprintf(&request, "Proxy-%s", proxyauthstr);
1325 av_bprintf(&request, "\r\n");
1327 av_log(h, AV_LOG_DEBUG, "request: %s\n", request.str);
1329 if (!av_bprint_is_complete(&request)) {
1330 av_log(h, AV_LOG_ERROR, "overlong headers\n");
1331 err = AVERROR(EINVAL);
1335 if ((err = ffurl_write(s->hd, request.str, request.len)) < 0)
1339 if ((err = ffurl_write(s->hd, s->post_data, s->post_datalen)) < 0)
1342 /* init input buffer */
1343 s->buf_ptr = s->buffer;
1344 s->buf_end = s->buffer;
1347 s->icy_data_read = 0;
1348 s->filesize = UINT64_MAX;
1350 s->end_chunked_post = 0;
1355 if (post && !s->post_data && !send_expect_100) {
1356 /* Pretend that it did work. We didn't read any header yet, since
1357 * we've still to send the POST data, but the code calling this
1358 * function will check http_code after we return. */
1364 /* wait for header */
1365 err = http_read_header(h, new_location);
1372 err = (off == s->off) ? 0 : -1;
1375 av_freep(&proxyauthstr);
1379 static int http_buf_read(URLContext *h, uint8_t *buf, int size)
1381 HTTPContext *s = h->priv_data;
1384 if (s->chunksize != UINT64_MAX) {
1388 if (!s->chunksize) {
1393 if ((err = http_get_line(s, line, sizeof(line))) < 0)
1395 } while (!*line); /* skip CR LF from last chunk */
1397 s->chunksize = strtoull(line, NULL, 16);
1399 av_log(h, AV_LOG_TRACE,
1400 "Chunked encoding data size: %"PRIu64"\n",
1403 if (!s->chunksize && s->multiple_requests) {
1404 http_get_line(s, line, sizeof(line)); // read empty chunk
1408 else if (!s->chunksize) {
1409 av_log(h, AV_LOG_DEBUG, "Last chunk received, closing conn\n");
1410 ffurl_closep(&s->hd);
1413 else if (s->chunksize == UINT64_MAX) {
1414 av_log(h, AV_LOG_ERROR, "Invalid chunk size %"PRIu64"\n",
1416 return AVERROR(EINVAL);
1419 size = FFMIN(size, s->chunksize);
1422 /* read bytes from input buffer first */
1423 len = s->buf_end - s->buf_ptr;
1427 memcpy(buf, s->buf_ptr, len);
1430 uint64_t target_end = s->end_off ? s->end_off : s->filesize;
1431 if ((!s->willclose || s->chunksize == UINT64_MAX) && s->off >= target_end)
1433 len = ffurl_read(s->hd, buf, size);
1434 if (!len && (!s->willclose || s->chunksize == UINT64_MAX) && s->off < target_end) {
1435 av_log(h, AV_LOG_ERROR,
1436 "Stream ends prematurely at %"PRIu64", should be %"PRIu64"\n",
1439 return AVERROR(EIO);
1444 if (s->chunksize > 0 && s->chunksize != UINT64_MAX) {
1445 av_assert0(s->chunksize >= len);
1446 s->chunksize -= len;
1453 #define DECOMPRESS_BUF_SIZE (256 * 1024)
1454 static int http_buf_read_compressed(URLContext *h, uint8_t *buf, int size)
1456 HTTPContext *s = h->priv_data;
1459 if (!s->inflate_buffer) {
1460 s->inflate_buffer = av_malloc(DECOMPRESS_BUF_SIZE);
1461 if (!s->inflate_buffer)
1462 return AVERROR(ENOMEM);
1465 if (s->inflate_stream.avail_in == 0) {
1466 int read = http_buf_read(h, s->inflate_buffer, DECOMPRESS_BUF_SIZE);
1469 s->inflate_stream.next_in = s->inflate_buffer;
1470 s->inflate_stream.avail_in = read;
1473 s->inflate_stream.avail_out = size;
1474 s->inflate_stream.next_out = buf;
1476 ret = inflate(&s->inflate_stream, Z_SYNC_FLUSH);
1477 if (ret != Z_OK && ret != Z_STREAM_END)
1478 av_log(h, AV_LOG_WARNING, "inflate return value: %d, %s\n",
1479 ret, s->inflate_stream.msg);
1481 return size - s->inflate_stream.avail_out;
1483 #endif /* CONFIG_ZLIB */
1485 static int64_t http_seek_internal(URLContext *h, int64_t off, int whence, int force_reconnect);
1487 static int http_read_stream(URLContext *h, uint8_t *buf, int size)
1489 HTTPContext *s = h->priv_data;
1490 int err, new_location, read_ret;
1492 int reconnect_delay = 0;
1497 if (s->end_chunked_post && !s->end_header) {
1498 err = http_read_header(h, &new_location);
1505 return http_buf_read_compressed(h, buf, size);
1506 #endif /* CONFIG_ZLIB */
1507 read_ret = http_buf_read(h, buf, size);
1508 while (read_ret < 0) {
1509 uint64_t target = h->is_streamed ? 0 : s->off;
1511 if (read_ret == AVERROR_EXIT)
1514 if (h->is_streamed && !s->reconnect_streamed)
1517 if (!(s->reconnect && s->filesize > 0 && s->off < s->filesize) &&
1518 !(s->reconnect_at_eof && read_ret == AVERROR_EOF))
1521 if (reconnect_delay > s->reconnect_delay_max)
1522 return AVERROR(EIO);
1524 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));
1525 err = ff_network_sleep_interruptible(1000U*1000*reconnect_delay, &h->interrupt_callback);
1526 if (err != AVERROR(ETIMEDOUT))
1528 reconnect_delay = 1 + 2*reconnect_delay;
1529 seek_ret = http_seek_internal(h, target, SEEK_SET, 1);
1530 if (seek_ret >= 0 && seek_ret != target) {
1531 av_log(h, AV_LOG_ERROR, "Failed to reconnect at %"PRIu64".\n", target);
1535 read_ret = http_buf_read(h, buf, size);
1541 // Like http_read_stream(), but no short reads.
1542 // Assumes partial reads are an error.
1543 static int http_read_stream_all(URLContext *h, uint8_t *buf, int size)
1546 while (pos < size) {
1547 int len = http_read_stream(h, buf + pos, size - pos);
1555 static void update_metadata(URLContext *h, char *data)
1561 HTTPContext *s = h->priv_data;
1565 val = strstr(key, "='");
1568 end = strstr(val, "';");
1576 av_dict_set(&s->metadata, key, val, 0);
1577 av_log(h, AV_LOG_VERBOSE, "Metadata update for %s: %s\n", key, val);
1583 static int store_icy(URLContext *h, int size)
1585 HTTPContext *s = h->priv_data;
1586 /* until next metadata packet */
1589 if (s->icy_metaint < s->icy_data_read)
1590 return AVERROR_INVALIDDATA;
1591 remaining = s->icy_metaint - s->icy_data_read;
1594 /* The metadata packet is variable sized. It has a 1 byte header
1595 * which sets the length of the packet (divided by 16). If it's 0,
1596 * the metadata doesn't change. After the packet, icy_metaint bytes
1597 * of normal data follows. */
1599 int len = http_read_stream_all(h, &ch, 1);
1603 char data[255 * 16 + 1];
1606 ret = http_read_stream_all(h, data, len);
1610 if ((ret = av_opt_set(s, "icy_metadata_packet", data, 0)) < 0)
1612 update_metadata(h, data);
1614 s->icy_data_read = 0;
1615 remaining = s->icy_metaint;
1618 return FFMIN(size, remaining);
1621 static int http_read(URLContext *h, uint8_t *buf, int size)
1623 HTTPContext *s = h->priv_data;
1625 if (s->icy_metaint > 0) {
1626 size = store_icy(h, size);
1631 size = http_read_stream(h, buf, size);
1633 s->icy_data_read += size;
1637 /* used only when posting data */
1638 static int http_write(URLContext *h, const uint8_t *buf, int size)
1640 char temp[11] = ""; /* 32-bit hex + CRLF + nul */
1642 char crlf[] = "\r\n";
1643 HTTPContext *s = h->priv_data;
1645 if (!s->chunked_post) {
1646 /* non-chunked data is sent without any special encoding */
1647 return ffurl_write(s->hd, buf, size);
1650 /* silently ignore zero-size data since chunk encoding that would
1653 /* upload data using chunked encoding */
1654 snprintf(temp, sizeof(temp), "%x\r\n", size);
1656 if ((ret = ffurl_write(s->hd, temp, strlen(temp))) < 0 ||
1657 (ret = ffurl_write(s->hd, buf, size)) < 0 ||
1658 (ret = ffurl_write(s->hd, crlf, sizeof(crlf) - 1)) < 0)
1664 static int http_shutdown(URLContext *h, int flags)
1667 char footer[] = "0\r\n\r\n";
1668 HTTPContext *s = h->priv_data;
1670 /* signal end of chunked encoding if used */
1671 if (((flags & AVIO_FLAG_WRITE) && s->chunked_post) ||
1672 ((flags & AVIO_FLAG_READ) && s->chunked_post && s->listen)) {
1673 ret = ffurl_write(s->hd, footer, sizeof(footer) - 1);
1674 ret = ret > 0 ? 0 : ret;
1675 /* flush the receive buffer when it is write only mode */
1676 if (!(flags & AVIO_FLAG_READ)) {
1679 s->hd->flags |= AVIO_FLAG_NONBLOCK;
1680 read_ret = ffurl_read(s->hd, buf, sizeof(buf));
1681 s->hd->flags &= ~AVIO_FLAG_NONBLOCK;
1682 if (read_ret < 0 && read_ret != AVERROR(EAGAIN)) {
1683 av_log(h, AV_LOG_ERROR, "URL read error: %s\n", av_err2str(read_ret));
1687 s->end_chunked_post = 1;
1693 static int http_close(URLContext *h)
1696 HTTPContext *s = h->priv_data;
1699 inflateEnd(&s->inflate_stream);
1700 av_freep(&s->inflate_buffer);
1701 #endif /* CONFIG_ZLIB */
1703 if (s->hd && !s->end_chunked_post)
1704 /* Close the write direction by sending the end of chunked encoding. */
1705 ret = http_shutdown(h, h->flags);
1708 ffurl_closep(&s->hd);
1709 av_dict_free(&s->chained_options);
1713 static int64_t http_seek_internal(URLContext *h, int64_t off, int whence, int force_reconnect)
1715 HTTPContext *s = h->priv_data;
1716 URLContext *old_hd = s->hd;
1717 uint64_t old_off = s->off;
1718 uint8_t old_buf[BUFFER_SIZE];
1719 int old_buf_size, ret;
1720 AVDictionary *options = NULL;
1722 if (whence == AVSEEK_SIZE)
1724 else if (!force_reconnect &&
1725 ((whence == SEEK_CUR && off == 0) ||
1726 (whence == SEEK_SET && off == s->off)))
1728 else if ((s->filesize == UINT64_MAX && whence == SEEK_END))
1729 return AVERROR(ENOSYS);
1731 if (whence == SEEK_CUR)
1733 else if (whence == SEEK_END)
1735 else if (whence != SEEK_SET)
1736 return AVERROR(EINVAL);
1738 return AVERROR(EINVAL);
1741 if (s->off && h->is_streamed)
1742 return AVERROR(ENOSYS);
1744 /* do not try to make a new connection if seeking past the end of the file */
1745 if (s->end_off || s->filesize != UINT64_MAX) {
1746 uint64_t end_pos = s->end_off ? s->end_off : s->filesize;
1747 if (s->off >= end_pos)
1751 /* we save the old context in case the seek fails */
1752 old_buf_size = s->buf_end - s->buf_ptr;
1753 memcpy(old_buf, s->buf_ptr, old_buf_size);
1756 /* if it fails, continue on old connection */
1757 if ((ret = http_open_cnx(h, &options)) < 0) {
1758 av_dict_free(&options);
1759 memcpy(s->buffer, old_buf, old_buf_size);
1760 s->buf_ptr = s->buffer;
1761 s->buf_end = s->buffer + old_buf_size;
1766 av_dict_free(&options);
1767 ffurl_close(old_hd);
1771 static int64_t http_seek(URLContext *h, int64_t off, int whence)
1773 return http_seek_internal(h, off, whence, 0);
1776 static int http_get_file_handle(URLContext *h)
1778 HTTPContext *s = h->priv_data;
1779 return ffurl_get_file_handle(s->hd);
1782 static int http_get_short_seek(URLContext *h)
1784 HTTPContext *s = h->priv_data;
1785 return ffurl_get_short_seek(s->hd);
1788 #define HTTP_CLASS(flavor) \
1789 static const AVClass flavor ## _context_class = { \
1790 .class_name = # flavor, \
1791 .item_name = av_default_item_name, \
1792 .option = options, \
1793 .version = LIBAVUTIL_VERSION_INT, \
1796 #if CONFIG_HTTP_PROTOCOL
1799 const URLProtocol ff_http_protocol = {
1801 .url_open2 = http_open,
1802 .url_accept = http_accept,
1803 .url_handshake = http_handshake,
1804 .url_read = http_read,
1805 .url_write = http_write,
1806 .url_seek = http_seek,
1807 .url_close = http_close,
1808 .url_get_file_handle = http_get_file_handle,
1809 .url_get_short_seek = http_get_short_seek,
1810 .url_shutdown = http_shutdown,
1811 .priv_data_size = sizeof(HTTPContext),
1812 .priv_data_class = &http_context_class,
1813 .flags = URL_PROTOCOL_FLAG_NETWORK,
1814 .default_whitelist = "http,https,tls,rtp,tcp,udp,crypto,httpproxy,data"
1816 #endif /* CONFIG_HTTP_PROTOCOL */
1818 #if CONFIG_HTTPS_PROTOCOL
1821 const URLProtocol ff_https_protocol = {
1823 .url_open2 = http_open,
1824 .url_read = http_read,
1825 .url_write = http_write,
1826 .url_seek = http_seek,
1827 .url_close = http_close,
1828 .url_get_file_handle = http_get_file_handle,
1829 .url_get_short_seek = http_get_short_seek,
1830 .url_shutdown = http_shutdown,
1831 .priv_data_size = sizeof(HTTPContext),
1832 .priv_data_class = &https_context_class,
1833 .flags = URL_PROTOCOL_FLAG_NETWORK,
1834 .default_whitelist = "http,https,tls,rtp,tcp,udp,crypto,httpproxy"
1836 #endif /* CONFIG_HTTPS_PROTOCOL */
1838 #if CONFIG_HTTPPROXY_PROTOCOL
1839 static int http_proxy_close(URLContext *h)
1841 HTTPContext *s = h->priv_data;
1843 ffurl_closep(&s->hd);
1847 static int http_proxy_open(URLContext *h, const char *uri, int flags)
1849 HTTPContext *s = h->priv_data;
1850 char hostname[1024], hoststr[1024];
1851 char auth[1024], pathbuf[1024], *path;
1852 char lower_url[100];
1853 int port, ret = 0, attempts = 0;
1854 HTTPAuthType cur_auth_type;
1858 if( s->seekable == 1 )
1863 av_url_split(NULL, 0, auth, sizeof(auth), hostname, sizeof(hostname), &port,
1864 pathbuf, sizeof(pathbuf), uri);
1865 ff_url_join(hoststr, sizeof(hoststr), NULL, NULL, hostname, port, NULL);
1870 ff_url_join(lower_url, sizeof(lower_url), "tcp", NULL, hostname, port,
1873 ret = ffurl_open_whitelist(&s->hd, lower_url, AVIO_FLAG_READ_WRITE,
1874 &h->interrupt_callback, NULL,
1875 h->protocol_whitelist, h->protocol_blacklist, h);
1879 authstr = ff_http_auth_create_response(&s->proxy_auth_state, auth,
1881 snprintf(s->buffer, sizeof(s->buffer),
1882 "CONNECT %s HTTP/1.1\r\n"
1884 "Connection: close\r\n"
1889 authstr ? "Proxy-" : "", authstr ? authstr : "");
1892 if ((ret = ffurl_write(s->hd, s->buffer, strlen(s->buffer))) < 0)
1895 s->buf_ptr = s->buffer;
1896 s->buf_end = s->buffer;
1898 s->filesize = UINT64_MAX;
1899 cur_auth_type = s->proxy_auth_state.auth_type;
1901 /* Note: This uses buffering, potentially reading more than the
1902 * HTTP header. If tunneling a protocol where the server starts
1903 * the conversation, we might buffer part of that here, too.
1904 * Reading that requires using the proper ffurl_read() function
1905 * on this URLContext, not using the fd directly (as the tls
1906 * protocol does). This shouldn't be an issue for tls though,
1907 * since the client starts the conversation there, so there
1908 * is no extra data that we might buffer up here.
1910 ret = http_read_header(h, &new_loc);
1915 if (s->http_code == 407 &&
1916 (cur_auth_type == HTTP_AUTH_NONE || s->proxy_auth_state.stale) &&
1917 s->proxy_auth_state.auth_type != HTTP_AUTH_NONE && attempts < 2) {
1918 ffurl_closep(&s->hd);
1922 if (s->http_code < 400)
1924 ret = ff_http_averror(s->http_code, AVERROR(EIO));
1927 http_proxy_close(h);
1931 static int http_proxy_write(URLContext *h, const uint8_t *buf, int size)
1933 HTTPContext *s = h->priv_data;
1934 return ffurl_write(s->hd, buf, size);
1937 const URLProtocol ff_httpproxy_protocol = {
1938 .name = "httpproxy",
1939 .url_open = http_proxy_open,
1940 .url_read = http_buf_read,
1941 .url_write = http_proxy_write,
1942 .url_close = http_proxy_close,
1943 .url_get_file_handle = http_get_file_handle,
1944 .priv_data_size = sizeof(HTTPContext),
1945 .flags = URL_PROTOCOL_FLAG_NETWORK,
1947 #endif /* CONFIG_HTTPPROXY_PROTOCOL */