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));
324 int ff_http_do_new_request(URLContext *h, const char *uri)
326 HTTPContext *s = h->priv_data;
327 AVDictionary *options = NULL;
329 char hostname1[1024], hostname2[1024], proto1[10], proto2[10];
333 !(!strcmp(h->prot->name, "http") ||
334 !strcmp(h->prot->name, "https")))
335 return AVERROR(EINVAL);
337 av_url_split(proto1, sizeof(proto1), NULL, 0,
338 hostname1, sizeof(hostname1), &port1,
339 NULL, 0, s->location);
340 av_url_split(proto2, sizeof(proto2), NULL, 0,
341 hostname2, sizeof(hostname2), &port2,
343 if (port1 != port2 || strncmp(hostname1, hostname2, sizeof(hostname2)) != 0) {
344 av_log(h, AV_LOG_ERROR, "Cannot reuse HTTP connection for different host: %s:%d != %s:%d\n",
348 return AVERROR(EINVAL);
351 if (!s->end_chunked_post) {
352 ret = http_shutdown(h, h->flags);
360 s->end_chunked_post = 0;
363 s->icy_data_read = 0;
364 av_free(s->location);
365 s->location = av_strdup(uri);
367 return AVERROR(ENOMEM);
369 av_log(s, AV_LOG_INFO, "Opening \'%s\' for %s\n", uri, h->flags & AVIO_FLAG_WRITE ? "writing" : "reading");
370 ret = http_open_cnx(h, &options);
371 av_dict_free(&options);
375 int ff_http_averror(int status_code, int default_averror)
377 switch (status_code) {
378 case 400: return AVERROR_HTTP_BAD_REQUEST;
379 case 401: return AVERROR_HTTP_UNAUTHORIZED;
380 case 403: return AVERROR_HTTP_FORBIDDEN;
381 case 404: return AVERROR_HTTP_NOT_FOUND;
384 if (status_code >= 400 && status_code <= 499)
385 return AVERROR_HTTP_OTHER_4XX;
386 else if (status_code >= 500)
387 return AVERROR_HTTP_SERVER_ERROR;
389 return default_averror;
392 static int http_write_reply(URLContext* h, int status_code)
394 int ret, body = 0, reply_code, message_len;
395 const char *reply_text, *content_type;
396 HTTPContext *s = h->priv_data;
397 char message[BUFFER_SIZE];
398 content_type = "text/plain";
402 switch (status_code) {
403 case AVERROR_HTTP_BAD_REQUEST:
406 reply_text = "Bad Request";
408 case AVERROR_HTTP_FORBIDDEN:
411 reply_text = "Forbidden";
413 case AVERROR_HTTP_NOT_FOUND:
416 reply_text = "Not Found";
421 content_type = s->content_type ? s->content_type : "application/octet-stream";
423 case AVERROR_HTTP_SERVER_ERROR:
426 reply_text = "Internal server error";
429 return AVERROR(EINVAL);
433 message_len = snprintf(message, sizeof(message),
434 "HTTP/1.1 %03d %s\r\n"
435 "Content-Type: %s\r\n"
436 "Content-Length: %"SIZE_SPECIFIER"\r\n"
443 strlen(reply_text) + 6, // 3 digit status code + space + \r\n
444 s->headers ? s->headers : "",
449 message_len = snprintf(message, sizeof(message),
450 "HTTP/1.1 %03d %s\r\n"
451 "Content-Type: %s\r\n"
452 "Transfer-Encoding: chunked\r\n"
458 s->headers ? s->headers : "");
460 av_log(h, AV_LOG_TRACE, "HTTP reply header: \n%s----\n", message);
461 if ((ret = ffurl_write(s->hd, message, message_len)) < 0)
466 static void handle_http_errors(URLContext *h, int error)
468 av_assert0(error < 0);
469 http_write_reply(h, error);
472 static int http_handshake(URLContext *c)
474 int ret, err, new_location;
475 HTTPContext *ch = c->priv_data;
476 URLContext *cl = ch->hd;
477 switch (ch->handshake_step) {
479 av_log(c, AV_LOG_TRACE, "Lower protocol\n");
480 if ((ret = ffurl_handshake(cl)) > 0)
484 ch->handshake_step = READ_HEADERS;
485 ch->is_connected_server = 1;
488 av_log(c, AV_LOG_TRACE, "Read headers\n");
489 if ((err = http_read_header(c, &new_location)) < 0) {
490 handle_http_errors(c, err);
493 ch->handshake_step = WRITE_REPLY_HEADERS;
495 case WRITE_REPLY_HEADERS:
496 av_log(c, AV_LOG_TRACE, "Reply code: %d\n", ch->reply_code);
497 if ((err = http_write_reply(c, ch->reply_code)) < 0)
499 ch->handshake_step = FINISH;
504 // this should never be reached.
505 return AVERROR(EINVAL);
508 static int http_listen(URLContext *h, const char *uri, int flags,
509 AVDictionary **options) {
510 HTTPContext *s = h->priv_data;
512 char hostname[1024], proto[10];
514 const char *lower_proto = "tcp";
516 av_url_split(proto, sizeof(proto), NULL, 0, hostname, sizeof(hostname), &port,
518 if (!strcmp(proto, "https"))
520 ff_url_join(lower_url, sizeof(lower_url), lower_proto, NULL, hostname, port,
522 if ((ret = av_dict_set_int(options, "listen", s->listen, 0)) < 0)
524 if ((ret = ffurl_open_whitelist(&s->hd, lower_url, AVIO_FLAG_READ_WRITE,
525 &h->interrupt_callback, options,
526 h->protocol_whitelist, h->protocol_blacklist, h
529 s->handshake_step = LOWER_PROTO;
530 if (s->listen == HTTP_SINGLE) { /* single client */
532 while ((ret = http_handshake(h)) > 0);
535 av_dict_free(&s->chained_options);
539 static int http_open(URLContext *h, const char *uri, int flags,
540 AVDictionary **options)
542 HTTPContext *s = h->priv_data;
545 if( s->seekable == 1 )
550 s->filesize = UINT64_MAX;
551 s->location = av_strdup(uri);
553 return AVERROR(ENOMEM);
555 av_dict_copy(&s->chained_options, *options, 0);
558 int len = strlen(s->headers);
559 if (len < 2 || strcmp("\r\n", s->headers + len - 2)) {
560 av_log(h, AV_LOG_WARNING,
561 "No trailing CRLF found in HTTP header. Adding it.\n");
562 ret = av_reallocp(&s->headers, len + 3);
565 s->headers[len] = '\r';
566 s->headers[len + 1] = '\n';
567 s->headers[len + 2] = '\0';
572 return http_listen(h, uri, flags, options);
574 ret = http_open_cnx(h, options);
576 av_dict_free(&s->chained_options);
580 static int http_accept(URLContext *s, URLContext **c)
583 HTTPContext *sc = s->priv_data;
585 URLContext *sl = sc->hd;
586 URLContext *cl = NULL;
588 av_assert0(sc->listen);
589 if ((ret = ffurl_alloc(c, s->filename, s->flags, &sl->interrupt_callback)) < 0)
591 cc = (*c)->priv_data;
592 if ((ret = ffurl_accept(sl, &cl)) < 0)
595 cc->is_multi_client = 1;
604 static int http_getc(HTTPContext *s)
607 if (s->buf_ptr >= s->buf_end) {
608 len = ffurl_read(s->hd, s->buffer, BUFFER_SIZE);
611 } else if (len == 0) {
614 s->buf_ptr = s->buffer;
615 s->buf_end = s->buffer + len;
618 return *s->buf_ptr++;
621 static int http_get_line(HTTPContext *s, char *line, int line_size)
633 if (q > line && q[-1] == '\r')
639 if ((q - line) < line_size - 1)
645 static int check_http_code(URLContext *h, int http_code, const char *end)
647 HTTPContext *s = h->priv_data;
648 /* error codes are 4xx and 5xx, but regard 401 as a success, so we
649 * don't abort until all headers have been parsed. */
650 if (http_code >= 400 && http_code < 600 &&
651 (http_code != 401 || s->auth_state.auth_type != HTTP_AUTH_NONE) &&
652 (http_code != 407 || s->proxy_auth_state.auth_type != HTTP_AUTH_NONE)) {
653 end += strspn(end, SPACE_CHARS);
654 av_log(h, AV_LOG_WARNING, "HTTP error %d %s\n", http_code, end);
655 return ff_http_averror(http_code, AVERROR(EIO));
660 static int parse_location(HTTPContext *s, const char *p)
662 char redirected_location[MAX_URL_SIZE], *new_loc;
663 ff_make_absolute_url(redirected_location, sizeof(redirected_location),
665 new_loc = av_strdup(redirected_location);
667 return AVERROR(ENOMEM);
668 av_free(s->location);
669 s->location = new_loc;
673 /* "bytes $from-$to/$document_size" */
674 static void parse_content_range(URLContext *h, const char *p)
676 HTTPContext *s = h->priv_data;
679 if (!strncmp(p, "bytes ", 6)) {
681 s->off = strtoull(p, NULL, 10);
682 if ((slash = strchr(p, '/')) && strlen(slash) > 0)
683 s->filesize = strtoull(slash + 1, NULL, 10);
685 if (s->seekable == -1 && (!s->is_akamai || s->filesize != 2147483647))
686 h->is_streamed = 0; /* we _can_ in fact seek */
689 static int parse_content_encoding(URLContext *h, const char *p)
691 if (!av_strncasecmp(p, "gzip", 4) ||
692 !av_strncasecmp(p, "deflate", 7)) {
694 HTTPContext *s = h->priv_data;
697 inflateEnd(&s->inflate_stream);
698 if (inflateInit2(&s->inflate_stream, 32 + 15) != Z_OK) {
699 av_log(h, AV_LOG_WARNING, "Error during zlib initialisation: %s\n",
700 s->inflate_stream.msg);
701 return AVERROR(ENOSYS);
703 if (zlibCompileFlags() & (1 << 17)) {
704 av_log(h, AV_LOG_WARNING,
705 "Your zlib was compiled without gzip support.\n");
706 return AVERROR(ENOSYS);
709 av_log(h, AV_LOG_WARNING,
710 "Compressed (%s) content, need zlib with gzip support\n", p);
711 return AVERROR(ENOSYS);
712 #endif /* CONFIG_ZLIB */
713 } else if (!av_strncasecmp(p, "identity", 8)) {
714 // The normal, no-encoding case (although servers shouldn't include
715 // the header at all if this is the case).
717 av_log(h, AV_LOG_WARNING, "Unknown content coding: %s\n", p);
722 // Concat all Icy- header lines
723 static int parse_icy(HTTPContext *s, const char *tag, const char *p)
725 int len = 4 + strlen(p) + strlen(tag);
726 int is_first = !s->icy_metadata_headers;
729 av_dict_set(&s->metadata, tag, p, 0);
731 if (s->icy_metadata_headers)
732 len += strlen(s->icy_metadata_headers);
734 if ((ret = av_reallocp(&s->icy_metadata_headers, len)) < 0)
738 *s->icy_metadata_headers = '\0';
740 av_strlcatf(s->icy_metadata_headers, len, "%s: %s\n", tag, p);
745 static int parse_set_cookie_expiry_time(const char *exp_str, struct tm *buf)
747 char exp_buf[MAX_EXPIRY];
748 int i, j, exp_buf_len = MAX_EXPIRY-1;
751 // strip off any punctuation or whitespace
752 for (i = 0, j = 0; exp_str[i] != '\0' && j < exp_buf_len; i++) {
753 if ((exp_str[i] >= '0' && exp_str[i] <= '9') ||
754 (exp_str[i] >= 'A' && exp_str[i] <= 'Z') ||
755 (exp_str[i] >= 'a' && exp_str[i] <= 'z')) {
756 exp_buf[j] = exp_str[i];
763 // move the string beyond the day of week
764 while ((*expiry < '0' || *expiry > '9') && *expiry != '\0')
767 return av_small_strptime(expiry, "%d%b%Y%H%M%S", buf) ? 0 : AVERROR(EINVAL);
770 static int parse_set_cookie(const char *set_cookie, AVDictionary **dict)
772 char *param, *next_param, *cstr, *back;
777 if (!(cstr = av_strdup(set_cookie)))
778 return AVERROR(EINVAL);
780 // strip any trailing whitespace
781 back = &cstr[strlen(cstr)-1];
782 while (strchr(WHITESPACES, *back)) {
790 while ((param = av_strtok(next_param, ";", &next_param))) {
792 param += strspn(param, WHITESPACES);
793 if ((name = av_strtok(param, "=", &value))) {
794 if (av_dict_set(dict, name, value, 0) < 0) {
805 static int parse_cookie(HTTPContext *s, const char *p, AVDictionary **cookies)
807 AVDictionary *new_params = NULL;
808 AVDictionaryEntry *e, *cookie_entry;
811 // ensure the cookie is parsable
812 if (parse_set_cookie(p, &new_params))
815 // if there is no cookie value there is nothing to parse
816 cookie_entry = av_dict_get(new_params, "", NULL, AV_DICT_IGNORE_SUFFIX);
817 if (!cookie_entry || !cookie_entry->value) {
818 av_dict_free(&new_params);
822 // ensure the cookie is not expired or older than an existing value
823 if ((e = av_dict_get(new_params, "expires", NULL, 0)) && e->value) {
824 struct tm new_tm = {0};
825 if (!parse_set_cookie_expiry_time(e->value, &new_tm)) {
826 AVDictionaryEntry *e2;
828 // if the cookie has already expired ignore it
829 if (av_timegm(&new_tm) < av_gettime() / 1000000) {
830 av_dict_free(&new_params);
834 // only replace an older cookie with the same name
835 e2 = av_dict_get(*cookies, cookie_entry->key, NULL, 0);
836 if (e2 && e2->value) {
837 AVDictionary *old_params = NULL;
838 if (!parse_set_cookie(p, &old_params)) {
839 e2 = av_dict_get(old_params, "expires", NULL, 0);
840 if (e2 && e2->value) {
841 struct tm old_tm = {0};
842 if (!parse_set_cookie_expiry_time(e->value, &old_tm)) {
843 if (av_timegm(&new_tm) < av_timegm(&old_tm)) {
844 av_dict_free(&new_params);
845 av_dict_free(&old_params);
851 av_dict_free(&old_params);
855 av_dict_free(&new_params);
857 // duplicate the cookie name (dict will dupe the value)
858 if (!(eql = strchr(p, '='))) return AVERROR(EINVAL);
859 if (!(name = av_strndup(p, eql - p))) return AVERROR(ENOMEM);
861 // add the cookie to the dictionary
862 av_dict_set(cookies, name, eql, AV_DICT_DONT_STRDUP_KEY);
867 static int cookie_string(AVDictionary *dict, char **cookies)
869 AVDictionaryEntry *e = NULL;
872 // determine how much memory is needed for the cookies string
873 while (e = av_dict_get(dict, "", e, AV_DICT_IGNORE_SUFFIX))
874 len += strlen(e->key) + strlen(e->value) + 1;
876 // reallocate the cookies
878 if (*cookies) av_free(*cookies);
879 *cookies = av_malloc(len);
880 if (!*cookies) return AVERROR(ENOMEM);
883 // write out the cookies
884 while (e = av_dict_get(dict, "", e, AV_DICT_IGNORE_SUFFIX))
885 av_strlcatf(*cookies, len, "%s%s\n", e->key, e->value);
890 static int process_line(URLContext *h, char *line, int line_count,
893 HTTPContext *s = h->priv_data;
894 const char *auto_method = h->flags & AVIO_FLAG_READ ? "POST" : "GET";
895 char *tag, *p, *end, *method, *resource, *version;
899 if (line[0] == '\0') {
905 if (line_count == 0) {
906 if (s->is_connected_server) {
909 while (*p && !av_isspace(*p))
912 av_log(h, AV_LOG_TRACE, "Received method: %s\n", method);
914 if (av_strcasecmp(s->method, method)) {
915 av_log(h, AV_LOG_ERROR, "Received and expected HTTP method do not match. (%s expected, %s received)\n",
917 return ff_http_averror(400, AVERROR(EIO));
920 // use autodetected HTTP method to expect
921 av_log(h, AV_LOG_TRACE, "Autodetected %s HTTP method\n", auto_method);
922 if (av_strcasecmp(auto_method, method)) {
923 av_log(h, AV_LOG_ERROR, "Received and autodetected HTTP method did not match "
924 "(%s autodetected %s received)\n", auto_method, method);
925 return ff_http_averror(400, AVERROR(EIO));
927 if (!(s->method = av_strdup(method)))
928 return AVERROR(ENOMEM);
932 while (av_isspace(*p))
935 while (*p && !av_isspace(*p))
938 av_log(h, AV_LOG_TRACE, "Requested resource: %s\n", resource);
939 if (!(s->resource = av_strdup(resource)))
940 return AVERROR(ENOMEM);
943 while (av_isspace(*p))
946 while (*p && !av_isspace(*p))
949 if (av_strncasecmp(version, "HTTP/", 5)) {
950 av_log(h, AV_LOG_ERROR, "Malformed HTTP version string.\n");
951 return ff_http_averror(400, AVERROR(EIO));
953 av_log(h, AV_LOG_TRACE, "HTTP version string: %s\n", version);
955 if (av_strncasecmp(p, "HTTP/1.0", 8) == 0)
957 while (*p != '/' && *p != '\0')
961 av_freep(&s->http_version);
962 s->http_version = av_strndup(p, 3);
963 while (!av_isspace(*p) && *p != '\0')
965 while (av_isspace(*p))
967 s->http_code = strtol(p, &end, 10);
969 av_log(h, AV_LOG_TRACE, "http_code=%d\n", s->http_code);
971 if ((ret = check_http_code(h, s->http_code, end)) < 0)
975 while (*p != '\0' && *p != ':')
983 while (av_isspace(*p))
985 if (!av_strcasecmp(tag, "Location")) {
986 if ((ret = parse_location(s, p)) < 0)
989 } else if (!av_strcasecmp(tag, "Content-Length") &&
990 s->filesize == UINT64_MAX) {
991 s->filesize = strtoull(p, NULL, 10);
992 } else if (!av_strcasecmp(tag, "Content-Range")) {
993 parse_content_range(h, p);
994 } else if (!av_strcasecmp(tag, "Accept-Ranges") &&
995 !strncmp(p, "bytes", 5) &&
998 } else if (!av_strcasecmp(tag, "Transfer-Encoding") &&
999 !av_strncasecmp(p, "chunked", 7)) {
1000 s->filesize = UINT64_MAX;
1002 } else if (!av_strcasecmp(tag, "WWW-Authenticate")) {
1003 ff_http_auth_handle_header(&s->auth_state, tag, p);
1004 } else if (!av_strcasecmp(tag, "Authentication-Info")) {
1005 ff_http_auth_handle_header(&s->auth_state, tag, p);
1006 } else if (!av_strcasecmp(tag, "Proxy-Authenticate")) {
1007 ff_http_auth_handle_header(&s->proxy_auth_state, tag, p);
1008 } else if (!av_strcasecmp(tag, "Connection")) {
1009 if (!strcmp(p, "close"))
1011 } else if (!av_strcasecmp(tag, "Server")) {
1012 if (!av_strcasecmp(p, "AkamaiGHost")) {
1014 } else if (!av_strncasecmp(p, "MediaGateway", 12)) {
1015 s->is_mediagateway = 1;
1017 } else if (!av_strcasecmp(tag, "Content-Type")) {
1018 av_free(s->mime_type);
1019 s->mime_type = av_strdup(p);
1020 } else if (!av_strcasecmp(tag, "Set-Cookie")) {
1021 if (parse_cookie(s, p, &s->cookie_dict))
1022 av_log(h, AV_LOG_WARNING, "Unable to parse '%s'\n", p);
1023 } else if (!av_strcasecmp(tag, "Icy-MetaInt")) {
1024 s->icy_metaint = strtoull(p, NULL, 10);
1025 } else if (!av_strncasecmp(tag, "Icy-", 4)) {
1026 if ((ret = parse_icy(s, tag, p)) < 0)
1028 } else if (!av_strcasecmp(tag, "Content-Encoding")) {
1029 if ((ret = parse_content_encoding(h, p)) < 0)
1037 * Create a string containing cookie values for use as a HTTP cookie header
1038 * field value for a particular path and domain from the cookie values stored in
1039 * the HTTP protocol context. The cookie string is stored in *cookies, and may
1040 * be NULL if there are no valid cookies.
1042 * @return a negative value if an error condition occurred, 0 otherwise
1044 static int get_cookies(HTTPContext *s, char **cookies, const char *path,
1047 // cookie strings will look like Set-Cookie header field values. Multiple
1048 // Set-Cookie fields will result in multiple values delimited by a newline
1050 char *cookie, *set_cookies, *next;
1052 // destroy any cookies in the dictionary.
1053 av_dict_free(&s->cookie_dict);
1058 next = set_cookies = av_strdup(s->cookies);
1060 return AVERROR(ENOMEM);
1063 while ((cookie = av_strtok(next, "\n", &next)) && !ret) {
1064 AVDictionary *cookie_params = NULL;
1065 AVDictionaryEntry *cookie_entry, *e;
1067 // store the cookie in a dict in case it is updated in the response
1068 if (parse_cookie(s, cookie, &s->cookie_dict))
1069 av_log(s, AV_LOG_WARNING, "Unable to parse '%s'\n", cookie);
1071 // continue on to the next cookie if this one cannot be parsed
1072 if (parse_set_cookie(cookie, &cookie_params))
1075 // if the cookie has no value, skip it
1076 cookie_entry = av_dict_get(cookie_params, "", NULL, AV_DICT_IGNORE_SUFFIX);
1077 if (!cookie_entry || !cookie_entry->value)
1080 // if the cookie has expired, don't add it
1081 if ((e = av_dict_get(cookie_params, "expires", NULL, 0)) && e->value) {
1082 struct tm tm_buf = {0};
1083 if (!parse_set_cookie_expiry_time(e->value, &tm_buf)) {
1084 if (av_timegm(&tm_buf) < av_gettime() / 1000000)
1089 // if no domain in the cookie assume it appied to this request
1090 if ((e = av_dict_get(cookie_params, "domain", NULL, 0)) && e->value) {
1091 // find the offset comparison is on the min domain (b.com, not a.b.com)
1092 int domain_offset = strlen(domain) - strlen(e->value);
1093 if (domain_offset < 0)
1096 // match the cookie domain
1097 if (av_strcasecmp(&domain[domain_offset], e->value))
1101 // ensure this cookie matches the path
1102 e = av_dict_get(cookie_params, "path", NULL, 0);
1103 if (!e || av_strncasecmp(path, e->value, strlen(e->value)))
1106 // cookie parameters match, so copy the value
1108 *cookies = av_asprintf("%s=%s", cookie_entry->key, cookie_entry->value);
1110 char *tmp = *cookies;
1111 *cookies = av_asprintf("%s; %s=%s", tmp, cookie_entry->key, cookie_entry->value);
1115 ret = AVERROR(ENOMEM);
1118 av_dict_free(&cookie_params);
1121 av_free(set_cookies);
1126 static inline int has_header(const char *str, const char *header)
1128 /* header + 2 to skip over CRLF prefix. (make sure you have one!) */
1131 return av_stristart(str, header + 2, NULL) || av_stristr(str, header);
1134 static int http_read_header(URLContext *h, int *new_location)
1136 HTTPContext *s = h->priv_data;
1137 char line[MAX_URL_SIZE];
1140 s->chunksize = UINT64_MAX;
1143 if ((err = http_get_line(s, line, sizeof(line))) < 0)
1146 av_log(h, AV_LOG_TRACE, "header='%s'\n", line);
1148 err = process_line(h, line, s->line_count, new_location);
1156 if (s->seekable == -1 && s->is_mediagateway && s->filesize == 2000000000)
1157 h->is_streamed = 1; /* we can in fact _not_ seek */
1159 // add any new cookies into the existing cookie string
1160 cookie_string(s->cookie_dict, &s->cookies);
1161 av_dict_free(&s->cookie_dict);
1166 static int http_connect(URLContext *h, const char *path, const char *local_path,
1167 const char *hoststr, const char *auth,
1168 const char *proxyauth, int *new_location)
1170 HTTPContext *s = h->priv_data;
1172 char headers[HTTP_HEADERS_SIZE] = "";
1173 char *authstr = NULL, *proxyauthstr = NULL;
1174 uint64_t off = s->off;
1177 int send_expect_100 = 0;
1180 /* send http header */
1181 post = h->flags & AVIO_FLAG_WRITE;
1184 /* force POST method and disable chunked encoding when
1185 * custom HTTP post data is set */
1187 s->chunked_post = 0;
1193 method = post ? "POST" : "GET";
1195 authstr = ff_http_auth_create_response(&s->auth_state, auth,
1196 local_path, method);
1197 proxyauthstr = ff_http_auth_create_response(&s->proxy_auth_state, proxyauth,
1198 local_path, method);
1200 if (post && !s->post_data) {
1201 if (s->send_expect_100 != -1) {
1202 send_expect_100 = s->send_expect_100;
1204 send_expect_100 = 0;
1205 /* The user has supplied authentication but we don't know the auth type,
1206 * send Expect: 100-continue to get the 401 response including the
1207 * WWW-Authenticate header, or an 100 continue if no auth actually
1209 if (auth && *auth &&
1210 s->auth_state.auth_type == HTTP_AUTH_NONE &&
1211 s->http_code != 401)
1212 send_expect_100 = 1;
1216 #if FF_API_HTTP_USER_AGENT
1217 if (strcmp(s->user_agent_deprecated, DEFAULT_USER_AGENT)) {
1218 s->user_agent = av_strdup(s->user_agent_deprecated);
1221 /* set default headers if needed */
1222 if (!has_header(s->headers, "\r\nUser-Agent: "))
1223 len += av_strlcatf(headers + len, sizeof(headers) - len,
1224 "User-Agent: %s\r\n", s->user_agent);
1226 /* set default headers if needed */
1227 if (!has_header(s->headers, "\r\nReferer: "))
1228 len += av_strlcatf(headers + len, sizeof(headers) - len,
1229 "Referer: %s\r\n", s->referer);
1231 if (!has_header(s->headers, "\r\nAccept: "))
1232 len += av_strlcpy(headers + len, "Accept: */*\r\n",
1233 sizeof(headers) - len);
1234 // Note: we send this on purpose even when s->off is 0 when we're probing,
1235 // since it allows us to detect more reliably if a (non-conforming)
1236 // server supports seeking by analysing the reply headers.
1237 if (!has_header(s->headers, "\r\nRange: ") && !post && (s->off > 0 || s->end_off || s->seekable == -1)) {
1238 len += av_strlcatf(headers + len, sizeof(headers) - len,
1239 "Range: bytes=%"PRIu64"-", s->off);
1241 len += av_strlcatf(headers + len, sizeof(headers) - len,
1242 "%"PRId64, s->end_off - 1);
1243 len += av_strlcpy(headers + len, "\r\n",
1244 sizeof(headers) - len);
1246 if (send_expect_100 && !has_header(s->headers, "\r\nExpect: "))
1247 len += av_strlcatf(headers + len, sizeof(headers) - len,
1248 "Expect: 100-continue\r\n");
1250 if (!has_header(s->headers, "\r\nConnection: ")) {
1251 if (s->multiple_requests)
1252 len += av_strlcpy(headers + len, "Connection: keep-alive\r\n",
1253 sizeof(headers) - len);
1255 len += av_strlcpy(headers + len, "Connection: close\r\n",
1256 sizeof(headers) - len);
1259 if (!has_header(s->headers, "\r\nHost: "))
1260 len += av_strlcatf(headers + len, sizeof(headers) - len,
1261 "Host: %s\r\n", hoststr);
1262 if (!has_header(s->headers, "\r\nContent-Length: ") && s->post_data)
1263 len += av_strlcatf(headers + len, sizeof(headers) - len,
1264 "Content-Length: %d\r\n", s->post_datalen);
1266 if (!has_header(s->headers, "\r\nContent-Type: ") && s->content_type)
1267 len += av_strlcatf(headers + len, sizeof(headers) - len,
1268 "Content-Type: %s\r\n", s->content_type);
1269 if (!has_header(s->headers, "\r\nCookie: ") && s->cookies) {
1270 char *cookies = NULL;
1271 if (!get_cookies(s, &cookies, path, hoststr) && cookies) {
1272 len += av_strlcatf(headers + len, sizeof(headers) - len,
1273 "Cookie: %s\r\n", cookies);
1277 if (!has_header(s->headers, "\r\nIcy-MetaData: ") && s->icy)
1278 len += av_strlcatf(headers + len, sizeof(headers) - len,
1279 "Icy-MetaData: %d\r\n", 1);
1281 /* now add in custom headers */
1283 av_strlcpy(headers + len, s->headers, sizeof(headers) - len);
1285 ret = snprintf(s->buffer, sizeof(s->buffer),
1286 "%s %s HTTP/1.1\r\n"
1294 post && s->chunked_post ? "Transfer-Encoding: chunked\r\n" : "",
1296 authstr ? authstr : "",
1297 proxyauthstr ? "Proxy-" : "", proxyauthstr ? proxyauthstr : "");
1299 av_log(h, AV_LOG_DEBUG, "request: %s\n", s->buffer);
1301 if (strlen(headers) + 1 == sizeof(headers) ||
1302 ret >= sizeof(s->buffer)) {
1303 av_log(h, AV_LOG_ERROR, "overlong headers\n");
1304 err = AVERROR(EINVAL);
1309 if ((err = ffurl_write(s->hd, s->buffer, strlen(s->buffer))) < 0)
1313 if ((err = ffurl_write(s->hd, s->post_data, s->post_datalen)) < 0)
1316 /* init input buffer */
1317 s->buf_ptr = s->buffer;
1318 s->buf_end = s->buffer;
1321 s->icy_data_read = 0;
1322 s->filesize = UINT64_MAX;
1324 s->end_chunked_post = 0;
1329 if (post && !s->post_data && !send_expect_100) {
1330 /* Pretend that it did work. We didn't read any header yet, since
1331 * we've still to send the POST data, but the code calling this
1332 * function will check http_code after we return. */
1338 /* wait for header */
1339 err = http_read_header(h, new_location);
1346 err = (off == s->off) ? 0 : -1;
1349 av_freep(&proxyauthstr);
1353 static int http_buf_read(URLContext *h, uint8_t *buf, int size)
1355 HTTPContext *s = h->priv_data;
1358 if (s->chunksize != UINT64_MAX) {
1362 if (!s->chunksize) {
1367 if ((err = http_get_line(s, line, sizeof(line))) < 0)
1369 } while (!*line); /* skip CR LF from last chunk */
1371 s->chunksize = strtoull(line, NULL, 16);
1373 av_log(h, AV_LOG_TRACE,
1374 "Chunked encoding data size: %"PRIu64"\n",
1377 if (!s->chunksize && s->multiple_requests) {
1378 http_get_line(s, line, sizeof(line)); // read empty chunk
1382 else if (!s->chunksize) {
1383 av_log(h, AV_LOG_DEBUG, "Last chunk received, closing conn\n");
1384 ffurl_closep(&s->hd);
1387 else if (s->chunksize == UINT64_MAX) {
1388 av_log(h, AV_LOG_ERROR, "Invalid chunk size %"PRIu64"\n",
1390 return AVERROR(EINVAL);
1393 size = FFMIN(size, s->chunksize);
1396 /* read bytes from input buffer first */
1397 len = s->buf_end - s->buf_ptr;
1401 memcpy(buf, s->buf_ptr, len);
1404 uint64_t target_end = s->end_off ? s->end_off : s->filesize;
1405 if ((!s->willclose || s->chunksize == UINT64_MAX) && s->off >= target_end)
1407 len = ffurl_read(s->hd, buf, size);
1408 if (!len && (!s->willclose || s->chunksize == UINT64_MAX) && s->off < target_end) {
1409 av_log(h, AV_LOG_ERROR,
1410 "Stream ends prematurely at %"PRIu64", should be %"PRIu64"\n",
1413 return AVERROR(EIO);
1418 if (s->chunksize > 0 && s->chunksize != UINT64_MAX) {
1419 av_assert0(s->chunksize >= len);
1420 s->chunksize -= len;
1427 #define DECOMPRESS_BUF_SIZE (256 * 1024)
1428 static int http_buf_read_compressed(URLContext *h, uint8_t *buf, int size)
1430 HTTPContext *s = h->priv_data;
1433 if (!s->inflate_buffer) {
1434 s->inflate_buffer = av_malloc(DECOMPRESS_BUF_SIZE);
1435 if (!s->inflate_buffer)
1436 return AVERROR(ENOMEM);
1439 if (s->inflate_stream.avail_in == 0) {
1440 int read = http_buf_read(h, s->inflate_buffer, DECOMPRESS_BUF_SIZE);
1443 s->inflate_stream.next_in = s->inflate_buffer;
1444 s->inflate_stream.avail_in = read;
1447 s->inflate_stream.avail_out = size;
1448 s->inflate_stream.next_out = buf;
1450 ret = inflate(&s->inflate_stream, Z_SYNC_FLUSH);
1451 if (ret != Z_OK && ret != Z_STREAM_END)
1452 av_log(h, AV_LOG_WARNING, "inflate return value: %d, %s\n",
1453 ret, s->inflate_stream.msg);
1455 return size - s->inflate_stream.avail_out;
1457 #endif /* CONFIG_ZLIB */
1459 static int64_t http_seek_internal(URLContext *h, int64_t off, int whence, int force_reconnect);
1461 static int http_read_stream(URLContext *h, uint8_t *buf, int size)
1463 HTTPContext *s = h->priv_data;
1464 int err, new_location, read_ret;
1466 int reconnect_delay = 0;
1471 if (s->end_chunked_post && !s->end_header) {
1472 err = http_read_header(h, &new_location);
1479 return http_buf_read_compressed(h, buf, size);
1480 #endif /* CONFIG_ZLIB */
1481 read_ret = http_buf_read(h, buf, size);
1482 while (read_ret < 0) {
1483 uint64_t target = h->is_streamed ? 0 : s->off;
1485 if (read_ret == AVERROR_EXIT)
1488 if (h->is_streamed && !s->reconnect_streamed)
1491 if (!(s->reconnect && s->filesize > 0 && s->off < s->filesize) &&
1492 !(s->reconnect_at_eof && read_ret == AVERROR_EOF))
1495 if (reconnect_delay > s->reconnect_delay_max)
1496 return AVERROR(EIO);
1498 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));
1499 err = ff_network_sleep_interruptible(1000U*1000*reconnect_delay, &h->interrupt_callback);
1500 if (err != AVERROR(ETIMEDOUT))
1502 reconnect_delay = 1 + 2*reconnect_delay;
1503 seek_ret = http_seek_internal(h, target, SEEK_SET, 1);
1504 if (seek_ret >= 0 && seek_ret != target) {
1505 av_log(h, AV_LOG_ERROR, "Failed to reconnect at %"PRIu64".\n", target);
1509 read_ret = http_buf_read(h, buf, size);
1515 // Like http_read_stream(), but no short reads.
1516 // Assumes partial reads are an error.
1517 static int http_read_stream_all(URLContext *h, uint8_t *buf, int size)
1520 while (pos < size) {
1521 int len = http_read_stream(h, buf + pos, size - pos);
1529 static void update_metadata(URLContext *h, char *data)
1535 HTTPContext *s = h->priv_data;
1539 val = strstr(key, "='");
1542 end = strstr(val, "';");
1550 av_dict_set(&s->metadata, key, val, 0);
1551 av_log(h, AV_LOG_VERBOSE, "Metadata update for %s: %s\n", key, val);
1557 static int store_icy(URLContext *h, int size)
1559 HTTPContext *s = h->priv_data;
1560 /* until next metadata packet */
1563 if (s->icy_metaint < s->icy_data_read)
1564 return AVERROR_INVALIDDATA;
1565 remaining = s->icy_metaint - s->icy_data_read;
1568 /* The metadata packet is variable sized. It has a 1 byte header
1569 * which sets the length of the packet (divided by 16). If it's 0,
1570 * the metadata doesn't change. After the packet, icy_metaint bytes
1571 * of normal data follows. */
1573 int len = http_read_stream_all(h, &ch, 1);
1577 char data[255 * 16 + 1];
1580 ret = http_read_stream_all(h, data, len);
1584 if ((ret = av_opt_set(s, "icy_metadata_packet", data, 0)) < 0)
1586 update_metadata(h, data);
1588 s->icy_data_read = 0;
1589 remaining = s->icy_metaint;
1592 return FFMIN(size, remaining);
1595 static int http_read(URLContext *h, uint8_t *buf, int size)
1597 HTTPContext *s = h->priv_data;
1599 if (s->icy_metaint > 0) {
1600 size = store_icy(h, size);
1605 size = http_read_stream(h, buf, size);
1607 s->icy_data_read += size;
1611 /* used only when posting data */
1612 static int http_write(URLContext *h, const uint8_t *buf, int size)
1614 char temp[11] = ""; /* 32-bit hex + CRLF + nul */
1616 char crlf[] = "\r\n";
1617 HTTPContext *s = h->priv_data;
1619 if (!s->chunked_post) {
1620 /* non-chunked data is sent without any special encoding */
1621 return ffurl_write(s->hd, buf, size);
1624 /* silently ignore zero-size data since chunk encoding that would
1627 /* upload data using chunked encoding */
1628 snprintf(temp, sizeof(temp), "%x\r\n", size);
1630 if ((ret = ffurl_write(s->hd, temp, strlen(temp))) < 0 ||
1631 (ret = ffurl_write(s->hd, buf, size)) < 0 ||
1632 (ret = ffurl_write(s->hd, crlf, sizeof(crlf) - 1)) < 0)
1638 static int http_shutdown(URLContext *h, int flags)
1641 char footer[] = "0\r\n\r\n";
1642 HTTPContext *s = h->priv_data;
1644 /* signal end of chunked encoding if used */
1645 if (((flags & AVIO_FLAG_WRITE) && s->chunked_post) ||
1646 ((flags & AVIO_FLAG_READ) && s->chunked_post && s->listen)) {
1647 ret = ffurl_write(s->hd, footer, sizeof(footer) - 1);
1648 ret = ret > 0 ? 0 : ret;
1649 /* flush the receive buffer when it is write only mode */
1650 if (!(flags & AVIO_FLAG_READ)) {
1653 s->hd->flags |= AVIO_FLAG_NONBLOCK;
1654 read_ret = ffurl_read(s->hd, buf, sizeof(buf));
1655 s->hd->flags &= ~AVIO_FLAG_NONBLOCK;
1656 if (read_ret < 0 && read_ret != AVERROR(EAGAIN)) {
1657 av_log(h, AV_LOG_ERROR, "URL read error: %s\n", av_err2str(read_ret));
1661 s->end_chunked_post = 1;
1667 static int http_close(URLContext *h)
1670 HTTPContext *s = h->priv_data;
1673 inflateEnd(&s->inflate_stream);
1674 av_freep(&s->inflate_buffer);
1675 #endif /* CONFIG_ZLIB */
1677 if (s->hd && !s->end_chunked_post)
1678 /* Close the write direction by sending the end of chunked encoding. */
1679 ret = http_shutdown(h, h->flags);
1682 ffurl_closep(&s->hd);
1683 av_dict_free(&s->chained_options);
1687 static int64_t http_seek_internal(URLContext *h, int64_t off, int whence, int force_reconnect)
1689 HTTPContext *s = h->priv_data;
1690 URLContext *old_hd = s->hd;
1691 uint64_t old_off = s->off;
1692 uint8_t old_buf[BUFFER_SIZE];
1693 int old_buf_size, ret;
1694 AVDictionary *options = NULL;
1696 if (whence == AVSEEK_SIZE)
1698 else if (!force_reconnect &&
1699 ((whence == SEEK_CUR && off == 0) ||
1700 (whence == SEEK_SET && off == s->off)))
1702 else if ((s->filesize == UINT64_MAX && whence == SEEK_END))
1703 return AVERROR(ENOSYS);
1705 if (whence == SEEK_CUR)
1707 else if (whence == SEEK_END)
1709 else if (whence != SEEK_SET)
1710 return AVERROR(EINVAL);
1712 return AVERROR(EINVAL);
1715 if (s->off && h->is_streamed)
1716 return AVERROR(ENOSYS);
1718 /* do not try to make a new connection if seeking past the end of the file */
1719 if (s->end_off || s->filesize != UINT64_MAX) {
1720 uint64_t end_pos = s->end_off ? s->end_off : s->filesize;
1721 if (s->off >= end_pos)
1725 /* we save the old context in case the seek fails */
1726 old_buf_size = s->buf_end - s->buf_ptr;
1727 memcpy(old_buf, s->buf_ptr, old_buf_size);
1730 /* if it fails, continue on old connection */
1731 if ((ret = http_open_cnx(h, &options)) < 0) {
1732 av_dict_free(&options);
1733 memcpy(s->buffer, old_buf, old_buf_size);
1734 s->buf_ptr = s->buffer;
1735 s->buf_end = s->buffer + old_buf_size;
1740 av_dict_free(&options);
1741 ffurl_close(old_hd);
1745 static int64_t http_seek(URLContext *h, int64_t off, int whence)
1747 return http_seek_internal(h, off, whence, 0);
1750 static int http_get_file_handle(URLContext *h)
1752 HTTPContext *s = h->priv_data;
1753 return ffurl_get_file_handle(s->hd);
1756 static int http_get_short_seek(URLContext *h)
1758 HTTPContext *s = h->priv_data;
1759 return ffurl_get_short_seek(s->hd);
1762 #define HTTP_CLASS(flavor) \
1763 static const AVClass flavor ## _context_class = { \
1764 .class_name = # flavor, \
1765 .item_name = av_default_item_name, \
1766 .option = options, \
1767 .version = LIBAVUTIL_VERSION_INT, \
1770 #if CONFIG_HTTP_PROTOCOL
1773 const URLProtocol ff_http_protocol = {
1775 .url_open2 = http_open,
1776 .url_accept = http_accept,
1777 .url_handshake = http_handshake,
1778 .url_read = http_read,
1779 .url_write = http_write,
1780 .url_seek = http_seek,
1781 .url_close = http_close,
1782 .url_get_file_handle = http_get_file_handle,
1783 .url_get_short_seek = http_get_short_seek,
1784 .url_shutdown = http_shutdown,
1785 .priv_data_size = sizeof(HTTPContext),
1786 .priv_data_class = &http_context_class,
1787 .flags = URL_PROTOCOL_FLAG_NETWORK,
1788 .default_whitelist = "http,https,tls,rtp,tcp,udp,crypto,httpproxy"
1790 #endif /* CONFIG_HTTP_PROTOCOL */
1792 #if CONFIG_HTTPS_PROTOCOL
1795 const URLProtocol ff_https_protocol = {
1797 .url_open2 = http_open,
1798 .url_read = http_read,
1799 .url_write = http_write,
1800 .url_seek = http_seek,
1801 .url_close = http_close,
1802 .url_get_file_handle = http_get_file_handle,
1803 .url_get_short_seek = http_get_short_seek,
1804 .url_shutdown = http_shutdown,
1805 .priv_data_size = sizeof(HTTPContext),
1806 .priv_data_class = &https_context_class,
1807 .flags = URL_PROTOCOL_FLAG_NETWORK,
1808 .default_whitelist = "http,https,tls,rtp,tcp,udp,crypto,httpproxy"
1810 #endif /* CONFIG_HTTPS_PROTOCOL */
1812 #if CONFIG_HTTPPROXY_PROTOCOL
1813 static int http_proxy_close(URLContext *h)
1815 HTTPContext *s = h->priv_data;
1817 ffurl_closep(&s->hd);
1821 static int http_proxy_open(URLContext *h, const char *uri, int flags)
1823 HTTPContext *s = h->priv_data;
1824 char hostname[1024], hoststr[1024];
1825 char auth[1024], pathbuf[1024], *path;
1826 char lower_url[100];
1827 int port, ret = 0, attempts = 0;
1828 HTTPAuthType cur_auth_type;
1832 if( s->seekable == 1 )
1837 av_url_split(NULL, 0, auth, sizeof(auth), hostname, sizeof(hostname), &port,
1838 pathbuf, sizeof(pathbuf), uri);
1839 ff_url_join(hoststr, sizeof(hoststr), NULL, NULL, hostname, port, NULL);
1844 ff_url_join(lower_url, sizeof(lower_url), "tcp", NULL, hostname, port,
1847 ret = ffurl_open_whitelist(&s->hd, lower_url, AVIO_FLAG_READ_WRITE,
1848 &h->interrupt_callback, NULL,
1849 h->protocol_whitelist, h->protocol_blacklist, h);
1853 authstr = ff_http_auth_create_response(&s->proxy_auth_state, auth,
1855 snprintf(s->buffer, sizeof(s->buffer),
1856 "CONNECT %s HTTP/1.1\r\n"
1858 "Connection: close\r\n"
1863 authstr ? "Proxy-" : "", authstr ? authstr : "");
1866 if ((ret = ffurl_write(s->hd, s->buffer, strlen(s->buffer))) < 0)
1869 s->buf_ptr = s->buffer;
1870 s->buf_end = s->buffer;
1872 s->filesize = UINT64_MAX;
1873 cur_auth_type = s->proxy_auth_state.auth_type;
1875 /* Note: This uses buffering, potentially reading more than the
1876 * HTTP header. If tunneling a protocol where the server starts
1877 * the conversation, we might buffer part of that here, too.
1878 * Reading that requires using the proper ffurl_read() function
1879 * on this URLContext, not using the fd directly (as the tls
1880 * protocol does). This shouldn't be an issue for tls though,
1881 * since the client starts the conversation there, so there
1882 * is no extra data that we might buffer up here.
1884 ret = http_read_header(h, &new_loc);
1889 if (s->http_code == 407 &&
1890 (cur_auth_type == HTTP_AUTH_NONE || s->proxy_auth_state.stale) &&
1891 s->proxy_auth_state.auth_type != HTTP_AUTH_NONE && attempts < 2) {
1892 ffurl_closep(&s->hd);
1896 if (s->http_code < 400)
1898 ret = ff_http_averror(s->http_code, AVERROR(EIO));
1901 http_proxy_close(h);
1905 static int http_proxy_write(URLContext *h, const uint8_t *buf, int size)
1907 HTTPContext *s = h->priv_data;
1908 return ffurl_write(s->hd, buf, size);
1911 const URLProtocol ff_httpproxy_protocol = {
1912 .name = "httpproxy",
1913 .url_open = http_proxy_open,
1914 .url_read = http_buf_read,
1915 .url_write = http_proxy_write,
1916 .url_close = http_proxy_close,
1917 .url_get_file_handle = http_get_file_handle,
1918 .priv_data_size = sizeof(HTTPContext),
1919 .flags = URL_PROTOCOL_FLAG_NETWORK,
1921 #endif /* CONFIG_HTTPPROXY_PROTOCOL */