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));
308 int ff_http_do_new_request(URLContext *h, const char *uri)
310 HTTPContext *s = h->priv_data;
311 AVDictionary *options = NULL;
313 char hostname1[1024], hostname2[1024], proto1[10], proto2[10];
317 !(!strcmp(h->prot->name, "http") ||
318 !strcmp(h->prot->name, "https")))
319 return AVERROR(EINVAL);
321 av_url_split(proto1, sizeof(proto1), NULL, 0,
322 hostname1, sizeof(hostname1), &port1,
323 NULL, 0, s->location);
324 av_url_split(proto2, sizeof(proto2), NULL, 0,
325 hostname2, sizeof(hostname2), &port2,
327 if (port1 != port2 || strncmp(hostname1, hostname2, sizeof(hostname2)) != 0) {
328 av_log(h, AV_LOG_ERROR, "Cannot reuse HTTP connection for different host: %s:%d != %s:%d\n",
332 return AVERROR(EINVAL);
335 if (!s->end_chunked_post) {
336 ret = http_shutdown(h, h->flags);
344 s->end_chunked_post = 0;
347 s->icy_data_read = 0;
348 av_free(s->location);
349 s->location = av_strdup(uri);
351 return AVERROR(ENOMEM);
353 av_log(s, AV_LOG_INFO, "Opening \'%s\' for %s\n", uri, h->flags & AVIO_FLAG_WRITE ? "writing" : "reading");
354 ret = http_open_cnx(h, &options);
355 av_dict_free(&options);
359 int ff_http_averror(int status_code, int default_averror)
361 switch (status_code) {
362 case 400: return AVERROR_HTTP_BAD_REQUEST;
363 case 401: return AVERROR_HTTP_UNAUTHORIZED;
364 case 403: return AVERROR_HTTP_FORBIDDEN;
365 case 404: return AVERROR_HTTP_NOT_FOUND;
368 if (status_code >= 400 && status_code <= 499)
369 return AVERROR_HTTP_OTHER_4XX;
370 else if (status_code >= 500)
371 return AVERROR_HTTP_SERVER_ERROR;
373 return default_averror;
376 static int http_write_reply(URLContext* h, int status_code)
378 int ret, body = 0, reply_code, message_len;
379 const char *reply_text, *content_type;
380 HTTPContext *s = h->priv_data;
381 char message[BUFFER_SIZE];
382 content_type = "text/plain";
386 switch (status_code) {
387 case AVERROR_HTTP_BAD_REQUEST:
390 reply_text = "Bad Request";
392 case AVERROR_HTTP_FORBIDDEN:
395 reply_text = "Forbidden";
397 case AVERROR_HTTP_NOT_FOUND:
400 reply_text = "Not Found";
405 content_type = s->content_type ? s->content_type : "application/octet-stream";
407 case AVERROR_HTTP_SERVER_ERROR:
410 reply_text = "Internal server error";
413 return AVERROR(EINVAL);
417 message_len = snprintf(message, sizeof(message),
418 "HTTP/1.1 %03d %s\r\n"
419 "Content-Type: %s\r\n"
420 "Content-Length: %"SIZE_SPECIFIER"\r\n"
427 strlen(reply_text) + 6, // 3 digit status code + space + \r\n
428 s->headers ? s->headers : "",
433 message_len = snprintf(message, sizeof(message),
434 "HTTP/1.1 %03d %s\r\n"
435 "Content-Type: %s\r\n"
436 "Transfer-Encoding: chunked\r\n"
442 s->headers ? s->headers : "");
444 av_log(h, AV_LOG_TRACE, "HTTP reply header: \n%s----\n", message);
445 if ((ret = ffurl_write(s->hd, message, message_len)) < 0)
450 static void handle_http_errors(URLContext *h, int error)
452 av_assert0(error < 0);
453 http_write_reply(h, error);
456 static int http_handshake(URLContext *c)
458 int ret, err, new_location;
459 HTTPContext *ch = c->priv_data;
460 URLContext *cl = ch->hd;
461 switch (ch->handshake_step) {
463 av_log(c, AV_LOG_TRACE, "Lower protocol\n");
464 if ((ret = ffurl_handshake(cl)) > 0)
468 ch->handshake_step = READ_HEADERS;
469 ch->is_connected_server = 1;
472 av_log(c, AV_LOG_TRACE, "Read headers\n");
473 if ((err = http_read_header(c, &new_location)) < 0) {
474 handle_http_errors(c, err);
477 ch->handshake_step = WRITE_REPLY_HEADERS;
479 case WRITE_REPLY_HEADERS:
480 av_log(c, AV_LOG_TRACE, "Reply code: %d\n", ch->reply_code);
481 if ((err = http_write_reply(c, ch->reply_code)) < 0)
483 ch->handshake_step = FINISH;
488 // this should never be reached.
489 return AVERROR(EINVAL);
492 static int http_listen(URLContext *h, const char *uri, int flags,
493 AVDictionary **options) {
494 HTTPContext *s = h->priv_data;
496 char hostname[1024], proto[10];
498 const char *lower_proto = "tcp";
500 av_url_split(proto, sizeof(proto), NULL, 0, hostname, sizeof(hostname), &port,
502 if (!strcmp(proto, "https"))
504 ff_url_join(lower_url, sizeof(lower_url), lower_proto, NULL, hostname, port,
506 if ((ret = av_dict_set_int(options, "listen", s->listen, 0)) < 0)
508 if ((ret = ffurl_open_whitelist(&s->hd, lower_url, AVIO_FLAG_READ_WRITE,
509 &h->interrupt_callback, options,
510 h->protocol_whitelist, h->protocol_blacklist, h
513 s->handshake_step = LOWER_PROTO;
514 if (s->listen == HTTP_SINGLE) { /* single client */
516 while ((ret = http_handshake(h)) > 0);
519 av_dict_free(&s->chained_options);
523 static int http_open(URLContext *h, const char *uri, int flags,
524 AVDictionary **options)
526 HTTPContext *s = h->priv_data;
529 if( s->seekable == 1 )
534 s->filesize = UINT64_MAX;
535 s->location = av_strdup(uri);
537 return AVERROR(ENOMEM);
539 av_dict_copy(&s->chained_options, *options, 0);
542 int len = strlen(s->headers);
543 if (len < 2 || strcmp("\r\n", s->headers + len - 2)) {
544 av_log(h, AV_LOG_WARNING,
545 "No trailing CRLF found in HTTP header. Adding it.\n");
546 ret = av_reallocp(&s->headers, len + 3);
549 s->headers[len] = '\r';
550 s->headers[len + 1] = '\n';
551 s->headers[len + 2] = '\0';
556 return http_listen(h, uri, flags, options);
558 ret = http_open_cnx(h, options);
560 av_dict_free(&s->chained_options);
564 static int http_accept(URLContext *s, URLContext **c)
567 HTTPContext *sc = s->priv_data;
569 URLContext *sl = sc->hd;
570 URLContext *cl = NULL;
572 av_assert0(sc->listen);
573 if ((ret = ffurl_alloc(c, s->filename, s->flags, &sl->interrupt_callback)) < 0)
575 cc = (*c)->priv_data;
576 if ((ret = ffurl_accept(sl, &cl)) < 0)
579 cc->is_multi_client = 1;
588 static int http_getc(HTTPContext *s)
591 if (s->buf_ptr >= s->buf_end) {
592 len = ffurl_read(s->hd, s->buffer, BUFFER_SIZE);
595 } else if (len == 0) {
598 s->buf_ptr = s->buffer;
599 s->buf_end = s->buffer + len;
602 return *s->buf_ptr++;
605 static int http_get_line(HTTPContext *s, char *line, int line_size)
617 if (q > line && q[-1] == '\r')
623 if ((q - line) < line_size - 1)
629 static int check_http_code(URLContext *h, int http_code, const char *end)
631 HTTPContext *s = h->priv_data;
632 /* error codes are 4xx and 5xx, but regard 401 as a success, so we
633 * don't abort until all headers have been parsed. */
634 if (http_code >= 400 && http_code < 600 &&
635 (http_code != 401 || s->auth_state.auth_type != HTTP_AUTH_NONE) &&
636 (http_code != 407 || s->proxy_auth_state.auth_type != HTTP_AUTH_NONE)) {
637 end += strspn(end, SPACE_CHARS);
638 av_log(h, AV_LOG_WARNING, "HTTP error %d %s\n", http_code, end);
639 return ff_http_averror(http_code, AVERROR(EIO));
644 static int parse_location(HTTPContext *s, const char *p)
646 char redirected_location[MAX_URL_SIZE], *new_loc;
647 ff_make_absolute_url(redirected_location, sizeof(redirected_location),
649 new_loc = av_strdup(redirected_location);
651 return AVERROR(ENOMEM);
652 av_free(s->location);
653 s->location = new_loc;
657 /* "bytes $from-$to/$document_size" */
658 static void parse_content_range(URLContext *h, const char *p)
660 HTTPContext *s = h->priv_data;
663 if (!strncmp(p, "bytes ", 6)) {
665 s->off = strtoull(p, NULL, 10);
666 if ((slash = strchr(p, '/')) && strlen(slash) > 0)
667 s->filesize = strtoull(slash + 1, NULL, 10);
669 if (s->seekable == -1 && (!s->is_akamai || s->filesize != 2147483647))
670 h->is_streamed = 0; /* we _can_ in fact seek */
673 static int parse_content_encoding(URLContext *h, const char *p)
675 if (!av_strncasecmp(p, "gzip", 4) ||
676 !av_strncasecmp(p, "deflate", 7)) {
678 HTTPContext *s = h->priv_data;
681 inflateEnd(&s->inflate_stream);
682 if (inflateInit2(&s->inflate_stream, 32 + 15) != Z_OK) {
683 av_log(h, AV_LOG_WARNING, "Error during zlib initialisation: %s\n",
684 s->inflate_stream.msg);
685 return AVERROR(ENOSYS);
687 if (zlibCompileFlags() & (1 << 17)) {
688 av_log(h, AV_LOG_WARNING,
689 "Your zlib was compiled without gzip support.\n");
690 return AVERROR(ENOSYS);
693 av_log(h, AV_LOG_WARNING,
694 "Compressed (%s) content, need zlib with gzip support\n", p);
695 return AVERROR(ENOSYS);
696 #endif /* CONFIG_ZLIB */
697 } else if (!av_strncasecmp(p, "identity", 8)) {
698 // The normal, no-encoding case (although servers shouldn't include
699 // the header at all if this is the case).
701 av_log(h, AV_LOG_WARNING, "Unknown content coding: %s\n", p);
706 // Concat all Icy- header lines
707 static int parse_icy(HTTPContext *s, const char *tag, const char *p)
709 int len = 4 + strlen(p) + strlen(tag);
710 int is_first = !s->icy_metadata_headers;
713 av_dict_set(&s->metadata, tag, p, 0);
715 if (s->icy_metadata_headers)
716 len += strlen(s->icy_metadata_headers);
718 if ((ret = av_reallocp(&s->icy_metadata_headers, len)) < 0)
722 *s->icy_metadata_headers = '\0';
724 av_strlcatf(s->icy_metadata_headers, len, "%s: %s\n", tag, p);
729 static int parse_set_cookie_expiry_time(const char *exp_str, struct tm *buf)
731 char exp_buf[MAX_EXPIRY];
732 int i, j, exp_buf_len = MAX_EXPIRY-1;
735 // strip off any punctuation or whitespace
736 for (i = 0, j = 0; exp_str[i] != '\0' && j < exp_buf_len; i++) {
737 if ((exp_str[i] >= '0' && exp_str[i] <= '9') ||
738 (exp_str[i] >= 'A' && exp_str[i] <= 'Z') ||
739 (exp_str[i] >= 'a' && exp_str[i] <= 'z')) {
740 exp_buf[j] = exp_str[i];
747 // move the string beyond the day of week
748 while ((*expiry < '0' || *expiry > '9') && *expiry != '\0')
751 return av_small_strptime(expiry, "%d%b%Y%H%M%S", buf) ? 0 : AVERROR(EINVAL);
754 static int parse_set_cookie(const char *set_cookie, AVDictionary **dict)
756 char *param, *next_param, *cstr, *back;
761 if (!(cstr = av_strdup(set_cookie)))
762 return AVERROR(EINVAL);
764 // strip any trailing whitespace
765 back = &cstr[strlen(cstr)-1];
766 while (strchr(WHITESPACES, *back)) {
774 while ((param = av_strtok(next_param, ";", &next_param))) {
776 param += strspn(param, WHITESPACES);
777 if ((name = av_strtok(param, "=", &value))) {
778 if (av_dict_set(dict, name, value, 0) < 0) {
789 static int parse_cookie(HTTPContext *s, const char *p, AVDictionary **cookies)
791 AVDictionary *new_params = NULL;
792 AVDictionaryEntry *e, *cookie_entry;
795 // ensure the cookie is parsable
796 if (parse_set_cookie(p, &new_params))
799 // if there is no cookie value there is nothing to parse
800 cookie_entry = av_dict_get(new_params, "", NULL, AV_DICT_IGNORE_SUFFIX);
801 if (!cookie_entry || !cookie_entry->value) {
802 av_dict_free(&new_params);
806 // ensure the cookie is not expired or older than an existing value
807 if ((e = av_dict_get(new_params, "expires", NULL, 0)) && e->value) {
808 struct tm new_tm = {0};
809 if (!parse_set_cookie_expiry_time(e->value, &new_tm)) {
810 AVDictionaryEntry *e2;
812 // if the cookie has already expired ignore it
813 if (av_timegm(&new_tm) < av_gettime() / 1000000) {
814 av_dict_free(&new_params);
818 // only replace an older cookie with the same name
819 e2 = av_dict_get(*cookies, cookie_entry->key, NULL, 0);
820 if (e2 && e2->value) {
821 AVDictionary *old_params = NULL;
822 if (!parse_set_cookie(p, &old_params)) {
823 e2 = av_dict_get(old_params, "expires", NULL, 0);
824 if (e2 && e2->value) {
825 struct tm old_tm = {0};
826 if (!parse_set_cookie_expiry_time(e->value, &old_tm)) {
827 if (av_timegm(&new_tm) < av_timegm(&old_tm)) {
828 av_dict_free(&new_params);
829 av_dict_free(&old_params);
835 av_dict_free(&old_params);
839 av_dict_free(&new_params);
841 // duplicate the cookie name (dict will dupe the value)
842 if (!(eql = strchr(p, '='))) return AVERROR(EINVAL);
843 if (!(name = av_strndup(p, eql - p))) return AVERROR(ENOMEM);
845 // add the cookie to the dictionary
846 av_dict_set(cookies, name, eql, AV_DICT_DONT_STRDUP_KEY);
851 static int cookie_string(AVDictionary *dict, char **cookies)
853 AVDictionaryEntry *e = NULL;
856 // determine how much memory is needed for the cookies string
857 while (e = av_dict_get(dict, "", e, AV_DICT_IGNORE_SUFFIX))
858 len += strlen(e->key) + strlen(e->value) + 1;
860 // reallocate the cookies
862 if (*cookies) av_free(*cookies);
863 *cookies = av_malloc(len);
864 if (!*cookies) return AVERROR(ENOMEM);
867 // write out the cookies
868 while (e = av_dict_get(dict, "", e, AV_DICT_IGNORE_SUFFIX))
869 av_strlcatf(*cookies, len, "%s%s\n", e->key, e->value);
874 static int process_line(URLContext *h, char *line, int line_count,
877 HTTPContext *s = h->priv_data;
878 const char *auto_method = h->flags & AVIO_FLAG_READ ? "POST" : "GET";
879 char *tag, *p, *end, *method, *resource, *version;
883 if (line[0] == '\0') {
889 if (line_count == 0) {
890 if (s->is_connected_server) {
893 while (*p && !av_isspace(*p))
896 av_log(h, AV_LOG_TRACE, "Received method: %s\n", method);
898 if (av_strcasecmp(s->method, method)) {
899 av_log(h, AV_LOG_ERROR, "Received and expected HTTP method do not match. (%s expected, %s received)\n",
901 return ff_http_averror(400, AVERROR(EIO));
904 // use autodetected HTTP method to expect
905 av_log(h, AV_LOG_TRACE, "Autodetected %s HTTP method\n", auto_method);
906 if (av_strcasecmp(auto_method, method)) {
907 av_log(h, AV_LOG_ERROR, "Received and autodetected HTTP method did not match "
908 "(%s autodetected %s received)\n", auto_method, method);
909 return ff_http_averror(400, AVERROR(EIO));
911 if (!(s->method = av_strdup(method)))
912 return AVERROR(ENOMEM);
916 while (av_isspace(*p))
919 while (*p && !av_isspace(*p))
922 av_log(h, AV_LOG_TRACE, "Requested resource: %s\n", resource);
923 if (!(s->resource = av_strdup(resource)))
924 return AVERROR(ENOMEM);
927 while (av_isspace(*p))
930 while (*p && !av_isspace(*p))
933 if (av_strncasecmp(version, "HTTP/", 5)) {
934 av_log(h, AV_LOG_ERROR, "Malformed HTTP version string.\n");
935 return ff_http_averror(400, AVERROR(EIO));
937 av_log(h, AV_LOG_TRACE, "HTTP version string: %s\n", version);
939 if (av_strncasecmp(p, "HTTP/1.0", 8) == 0)
941 while (*p != '/' && *p != '\0')
945 av_freep(&s->http_version);
946 s->http_version = av_strndup(p, 3);
947 while (!av_isspace(*p) && *p != '\0')
949 while (av_isspace(*p))
951 s->http_code = strtol(p, &end, 10);
953 av_log(h, AV_LOG_TRACE, "http_code=%d\n", s->http_code);
955 if ((ret = check_http_code(h, s->http_code, end)) < 0)
959 while (*p != '\0' && *p != ':')
967 while (av_isspace(*p))
969 if (!av_strcasecmp(tag, "Location")) {
970 if ((ret = parse_location(s, p)) < 0)
973 } else if (!av_strcasecmp(tag, "Content-Length") &&
974 s->filesize == UINT64_MAX) {
975 s->filesize = strtoull(p, NULL, 10);
976 } else if (!av_strcasecmp(tag, "Content-Range")) {
977 parse_content_range(h, p);
978 } else if (!av_strcasecmp(tag, "Accept-Ranges") &&
979 !strncmp(p, "bytes", 5) &&
982 } else if (!av_strcasecmp(tag, "Transfer-Encoding") &&
983 !av_strncasecmp(p, "chunked", 7)) {
984 s->filesize = UINT64_MAX;
986 } else if (!av_strcasecmp(tag, "WWW-Authenticate")) {
987 ff_http_auth_handle_header(&s->auth_state, tag, p);
988 } else if (!av_strcasecmp(tag, "Authentication-Info")) {
989 ff_http_auth_handle_header(&s->auth_state, tag, p);
990 } else if (!av_strcasecmp(tag, "Proxy-Authenticate")) {
991 ff_http_auth_handle_header(&s->proxy_auth_state, tag, p);
992 } else if (!av_strcasecmp(tag, "Connection")) {
993 if (!strcmp(p, "close"))
995 } else if (!av_strcasecmp(tag, "Server")) {
996 if (!av_strcasecmp(p, "AkamaiGHost")) {
998 } else if (!av_strncasecmp(p, "MediaGateway", 12)) {
999 s->is_mediagateway = 1;
1001 } else if (!av_strcasecmp(tag, "Content-Type")) {
1002 av_free(s->mime_type);
1003 s->mime_type = av_strdup(p);
1004 } else if (!av_strcasecmp(tag, "Set-Cookie")) {
1005 if (parse_cookie(s, p, &s->cookie_dict))
1006 av_log(h, AV_LOG_WARNING, "Unable to parse '%s'\n", p);
1007 } else if (!av_strcasecmp(tag, "Icy-MetaInt")) {
1008 s->icy_metaint = strtoull(p, NULL, 10);
1009 } else if (!av_strncasecmp(tag, "Icy-", 4)) {
1010 if ((ret = parse_icy(s, tag, p)) < 0)
1012 } else if (!av_strcasecmp(tag, "Content-Encoding")) {
1013 if ((ret = parse_content_encoding(h, p)) < 0)
1021 * Create a string containing cookie values for use as a HTTP cookie header
1022 * field value for a particular path and domain from the cookie values stored in
1023 * the HTTP protocol context. The cookie string is stored in *cookies, and may
1024 * be NULL if there are no valid cookies.
1026 * @return a negative value if an error condition occurred, 0 otherwise
1028 static int get_cookies(HTTPContext *s, char **cookies, const char *path,
1031 // cookie strings will look like Set-Cookie header field values. Multiple
1032 // Set-Cookie fields will result in multiple values delimited by a newline
1034 char *cookie, *set_cookies, *next;
1036 // destroy any cookies in the dictionary.
1037 av_dict_free(&s->cookie_dict);
1042 next = set_cookies = av_strdup(s->cookies);
1044 return AVERROR(ENOMEM);
1047 while ((cookie = av_strtok(next, "\n", &next)) && !ret) {
1048 AVDictionary *cookie_params = NULL;
1049 AVDictionaryEntry *cookie_entry, *e;
1051 // store the cookie in a dict in case it is updated in the response
1052 if (parse_cookie(s, cookie, &s->cookie_dict))
1053 av_log(s, AV_LOG_WARNING, "Unable to parse '%s'\n", cookie);
1055 // continue on to the next cookie if this one cannot be parsed
1056 if (parse_set_cookie(cookie, &cookie_params))
1059 // if the cookie has no value, skip it
1060 cookie_entry = av_dict_get(cookie_params, "", NULL, AV_DICT_IGNORE_SUFFIX);
1061 if (!cookie_entry || !cookie_entry->value)
1064 // if the cookie has expired, don't add it
1065 if ((e = av_dict_get(cookie_params, "expires", NULL, 0)) && e->value) {
1066 struct tm tm_buf = {0};
1067 if (!parse_set_cookie_expiry_time(e->value, &tm_buf)) {
1068 if (av_timegm(&tm_buf) < av_gettime() / 1000000)
1073 // if no domain in the cookie assume it appied to this request
1074 if ((e = av_dict_get(cookie_params, "domain", NULL, 0)) && e->value) {
1075 // find the offset comparison is on the min domain (b.com, not a.b.com)
1076 int domain_offset = strlen(domain) - strlen(e->value);
1077 if (domain_offset < 0)
1080 // match the cookie domain
1081 if (av_strcasecmp(&domain[domain_offset], e->value))
1085 // ensure this cookie matches the path
1086 e = av_dict_get(cookie_params, "path", NULL, 0);
1087 if (!e || av_strncasecmp(path, e->value, strlen(e->value)))
1090 // cookie parameters match, so copy the value
1092 *cookies = av_asprintf("%s=%s", cookie_entry->key, cookie_entry->value);
1094 char *tmp = *cookies;
1095 *cookies = av_asprintf("%s; %s=%s", tmp, cookie_entry->key, cookie_entry->value);
1099 ret = AVERROR(ENOMEM);
1102 av_dict_free(&cookie_params);
1105 av_free(set_cookies);
1110 static inline int has_header(const char *str, const char *header)
1112 /* header + 2 to skip over CRLF prefix. (make sure you have one!) */
1115 return av_stristart(str, header + 2, NULL) || av_stristr(str, header);
1118 static int http_read_header(URLContext *h, int *new_location)
1120 HTTPContext *s = h->priv_data;
1121 char line[MAX_URL_SIZE];
1124 s->chunksize = UINT64_MAX;
1127 if ((err = http_get_line(s, line, sizeof(line))) < 0)
1130 av_log(h, AV_LOG_TRACE, "header='%s'\n", line);
1132 err = process_line(h, line, s->line_count, new_location);
1140 if (s->seekable == -1 && s->is_mediagateway && s->filesize == 2000000000)
1141 h->is_streamed = 1; /* we can in fact _not_ seek */
1143 // add any new cookies into the existing cookie string
1144 cookie_string(s->cookie_dict, &s->cookies);
1145 av_dict_free(&s->cookie_dict);
1150 static int http_connect(URLContext *h, const char *path, const char *local_path,
1151 const char *hoststr, const char *auth,
1152 const char *proxyauth, int *new_location)
1154 HTTPContext *s = h->priv_data;
1156 char headers[HTTP_HEADERS_SIZE] = "";
1157 char *authstr = NULL, *proxyauthstr = NULL;
1158 uint64_t off = s->off;
1161 int send_expect_100 = 0;
1164 /* send http header */
1165 post = h->flags & AVIO_FLAG_WRITE;
1168 /* force POST method and disable chunked encoding when
1169 * custom HTTP post data is set */
1171 s->chunked_post = 0;
1177 method = post ? "POST" : "GET";
1179 authstr = ff_http_auth_create_response(&s->auth_state, auth,
1180 local_path, method);
1181 proxyauthstr = ff_http_auth_create_response(&s->proxy_auth_state, proxyauth,
1182 local_path, method);
1184 if (post && !s->post_data) {
1185 if (s->send_expect_100 != -1) {
1186 send_expect_100 = s->send_expect_100;
1188 send_expect_100 = 0;
1189 /* The user has supplied authentication but we don't know the auth type,
1190 * send Expect: 100-continue to get the 401 response including the
1191 * WWW-Authenticate header, or an 100 continue if no auth actually
1193 if (auth && *auth &&
1194 s->auth_state.auth_type == HTTP_AUTH_NONE &&
1195 s->http_code != 401)
1196 send_expect_100 = 1;
1200 #if FF_API_HTTP_USER_AGENT
1201 if (strcmp(s->user_agent_deprecated, DEFAULT_USER_AGENT)) {
1202 s->user_agent = av_strdup(s->user_agent_deprecated);
1205 /* set default headers if needed */
1206 if (!has_header(s->headers, "\r\nUser-Agent: "))
1207 len += av_strlcatf(headers + len, sizeof(headers) - len,
1208 "User-Agent: %s\r\n", s->user_agent);
1210 /* set default headers if needed */
1211 if (!has_header(s->headers, "\r\nReferer: "))
1212 len += av_strlcatf(headers + len, sizeof(headers) - len,
1213 "Referer: %s\r\n", s->referer);
1215 if (!has_header(s->headers, "\r\nAccept: "))
1216 len += av_strlcpy(headers + len, "Accept: */*\r\n",
1217 sizeof(headers) - len);
1218 // Note: we send this on purpose even when s->off is 0 when we're probing,
1219 // since it allows us to detect more reliably if a (non-conforming)
1220 // server supports seeking by analysing the reply headers.
1221 if (!has_header(s->headers, "\r\nRange: ") && !post && (s->off > 0 || s->end_off || s->seekable == -1)) {
1222 len += av_strlcatf(headers + len, sizeof(headers) - len,
1223 "Range: bytes=%"PRIu64"-", s->off);
1225 len += av_strlcatf(headers + len, sizeof(headers) - len,
1226 "%"PRId64, s->end_off - 1);
1227 len += av_strlcpy(headers + len, "\r\n",
1228 sizeof(headers) - len);
1230 if (send_expect_100 && !has_header(s->headers, "\r\nExpect: "))
1231 len += av_strlcatf(headers + len, sizeof(headers) - len,
1232 "Expect: 100-continue\r\n");
1234 if (!has_header(s->headers, "\r\nConnection: ")) {
1235 if (s->multiple_requests)
1236 len += av_strlcpy(headers + len, "Connection: keep-alive\r\n",
1237 sizeof(headers) - len);
1239 len += av_strlcpy(headers + len, "Connection: close\r\n",
1240 sizeof(headers) - len);
1243 if (!has_header(s->headers, "\r\nHost: "))
1244 len += av_strlcatf(headers + len, sizeof(headers) - len,
1245 "Host: %s\r\n", hoststr);
1246 if (!has_header(s->headers, "\r\nContent-Length: ") && s->post_data)
1247 len += av_strlcatf(headers + len, sizeof(headers) - len,
1248 "Content-Length: %d\r\n", s->post_datalen);
1250 if (!has_header(s->headers, "\r\nContent-Type: ") && s->content_type)
1251 len += av_strlcatf(headers + len, sizeof(headers) - len,
1252 "Content-Type: %s\r\n", s->content_type);
1253 if (!has_header(s->headers, "\r\nCookie: ") && s->cookies) {
1254 char *cookies = NULL;
1255 if (!get_cookies(s, &cookies, path, hoststr) && cookies) {
1256 len += av_strlcatf(headers + len, sizeof(headers) - len,
1257 "Cookie: %s\r\n", cookies);
1261 if (!has_header(s->headers, "\r\nIcy-MetaData: ") && s->icy)
1262 len += av_strlcatf(headers + len, sizeof(headers) - len,
1263 "Icy-MetaData: %d\r\n", 1);
1265 /* now add in custom headers */
1267 av_strlcpy(headers + len, s->headers, sizeof(headers) - len);
1269 ret = snprintf(s->buffer, sizeof(s->buffer),
1270 "%s %s HTTP/1.1\r\n"
1278 post && s->chunked_post ? "Transfer-Encoding: chunked\r\n" : "",
1280 authstr ? authstr : "",
1281 proxyauthstr ? "Proxy-" : "", proxyauthstr ? proxyauthstr : "");
1283 av_log(h, AV_LOG_DEBUG, "request: %s\n", s->buffer);
1285 if (strlen(headers) + 1 == sizeof(headers) ||
1286 ret >= sizeof(s->buffer)) {
1287 av_log(h, AV_LOG_ERROR, "overlong headers\n");
1288 err = AVERROR(EINVAL);
1293 if ((err = ffurl_write(s->hd, s->buffer, strlen(s->buffer))) < 0)
1297 if ((err = ffurl_write(s->hd, s->post_data, s->post_datalen)) < 0)
1300 /* init input buffer */
1301 s->buf_ptr = s->buffer;
1302 s->buf_end = s->buffer;
1305 s->icy_data_read = 0;
1306 s->filesize = UINT64_MAX;
1308 s->end_chunked_post = 0;
1313 if (post && !s->post_data && !send_expect_100) {
1314 /* Pretend that it did work. We didn't read any header yet, since
1315 * we've still to send the POST data, but the code calling this
1316 * function will check http_code after we return. */
1322 /* wait for header */
1323 err = http_read_header(h, new_location);
1330 err = (off == s->off) ? 0 : -1;
1333 av_freep(&proxyauthstr);
1337 static int http_buf_read(URLContext *h, uint8_t *buf, int size)
1339 HTTPContext *s = h->priv_data;
1342 if (s->chunksize != UINT64_MAX) {
1346 if (!s->chunksize) {
1351 if ((err = http_get_line(s, line, sizeof(line))) < 0)
1353 } while (!*line); /* skip CR LF from last chunk */
1355 s->chunksize = strtoull(line, NULL, 16);
1357 av_log(h, AV_LOG_TRACE,
1358 "Chunked encoding data size: %"PRIu64"\n",
1361 if (!s->chunksize && s->multiple_requests) {
1362 http_get_line(s, line, sizeof(line)); // read empty chunk
1366 else if (!s->chunksize) {
1367 av_log(h, AV_LOG_DEBUG, "Last chunk received, closing conn\n");
1368 ffurl_closep(&s->hd);
1371 else if (s->chunksize == UINT64_MAX) {
1372 av_log(h, AV_LOG_ERROR, "Invalid chunk size %"PRIu64"\n",
1374 return AVERROR(EINVAL);
1377 size = FFMIN(size, s->chunksize);
1380 /* read bytes from input buffer first */
1381 len = s->buf_end - s->buf_ptr;
1385 memcpy(buf, s->buf_ptr, len);
1388 uint64_t target_end = s->end_off ? s->end_off : s->filesize;
1389 if ((!s->willclose || s->chunksize == UINT64_MAX) && s->off >= target_end)
1391 len = ffurl_read(s->hd, buf, size);
1392 if (!len && (!s->willclose || s->chunksize == UINT64_MAX) && s->off < target_end) {
1393 av_log(h, AV_LOG_ERROR,
1394 "Stream ends prematurely at %"PRIu64", should be %"PRIu64"\n",
1397 return AVERROR(EIO);
1402 if (s->chunksize > 0 && s->chunksize != UINT64_MAX) {
1403 av_assert0(s->chunksize >= len);
1404 s->chunksize -= len;
1411 #define DECOMPRESS_BUF_SIZE (256 * 1024)
1412 static int http_buf_read_compressed(URLContext *h, uint8_t *buf, int size)
1414 HTTPContext *s = h->priv_data;
1417 if (!s->inflate_buffer) {
1418 s->inflate_buffer = av_malloc(DECOMPRESS_BUF_SIZE);
1419 if (!s->inflate_buffer)
1420 return AVERROR(ENOMEM);
1423 if (s->inflate_stream.avail_in == 0) {
1424 int read = http_buf_read(h, s->inflate_buffer, DECOMPRESS_BUF_SIZE);
1427 s->inflate_stream.next_in = s->inflate_buffer;
1428 s->inflate_stream.avail_in = read;
1431 s->inflate_stream.avail_out = size;
1432 s->inflate_stream.next_out = buf;
1434 ret = inflate(&s->inflate_stream, Z_SYNC_FLUSH);
1435 if (ret != Z_OK && ret != Z_STREAM_END)
1436 av_log(h, AV_LOG_WARNING, "inflate return value: %d, %s\n",
1437 ret, s->inflate_stream.msg);
1439 return size - s->inflate_stream.avail_out;
1441 #endif /* CONFIG_ZLIB */
1443 static int64_t http_seek_internal(URLContext *h, int64_t off, int whence, int force_reconnect);
1445 static int http_read_stream(URLContext *h, uint8_t *buf, int size)
1447 HTTPContext *s = h->priv_data;
1448 int err, new_location, read_ret;
1450 int reconnect_delay = 0;
1455 if (s->end_chunked_post && !s->end_header) {
1456 err = http_read_header(h, &new_location);
1463 return http_buf_read_compressed(h, buf, size);
1464 #endif /* CONFIG_ZLIB */
1465 read_ret = http_buf_read(h, buf, size);
1466 while (read_ret < 0) {
1467 uint64_t target = h->is_streamed ? 0 : s->off;
1469 if (read_ret == AVERROR_EXIT)
1472 if (h->is_streamed && !s->reconnect_streamed)
1475 if (!(s->reconnect && s->filesize > 0 && s->off < s->filesize) &&
1476 !(s->reconnect_at_eof && read_ret == AVERROR_EOF))
1479 if (reconnect_delay > s->reconnect_delay_max)
1480 return AVERROR(EIO);
1482 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));
1483 err = ff_network_sleep_interruptible(1000U*1000*reconnect_delay, &h->interrupt_callback);
1484 if (err != AVERROR(ETIMEDOUT))
1486 reconnect_delay = 1 + 2*reconnect_delay;
1487 seek_ret = http_seek_internal(h, target, SEEK_SET, 1);
1488 if (seek_ret >= 0 && seek_ret != target) {
1489 av_log(h, AV_LOG_ERROR, "Failed to reconnect at %"PRIu64".\n", target);
1493 read_ret = http_buf_read(h, buf, size);
1499 // Like http_read_stream(), but no short reads.
1500 // Assumes partial reads are an error.
1501 static int http_read_stream_all(URLContext *h, uint8_t *buf, int size)
1504 while (pos < size) {
1505 int len = http_read_stream(h, buf + pos, size - pos);
1513 static void update_metadata(URLContext *h, char *data)
1519 HTTPContext *s = h->priv_data;
1523 val = strstr(key, "='");
1526 end = strstr(val, "';");
1534 av_dict_set(&s->metadata, key, val, 0);
1535 av_log(h, AV_LOG_VERBOSE, "Metadata update for %s: %s\n", key, val);
1541 static int store_icy(URLContext *h, int size)
1543 HTTPContext *s = h->priv_data;
1544 /* until next metadata packet */
1547 if (s->icy_metaint < s->icy_data_read)
1548 return AVERROR_INVALIDDATA;
1549 remaining = s->icy_metaint - s->icy_data_read;
1552 /* The metadata packet is variable sized. It has a 1 byte header
1553 * which sets the length of the packet (divided by 16). If it's 0,
1554 * the metadata doesn't change. After the packet, icy_metaint bytes
1555 * of normal data follows. */
1557 int len = http_read_stream_all(h, &ch, 1);
1561 char data[255 * 16 + 1];
1564 ret = http_read_stream_all(h, data, len);
1568 if ((ret = av_opt_set(s, "icy_metadata_packet", data, 0)) < 0)
1570 update_metadata(h, data);
1572 s->icy_data_read = 0;
1573 remaining = s->icy_metaint;
1576 return FFMIN(size, remaining);
1579 static int http_read(URLContext *h, uint8_t *buf, int size)
1581 HTTPContext *s = h->priv_data;
1583 if (s->icy_metaint > 0) {
1584 size = store_icy(h, size);
1589 size = http_read_stream(h, buf, size);
1591 s->icy_data_read += size;
1595 /* used only when posting data */
1596 static int http_write(URLContext *h, const uint8_t *buf, int size)
1598 char temp[11] = ""; /* 32-bit hex + CRLF + nul */
1600 char crlf[] = "\r\n";
1601 HTTPContext *s = h->priv_data;
1603 if (!s->chunked_post) {
1604 /* non-chunked data is sent without any special encoding */
1605 return ffurl_write(s->hd, buf, size);
1608 /* silently ignore zero-size data since chunk encoding that would
1611 /* upload data using chunked encoding */
1612 snprintf(temp, sizeof(temp), "%x\r\n", size);
1614 if ((ret = ffurl_write(s->hd, temp, strlen(temp))) < 0 ||
1615 (ret = ffurl_write(s->hd, buf, size)) < 0 ||
1616 (ret = ffurl_write(s->hd, crlf, sizeof(crlf) - 1)) < 0)
1622 static int http_shutdown(URLContext *h, int flags)
1625 char footer[] = "0\r\n\r\n";
1626 HTTPContext *s = h->priv_data;
1628 /* signal end of chunked encoding if used */
1629 if (((flags & AVIO_FLAG_WRITE) && s->chunked_post) ||
1630 ((flags & AVIO_FLAG_READ) && s->chunked_post && s->listen)) {
1631 ret = ffurl_write(s->hd, footer, sizeof(footer) - 1);
1632 ret = ret > 0 ? 0 : ret;
1633 /* flush the receive buffer when it is write only mode */
1634 if (!(flags & AVIO_FLAG_READ)) {
1637 s->hd->flags |= AVIO_FLAG_NONBLOCK;
1638 read_ret = ffurl_read(s->hd, buf, sizeof(buf));
1639 s->hd->flags &= ~AVIO_FLAG_NONBLOCK;
1640 if (read_ret < 0 && read_ret != AVERROR(EAGAIN)) {
1641 av_log(h, AV_LOG_ERROR, "URL read error: %d\n", read_ret);
1645 s->end_chunked_post = 1;
1651 static int http_close(URLContext *h)
1654 HTTPContext *s = h->priv_data;
1657 inflateEnd(&s->inflate_stream);
1658 av_freep(&s->inflate_buffer);
1659 #endif /* CONFIG_ZLIB */
1661 if (s->hd && !s->end_chunked_post)
1662 /* Close the write direction by sending the end of chunked encoding. */
1663 ret = http_shutdown(h, h->flags);
1666 ffurl_closep(&s->hd);
1667 av_dict_free(&s->chained_options);
1671 static int64_t http_seek_internal(URLContext *h, int64_t off, int whence, int force_reconnect)
1673 HTTPContext *s = h->priv_data;
1674 URLContext *old_hd = s->hd;
1675 uint64_t old_off = s->off;
1676 uint8_t old_buf[BUFFER_SIZE];
1677 int old_buf_size, ret;
1678 AVDictionary *options = NULL;
1680 if (whence == AVSEEK_SIZE)
1682 else if (!force_reconnect &&
1683 ((whence == SEEK_CUR && off == 0) ||
1684 (whence == SEEK_SET && off == s->off)))
1686 else if ((s->filesize == UINT64_MAX && whence == SEEK_END))
1687 return AVERROR(ENOSYS);
1689 if (whence == SEEK_CUR)
1691 else if (whence == SEEK_END)
1693 else if (whence != SEEK_SET)
1694 return AVERROR(EINVAL);
1696 return AVERROR(EINVAL);
1699 if (s->off && h->is_streamed)
1700 return AVERROR(ENOSYS);
1702 /* do not try to make a new connection if seeking past the end of the file */
1703 if (s->end_off || s->filesize != UINT64_MAX) {
1704 uint64_t end_pos = s->end_off ? s->end_off : s->filesize;
1705 if (s->off >= end_pos)
1709 /* we save the old context in case the seek fails */
1710 old_buf_size = s->buf_end - s->buf_ptr;
1711 memcpy(old_buf, s->buf_ptr, old_buf_size);
1714 /* if it fails, continue on old connection */
1715 if ((ret = http_open_cnx(h, &options)) < 0) {
1716 av_dict_free(&options);
1717 memcpy(s->buffer, old_buf, old_buf_size);
1718 s->buf_ptr = s->buffer;
1719 s->buf_end = s->buffer + old_buf_size;
1724 av_dict_free(&options);
1725 ffurl_close(old_hd);
1729 static int64_t http_seek(URLContext *h, int64_t off, int whence)
1731 return http_seek_internal(h, off, whence, 0);
1734 static int http_get_file_handle(URLContext *h)
1736 HTTPContext *s = h->priv_data;
1737 return ffurl_get_file_handle(s->hd);
1740 static int http_get_short_seek(URLContext *h)
1742 HTTPContext *s = h->priv_data;
1743 return ffurl_get_short_seek(s->hd);
1746 #define HTTP_CLASS(flavor) \
1747 static const AVClass flavor ## _context_class = { \
1748 .class_name = # flavor, \
1749 .item_name = av_default_item_name, \
1750 .option = options, \
1751 .version = LIBAVUTIL_VERSION_INT, \
1754 #if CONFIG_HTTP_PROTOCOL
1757 const URLProtocol ff_http_protocol = {
1759 .url_open2 = http_open,
1760 .url_accept = http_accept,
1761 .url_handshake = http_handshake,
1762 .url_read = http_read,
1763 .url_write = http_write,
1764 .url_seek = http_seek,
1765 .url_close = http_close,
1766 .url_get_file_handle = http_get_file_handle,
1767 .url_get_short_seek = http_get_short_seek,
1768 .url_shutdown = http_shutdown,
1769 .priv_data_size = sizeof(HTTPContext),
1770 .priv_data_class = &http_context_class,
1771 .flags = URL_PROTOCOL_FLAG_NETWORK,
1772 .default_whitelist = "http,https,tls,rtp,tcp,udp,crypto,httpproxy"
1774 #endif /* CONFIG_HTTP_PROTOCOL */
1776 #if CONFIG_HTTPS_PROTOCOL
1779 const URLProtocol ff_https_protocol = {
1781 .url_open2 = http_open,
1782 .url_read = http_read,
1783 .url_write = http_write,
1784 .url_seek = http_seek,
1785 .url_close = http_close,
1786 .url_get_file_handle = http_get_file_handle,
1787 .url_get_short_seek = http_get_short_seek,
1788 .url_shutdown = http_shutdown,
1789 .priv_data_size = sizeof(HTTPContext),
1790 .priv_data_class = &https_context_class,
1791 .flags = URL_PROTOCOL_FLAG_NETWORK,
1792 .default_whitelist = "http,https,tls,rtp,tcp,udp,crypto,httpproxy"
1794 #endif /* CONFIG_HTTPS_PROTOCOL */
1796 #if CONFIG_HTTPPROXY_PROTOCOL
1797 static int http_proxy_close(URLContext *h)
1799 HTTPContext *s = h->priv_data;
1801 ffurl_closep(&s->hd);
1805 static int http_proxy_open(URLContext *h, const char *uri, int flags)
1807 HTTPContext *s = h->priv_data;
1808 char hostname[1024], hoststr[1024];
1809 char auth[1024], pathbuf[1024], *path;
1810 char lower_url[100];
1811 int port, ret = 0, attempts = 0;
1812 HTTPAuthType cur_auth_type;
1816 if( s->seekable == 1 )
1821 av_url_split(NULL, 0, auth, sizeof(auth), hostname, sizeof(hostname), &port,
1822 pathbuf, sizeof(pathbuf), uri);
1823 ff_url_join(hoststr, sizeof(hoststr), NULL, NULL, hostname, port, NULL);
1828 ff_url_join(lower_url, sizeof(lower_url), "tcp", NULL, hostname, port,
1831 ret = ffurl_open_whitelist(&s->hd, lower_url, AVIO_FLAG_READ_WRITE,
1832 &h->interrupt_callback, NULL,
1833 h->protocol_whitelist, h->protocol_blacklist, h);
1837 authstr = ff_http_auth_create_response(&s->proxy_auth_state, auth,
1839 snprintf(s->buffer, sizeof(s->buffer),
1840 "CONNECT %s HTTP/1.1\r\n"
1842 "Connection: close\r\n"
1847 authstr ? "Proxy-" : "", authstr ? authstr : "");
1850 if ((ret = ffurl_write(s->hd, s->buffer, strlen(s->buffer))) < 0)
1853 s->buf_ptr = s->buffer;
1854 s->buf_end = s->buffer;
1856 s->filesize = UINT64_MAX;
1857 cur_auth_type = s->proxy_auth_state.auth_type;
1859 /* Note: This uses buffering, potentially reading more than the
1860 * HTTP header. If tunneling a protocol where the server starts
1861 * the conversation, we might buffer part of that here, too.
1862 * Reading that requires using the proper ffurl_read() function
1863 * on this URLContext, not using the fd directly (as the tls
1864 * protocol does). This shouldn't be an issue for tls though,
1865 * since the client starts the conversation there, so there
1866 * is no extra data that we might buffer up here.
1868 ret = http_read_header(h, &new_loc);
1873 if (s->http_code == 407 &&
1874 (cur_auth_type == HTTP_AUTH_NONE || s->proxy_auth_state.stale) &&
1875 s->proxy_auth_state.auth_type != HTTP_AUTH_NONE && attempts < 2) {
1876 ffurl_closep(&s->hd);
1880 if (s->http_code < 400)
1882 ret = ff_http_averror(s->http_code, AVERROR(EIO));
1885 http_proxy_close(h);
1889 static int http_proxy_write(URLContext *h, const uint8_t *buf, int size)
1891 HTTPContext *s = h->priv_data;
1892 return ffurl_write(s->hd, buf, size);
1895 const URLProtocol ff_httpproxy_protocol = {
1896 .name = "httpproxy",
1897 .url_open = http_proxy_open,
1898 .url_read = http_buf_read,
1899 .url_write = http_proxy_write,
1900 .url_close = http_proxy_close,
1901 .url_get_file_handle = http_get_file_handle,
1902 .priv_data_size = sizeof(HTTPContext),
1903 .flags = URL_PROTOCOL_FLAG_NETWORK,
1905 #endif /* CONFIG_HTTPPROXY_PROTOCOL */