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/opt.h"
31 #include "libavutil/time.h"
32 #include "libavutil/parseutils.h"
39 #include "os_support.h"
42 /* XXX: POST protocol is not completely implemented because ffmpeg uses
43 * only a subset of it. */
45 /* The IO buffer size is unrelated to the max URL size in itself, but needs
46 * to be large enough to fit the full request headers (including long
48 #define BUFFER_SIZE MAX_URL_SIZE
49 #define MAX_REDIRECTS 8
53 #define WHITESPACES " \n\t\r"
61 typedef struct HTTPContext {
64 unsigned char buffer[BUFFER_SIZE], *buf_ptr, *buf_end;
67 /* Used if "Transfer-Encoding: chunked" otherwise -1. */
70 uint64_t off, end_off, filesize;
72 HTTPAuthState auth_state;
73 HTTPAuthState proxy_auth_state;
80 #if FF_API_HTTP_USER_AGENT
81 char *user_agent_deprecated;
84 /* Set if the server correctly handles Connection: close and will close
85 * the connection after feeding us the content. */
87 int seekable; /**< Control seekability, 0 = disable, 1 = enable, -1 = probe. */
89 /* A flag which indicates if the end of chunked encoding has been sent. */
91 /* A flag which indicates we have finished to read POST reply. */
93 /* A flag which indicates if we use persistent connections. */
94 int multiple_requests;
99 char *cookies; ///< holds newline (\n) delimited Set-Cookie header field values (without the "Set-Cookie: " field name)
100 /* A dictionary containing cookies keyed by cookie name */
101 AVDictionary *cookie_dict;
103 /* how much data was read since the last ICY metadata packet */
104 uint64_t icy_data_read;
105 /* after how many bytes of read data a new metadata packet will be found */
106 uint64_t icy_metaint;
107 char *icy_metadata_headers;
108 char *icy_metadata_packet;
109 AVDictionary *metadata;
112 z_stream inflate_stream;
113 uint8_t *inflate_buffer;
114 #endif /* CONFIG_ZLIB */
115 AVDictionary *chained_options;
116 /* -1 = try to send if applicable, 0 = always disabled, 1 = always enabled */
120 int reconnect_at_eof;
121 int reconnect_streamed;
122 int reconnect_delay_max;
127 HandshakeState handshake_step;
128 int is_connected_server;
131 #define OFFSET(x) offsetof(HTTPContext, x)
132 #define D AV_OPT_FLAG_DECODING_PARAM
133 #define E AV_OPT_FLAG_ENCODING_PARAM
134 #define DEFAULT_USER_AGENT "Lavf/" AV_STRINGIFY(LIBAVFORMAT_VERSION)
136 static const AVOption options[] = {
137 { "seekable", "control seekability of connection", OFFSET(seekable), AV_OPT_TYPE_BOOL, { .i64 = -1 }, -1, 1, D },
138 { "chunked_post", "use chunked transfer-encoding for posts", OFFSET(chunked_post), AV_OPT_TYPE_BOOL, { .i64 = 1 }, 0, 1, E },
139 { "http_proxy", "set HTTP proxy to tunnel through", OFFSET(http_proxy), AV_OPT_TYPE_STRING, { .str = NULL }, 0, 0, D | E },
140 { "headers", "set custom HTTP headers, can override built in default headers", OFFSET(headers), AV_OPT_TYPE_STRING, { .str = NULL }, 0, 0, D | E },
141 { "content_type", "set a specific content type for the POST messages", OFFSET(content_type), AV_OPT_TYPE_STRING, { .str = NULL }, 0, 0, D | E },
142 { "user_agent", "override User-Agent header", OFFSET(user_agent), AV_OPT_TYPE_STRING, { .str = DEFAULT_USER_AGENT }, 0, 0, D },
143 { "referer", "override referer header", OFFSET(referer), AV_OPT_TYPE_STRING, { .str = NULL }, 0, 0, D },
144 #if FF_API_HTTP_USER_AGENT
145 { "user-agent", "use the \"user_agent\" option instead", OFFSET(user_agent_deprecated), AV_OPT_TYPE_STRING, { .str = DEFAULT_USER_AGENT }, 0, 0, D|AV_OPT_FLAG_DEPRECATED },
147 { "multiple_requests", "use persistent connections", OFFSET(multiple_requests), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, D | E },
148 { "post_data", "set custom HTTP post data", OFFSET(post_data), AV_OPT_TYPE_BINARY, .flags = D | E },
149 { "mime_type", "export the MIME type", OFFSET(mime_type), AV_OPT_TYPE_STRING, { .str = NULL }, 0, 0, AV_OPT_FLAG_EXPORT | AV_OPT_FLAG_READONLY },
150 { "http_version", "export the http response version", OFFSET(http_version), AV_OPT_TYPE_STRING, { .str = NULL }, 0, 0, AV_OPT_FLAG_EXPORT | AV_OPT_FLAG_READONLY },
151 { "cookies", "set cookies to be sent in applicable future requests, use newline delimited Set-Cookie HTTP field value syntax", OFFSET(cookies), AV_OPT_TYPE_STRING, { .str = NULL }, 0, 0, D },
152 { "icy", "request ICY metadata", OFFSET(icy), AV_OPT_TYPE_BOOL, { .i64 = 1 }, 0, 1, D },
153 { "icy_metadata_headers", "return ICY metadata headers", OFFSET(icy_metadata_headers), AV_OPT_TYPE_STRING, { .str = NULL }, 0, 0, AV_OPT_FLAG_EXPORT },
154 { "icy_metadata_packet", "return current ICY metadata packet", OFFSET(icy_metadata_packet), AV_OPT_TYPE_STRING, { .str = NULL }, 0, 0, AV_OPT_FLAG_EXPORT },
155 { "metadata", "metadata read from the bitstream", OFFSET(metadata), AV_OPT_TYPE_DICT, {0}, 0, 0, AV_OPT_FLAG_EXPORT },
156 { "auth_type", "HTTP authentication type", OFFSET(auth_state.auth_type), AV_OPT_TYPE_INT, { .i64 = HTTP_AUTH_NONE }, HTTP_AUTH_NONE, HTTP_AUTH_BASIC, D | E, "auth_type"},
157 { "none", "No auth method set, autodetect", 0, AV_OPT_TYPE_CONST, { .i64 = HTTP_AUTH_NONE }, 0, 0, D | E, "auth_type"},
158 { "basic", "HTTP basic authentication", 0, AV_OPT_TYPE_CONST, { .i64 = HTTP_AUTH_BASIC }, 0, 0, D | E, "auth_type"},
159 { "send_expect_100", "Force sending an Expect: 100-continue header for POST", OFFSET(send_expect_100), AV_OPT_TYPE_BOOL, { .i64 = -1 }, -1, 1, E },
160 { "location", "The actual location of the data received", OFFSET(location), AV_OPT_TYPE_STRING, { .str = NULL }, 0, 0, D | E },
161 { "offset", "initial byte offset", OFFSET(off), AV_OPT_TYPE_INT64, { .i64 = 0 }, 0, INT64_MAX, D },
162 { "end_offset", "try to limit the request to bytes preceding this offset", OFFSET(end_off), AV_OPT_TYPE_INT64, { .i64 = 0 }, 0, INT64_MAX, D },
163 { "method", "Override the HTTP method or set the expected HTTP method from a client", OFFSET(method), AV_OPT_TYPE_STRING, { .str = NULL }, 0, 0, D | E },
164 { "reconnect", "auto reconnect after disconnect before EOF", OFFSET(reconnect), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, D },
165 { "reconnect_at_eof", "auto reconnect at EOF", OFFSET(reconnect_at_eof), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, D },
166 { "reconnect_streamed", "auto reconnect streamed / non seekable streams", OFFSET(reconnect_streamed), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, D },
167 { "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 },
168 { "listen", "listen on HTTP", OFFSET(listen), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 2, D | E },
169 { "resource", "The resource requested by a client", OFFSET(resource), AV_OPT_TYPE_STRING, { .str = NULL }, 0, 0, E },
170 { "reply_code", "The http status code to return to a client", OFFSET(reply_code), AV_OPT_TYPE_INT, { .i64 = 200}, INT_MIN, 599, E},
174 static int http_connect(URLContext *h, const char *path, const char *local_path,
175 const char *hoststr, const char *auth,
176 const char *proxyauth, int *new_location);
177 static int http_read_header(URLContext *h, int *new_location);
178 static int http_shutdown(URLContext *h, int flags);
180 void ff_http_init_auth_state(URLContext *dest, const URLContext *src)
182 memcpy(&((HTTPContext *)dest->priv_data)->auth_state,
183 &((HTTPContext *)src->priv_data)->auth_state,
184 sizeof(HTTPAuthState));
185 memcpy(&((HTTPContext *)dest->priv_data)->proxy_auth_state,
186 &((HTTPContext *)src->priv_data)->proxy_auth_state,
187 sizeof(HTTPAuthState));
190 static int http_open_cnx_internal(URLContext *h, AVDictionary **options)
192 const char *path, *proxy_path, *lower_proto = "tcp", *local_path;
193 char hostname[1024], hoststr[1024], proto[10];
194 char auth[1024], proxyauth[1024] = "";
195 char path1[MAX_URL_SIZE];
196 char buf[1024], urlbuf[MAX_URL_SIZE];
197 int port, use_proxy, err, location_changed = 0;
198 HTTPContext *s = h->priv_data;
200 av_url_split(proto, sizeof(proto), auth, sizeof(auth),
201 hostname, sizeof(hostname), &port,
202 path1, sizeof(path1), s->location);
203 ff_url_join(hoststr, sizeof(hoststr), NULL, NULL, hostname, port, NULL);
205 proxy_path = s->http_proxy ? s->http_proxy : getenv("http_proxy");
206 use_proxy = !ff_http_match_no_proxy(getenv("no_proxy"), hostname) &&
207 proxy_path && av_strstart(proxy_path, "http://", NULL);
209 if (!strcmp(proto, "https")) {
218 if (path1[0] == '\0')
224 /* Reassemble the request URL without auth string - we don't
225 * want to leak the auth to the proxy. */
226 ff_url_join(urlbuf, sizeof(urlbuf), proto, NULL, hostname, port, "%s",
229 av_url_split(NULL, 0, proxyauth, sizeof(proxyauth),
230 hostname, sizeof(hostname), &port, NULL, 0, proxy_path);
233 ff_url_join(buf, sizeof(buf), lower_proto, NULL, hostname, port, NULL);
236 err = ffurl_open_whitelist(&s->hd, buf, AVIO_FLAG_READ_WRITE,
237 &h->interrupt_callback, options,
238 h->protocol_whitelist, h->protocol_blacklist, h);
243 err = http_connect(h, path, local_path, hoststr,
244 auth, proxyauth, &location_changed);
248 return location_changed;
251 /* return non zero if error */
252 static int http_open_cnx(URLContext *h, AVDictionary **options)
254 HTTPAuthType cur_auth_type, cur_proxy_auth_type;
255 HTTPContext *s = h->priv_data;
256 int location_changed, attempts = 0, redirects = 0;
258 av_dict_copy(options, s->chained_options, 0);
260 cur_auth_type = s->auth_state.auth_type;
261 cur_proxy_auth_type = s->auth_state.auth_type;
263 location_changed = http_open_cnx_internal(h, options);
264 if (location_changed < 0)
268 if (s->http_code == 401) {
269 if ((cur_auth_type == HTTP_AUTH_NONE || s->auth_state.stale) &&
270 s->auth_state.auth_type != HTTP_AUTH_NONE && attempts < 4) {
271 ffurl_closep(&s->hd);
276 if (s->http_code == 407) {
277 if ((cur_proxy_auth_type == HTTP_AUTH_NONE || s->proxy_auth_state.stale) &&
278 s->proxy_auth_state.auth_type != HTTP_AUTH_NONE && attempts < 4) {
279 ffurl_closep(&s->hd);
284 if ((s->http_code == 301 || s->http_code == 302 ||
285 s->http_code == 303 || s->http_code == 307) &&
286 location_changed == 1) {
287 /* url moved, get next */
288 ffurl_closep(&s->hd);
289 if (redirects++ >= MAX_REDIRECTS)
291 /* Restart the authentication process with the new target, which
292 * might use a different auth mechanism. */
293 memset(&s->auth_state, 0, sizeof(s->auth_state));
295 location_changed = 0;
302 ffurl_closep(&s->hd);
303 if (location_changed < 0)
304 return location_changed;
305 return ff_http_averror(s->http_code, AVERROR(EIO));
307 int ff_http_get_shutdown_status(URLContext *h)
310 HTTPContext *s = h->priv_data;
312 /* flush the receive buffer when it is write only mode */
315 read_ret = ffurl_read(s->hd, buf, sizeof(buf));
323 int ff_http_do_new_request(URLContext *h, const char *uri) {
324 return ff_http_do_new_request2(h, uri, NULL);
327 int ff_http_do_new_request2(URLContext *h, const char *uri, AVDictionary **opts)
329 HTTPContext *s = h->priv_data;
330 AVDictionary *options = NULL;
332 char hostname1[1024], hostname2[1024], proto1[10], proto2[10];
336 !(!strcmp(h->prot->name, "http") ||
337 !strcmp(h->prot->name, "https")))
338 return AVERROR(EINVAL);
340 av_url_split(proto1, sizeof(proto1), NULL, 0,
341 hostname1, sizeof(hostname1), &port1,
342 NULL, 0, s->location);
343 av_url_split(proto2, sizeof(proto2), NULL, 0,
344 hostname2, sizeof(hostname2), &port2,
346 if (port1 != port2 || strncmp(hostname1, hostname2, sizeof(hostname2)) != 0) {
347 av_log(h, AV_LOG_ERROR, "Cannot reuse HTTP connection for different host: %s:%d != %s:%d\n",
351 return AVERROR(EINVAL);
354 if (!s->end_chunked_post) {
355 ret = http_shutdown(h, h->flags);
363 s->end_chunked_post = 0;
366 s->icy_data_read = 0;
367 av_free(s->location);
368 s->location = av_strdup(uri);
370 return AVERROR(ENOMEM);
372 if ((ret = av_opt_set_dict(s, opts)) < 0)
375 av_log(s, AV_LOG_INFO, "Opening \'%s\' for %s\n", uri, h->flags & AVIO_FLAG_WRITE ? "writing" : "reading");
376 ret = http_open_cnx(h, &options);
377 av_dict_free(&options);
381 int ff_http_averror(int status_code, int default_averror)
383 switch (status_code) {
384 case 400: return AVERROR_HTTP_BAD_REQUEST;
385 case 401: return AVERROR_HTTP_UNAUTHORIZED;
386 case 403: return AVERROR_HTTP_FORBIDDEN;
387 case 404: return AVERROR_HTTP_NOT_FOUND;
390 if (status_code >= 400 && status_code <= 499)
391 return AVERROR_HTTP_OTHER_4XX;
392 else if (status_code >= 500)
393 return AVERROR_HTTP_SERVER_ERROR;
395 return default_averror;
398 static int http_write_reply(URLContext* h, int status_code)
400 int ret, body = 0, reply_code, message_len;
401 const char *reply_text, *content_type;
402 HTTPContext *s = h->priv_data;
403 char message[BUFFER_SIZE];
404 content_type = "text/plain";
408 switch (status_code) {
409 case AVERROR_HTTP_BAD_REQUEST:
412 reply_text = "Bad Request";
414 case AVERROR_HTTP_FORBIDDEN:
417 reply_text = "Forbidden";
419 case AVERROR_HTTP_NOT_FOUND:
422 reply_text = "Not Found";
427 content_type = s->content_type ? s->content_type : "application/octet-stream";
429 case AVERROR_HTTP_SERVER_ERROR:
432 reply_text = "Internal server error";
435 return AVERROR(EINVAL);
439 message_len = snprintf(message, sizeof(message),
440 "HTTP/1.1 %03d %s\r\n"
441 "Content-Type: %s\r\n"
442 "Content-Length: %"SIZE_SPECIFIER"\r\n"
449 strlen(reply_text) + 6, // 3 digit status code + space + \r\n
450 s->headers ? s->headers : "",
455 message_len = snprintf(message, sizeof(message),
456 "HTTP/1.1 %03d %s\r\n"
457 "Content-Type: %s\r\n"
458 "Transfer-Encoding: chunked\r\n"
464 s->headers ? s->headers : "");
466 av_log(h, AV_LOG_TRACE, "HTTP reply header: \n%s----\n", message);
467 if ((ret = ffurl_write(s->hd, message, message_len)) < 0)
472 static void handle_http_errors(URLContext *h, int error)
474 av_assert0(error < 0);
475 http_write_reply(h, error);
478 static int http_handshake(URLContext *c)
480 int ret, err, new_location;
481 HTTPContext *ch = c->priv_data;
482 URLContext *cl = ch->hd;
483 switch (ch->handshake_step) {
485 av_log(c, AV_LOG_TRACE, "Lower protocol\n");
486 if ((ret = ffurl_handshake(cl)) > 0)
490 ch->handshake_step = READ_HEADERS;
491 ch->is_connected_server = 1;
494 av_log(c, AV_LOG_TRACE, "Read headers\n");
495 if ((err = http_read_header(c, &new_location)) < 0) {
496 handle_http_errors(c, err);
499 ch->handshake_step = WRITE_REPLY_HEADERS;
501 case WRITE_REPLY_HEADERS:
502 av_log(c, AV_LOG_TRACE, "Reply code: %d\n", ch->reply_code);
503 if ((err = http_write_reply(c, ch->reply_code)) < 0)
505 ch->handshake_step = FINISH;
510 // this should never be reached.
511 return AVERROR(EINVAL);
514 static int http_listen(URLContext *h, const char *uri, int flags,
515 AVDictionary **options) {
516 HTTPContext *s = h->priv_data;
518 char hostname[1024], proto[10];
520 const char *lower_proto = "tcp";
522 av_url_split(proto, sizeof(proto), NULL, 0, hostname, sizeof(hostname), &port,
524 if (!strcmp(proto, "https"))
526 ff_url_join(lower_url, sizeof(lower_url), lower_proto, NULL, hostname, port,
528 if ((ret = av_dict_set_int(options, "listen", s->listen, 0)) < 0)
530 if ((ret = ffurl_open_whitelist(&s->hd, lower_url, AVIO_FLAG_READ_WRITE,
531 &h->interrupt_callback, options,
532 h->protocol_whitelist, h->protocol_blacklist, h
535 s->handshake_step = LOWER_PROTO;
536 if (s->listen == HTTP_SINGLE) { /* single client */
538 while ((ret = http_handshake(h)) > 0);
541 av_dict_free(&s->chained_options);
545 static int http_open(URLContext *h, const char *uri, int flags,
546 AVDictionary **options)
548 HTTPContext *s = h->priv_data;
551 if( s->seekable == 1 )
556 s->filesize = UINT64_MAX;
557 s->location = av_strdup(uri);
559 return AVERROR(ENOMEM);
561 av_dict_copy(&s->chained_options, *options, 0);
564 int len = strlen(s->headers);
565 if (len < 2 || strcmp("\r\n", s->headers + len - 2)) {
566 av_log(h, AV_LOG_WARNING,
567 "No trailing CRLF found in HTTP header. Adding it.\n");
568 ret = av_reallocp(&s->headers, len + 3);
571 s->headers[len] = '\r';
572 s->headers[len + 1] = '\n';
573 s->headers[len + 2] = '\0';
578 return http_listen(h, uri, flags, options);
580 ret = http_open_cnx(h, options);
582 av_dict_free(&s->chained_options);
586 static int http_accept(URLContext *s, URLContext **c)
589 HTTPContext *sc = s->priv_data;
591 URLContext *sl = sc->hd;
592 URLContext *cl = NULL;
594 av_assert0(sc->listen);
595 if ((ret = ffurl_alloc(c, s->filename, s->flags, &sl->interrupt_callback)) < 0)
597 cc = (*c)->priv_data;
598 if ((ret = ffurl_accept(sl, &cl)) < 0)
601 cc->is_multi_client = 1;
610 static int http_getc(HTTPContext *s)
613 if (s->buf_ptr >= s->buf_end) {
614 len = ffurl_read(s->hd, s->buffer, BUFFER_SIZE);
617 } else if (len == 0) {
620 s->buf_ptr = s->buffer;
621 s->buf_end = s->buffer + len;
624 return *s->buf_ptr++;
627 static int http_get_line(HTTPContext *s, char *line, int line_size)
639 if (q > line && q[-1] == '\r')
645 if ((q - line) < line_size - 1)
651 static int check_http_code(URLContext *h, int http_code, const char *end)
653 HTTPContext *s = h->priv_data;
654 /* error codes are 4xx and 5xx, but regard 401 as a success, so we
655 * don't abort until all headers have been parsed. */
656 if (http_code >= 400 && http_code < 600 &&
657 (http_code != 401 || s->auth_state.auth_type != HTTP_AUTH_NONE) &&
658 (http_code != 407 || s->proxy_auth_state.auth_type != HTTP_AUTH_NONE)) {
659 end += strspn(end, SPACE_CHARS);
660 av_log(h, AV_LOG_WARNING, "HTTP error %d %s\n", http_code, end);
661 return ff_http_averror(http_code, AVERROR(EIO));
666 static int parse_location(HTTPContext *s, const char *p)
668 char redirected_location[MAX_URL_SIZE], *new_loc;
669 ff_make_absolute_url(redirected_location, sizeof(redirected_location),
671 new_loc = av_strdup(redirected_location);
673 return AVERROR(ENOMEM);
674 av_free(s->location);
675 s->location = new_loc;
679 /* "bytes $from-$to/$document_size" */
680 static void parse_content_range(URLContext *h, const char *p)
682 HTTPContext *s = h->priv_data;
685 if (!strncmp(p, "bytes ", 6)) {
687 s->off = strtoull(p, NULL, 10);
688 if ((slash = strchr(p, '/')) && strlen(slash) > 0)
689 s->filesize = strtoull(slash + 1, NULL, 10);
691 if (s->seekable == -1 && (!s->is_akamai || s->filesize != 2147483647))
692 h->is_streamed = 0; /* we _can_ in fact seek */
695 static int parse_content_encoding(URLContext *h, const char *p)
697 if (!av_strncasecmp(p, "gzip", 4) ||
698 !av_strncasecmp(p, "deflate", 7)) {
700 HTTPContext *s = h->priv_data;
703 inflateEnd(&s->inflate_stream);
704 if (inflateInit2(&s->inflate_stream, 32 + 15) != Z_OK) {
705 av_log(h, AV_LOG_WARNING, "Error during zlib initialisation: %s\n",
706 s->inflate_stream.msg);
707 return AVERROR(ENOSYS);
709 if (zlibCompileFlags() & (1 << 17)) {
710 av_log(h, AV_LOG_WARNING,
711 "Your zlib was compiled without gzip support.\n");
712 return AVERROR(ENOSYS);
715 av_log(h, AV_LOG_WARNING,
716 "Compressed (%s) content, need zlib with gzip support\n", p);
717 return AVERROR(ENOSYS);
718 #endif /* CONFIG_ZLIB */
719 } else if (!av_strncasecmp(p, "identity", 8)) {
720 // The normal, no-encoding case (although servers shouldn't include
721 // the header at all if this is the case).
723 av_log(h, AV_LOG_WARNING, "Unknown content coding: %s\n", p);
728 // Concat all Icy- header lines
729 static int parse_icy(HTTPContext *s, const char *tag, const char *p)
731 int len = 4 + strlen(p) + strlen(tag);
732 int is_first = !s->icy_metadata_headers;
735 av_dict_set(&s->metadata, tag, p, 0);
737 if (s->icy_metadata_headers)
738 len += strlen(s->icy_metadata_headers);
740 if ((ret = av_reallocp(&s->icy_metadata_headers, len)) < 0)
744 *s->icy_metadata_headers = '\0';
746 av_strlcatf(s->icy_metadata_headers, len, "%s: %s\n", tag, p);
751 static int parse_set_cookie_expiry_time(const char *exp_str, struct tm *buf)
753 char exp_buf[MAX_EXPIRY];
754 int i, j, exp_buf_len = MAX_EXPIRY-1;
757 // strip off any punctuation or whitespace
758 for (i = 0, j = 0; exp_str[i] != '\0' && j < exp_buf_len; i++) {
759 if ((exp_str[i] >= '0' && exp_str[i] <= '9') ||
760 (exp_str[i] >= 'A' && exp_str[i] <= 'Z') ||
761 (exp_str[i] >= 'a' && exp_str[i] <= 'z')) {
762 exp_buf[j] = exp_str[i];
769 // move the string beyond the day of week
770 while ((*expiry < '0' || *expiry > '9') && *expiry != '\0')
773 return av_small_strptime(expiry, "%d%b%Y%H%M%S", buf) ? 0 : AVERROR(EINVAL);
776 static int parse_set_cookie(const char *set_cookie, AVDictionary **dict)
778 char *param, *next_param, *cstr, *back;
783 if (!(cstr = av_strdup(set_cookie)))
784 return AVERROR(EINVAL);
786 // strip any trailing whitespace
787 back = &cstr[strlen(cstr)-1];
788 while (strchr(WHITESPACES, *back)) {
796 while ((param = av_strtok(next_param, ";", &next_param))) {
798 param += strspn(param, WHITESPACES);
799 if ((name = av_strtok(param, "=", &value))) {
800 if (av_dict_set(dict, name, value, 0) < 0) {
811 static int parse_cookie(HTTPContext *s, const char *p, AVDictionary **cookies)
813 AVDictionary *new_params = NULL;
814 AVDictionaryEntry *e, *cookie_entry;
817 // ensure the cookie is parsable
818 if (parse_set_cookie(p, &new_params))
821 // if there is no cookie value there is nothing to parse
822 cookie_entry = av_dict_get(new_params, "", NULL, AV_DICT_IGNORE_SUFFIX);
823 if (!cookie_entry || !cookie_entry->value) {
824 av_dict_free(&new_params);
828 // ensure the cookie is not expired or older than an existing value
829 if ((e = av_dict_get(new_params, "expires", NULL, 0)) && e->value) {
830 struct tm new_tm = {0};
831 if (!parse_set_cookie_expiry_time(e->value, &new_tm)) {
832 AVDictionaryEntry *e2;
834 // if the cookie has already expired ignore it
835 if (av_timegm(&new_tm) < av_gettime() / 1000000) {
836 av_dict_free(&new_params);
840 // only replace an older cookie with the same name
841 e2 = av_dict_get(*cookies, cookie_entry->key, NULL, 0);
842 if (e2 && e2->value) {
843 AVDictionary *old_params = NULL;
844 if (!parse_set_cookie(p, &old_params)) {
845 e2 = av_dict_get(old_params, "expires", NULL, 0);
846 if (e2 && e2->value) {
847 struct tm old_tm = {0};
848 if (!parse_set_cookie_expiry_time(e->value, &old_tm)) {
849 if (av_timegm(&new_tm) < av_timegm(&old_tm)) {
850 av_dict_free(&new_params);
851 av_dict_free(&old_params);
857 av_dict_free(&old_params);
861 av_dict_free(&new_params);
863 // duplicate the cookie name (dict will dupe the value)
864 if (!(eql = strchr(p, '='))) return AVERROR(EINVAL);
865 if (!(name = av_strndup(p, eql - p))) return AVERROR(ENOMEM);
867 // add the cookie to the dictionary
868 av_dict_set(cookies, name, eql, AV_DICT_DONT_STRDUP_KEY);
873 static int cookie_string(AVDictionary *dict, char **cookies)
875 AVDictionaryEntry *e = NULL;
878 // determine how much memory is needed for the cookies string
879 while (e = av_dict_get(dict, "", e, AV_DICT_IGNORE_SUFFIX))
880 len += strlen(e->key) + strlen(e->value) + 1;
882 // reallocate the cookies
884 if (*cookies) av_free(*cookies);
885 *cookies = av_malloc(len);
886 if (!*cookies) return AVERROR(ENOMEM);
889 // write out the cookies
890 while (e = av_dict_get(dict, "", e, AV_DICT_IGNORE_SUFFIX))
891 av_strlcatf(*cookies, len, "%s%s\n", e->key, e->value);
896 static int process_line(URLContext *h, char *line, int line_count,
899 HTTPContext *s = h->priv_data;
900 const char *auto_method = h->flags & AVIO_FLAG_READ ? "POST" : "GET";
901 char *tag, *p, *end, *method, *resource, *version;
905 if (line[0] == '\0') {
911 if (line_count == 0) {
912 if (s->is_connected_server) {
915 while (*p && !av_isspace(*p))
918 av_log(h, AV_LOG_TRACE, "Received method: %s\n", method);
920 if (av_strcasecmp(s->method, method)) {
921 av_log(h, AV_LOG_ERROR, "Received and expected HTTP method do not match. (%s expected, %s received)\n",
923 return ff_http_averror(400, AVERROR(EIO));
926 // use autodetected HTTP method to expect
927 av_log(h, AV_LOG_TRACE, "Autodetected %s HTTP method\n", auto_method);
928 if (av_strcasecmp(auto_method, method)) {
929 av_log(h, AV_LOG_ERROR, "Received and autodetected HTTP method did not match "
930 "(%s autodetected %s received)\n", auto_method, method);
931 return ff_http_averror(400, AVERROR(EIO));
933 if (!(s->method = av_strdup(method)))
934 return AVERROR(ENOMEM);
938 while (av_isspace(*p))
941 while (*p && !av_isspace(*p))
944 av_log(h, AV_LOG_TRACE, "Requested resource: %s\n", resource);
945 if (!(s->resource = av_strdup(resource)))
946 return AVERROR(ENOMEM);
949 while (av_isspace(*p))
952 while (*p && !av_isspace(*p))
955 if (av_strncasecmp(version, "HTTP/", 5)) {
956 av_log(h, AV_LOG_ERROR, "Malformed HTTP version string.\n");
957 return ff_http_averror(400, AVERROR(EIO));
959 av_log(h, AV_LOG_TRACE, "HTTP version string: %s\n", version);
961 if (av_strncasecmp(p, "HTTP/1.0", 8) == 0)
963 while (*p != '/' && *p != '\0')
967 av_freep(&s->http_version);
968 s->http_version = av_strndup(p, 3);
969 while (!av_isspace(*p) && *p != '\0')
971 while (av_isspace(*p))
973 s->http_code = strtol(p, &end, 10);
975 av_log(h, AV_LOG_TRACE, "http_code=%d\n", s->http_code);
977 if ((ret = check_http_code(h, s->http_code, end)) < 0)
981 while (*p != '\0' && *p != ':')
989 while (av_isspace(*p))
991 if (!av_strcasecmp(tag, "Location")) {
992 if ((ret = parse_location(s, p)) < 0)
995 } else if (!av_strcasecmp(tag, "Content-Length") &&
996 s->filesize == UINT64_MAX) {
997 s->filesize = strtoull(p, NULL, 10);
998 } else if (!av_strcasecmp(tag, "Content-Range")) {
999 parse_content_range(h, p);
1000 } else if (!av_strcasecmp(tag, "Accept-Ranges") &&
1001 !strncmp(p, "bytes", 5) &&
1002 s->seekable == -1) {
1004 } else if (!av_strcasecmp(tag, "Transfer-Encoding") &&
1005 !av_strncasecmp(p, "chunked", 7)) {
1006 s->filesize = UINT64_MAX;
1008 } else if (!av_strcasecmp(tag, "WWW-Authenticate")) {
1009 ff_http_auth_handle_header(&s->auth_state, tag, p);
1010 } else if (!av_strcasecmp(tag, "Authentication-Info")) {
1011 ff_http_auth_handle_header(&s->auth_state, tag, p);
1012 } else if (!av_strcasecmp(tag, "Proxy-Authenticate")) {
1013 ff_http_auth_handle_header(&s->proxy_auth_state, tag, p);
1014 } else if (!av_strcasecmp(tag, "Connection")) {
1015 if (!strcmp(p, "close"))
1017 } else if (!av_strcasecmp(tag, "Server")) {
1018 if (!av_strcasecmp(p, "AkamaiGHost")) {
1020 } else if (!av_strncasecmp(p, "MediaGateway", 12)) {
1021 s->is_mediagateway = 1;
1023 } else if (!av_strcasecmp(tag, "Content-Type")) {
1024 av_free(s->mime_type);
1025 s->mime_type = av_strdup(p);
1026 } else if (!av_strcasecmp(tag, "Set-Cookie")) {
1027 if (parse_cookie(s, p, &s->cookie_dict))
1028 av_log(h, AV_LOG_WARNING, "Unable to parse '%s'\n", p);
1029 } else if (!av_strcasecmp(tag, "Icy-MetaInt")) {
1030 s->icy_metaint = strtoull(p, NULL, 10);
1031 } else if (!av_strncasecmp(tag, "Icy-", 4)) {
1032 if ((ret = parse_icy(s, tag, p)) < 0)
1034 } else if (!av_strcasecmp(tag, "Content-Encoding")) {
1035 if ((ret = parse_content_encoding(h, p)) < 0)
1043 * Create a string containing cookie values for use as a HTTP cookie header
1044 * field value for a particular path and domain from the cookie values stored in
1045 * the HTTP protocol context. The cookie string is stored in *cookies, and may
1046 * be NULL if there are no valid cookies.
1048 * @return a negative value if an error condition occurred, 0 otherwise
1050 static int get_cookies(HTTPContext *s, char **cookies, const char *path,
1053 // cookie strings will look like Set-Cookie header field values. Multiple
1054 // Set-Cookie fields will result in multiple values delimited by a newline
1056 char *cookie, *set_cookies, *next;
1058 // destroy any cookies in the dictionary.
1059 av_dict_free(&s->cookie_dict);
1064 next = set_cookies = av_strdup(s->cookies);
1066 return AVERROR(ENOMEM);
1069 while ((cookie = av_strtok(next, "\n", &next)) && !ret) {
1070 AVDictionary *cookie_params = NULL;
1071 AVDictionaryEntry *cookie_entry, *e;
1073 // store the cookie in a dict in case it is updated in the response
1074 if (parse_cookie(s, cookie, &s->cookie_dict))
1075 av_log(s, AV_LOG_WARNING, "Unable to parse '%s'\n", cookie);
1077 // continue on to the next cookie if this one cannot be parsed
1078 if (parse_set_cookie(cookie, &cookie_params))
1081 // if the cookie has no value, skip it
1082 cookie_entry = av_dict_get(cookie_params, "", NULL, AV_DICT_IGNORE_SUFFIX);
1083 if (!cookie_entry || !cookie_entry->value)
1086 // if the cookie has expired, don't add it
1087 if ((e = av_dict_get(cookie_params, "expires", NULL, 0)) && e->value) {
1088 struct tm tm_buf = {0};
1089 if (!parse_set_cookie_expiry_time(e->value, &tm_buf)) {
1090 if (av_timegm(&tm_buf) < av_gettime() / 1000000)
1095 // if no domain in the cookie assume it appied to this request
1096 if ((e = av_dict_get(cookie_params, "domain", NULL, 0)) && e->value) {
1097 // find the offset comparison is on the min domain (b.com, not a.b.com)
1098 int domain_offset = strlen(domain) - strlen(e->value);
1099 if (domain_offset < 0)
1102 // match the cookie domain
1103 if (av_strcasecmp(&domain[domain_offset], e->value))
1107 // ensure this cookie matches the path
1108 e = av_dict_get(cookie_params, "path", NULL, 0);
1109 if (!e || av_strncasecmp(path, e->value, strlen(e->value)))
1112 // cookie parameters match, so copy the value
1114 *cookies = av_asprintf("%s=%s", cookie_entry->key, cookie_entry->value);
1116 char *tmp = *cookies;
1117 *cookies = av_asprintf("%s; %s=%s", tmp, cookie_entry->key, cookie_entry->value);
1121 ret = AVERROR(ENOMEM);
1124 av_dict_free(&cookie_params);
1127 av_free(set_cookies);
1132 static inline int has_header(const char *str, const char *header)
1134 /* header + 2 to skip over CRLF prefix. (make sure you have one!) */
1137 return av_stristart(str, header + 2, NULL) || av_stristr(str, header);
1140 static int http_read_header(URLContext *h, int *new_location)
1142 HTTPContext *s = h->priv_data;
1143 char line[MAX_URL_SIZE];
1146 s->chunksize = UINT64_MAX;
1149 if ((err = http_get_line(s, line, sizeof(line))) < 0)
1152 av_log(h, AV_LOG_TRACE, "header='%s'\n", line);
1154 err = process_line(h, line, s->line_count, new_location);
1162 if (s->seekable == -1 && s->is_mediagateway && s->filesize == 2000000000)
1163 h->is_streamed = 1; /* we can in fact _not_ seek */
1165 // add any new cookies into the existing cookie string
1166 cookie_string(s->cookie_dict, &s->cookies);
1167 av_dict_free(&s->cookie_dict);
1172 static int http_connect(URLContext *h, const char *path, const char *local_path,
1173 const char *hoststr, const char *auth,
1174 const char *proxyauth, int *new_location)
1176 HTTPContext *s = h->priv_data;
1178 char headers[HTTP_HEADERS_SIZE] = "";
1179 char *authstr = NULL, *proxyauthstr = NULL;
1180 uint64_t off = s->off;
1183 int send_expect_100 = 0;
1186 /* send http header */
1187 post = h->flags & AVIO_FLAG_WRITE;
1190 /* force POST method and disable chunked encoding when
1191 * custom HTTP post data is set */
1193 s->chunked_post = 0;
1199 method = post ? "POST" : "GET";
1201 authstr = ff_http_auth_create_response(&s->auth_state, auth,
1202 local_path, method);
1203 proxyauthstr = ff_http_auth_create_response(&s->proxy_auth_state, proxyauth,
1204 local_path, method);
1206 if (post && !s->post_data) {
1207 if (s->send_expect_100 != -1) {
1208 send_expect_100 = s->send_expect_100;
1210 send_expect_100 = 0;
1211 /* The user has supplied authentication but we don't know the auth type,
1212 * send Expect: 100-continue to get the 401 response including the
1213 * WWW-Authenticate header, or an 100 continue if no auth actually
1215 if (auth && *auth &&
1216 s->auth_state.auth_type == HTTP_AUTH_NONE &&
1217 s->http_code != 401)
1218 send_expect_100 = 1;
1222 #if FF_API_HTTP_USER_AGENT
1223 if (strcmp(s->user_agent_deprecated, DEFAULT_USER_AGENT)) {
1224 s->user_agent = av_strdup(s->user_agent_deprecated);
1227 /* set default headers if needed */
1228 if (!has_header(s->headers, "\r\nUser-Agent: "))
1229 len += av_strlcatf(headers + len, sizeof(headers) - len,
1230 "User-Agent: %s\r\n", s->user_agent);
1232 /* set default headers if needed */
1233 if (!has_header(s->headers, "\r\nReferer: "))
1234 len += av_strlcatf(headers + len, sizeof(headers) - len,
1235 "Referer: %s\r\n", s->referer);
1237 if (!has_header(s->headers, "\r\nAccept: "))
1238 len += av_strlcpy(headers + len, "Accept: */*\r\n",
1239 sizeof(headers) - len);
1240 // Note: we send this on purpose even when s->off is 0 when we're probing,
1241 // since it allows us to detect more reliably if a (non-conforming)
1242 // server supports seeking by analysing the reply headers.
1243 if (!has_header(s->headers, "\r\nRange: ") && !post && (s->off > 0 || s->end_off || s->seekable == -1)) {
1244 len += av_strlcatf(headers + len, sizeof(headers) - len,
1245 "Range: bytes=%"PRIu64"-", s->off);
1247 len += av_strlcatf(headers + len, sizeof(headers) - len,
1248 "%"PRId64, s->end_off - 1);
1249 len += av_strlcpy(headers + len, "\r\n",
1250 sizeof(headers) - len);
1252 if (send_expect_100 && !has_header(s->headers, "\r\nExpect: "))
1253 len += av_strlcatf(headers + len, sizeof(headers) - len,
1254 "Expect: 100-continue\r\n");
1256 if (!has_header(s->headers, "\r\nConnection: ")) {
1257 if (s->multiple_requests)
1258 len += av_strlcpy(headers + len, "Connection: keep-alive\r\n",
1259 sizeof(headers) - len);
1261 len += av_strlcpy(headers + len, "Connection: close\r\n",
1262 sizeof(headers) - len);
1265 if (!has_header(s->headers, "\r\nHost: "))
1266 len += av_strlcatf(headers + len, sizeof(headers) - len,
1267 "Host: %s\r\n", hoststr);
1268 if (!has_header(s->headers, "\r\nContent-Length: ") && s->post_data)
1269 len += av_strlcatf(headers + len, sizeof(headers) - len,
1270 "Content-Length: %d\r\n", s->post_datalen);
1272 if (!has_header(s->headers, "\r\nContent-Type: ") && s->content_type)
1273 len += av_strlcatf(headers + len, sizeof(headers) - len,
1274 "Content-Type: %s\r\n", s->content_type);
1275 if (!has_header(s->headers, "\r\nCookie: ") && s->cookies) {
1276 char *cookies = NULL;
1277 if (!get_cookies(s, &cookies, path, hoststr) && cookies) {
1278 len += av_strlcatf(headers + len, sizeof(headers) - len,
1279 "Cookie: %s\r\n", cookies);
1283 if (!has_header(s->headers, "\r\nIcy-MetaData: ") && s->icy)
1284 len += av_strlcatf(headers + len, sizeof(headers) - len,
1285 "Icy-MetaData: %d\r\n", 1);
1287 /* now add in custom headers */
1289 av_strlcpy(headers + len, s->headers, sizeof(headers) - len);
1291 ret = snprintf(s->buffer, sizeof(s->buffer),
1292 "%s %s HTTP/1.1\r\n"
1300 post && s->chunked_post ? "Transfer-Encoding: chunked\r\n" : "",
1302 authstr ? authstr : "",
1303 proxyauthstr ? "Proxy-" : "", proxyauthstr ? proxyauthstr : "");
1305 av_log(h, AV_LOG_DEBUG, "request: %s\n", s->buffer);
1307 if (strlen(headers) + 1 == sizeof(headers) ||
1308 ret >= sizeof(s->buffer)) {
1309 av_log(h, AV_LOG_ERROR, "overlong headers\n");
1310 err = AVERROR(EINVAL);
1315 if ((err = ffurl_write(s->hd, s->buffer, strlen(s->buffer))) < 0)
1319 if ((err = ffurl_write(s->hd, s->post_data, s->post_datalen)) < 0)
1322 /* init input buffer */
1323 s->buf_ptr = s->buffer;
1324 s->buf_end = s->buffer;
1327 s->icy_data_read = 0;
1328 s->filesize = UINT64_MAX;
1330 s->end_chunked_post = 0;
1335 if (post && !s->post_data && !send_expect_100) {
1336 /* Pretend that it did work. We didn't read any header yet, since
1337 * we've still to send the POST data, but the code calling this
1338 * function will check http_code after we return. */
1344 /* wait for header */
1345 err = http_read_header(h, new_location);
1352 err = (off == s->off) ? 0 : -1;
1355 av_freep(&proxyauthstr);
1359 static int http_buf_read(URLContext *h, uint8_t *buf, int size)
1361 HTTPContext *s = h->priv_data;
1364 if (s->chunksize != UINT64_MAX) {
1368 if (!s->chunksize) {
1373 if ((err = http_get_line(s, line, sizeof(line))) < 0)
1375 } while (!*line); /* skip CR LF from last chunk */
1377 s->chunksize = strtoull(line, NULL, 16);
1379 av_log(h, AV_LOG_TRACE,
1380 "Chunked encoding data size: %"PRIu64"\n",
1383 if (!s->chunksize && s->multiple_requests) {
1384 http_get_line(s, line, sizeof(line)); // read empty chunk
1388 else if (!s->chunksize) {
1389 av_log(h, AV_LOG_DEBUG, "Last chunk received, closing conn\n");
1390 ffurl_closep(&s->hd);
1393 else if (s->chunksize == UINT64_MAX) {
1394 av_log(h, AV_LOG_ERROR, "Invalid chunk size %"PRIu64"\n",
1396 return AVERROR(EINVAL);
1399 size = FFMIN(size, s->chunksize);
1402 /* read bytes from input buffer first */
1403 len = s->buf_end - s->buf_ptr;
1407 memcpy(buf, s->buf_ptr, len);
1410 uint64_t target_end = s->end_off ? s->end_off : s->filesize;
1411 if ((!s->willclose || s->chunksize == UINT64_MAX) && s->off >= target_end)
1413 len = ffurl_read(s->hd, buf, size);
1414 if (!len && (!s->willclose || s->chunksize == UINT64_MAX) && s->off < target_end) {
1415 av_log(h, AV_LOG_ERROR,
1416 "Stream ends prematurely at %"PRIu64", should be %"PRIu64"\n",
1419 return AVERROR(EIO);
1424 if (s->chunksize > 0 && s->chunksize != UINT64_MAX) {
1425 av_assert0(s->chunksize >= len);
1426 s->chunksize -= len;
1433 #define DECOMPRESS_BUF_SIZE (256 * 1024)
1434 static int http_buf_read_compressed(URLContext *h, uint8_t *buf, int size)
1436 HTTPContext *s = h->priv_data;
1439 if (!s->inflate_buffer) {
1440 s->inflate_buffer = av_malloc(DECOMPRESS_BUF_SIZE);
1441 if (!s->inflate_buffer)
1442 return AVERROR(ENOMEM);
1445 if (s->inflate_stream.avail_in == 0) {
1446 int read = http_buf_read(h, s->inflate_buffer, DECOMPRESS_BUF_SIZE);
1449 s->inflate_stream.next_in = s->inflate_buffer;
1450 s->inflate_stream.avail_in = read;
1453 s->inflate_stream.avail_out = size;
1454 s->inflate_stream.next_out = buf;
1456 ret = inflate(&s->inflate_stream, Z_SYNC_FLUSH);
1457 if (ret != Z_OK && ret != Z_STREAM_END)
1458 av_log(h, AV_LOG_WARNING, "inflate return value: %d, %s\n",
1459 ret, s->inflate_stream.msg);
1461 return size - s->inflate_stream.avail_out;
1463 #endif /* CONFIG_ZLIB */
1465 static int64_t http_seek_internal(URLContext *h, int64_t off, int whence, int force_reconnect);
1467 static int http_read_stream(URLContext *h, uint8_t *buf, int size)
1469 HTTPContext *s = h->priv_data;
1470 int err, new_location, read_ret;
1472 int reconnect_delay = 0;
1477 if (s->end_chunked_post && !s->end_header) {
1478 err = http_read_header(h, &new_location);
1485 return http_buf_read_compressed(h, buf, size);
1486 #endif /* CONFIG_ZLIB */
1487 read_ret = http_buf_read(h, buf, size);
1488 while (read_ret < 0) {
1489 uint64_t target = h->is_streamed ? 0 : s->off;
1491 if (read_ret == AVERROR_EXIT)
1494 if (h->is_streamed && !s->reconnect_streamed)
1497 if (!(s->reconnect && s->filesize > 0 && s->off < s->filesize) &&
1498 !(s->reconnect_at_eof && read_ret == AVERROR_EOF))
1501 if (reconnect_delay > s->reconnect_delay_max)
1502 return AVERROR(EIO);
1504 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));
1505 err = ff_network_sleep_interruptible(1000U*1000*reconnect_delay, &h->interrupt_callback);
1506 if (err != AVERROR(ETIMEDOUT))
1508 reconnect_delay = 1 + 2*reconnect_delay;
1509 seek_ret = http_seek_internal(h, target, SEEK_SET, 1);
1510 if (seek_ret >= 0 && seek_ret != target) {
1511 av_log(h, AV_LOG_ERROR, "Failed to reconnect at %"PRIu64".\n", target);
1515 read_ret = http_buf_read(h, buf, size);
1521 // Like http_read_stream(), but no short reads.
1522 // Assumes partial reads are an error.
1523 static int http_read_stream_all(URLContext *h, uint8_t *buf, int size)
1526 while (pos < size) {
1527 int len = http_read_stream(h, buf + pos, size - pos);
1535 static void update_metadata(URLContext *h, char *data)
1541 HTTPContext *s = h->priv_data;
1545 val = strstr(key, "='");
1548 end = strstr(val, "';");
1556 av_dict_set(&s->metadata, key, val, 0);
1557 av_log(h, AV_LOG_VERBOSE, "Metadata update for %s: %s\n", key, val);
1563 static int store_icy(URLContext *h, int size)
1565 HTTPContext *s = h->priv_data;
1566 /* until next metadata packet */
1569 if (s->icy_metaint < s->icy_data_read)
1570 return AVERROR_INVALIDDATA;
1571 remaining = s->icy_metaint - s->icy_data_read;
1574 /* The metadata packet is variable sized. It has a 1 byte header
1575 * which sets the length of the packet (divided by 16). If it's 0,
1576 * the metadata doesn't change. After the packet, icy_metaint bytes
1577 * of normal data follows. */
1579 int len = http_read_stream_all(h, &ch, 1);
1583 char data[255 * 16 + 1];
1586 ret = http_read_stream_all(h, data, len);
1590 if ((ret = av_opt_set(s, "icy_metadata_packet", data, 0)) < 0)
1592 update_metadata(h, data);
1594 s->icy_data_read = 0;
1595 remaining = s->icy_metaint;
1598 return FFMIN(size, remaining);
1601 static int http_read(URLContext *h, uint8_t *buf, int size)
1603 HTTPContext *s = h->priv_data;
1605 if (s->icy_metaint > 0) {
1606 size = store_icy(h, size);
1611 size = http_read_stream(h, buf, size);
1613 s->icy_data_read += size;
1617 /* used only when posting data */
1618 static int http_write(URLContext *h, const uint8_t *buf, int size)
1620 char temp[11] = ""; /* 32-bit hex + CRLF + nul */
1622 char crlf[] = "\r\n";
1623 HTTPContext *s = h->priv_data;
1625 if (!s->chunked_post) {
1626 /* non-chunked data is sent without any special encoding */
1627 return ffurl_write(s->hd, buf, size);
1630 /* silently ignore zero-size data since chunk encoding that would
1633 /* upload data using chunked encoding */
1634 snprintf(temp, sizeof(temp), "%x\r\n", size);
1636 if ((ret = ffurl_write(s->hd, temp, strlen(temp))) < 0 ||
1637 (ret = ffurl_write(s->hd, buf, size)) < 0 ||
1638 (ret = ffurl_write(s->hd, crlf, sizeof(crlf) - 1)) < 0)
1644 static int http_shutdown(URLContext *h, int flags)
1647 char footer[] = "0\r\n\r\n";
1648 HTTPContext *s = h->priv_data;
1650 /* signal end of chunked encoding if used */
1651 if (((flags & AVIO_FLAG_WRITE) && s->chunked_post) ||
1652 ((flags & AVIO_FLAG_READ) && s->chunked_post && s->listen)) {
1653 ret = ffurl_write(s->hd, footer, sizeof(footer) - 1);
1654 ret = ret > 0 ? 0 : ret;
1655 /* flush the receive buffer when it is write only mode */
1656 if (!(flags & AVIO_FLAG_READ)) {
1659 s->hd->flags |= AVIO_FLAG_NONBLOCK;
1660 read_ret = ffurl_read(s->hd, buf, sizeof(buf));
1661 s->hd->flags &= ~AVIO_FLAG_NONBLOCK;
1662 if (read_ret < 0 && read_ret != AVERROR(EAGAIN)) {
1663 av_log(h, AV_LOG_ERROR, "URL read error: %s\n", av_err2str(read_ret));
1667 s->end_chunked_post = 1;
1673 static int http_close(URLContext *h)
1676 HTTPContext *s = h->priv_data;
1679 inflateEnd(&s->inflate_stream);
1680 av_freep(&s->inflate_buffer);
1681 #endif /* CONFIG_ZLIB */
1683 if (s->hd && !s->end_chunked_post)
1684 /* Close the write direction by sending the end of chunked encoding. */
1685 ret = http_shutdown(h, h->flags);
1688 ffurl_closep(&s->hd);
1689 av_dict_free(&s->chained_options);
1693 static int64_t http_seek_internal(URLContext *h, int64_t off, int whence, int force_reconnect)
1695 HTTPContext *s = h->priv_data;
1696 URLContext *old_hd = s->hd;
1697 uint64_t old_off = s->off;
1698 uint8_t old_buf[BUFFER_SIZE];
1699 int old_buf_size, ret;
1700 AVDictionary *options = NULL;
1702 if (whence == AVSEEK_SIZE)
1704 else if (!force_reconnect &&
1705 ((whence == SEEK_CUR && off == 0) ||
1706 (whence == SEEK_SET && off == s->off)))
1708 else if ((s->filesize == UINT64_MAX && whence == SEEK_END))
1709 return AVERROR(ENOSYS);
1711 if (whence == SEEK_CUR)
1713 else if (whence == SEEK_END)
1715 else if (whence != SEEK_SET)
1716 return AVERROR(EINVAL);
1718 return AVERROR(EINVAL);
1721 if (s->off && h->is_streamed)
1722 return AVERROR(ENOSYS);
1724 /* do not try to make a new connection if seeking past the end of the file */
1725 if (s->end_off || s->filesize != UINT64_MAX) {
1726 uint64_t end_pos = s->end_off ? s->end_off : s->filesize;
1727 if (s->off >= end_pos)
1731 /* we save the old context in case the seek fails */
1732 old_buf_size = s->buf_end - s->buf_ptr;
1733 memcpy(old_buf, s->buf_ptr, old_buf_size);
1736 /* if it fails, continue on old connection */
1737 if ((ret = http_open_cnx(h, &options)) < 0) {
1738 av_dict_free(&options);
1739 memcpy(s->buffer, old_buf, old_buf_size);
1740 s->buf_ptr = s->buffer;
1741 s->buf_end = s->buffer + old_buf_size;
1746 av_dict_free(&options);
1747 ffurl_close(old_hd);
1751 static int64_t http_seek(URLContext *h, int64_t off, int whence)
1753 return http_seek_internal(h, off, whence, 0);
1756 static int http_get_file_handle(URLContext *h)
1758 HTTPContext *s = h->priv_data;
1759 return ffurl_get_file_handle(s->hd);
1762 static int http_get_short_seek(URLContext *h)
1764 HTTPContext *s = h->priv_data;
1765 return ffurl_get_short_seek(s->hd);
1768 #define HTTP_CLASS(flavor) \
1769 static const AVClass flavor ## _context_class = { \
1770 .class_name = # flavor, \
1771 .item_name = av_default_item_name, \
1772 .option = options, \
1773 .version = LIBAVUTIL_VERSION_INT, \
1776 #if CONFIG_HTTP_PROTOCOL
1779 const URLProtocol ff_http_protocol = {
1781 .url_open2 = http_open,
1782 .url_accept = http_accept,
1783 .url_handshake = http_handshake,
1784 .url_read = http_read,
1785 .url_write = http_write,
1786 .url_seek = http_seek,
1787 .url_close = http_close,
1788 .url_get_file_handle = http_get_file_handle,
1789 .url_get_short_seek = http_get_short_seek,
1790 .url_shutdown = http_shutdown,
1791 .priv_data_size = sizeof(HTTPContext),
1792 .priv_data_class = &http_context_class,
1793 .flags = URL_PROTOCOL_FLAG_NETWORK,
1794 .default_whitelist = "http,https,tls,rtp,tcp,udp,crypto,httpproxy,data"
1796 #endif /* CONFIG_HTTP_PROTOCOL */
1798 #if CONFIG_HTTPS_PROTOCOL
1801 const URLProtocol ff_https_protocol = {
1803 .url_open2 = http_open,
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 = &https_context_class,
1813 .flags = URL_PROTOCOL_FLAG_NETWORK,
1814 .default_whitelist = "http,https,tls,rtp,tcp,udp,crypto,httpproxy"
1816 #endif /* CONFIG_HTTPS_PROTOCOL */
1818 #if CONFIG_HTTPPROXY_PROTOCOL
1819 static int http_proxy_close(URLContext *h)
1821 HTTPContext *s = h->priv_data;
1823 ffurl_closep(&s->hd);
1827 static int http_proxy_open(URLContext *h, const char *uri, int flags)
1829 HTTPContext *s = h->priv_data;
1830 char hostname[1024], hoststr[1024];
1831 char auth[1024], pathbuf[1024], *path;
1832 char lower_url[100];
1833 int port, ret = 0, attempts = 0;
1834 HTTPAuthType cur_auth_type;
1838 if( s->seekable == 1 )
1843 av_url_split(NULL, 0, auth, sizeof(auth), hostname, sizeof(hostname), &port,
1844 pathbuf, sizeof(pathbuf), uri);
1845 ff_url_join(hoststr, sizeof(hoststr), NULL, NULL, hostname, port, NULL);
1850 ff_url_join(lower_url, sizeof(lower_url), "tcp", NULL, hostname, port,
1853 ret = ffurl_open_whitelist(&s->hd, lower_url, AVIO_FLAG_READ_WRITE,
1854 &h->interrupt_callback, NULL,
1855 h->protocol_whitelist, h->protocol_blacklist, h);
1859 authstr = ff_http_auth_create_response(&s->proxy_auth_state, auth,
1861 snprintf(s->buffer, sizeof(s->buffer),
1862 "CONNECT %s HTTP/1.1\r\n"
1864 "Connection: close\r\n"
1869 authstr ? "Proxy-" : "", authstr ? authstr : "");
1872 if ((ret = ffurl_write(s->hd, s->buffer, strlen(s->buffer))) < 0)
1875 s->buf_ptr = s->buffer;
1876 s->buf_end = s->buffer;
1878 s->filesize = UINT64_MAX;
1879 cur_auth_type = s->proxy_auth_state.auth_type;
1881 /* Note: This uses buffering, potentially reading more than the
1882 * HTTP header. If tunneling a protocol where the server starts
1883 * the conversation, we might buffer part of that here, too.
1884 * Reading that requires using the proper ffurl_read() function
1885 * on this URLContext, not using the fd directly (as the tls
1886 * protocol does). This shouldn't be an issue for tls though,
1887 * since the client starts the conversation there, so there
1888 * is no extra data that we might buffer up here.
1890 ret = http_read_header(h, &new_loc);
1895 if (s->http_code == 407 &&
1896 (cur_auth_type == HTTP_AUTH_NONE || s->proxy_auth_state.stale) &&
1897 s->proxy_auth_state.auth_type != HTTP_AUTH_NONE && attempts < 2) {
1898 ffurl_closep(&s->hd);
1902 if (s->http_code < 400)
1904 ret = ff_http_averror(s->http_code, AVERROR(EIO));
1907 http_proxy_close(h);
1911 static int http_proxy_write(URLContext *h, const uint8_t *buf, int size)
1913 HTTPContext *s = h->priv_data;
1914 return ffurl_write(s->hd, buf, size);
1917 const URLProtocol ff_httpproxy_protocol = {
1918 .name = "httpproxy",
1919 .url_open = http_proxy_open,
1920 .url_read = http_buf_read,
1921 .url_write = http_proxy_write,
1922 .url_close = http_proxy_close,
1923 .url_get_file_handle = http_get_file_handle,
1924 .priv_data_size = sizeof(HTTPContext),
1925 .flags = URL_PROTOCOL_FLAG_NETWORK,
1927 #endif /* CONFIG_HTTPPROXY_PROTOCOL */