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;
119 int reconnect_at_eof;
120 int reconnect_streamed;
121 int reconnect_delay_max;
126 HandshakeState handshake_step;
127 int is_connected_server;
130 #define OFFSET(x) offsetof(HTTPContext, x)
131 #define D AV_OPT_FLAG_DECODING_PARAM
132 #define E AV_OPT_FLAG_ENCODING_PARAM
133 #define DEFAULT_USER_AGENT "Lavf/" AV_STRINGIFY(LIBAVFORMAT_VERSION)
135 static const AVOption options[] = {
136 { "seekable", "control seekability of connection", OFFSET(seekable), AV_OPT_TYPE_BOOL, { .i64 = -1 }, -1, 1, D },
137 { "chunked_post", "use chunked transfer-encoding for posts", OFFSET(chunked_post), AV_OPT_TYPE_BOOL, { .i64 = 1 }, 0, 1, E },
138 { "http_proxy", "set HTTP proxy to tunnel through", OFFSET(http_proxy), AV_OPT_TYPE_STRING, { .str = NULL }, 0, 0, D | E },
139 { "headers", "set custom HTTP headers, can override built in default headers", OFFSET(headers), AV_OPT_TYPE_STRING, { .str = NULL }, 0, 0, D | E },
140 { "content_type", "set a specific content type for the POST messages", OFFSET(content_type), AV_OPT_TYPE_STRING, { .str = NULL }, 0, 0, D | E },
141 { "user_agent", "override User-Agent header", OFFSET(user_agent), AV_OPT_TYPE_STRING, { .str = DEFAULT_USER_AGENT }, 0, 0, D },
142 { "referer", "override referer header", OFFSET(referer), AV_OPT_TYPE_STRING, { .str = NULL }, 0, 0, D },
143 #if FF_API_HTTP_USER_AGENT
144 { "user-agent", "override User-Agent header", OFFSET(user_agent_deprecated), AV_OPT_TYPE_STRING, { .str = DEFAULT_USER_AGENT }, 0, 0, D },
146 { "multiple_requests", "use persistent connections", OFFSET(multiple_requests), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, D | E },
147 { "post_data", "set custom HTTP post data", OFFSET(post_data), AV_OPT_TYPE_BINARY, .flags = D | E },
148 { "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 },
149 { "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 },
150 { "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 },
151 { "icy", "request ICY metadata", OFFSET(icy), AV_OPT_TYPE_BOOL, { .i64 = 1 }, 0, 1, D },
152 { "icy_metadata_headers", "return ICY metadata headers", OFFSET(icy_metadata_headers), AV_OPT_TYPE_STRING, { .str = NULL }, 0, 0, AV_OPT_FLAG_EXPORT },
153 { "icy_metadata_packet", "return current ICY metadata packet", OFFSET(icy_metadata_packet), AV_OPT_TYPE_STRING, { .str = NULL }, 0, 0, AV_OPT_FLAG_EXPORT },
154 { "metadata", "metadata read from the bitstream", OFFSET(metadata), AV_OPT_TYPE_DICT, {0}, 0, 0, AV_OPT_FLAG_EXPORT },
155 { "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"},
156 { "none", "No auth method set, autodetect", 0, AV_OPT_TYPE_CONST, { .i64 = HTTP_AUTH_NONE }, 0, 0, D | E, "auth_type"},
157 { "basic", "HTTP basic authentication", 0, AV_OPT_TYPE_CONST, { .i64 = HTTP_AUTH_BASIC }, 0, 0, D | E, "auth_type"},
158 { "send_expect_100", "Force sending an Expect: 100-continue header for POST", OFFSET(send_expect_100), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, E },
159 { "location", "The actual location of the data received", OFFSET(location), AV_OPT_TYPE_STRING, { .str = NULL }, 0, 0, D | E },
160 { "offset", "initial byte offset", OFFSET(off), AV_OPT_TYPE_INT64, { .i64 = 0 }, 0, INT64_MAX, D },
161 { "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 },
162 { "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 },
163 { "reconnect", "auto reconnect after disconnect before EOF", OFFSET(reconnect), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, D },
164 { "reconnect_at_eof", "auto reconnect at EOF", OFFSET(reconnect_at_eof), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, D },
165 { "reconnect_streamed", "auto reconnect streamed / non seekable streams", OFFSET(reconnect_streamed), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, D },
166 { "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 },
167 { "listen", "listen on HTTP", OFFSET(listen), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 2, D | E },
168 { "resource", "The resource requested by a client", OFFSET(resource), AV_OPT_TYPE_STRING, { .str = NULL }, 0, 0, E },
169 { "reply_code", "The http status code to return to a client", OFFSET(reply_code), AV_OPT_TYPE_INT, { .i64 = 200}, INT_MIN, 599, E},
173 static int http_connect(URLContext *h, const char *path, const char *local_path,
174 const char *hoststr, const char *auth,
175 const char *proxyauth, int *new_location);
176 static int http_read_header(URLContext *h, int *new_location);
177 static int http_shutdown(URLContext *h, int flags);
179 void ff_http_init_auth_state(URLContext *dest, const URLContext *src)
181 memcpy(&((HTTPContext *)dest->priv_data)->auth_state,
182 &((HTTPContext *)src->priv_data)->auth_state,
183 sizeof(HTTPAuthState));
184 memcpy(&((HTTPContext *)dest->priv_data)->proxy_auth_state,
185 &((HTTPContext *)src->priv_data)->proxy_auth_state,
186 sizeof(HTTPAuthState));
189 static int http_open_cnx_internal(URLContext *h, AVDictionary **options)
191 const char *path, *proxy_path, *lower_proto = "tcp", *local_path;
192 char hostname[1024], hoststr[1024], proto[10];
193 char auth[1024], proxyauth[1024] = "";
194 char path1[MAX_URL_SIZE];
195 char buf[1024], urlbuf[MAX_URL_SIZE];
196 int port, use_proxy, err, location_changed = 0;
197 HTTPContext *s = h->priv_data;
199 av_url_split(proto, sizeof(proto), auth, sizeof(auth),
200 hostname, sizeof(hostname), &port,
201 path1, sizeof(path1), s->location);
202 ff_url_join(hoststr, sizeof(hoststr), NULL, NULL, hostname, port, NULL);
204 proxy_path = s->http_proxy ? s->http_proxy : getenv("http_proxy");
205 use_proxy = !ff_http_match_no_proxy(getenv("no_proxy"), hostname) &&
206 proxy_path && av_strstart(proxy_path, "http://", NULL);
208 if (!strcmp(proto, "https")) {
217 if (path1[0] == '\0')
223 /* Reassemble the request URL without auth string - we don't
224 * want to leak the auth to the proxy. */
225 ff_url_join(urlbuf, sizeof(urlbuf), proto, NULL, hostname, port, "%s",
228 av_url_split(NULL, 0, proxyauth, sizeof(proxyauth),
229 hostname, sizeof(hostname), &port, NULL, 0, proxy_path);
232 ff_url_join(buf, sizeof(buf), lower_proto, NULL, hostname, port, NULL);
235 err = ffurl_open_whitelist(&s->hd, buf, AVIO_FLAG_READ_WRITE,
236 &h->interrupt_callback, options,
237 h->protocol_whitelist, h->protocol_blacklist, h);
242 err = http_connect(h, path, local_path, hoststr,
243 auth, proxyauth, &location_changed);
247 return location_changed;
250 /* return non zero if error */
251 static int http_open_cnx(URLContext *h, AVDictionary **options)
253 HTTPAuthType cur_auth_type, cur_proxy_auth_type;
254 HTTPContext *s = h->priv_data;
255 int location_changed, attempts = 0, redirects = 0;
257 av_dict_copy(options, s->chained_options, 0);
259 cur_auth_type = s->auth_state.auth_type;
260 cur_proxy_auth_type = s->auth_state.auth_type;
262 location_changed = http_open_cnx_internal(h, options);
263 if (location_changed < 0)
267 if (s->http_code == 401) {
268 if ((cur_auth_type == HTTP_AUTH_NONE || s->auth_state.stale) &&
269 s->auth_state.auth_type != HTTP_AUTH_NONE && attempts < 4) {
270 ffurl_closep(&s->hd);
275 if (s->http_code == 407) {
276 if ((cur_proxy_auth_type == HTTP_AUTH_NONE || s->proxy_auth_state.stale) &&
277 s->proxy_auth_state.auth_type != HTTP_AUTH_NONE && attempts < 4) {
278 ffurl_closep(&s->hd);
283 if ((s->http_code == 301 || s->http_code == 302 ||
284 s->http_code == 303 || s->http_code == 307) &&
285 location_changed == 1) {
286 /* url moved, get next */
287 ffurl_closep(&s->hd);
288 if (redirects++ >= MAX_REDIRECTS)
290 /* Restart the authentication process with the new target, which
291 * might use a different auth mechanism. */
292 memset(&s->auth_state, 0, sizeof(s->auth_state));
294 location_changed = 0;
301 ffurl_closep(&s->hd);
302 if (location_changed < 0)
303 return location_changed;
304 return ff_http_averror(s->http_code, AVERROR(EIO));
307 int ff_http_do_new_request(URLContext *h, const char *uri)
309 HTTPContext *s = h->priv_data;
310 AVDictionary *options = NULL;
312 char hostname1[1024], hostname2[1024], proto1[10], proto2[10];
316 !(!strcmp(h->prot->name, "http") ||
317 !strcmp(h->prot->name, "https")))
318 return AVERROR(EINVAL);
320 av_url_split(proto1, sizeof(proto1), NULL, 0,
321 hostname1, sizeof(hostname1), &port1,
322 NULL, 0, s->location);
323 av_url_split(proto2, sizeof(proto2), NULL, 0,
324 hostname2, sizeof(hostname2), &port2,
326 if (port1 != port2 || strncmp(hostname1, hostname2, sizeof(hostname2)) != 0) {
327 av_log(h, AV_LOG_ERROR, "Cannot reuse HTTP connection for different host: %s:%d != %s:%d\n",
331 return AVERROR(EINVAL);
334 if (!s->end_chunked_post) {
335 ret = http_shutdown(h, h->flags);
343 s->end_chunked_post = 0;
346 s->icy_data_read = 0;
347 av_free(s->location);
348 s->location = av_strdup(uri);
350 return AVERROR(ENOMEM);
352 av_log(s, AV_LOG_INFO, "Opening \'%s\' for %s\n", uri, h->flags & AVIO_FLAG_WRITE ? "writing" : "reading");
353 ret = http_open_cnx(h, &options);
354 av_dict_free(&options);
358 int ff_http_averror(int status_code, int default_averror)
360 switch (status_code) {
361 case 400: return AVERROR_HTTP_BAD_REQUEST;
362 case 401: return AVERROR_HTTP_UNAUTHORIZED;
363 case 403: return AVERROR_HTTP_FORBIDDEN;
364 case 404: return AVERROR_HTTP_NOT_FOUND;
367 if (status_code >= 400 && status_code <= 499)
368 return AVERROR_HTTP_OTHER_4XX;
369 else if (status_code >= 500)
370 return AVERROR_HTTP_SERVER_ERROR;
372 return default_averror;
375 static int http_write_reply(URLContext* h, int status_code)
377 int ret, body = 0, reply_code, message_len;
378 const char *reply_text, *content_type;
379 HTTPContext *s = h->priv_data;
380 char message[BUFFER_SIZE];
381 content_type = "text/plain";
385 switch (status_code) {
386 case AVERROR_HTTP_BAD_REQUEST:
389 reply_text = "Bad Request";
391 case AVERROR_HTTP_FORBIDDEN:
394 reply_text = "Forbidden";
396 case AVERROR_HTTP_NOT_FOUND:
399 reply_text = "Not Found";
404 content_type = s->content_type ? s->content_type : "application/octet-stream";
406 case AVERROR_HTTP_SERVER_ERROR:
409 reply_text = "Internal server error";
412 return AVERROR(EINVAL);
416 message_len = snprintf(message, sizeof(message),
417 "HTTP/1.1 %03d %s\r\n"
418 "Content-Type: %s\r\n"
419 "Content-Length: %"SIZE_SPECIFIER"\r\n"
426 strlen(reply_text) + 6, // 3 digit status code + space + \r\n
427 s->headers ? s->headers : "",
432 message_len = snprintf(message, sizeof(message),
433 "HTTP/1.1 %03d %s\r\n"
434 "Content-Type: %s\r\n"
435 "Transfer-Encoding: chunked\r\n"
441 s->headers ? s->headers : "");
443 av_log(h, AV_LOG_TRACE, "HTTP reply header: \n%s----\n", message);
444 if ((ret = ffurl_write(s->hd, message, message_len)) < 0)
449 static void handle_http_errors(URLContext *h, int error)
451 av_assert0(error < 0);
452 http_write_reply(h, error);
455 static int http_handshake(URLContext *c)
457 int ret, err, new_location;
458 HTTPContext *ch = c->priv_data;
459 URLContext *cl = ch->hd;
460 switch (ch->handshake_step) {
462 av_log(c, AV_LOG_TRACE, "Lower protocol\n");
463 if ((ret = ffurl_handshake(cl)) > 0)
467 ch->handshake_step = READ_HEADERS;
468 ch->is_connected_server = 1;
471 av_log(c, AV_LOG_TRACE, "Read headers\n");
472 if ((err = http_read_header(c, &new_location)) < 0) {
473 handle_http_errors(c, err);
476 ch->handshake_step = WRITE_REPLY_HEADERS;
478 case WRITE_REPLY_HEADERS:
479 av_log(c, AV_LOG_TRACE, "Reply code: %d\n", ch->reply_code);
480 if ((err = http_write_reply(c, ch->reply_code)) < 0)
482 ch->handshake_step = FINISH;
487 // this should never be reached.
488 return AVERROR(EINVAL);
491 static int http_listen(URLContext *h, const char *uri, int flags,
492 AVDictionary **options) {
493 HTTPContext *s = h->priv_data;
495 char hostname[1024], proto[10];
497 const char *lower_proto = "tcp";
499 av_url_split(proto, sizeof(proto), NULL, 0, hostname, sizeof(hostname), &port,
501 if (!strcmp(proto, "https"))
503 ff_url_join(lower_url, sizeof(lower_url), lower_proto, NULL, hostname, port,
505 if ((ret = av_dict_set_int(options, "listen", s->listen, 0)) < 0)
507 if ((ret = ffurl_open_whitelist(&s->hd, lower_url, AVIO_FLAG_READ_WRITE,
508 &h->interrupt_callback, options,
509 h->protocol_whitelist, h->protocol_blacklist, h
512 s->handshake_step = LOWER_PROTO;
513 if (s->listen == HTTP_SINGLE) { /* single client */
515 while ((ret = http_handshake(h)) > 0);
518 av_dict_free(&s->chained_options);
522 static int http_open(URLContext *h, const char *uri, int flags,
523 AVDictionary **options)
525 HTTPContext *s = h->priv_data;
528 if( s->seekable == 1 )
533 s->filesize = UINT64_MAX;
534 s->location = av_strdup(uri);
536 return AVERROR(ENOMEM);
538 av_dict_copy(&s->chained_options, *options, 0);
541 int len = strlen(s->headers);
542 if (len < 2 || strcmp("\r\n", s->headers + len - 2)) {
543 av_log(h, AV_LOG_WARNING,
544 "No trailing CRLF found in HTTP header.\n");
545 ret = av_reallocp(&s->headers, len + 3);
548 s->headers[len] = '\r';
549 s->headers[len + 1] = '\n';
550 s->headers[len + 2] = '\0';
555 return http_listen(h, uri, flags, options);
557 ret = http_open_cnx(h, options);
559 av_dict_free(&s->chained_options);
563 static int http_accept(URLContext *s, URLContext **c)
566 HTTPContext *sc = s->priv_data;
568 URLContext *sl = sc->hd;
569 URLContext *cl = NULL;
571 av_assert0(sc->listen);
572 if ((ret = ffurl_alloc(c, s->filename, s->flags, &sl->interrupt_callback)) < 0)
574 cc = (*c)->priv_data;
575 if ((ret = ffurl_accept(sl, &cl)) < 0)
578 cc->is_multi_client = 1;
587 static int http_getc(HTTPContext *s)
590 if (s->buf_ptr >= s->buf_end) {
591 len = ffurl_read(s->hd, s->buffer, BUFFER_SIZE);
594 } else if (len == 0) {
597 s->buf_ptr = s->buffer;
598 s->buf_end = s->buffer + len;
601 return *s->buf_ptr++;
604 static int http_get_line(HTTPContext *s, char *line, int line_size)
616 if (q > line && q[-1] == '\r')
622 if ((q - line) < line_size - 1)
628 static int check_http_code(URLContext *h, int http_code, const char *end)
630 HTTPContext *s = h->priv_data;
631 /* error codes are 4xx and 5xx, but regard 401 as a success, so we
632 * don't abort until all headers have been parsed. */
633 if (http_code >= 400 && http_code < 600 &&
634 (http_code != 401 || s->auth_state.auth_type != HTTP_AUTH_NONE) &&
635 (http_code != 407 || s->proxy_auth_state.auth_type != HTTP_AUTH_NONE)) {
636 end += strspn(end, SPACE_CHARS);
637 av_log(h, AV_LOG_WARNING, "HTTP error %d %s\n", http_code, end);
638 return ff_http_averror(http_code, AVERROR(EIO));
643 static int parse_location(HTTPContext *s, const char *p)
645 char redirected_location[MAX_URL_SIZE], *new_loc;
646 ff_make_absolute_url(redirected_location, sizeof(redirected_location),
648 new_loc = av_strdup(redirected_location);
650 return AVERROR(ENOMEM);
651 av_free(s->location);
652 s->location = new_loc;
656 /* "bytes $from-$to/$document_size" */
657 static void parse_content_range(URLContext *h, const char *p)
659 HTTPContext *s = h->priv_data;
662 if (!strncmp(p, "bytes ", 6)) {
664 s->off = strtoull(p, NULL, 10);
665 if ((slash = strchr(p, '/')) && strlen(slash) > 0)
666 s->filesize = strtoull(slash + 1, NULL, 10);
668 if (s->seekable == -1 && (!s->is_akamai || s->filesize != 2147483647))
669 h->is_streamed = 0; /* we _can_ in fact seek */
672 static int parse_content_encoding(URLContext *h, const char *p)
674 if (!av_strncasecmp(p, "gzip", 4) ||
675 !av_strncasecmp(p, "deflate", 7)) {
677 HTTPContext *s = h->priv_data;
680 inflateEnd(&s->inflate_stream);
681 if (inflateInit2(&s->inflate_stream, 32 + 15) != Z_OK) {
682 av_log(h, AV_LOG_WARNING, "Error during zlib initialisation: %s\n",
683 s->inflate_stream.msg);
684 return AVERROR(ENOSYS);
686 if (zlibCompileFlags() & (1 << 17)) {
687 av_log(h, AV_LOG_WARNING,
688 "Your zlib was compiled without gzip support.\n");
689 return AVERROR(ENOSYS);
692 av_log(h, AV_LOG_WARNING,
693 "Compressed (%s) content, need zlib with gzip support\n", p);
694 return AVERROR(ENOSYS);
695 #endif /* CONFIG_ZLIB */
696 } else if (!av_strncasecmp(p, "identity", 8)) {
697 // The normal, no-encoding case (although servers shouldn't include
698 // the header at all if this is the case).
700 av_log(h, AV_LOG_WARNING, "Unknown content coding: %s\n", p);
705 // Concat all Icy- header lines
706 static int parse_icy(HTTPContext *s, const char *tag, const char *p)
708 int len = 4 + strlen(p) + strlen(tag);
709 int is_first = !s->icy_metadata_headers;
712 av_dict_set(&s->metadata, tag, p, 0);
714 if (s->icy_metadata_headers)
715 len += strlen(s->icy_metadata_headers);
717 if ((ret = av_reallocp(&s->icy_metadata_headers, len)) < 0)
721 *s->icy_metadata_headers = '\0';
723 av_strlcatf(s->icy_metadata_headers, len, "%s: %s\n", tag, p);
728 static int parse_set_cookie_expiry_time(const char *exp_str, struct tm *buf)
730 char exp_buf[MAX_EXPIRY];
731 int i, j, exp_buf_len = MAX_EXPIRY-1;
734 // strip off any punctuation or whitespace
735 for (i = 0, j = 0; exp_str[i] != '\0' && j < exp_buf_len; i++) {
736 if ((exp_str[i] >= '0' && exp_str[i] <= '9') ||
737 (exp_str[i] >= 'A' && exp_str[i] <= 'Z') ||
738 (exp_str[i] >= 'a' && exp_str[i] <= 'z')) {
739 exp_buf[j] = exp_str[i];
746 // move the string beyond the day of week
747 while ((*expiry < '0' || *expiry > '9') && *expiry != '\0')
750 return av_small_strptime(expiry, "%d%b%Y%H%M%S", buf) ? 0 : AVERROR(EINVAL);
753 static int parse_set_cookie(const char *set_cookie, AVDictionary **dict)
755 char *param, *next_param, *cstr, *back;
760 if (!(cstr = av_strdup(set_cookie)))
761 return AVERROR(EINVAL);
763 // strip any trailing whitespace
764 back = &cstr[strlen(cstr)-1];
765 while (strchr(WHITESPACES, *back)) {
773 while ((param = av_strtok(next_param, ";", &next_param))) {
775 param += strspn(param, WHITESPACES);
776 if ((name = av_strtok(param, "=", &value))) {
777 if (av_dict_set(dict, name, value, 0) < 0) {
788 static int parse_cookie(HTTPContext *s, const char *p, AVDictionary **cookies)
790 AVDictionary *new_params = NULL;
791 AVDictionaryEntry *e, *cookie_entry;
794 // ensure the cookie is parsable
795 if (parse_set_cookie(p, &new_params))
798 // if there is no cookie value there is nothing to parse
799 cookie_entry = av_dict_get(new_params, "", NULL, AV_DICT_IGNORE_SUFFIX);
800 if (!cookie_entry || !cookie_entry->value) {
801 av_dict_free(&new_params);
805 // ensure the cookie is not expired or older than an existing value
806 if ((e = av_dict_get(new_params, "expires", NULL, 0)) && e->value) {
807 struct tm new_tm = {0};
808 if (!parse_set_cookie_expiry_time(e->value, &new_tm)) {
809 AVDictionaryEntry *e2;
811 // if the cookie has already expired ignore it
812 if (av_timegm(&new_tm) < av_gettime() / 1000000) {
813 av_dict_free(&new_params);
817 // only replace an older cookie with the same name
818 e2 = av_dict_get(*cookies, cookie_entry->key, NULL, 0);
819 if (e2 && e2->value) {
820 AVDictionary *old_params = NULL;
821 if (!parse_set_cookie(p, &old_params)) {
822 e2 = av_dict_get(old_params, "expires", NULL, 0);
823 if (e2 && e2->value) {
824 struct tm old_tm = {0};
825 if (!parse_set_cookie_expiry_time(e->value, &old_tm)) {
826 if (av_timegm(&new_tm) < av_timegm(&old_tm)) {
827 av_dict_free(&new_params);
828 av_dict_free(&old_params);
834 av_dict_free(&old_params);
838 av_dict_free(&new_params);
840 // duplicate the cookie name (dict will dupe the value)
841 if (!(eql = strchr(p, '='))) return AVERROR(EINVAL);
842 if (!(name = av_strndup(p, eql - p))) return AVERROR(ENOMEM);
844 // add the cookie to the dictionary
845 av_dict_set(cookies, name, eql, AV_DICT_DONT_STRDUP_KEY);
850 static int cookie_string(AVDictionary *dict, char **cookies)
852 AVDictionaryEntry *e = NULL;
855 // determine how much memory is needed for the cookies string
856 while (e = av_dict_get(dict, "", e, AV_DICT_IGNORE_SUFFIX))
857 len += strlen(e->key) + strlen(e->value) + 1;
859 // reallocate the cookies
861 if (*cookies) av_free(*cookies);
862 *cookies = av_malloc(len);
863 if (!*cookies) return AVERROR(ENOMEM);
866 // write out the cookies
867 while (e = av_dict_get(dict, "", e, AV_DICT_IGNORE_SUFFIX))
868 av_strlcatf(*cookies, len, "%s%s\n", e->key, e->value);
873 static int process_line(URLContext *h, char *line, int line_count,
876 HTTPContext *s = h->priv_data;
877 const char *auto_method = h->flags & AVIO_FLAG_READ ? "POST" : "GET";
878 char *tag, *p, *end, *method, *resource, *version;
882 if (line[0] == '\0') {
888 if (line_count == 0) {
889 if (s->is_connected_server) {
892 while (*p && !av_isspace(*p))
895 av_log(h, AV_LOG_TRACE, "Received method: %s\n", method);
897 if (av_strcasecmp(s->method, method)) {
898 av_log(h, AV_LOG_ERROR, "Received and expected HTTP method do not match. (%s expected, %s received)\n",
900 return ff_http_averror(400, AVERROR(EIO));
903 // use autodetected HTTP method to expect
904 av_log(h, AV_LOG_TRACE, "Autodetected %s HTTP method\n", auto_method);
905 if (av_strcasecmp(auto_method, method)) {
906 av_log(h, AV_LOG_ERROR, "Received and autodetected HTTP method did not match "
907 "(%s autodetected %s received)\n", auto_method, method);
908 return ff_http_averror(400, AVERROR(EIO));
910 if (!(s->method = av_strdup(method)))
911 return AVERROR(ENOMEM);
915 while (av_isspace(*p))
918 while (!av_isspace(*p))
921 av_log(h, AV_LOG_TRACE, "Requested resource: %s\n", resource);
922 if (!(s->resource = av_strdup(resource)))
923 return AVERROR(ENOMEM);
926 while (av_isspace(*p))
929 while (*p && !av_isspace(*p))
932 if (av_strncasecmp(version, "HTTP/", 5)) {
933 av_log(h, AV_LOG_ERROR, "Malformed HTTP version string.\n");
934 return ff_http_averror(400, AVERROR(EIO));
936 av_log(h, AV_LOG_TRACE, "HTTP version string: %s\n", version);
938 if (av_strncasecmp(p, "HTTP/1.0", 8) == 0)
940 while (*p != '/' && *p != '\0')
944 av_freep(&s->http_version);
945 s->http_version = av_strndup(p, 3);
946 while (!av_isspace(*p) && *p != '\0')
948 while (av_isspace(*p))
950 s->http_code = strtol(p, &end, 10);
952 av_log(h, AV_LOG_TRACE, "http_code=%d\n", s->http_code);
954 if ((ret = check_http_code(h, s->http_code, end)) < 0)
958 while (*p != '\0' && *p != ':')
966 while (av_isspace(*p))
968 if (!av_strcasecmp(tag, "Location")) {
969 if ((ret = parse_location(s, p)) < 0)
972 } else if (!av_strcasecmp(tag, "Content-Length") &&
973 s->filesize == UINT64_MAX) {
974 s->filesize = strtoull(p, NULL, 10);
975 } else if (!av_strcasecmp(tag, "Content-Range")) {
976 parse_content_range(h, p);
977 } else if (!av_strcasecmp(tag, "Accept-Ranges") &&
978 !strncmp(p, "bytes", 5) &&
981 } else if (!av_strcasecmp(tag, "Transfer-Encoding") &&
982 !av_strncasecmp(p, "chunked", 7)) {
983 s->filesize = UINT64_MAX;
985 } else if (!av_strcasecmp(tag, "WWW-Authenticate")) {
986 ff_http_auth_handle_header(&s->auth_state, tag, p);
987 } else if (!av_strcasecmp(tag, "Authentication-Info")) {
988 ff_http_auth_handle_header(&s->auth_state, tag, p);
989 } else if (!av_strcasecmp(tag, "Proxy-Authenticate")) {
990 ff_http_auth_handle_header(&s->proxy_auth_state, tag, p);
991 } else if (!av_strcasecmp(tag, "Connection")) {
992 if (!strcmp(p, "close"))
994 } else if (!av_strcasecmp(tag, "Server")) {
995 if (!av_strcasecmp(p, "AkamaiGHost")) {
997 } else if (!av_strncasecmp(p, "MediaGateway", 12)) {
998 s->is_mediagateway = 1;
1000 } else if (!av_strcasecmp(tag, "Content-Type")) {
1001 av_free(s->mime_type);
1002 s->mime_type = av_strdup(p);
1003 } else if (!av_strcasecmp(tag, "Set-Cookie")) {
1004 if (parse_cookie(s, p, &s->cookie_dict))
1005 av_log(h, AV_LOG_WARNING, "Unable to parse '%s'\n", p);
1006 } else if (!av_strcasecmp(tag, "Icy-MetaInt")) {
1007 s->icy_metaint = strtoull(p, NULL, 10);
1008 } else if (!av_strncasecmp(tag, "Icy-", 4)) {
1009 if ((ret = parse_icy(s, tag, p)) < 0)
1011 } else if (!av_strcasecmp(tag, "Content-Encoding")) {
1012 if ((ret = parse_content_encoding(h, p)) < 0)
1020 * Create a string containing cookie values for use as a HTTP cookie header
1021 * field value for a particular path and domain from the cookie values stored in
1022 * the HTTP protocol context. The cookie string is stored in *cookies, and may
1023 * be NULL if there are no valid cookies.
1025 * @return a negative value if an error condition occurred, 0 otherwise
1027 static int get_cookies(HTTPContext *s, char **cookies, const char *path,
1030 // cookie strings will look like Set-Cookie header field values. Multiple
1031 // Set-Cookie fields will result in multiple values delimited by a newline
1033 char *cookie, *set_cookies, *next;
1035 // destroy any cookies in the dictionary.
1036 av_dict_free(&s->cookie_dict);
1041 next = set_cookies = av_strdup(s->cookies);
1043 return AVERROR(ENOMEM);
1046 while ((cookie = av_strtok(next, "\n", &next)) && !ret) {
1047 AVDictionary *cookie_params = NULL;
1048 AVDictionaryEntry *cookie_entry, *e;
1050 // store the cookie in a dict in case it is updated in the response
1051 if (parse_cookie(s, cookie, &s->cookie_dict))
1052 av_log(s, AV_LOG_WARNING, "Unable to parse '%s'\n", cookie);
1054 // continue on to the next cookie if this one cannot be parsed
1055 if (parse_set_cookie(cookie, &cookie_params))
1058 // if the cookie has no value, skip it
1059 cookie_entry = av_dict_get(cookie_params, "", NULL, AV_DICT_IGNORE_SUFFIX);
1060 if (!cookie_entry || !cookie_entry->value)
1063 // if the cookie has expired, don't add it
1064 if ((e = av_dict_get(cookie_params, "expires", NULL, 0)) && e->value) {
1065 struct tm tm_buf = {0};
1066 if (!parse_set_cookie_expiry_time(e->value, &tm_buf)) {
1067 if (av_timegm(&tm_buf) < av_gettime() / 1000000)
1072 // if no domain in the cookie assume it appied to this request
1073 if ((e = av_dict_get(cookie_params, "domain", NULL, 0)) && e->value) {
1074 // find the offset comparison is on the min domain (b.com, not a.b.com)
1075 int domain_offset = strlen(domain) - strlen(e->value);
1076 if (domain_offset < 0)
1079 // match the cookie domain
1080 if (av_strcasecmp(&domain[domain_offset], e->value))
1084 // ensure this cookie matches the path
1085 e = av_dict_get(cookie_params, "path", NULL, 0);
1086 if (!e || av_strncasecmp(path, e->value, strlen(e->value)))
1089 // cookie parameters match, so copy the value
1091 *cookies = av_asprintf("%s=%s", cookie_entry->key, cookie_entry->value);
1093 char *tmp = *cookies;
1094 *cookies = av_asprintf("%s; %s=%s", tmp, cookie_entry->key, cookie_entry->value);
1098 ret = AVERROR(ENOMEM);
1101 av_dict_free(&cookie_params);
1104 av_free(set_cookies);
1109 static inline int has_header(const char *str, const char *header)
1111 /* header + 2 to skip over CRLF prefix. (make sure you have one!) */
1114 return av_stristart(str, header + 2, NULL) || av_stristr(str, header);
1117 static int http_read_header(URLContext *h, int *new_location)
1119 HTTPContext *s = h->priv_data;
1120 char line[MAX_URL_SIZE];
1123 s->chunksize = UINT64_MAX;
1126 if ((err = http_get_line(s, line, sizeof(line))) < 0)
1129 av_log(h, AV_LOG_TRACE, "header='%s'\n", line);
1131 err = process_line(h, line, s->line_count, new_location);
1139 if (s->seekable == -1 && s->is_mediagateway && s->filesize == 2000000000)
1140 h->is_streamed = 1; /* we can in fact _not_ seek */
1142 // add any new cookies into the existing cookie string
1143 cookie_string(s->cookie_dict, &s->cookies);
1144 av_dict_free(&s->cookie_dict);
1149 static int http_connect(URLContext *h, const char *path, const char *local_path,
1150 const char *hoststr, const char *auth,
1151 const char *proxyauth, int *new_location)
1153 HTTPContext *s = h->priv_data;
1155 char headers[HTTP_HEADERS_SIZE] = "";
1156 char *authstr = NULL, *proxyauthstr = NULL;
1157 uint64_t off = s->off;
1160 int send_expect_100 = 0;
1163 /* send http header */
1164 post = h->flags & AVIO_FLAG_WRITE;
1167 /* force POST method and disable chunked encoding when
1168 * custom HTTP post data is set */
1170 s->chunked_post = 0;
1176 method = post ? "POST" : "GET";
1178 authstr = ff_http_auth_create_response(&s->auth_state, auth,
1179 local_path, method);
1180 proxyauthstr = ff_http_auth_create_response(&s->proxy_auth_state, proxyauth,
1181 local_path, method);
1182 if (post && !s->post_data) {
1183 send_expect_100 = s->send_expect_100;
1184 /* The user has supplied authentication but we don't know the auth type,
1185 * send Expect: 100-continue to get the 401 response including the
1186 * WWW-Authenticate header, or an 100 continue if no auth actually
1188 if (auth && *auth &&
1189 s->auth_state.auth_type == HTTP_AUTH_NONE &&
1190 s->http_code != 401)
1191 send_expect_100 = 1;
1194 #if FF_API_HTTP_USER_AGENT
1195 if (strcmp(s->user_agent_deprecated, DEFAULT_USER_AGENT)) {
1196 av_log(s, AV_LOG_WARNING, "the user-agent option is deprecated, please use user_agent option\n");
1197 s->user_agent = av_strdup(s->user_agent_deprecated);
1200 /* set default headers if needed */
1201 if (!has_header(s->headers, "\r\nUser-Agent: "))
1202 len += av_strlcatf(headers + len, sizeof(headers) - len,
1203 "User-Agent: %s\r\n", s->user_agent);
1205 /* set default headers if needed */
1206 if (!has_header(s->headers, "\r\nReferer: "))
1207 len += av_strlcatf(headers + len, sizeof(headers) - len,
1208 "Referer: %s\r\n", s->referer);
1210 if (!has_header(s->headers, "\r\nAccept: "))
1211 len += av_strlcpy(headers + len, "Accept: */*\r\n",
1212 sizeof(headers) - len);
1213 // Note: we send this on purpose even when s->off is 0 when we're probing,
1214 // since it allows us to detect more reliably if a (non-conforming)
1215 // server supports seeking by analysing the reply headers.
1216 if (!has_header(s->headers, "\r\nRange: ") && !post && (s->off > 0 || s->end_off || s->seekable == -1)) {
1217 len += av_strlcatf(headers + len, sizeof(headers) - len,
1218 "Range: bytes=%"PRIu64"-", s->off);
1220 len += av_strlcatf(headers + len, sizeof(headers) - len,
1221 "%"PRId64, s->end_off - 1);
1222 len += av_strlcpy(headers + len, "\r\n",
1223 sizeof(headers) - len);
1225 if (send_expect_100 && !has_header(s->headers, "\r\nExpect: "))
1226 len += av_strlcatf(headers + len, sizeof(headers) - len,
1227 "Expect: 100-continue\r\n");
1229 if (!has_header(s->headers, "\r\nConnection: ")) {
1230 if (s->multiple_requests)
1231 len += av_strlcpy(headers + len, "Connection: keep-alive\r\n",
1232 sizeof(headers) - len);
1234 len += av_strlcpy(headers + len, "Connection: close\r\n",
1235 sizeof(headers) - len);
1238 if (!has_header(s->headers, "\r\nHost: "))
1239 len += av_strlcatf(headers + len, sizeof(headers) - len,
1240 "Host: %s\r\n", hoststr);
1241 if (!has_header(s->headers, "\r\nContent-Length: ") && s->post_data)
1242 len += av_strlcatf(headers + len, sizeof(headers) - len,
1243 "Content-Length: %d\r\n", s->post_datalen);
1245 if (!has_header(s->headers, "\r\nContent-Type: ") && s->content_type)
1246 len += av_strlcatf(headers + len, sizeof(headers) - len,
1247 "Content-Type: %s\r\n", s->content_type);
1248 if (!has_header(s->headers, "\r\nCookie: ") && s->cookies) {
1249 char *cookies = NULL;
1250 if (!get_cookies(s, &cookies, path, hoststr) && cookies) {
1251 len += av_strlcatf(headers + len, sizeof(headers) - len,
1252 "Cookie: %s\r\n", cookies);
1256 if (!has_header(s->headers, "\r\nIcy-MetaData: ") && s->icy)
1257 len += av_strlcatf(headers + len, sizeof(headers) - len,
1258 "Icy-MetaData: %d\r\n", 1);
1260 /* now add in custom headers */
1262 av_strlcpy(headers + len, s->headers, sizeof(headers) - len);
1264 ret = snprintf(s->buffer, sizeof(s->buffer),
1265 "%s %s HTTP/1.1\r\n"
1273 post && s->chunked_post ? "Transfer-Encoding: chunked\r\n" : "",
1275 authstr ? authstr : "",
1276 proxyauthstr ? "Proxy-" : "", proxyauthstr ? proxyauthstr : "");
1278 av_log(h, AV_LOG_DEBUG, "request: %s\n", s->buffer);
1280 if (strlen(headers) + 1 == sizeof(headers) ||
1281 ret >= sizeof(s->buffer)) {
1282 av_log(h, AV_LOG_ERROR, "overlong headers\n");
1283 err = AVERROR(EINVAL);
1288 if ((err = ffurl_write(s->hd, s->buffer, strlen(s->buffer))) < 0)
1292 if ((err = ffurl_write(s->hd, s->post_data, s->post_datalen)) < 0)
1295 /* init input buffer */
1296 s->buf_ptr = s->buffer;
1297 s->buf_end = s->buffer;
1300 s->icy_data_read = 0;
1301 s->filesize = UINT64_MAX;
1303 s->end_chunked_post = 0;
1308 if (post && !s->post_data && !send_expect_100) {
1309 /* Pretend that it did work. We didn't read any header yet, since
1310 * we've still to send the POST data, but the code calling this
1311 * function will check http_code after we return. */
1317 /* wait for header */
1318 err = http_read_header(h, new_location);
1325 err = (off == s->off) ? 0 : -1;
1328 av_freep(&proxyauthstr);
1332 static int http_buf_read(URLContext *h, uint8_t *buf, int size)
1334 HTTPContext *s = h->priv_data;
1337 if (s->chunksize != UINT64_MAX) {
1341 if (!s->chunksize) {
1346 if ((err = http_get_line(s, line, sizeof(line))) < 0)
1348 } while (!*line); /* skip CR LF from last chunk */
1350 s->chunksize = strtoull(line, NULL, 16);
1352 av_log(h, AV_LOG_TRACE,
1353 "Chunked encoding data size: %"PRIu64"\n",
1356 if (!s->chunksize && s->multiple_requests) {
1357 http_get_line(s, line, sizeof(line)); // read empty chunk
1361 else if (!s->chunksize) {
1362 av_log(h, AV_LOG_DEBUG, "Last chunk received, closing conn\n");
1363 ffurl_closep(&s->hd);
1366 else if (s->chunksize == UINT64_MAX) {
1367 av_log(h, AV_LOG_ERROR, "Invalid chunk size %"PRIu64"\n",
1369 return AVERROR(EINVAL);
1372 size = FFMIN(size, s->chunksize);
1375 /* read bytes from input buffer first */
1376 len = s->buf_end - s->buf_ptr;
1380 memcpy(buf, s->buf_ptr, len);
1383 uint64_t target_end = s->end_off ? s->end_off : s->filesize;
1384 if ((!s->willclose || s->chunksize == UINT64_MAX) && s->off >= target_end)
1386 len = ffurl_read(s->hd, buf, size);
1387 if (!len && (!s->willclose || s->chunksize == UINT64_MAX) && s->off < target_end) {
1388 av_log(h, AV_LOG_ERROR,
1389 "Stream ends prematurely at %"PRIu64", should be %"PRIu64"\n",
1392 return AVERROR(EIO);
1397 if (s->chunksize > 0 && s->chunksize != UINT64_MAX) {
1398 av_assert0(s->chunksize >= len);
1399 s->chunksize -= len;
1406 #define DECOMPRESS_BUF_SIZE (256 * 1024)
1407 static int http_buf_read_compressed(URLContext *h, uint8_t *buf, int size)
1409 HTTPContext *s = h->priv_data;
1412 if (!s->inflate_buffer) {
1413 s->inflate_buffer = av_malloc(DECOMPRESS_BUF_SIZE);
1414 if (!s->inflate_buffer)
1415 return AVERROR(ENOMEM);
1418 if (s->inflate_stream.avail_in == 0) {
1419 int read = http_buf_read(h, s->inflate_buffer, DECOMPRESS_BUF_SIZE);
1422 s->inflate_stream.next_in = s->inflate_buffer;
1423 s->inflate_stream.avail_in = read;
1426 s->inflate_stream.avail_out = size;
1427 s->inflate_stream.next_out = buf;
1429 ret = inflate(&s->inflate_stream, Z_SYNC_FLUSH);
1430 if (ret != Z_OK && ret != Z_STREAM_END)
1431 av_log(h, AV_LOG_WARNING, "inflate return value: %d, %s\n",
1432 ret, s->inflate_stream.msg);
1434 return size - s->inflate_stream.avail_out;
1436 #endif /* CONFIG_ZLIB */
1438 static int64_t http_seek_internal(URLContext *h, int64_t off, int whence, int force_reconnect);
1440 static int http_read_stream(URLContext *h, uint8_t *buf, int size)
1442 HTTPContext *s = h->priv_data;
1443 int err, new_location, read_ret;
1445 int reconnect_delay = 0;
1450 if (s->end_chunked_post && !s->end_header) {
1451 err = http_read_header(h, &new_location);
1458 return http_buf_read_compressed(h, buf, size);
1459 #endif /* CONFIG_ZLIB */
1460 read_ret = http_buf_read(h, buf, size);
1461 while (read_ret < 0) {
1462 uint64_t target = h->is_streamed ? 0 : s->off;
1464 if (read_ret == AVERROR_EXIT)
1467 if (h->is_streamed && !s->reconnect_streamed)
1470 if (!(s->reconnect && s->filesize > 0 && s->off < s->filesize) &&
1471 !(s->reconnect_at_eof && read_ret == AVERROR_EOF))
1474 if (reconnect_delay > s->reconnect_delay_max)
1475 return AVERROR(EIO);
1477 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));
1478 err = ff_network_sleep_interruptible(1000U*1000*reconnect_delay, &h->interrupt_callback);
1479 if (err != AVERROR(ETIMEDOUT))
1481 reconnect_delay = 1 + 2*reconnect_delay;
1482 seek_ret = http_seek_internal(h, target, SEEK_SET, 1);
1483 if (seek_ret >= 0 && seek_ret != target) {
1484 av_log(h, AV_LOG_ERROR, "Failed to reconnect at %"PRIu64".\n", target);
1488 read_ret = http_buf_read(h, buf, size);
1494 // Like http_read_stream(), but no short reads.
1495 // Assumes partial reads are an error.
1496 static int http_read_stream_all(URLContext *h, uint8_t *buf, int size)
1499 while (pos < size) {
1500 int len = http_read_stream(h, buf + pos, size - pos);
1508 static void update_metadata(HTTPContext *s, char *data)
1517 val = strstr(key, "='");
1520 end = strstr(val, "';");
1528 av_dict_set(&s->metadata, key, val, 0);
1534 static int store_icy(URLContext *h, int size)
1536 HTTPContext *s = h->priv_data;
1537 /* until next metadata packet */
1540 if (s->icy_metaint < s->icy_data_read)
1541 return AVERROR_INVALIDDATA;
1542 remaining = s->icy_metaint - s->icy_data_read;
1545 /* The metadata packet is variable sized. It has a 1 byte header
1546 * which sets the length of the packet (divided by 16). If it's 0,
1547 * the metadata doesn't change. After the packet, icy_metaint bytes
1548 * of normal data follows. */
1550 int len = http_read_stream_all(h, &ch, 1);
1554 char data[255 * 16 + 1];
1557 ret = http_read_stream_all(h, data, len);
1561 if ((ret = av_opt_set(s, "icy_metadata_packet", data, 0)) < 0)
1563 update_metadata(s, data);
1565 s->icy_data_read = 0;
1566 remaining = s->icy_metaint;
1569 return FFMIN(size, remaining);
1572 static int http_read(URLContext *h, uint8_t *buf, int size)
1574 HTTPContext *s = h->priv_data;
1576 if (s->icy_metaint > 0) {
1577 size = store_icy(h, size);
1582 size = http_read_stream(h, buf, size);
1584 s->icy_data_read += size;
1588 /* used only when posting data */
1589 static int http_write(URLContext *h, const uint8_t *buf, int size)
1591 char temp[11] = ""; /* 32-bit hex + CRLF + nul */
1593 char crlf[] = "\r\n";
1594 HTTPContext *s = h->priv_data;
1596 if (!s->chunked_post) {
1597 /* non-chunked data is sent without any special encoding */
1598 return ffurl_write(s->hd, buf, size);
1601 /* silently ignore zero-size data since chunk encoding that would
1604 /* upload data using chunked encoding */
1605 snprintf(temp, sizeof(temp), "%x\r\n", size);
1607 if ((ret = ffurl_write(s->hd, temp, strlen(temp))) < 0 ||
1608 (ret = ffurl_write(s->hd, buf, size)) < 0 ||
1609 (ret = ffurl_write(s->hd, crlf, sizeof(crlf) - 1)) < 0)
1615 static int http_shutdown(URLContext *h, int flags)
1618 char footer[] = "0\r\n\r\n";
1619 HTTPContext *s = h->priv_data;
1621 /* signal end of chunked encoding if used */
1622 if (((flags & AVIO_FLAG_WRITE) && s->chunked_post) ||
1623 ((flags & AVIO_FLAG_READ) && s->chunked_post && s->listen)) {
1624 ret = ffurl_write(s->hd, footer, sizeof(footer) - 1);
1625 ret = ret > 0 ? 0 : ret;
1626 /* flush the receive buffer when it is write only mode */
1627 if (!(flags & AVIO_FLAG_READ)) {
1630 s->hd->flags |= AVIO_FLAG_NONBLOCK;
1631 read_ret = ffurl_read(s->hd, buf, sizeof(buf));
1632 s->hd->flags &= ~AVIO_FLAG_NONBLOCK;
1633 if (read_ret < 0 && read_ret != AVERROR(EAGAIN)) {
1634 av_log(h, AV_LOG_ERROR, "URL read error: %d\n", read_ret);
1638 s->end_chunked_post = 1;
1644 static int http_close(URLContext *h)
1647 HTTPContext *s = h->priv_data;
1650 inflateEnd(&s->inflate_stream);
1651 av_freep(&s->inflate_buffer);
1652 #endif /* CONFIG_ZLIB */
1654 if (!s->end_chunked_post)
1655 /* Close the write direction by sending the end of chunked encoding. */
1656 ret = http_shutdown(h, h->flags);
1659 ffurl_closep(&s->hd);
1660 av_dict_free(&s->chained_options);
1664 static int64_t http_seek_internal(URLContext *h, int64_t off, int whence, int force_reconnect)
1666 HTTPContext *s = h->priv_data;
1667 URLContext *old_hd = s->hd;
1668 uint64_t old_off = s->off;
1669 uint8_t old_buf[BUFFER_SIZE];
1670 int old_buf_size, ret;
1671 AVDictionary *options = NULL;
1673 if (whence == AVSEEK_SIZE)
1675 else if (!force_reconnect &&
1676 ((whence == SEEK_CUR && off == 0) ||
1677 (whence == SEEK_SET && off == s->off)))
1679 else if ((s->filesize == UINT64_MAX && whence == SEEK_END))
1680 return AVERROR(ENOSYS);
1682 if (whence == SEEK_CUR)
1684 else if (whence == SEEK_END)
1686 else if (whence != SEEK_SET)
1687 return AVERROR(EINVAL);
1689 return AVERROR(EINVAL);
1692 if (s->off && h->is_streamed)
1693 return AVERROR(ENOSYS);
1695 /* we save the old context in case the seek fails */
1696 old_buf_size = s->buf_end - s->buf_ptr;
1697 memcpy(old_buf, s->buf_ptr, old_buf_size);
1700 /* if it fails, continue on old connection */
1701 if ((ret = http_open_cnx(h, &options)) < 0) {
1702 av_dict_free(&options);
1703 memcpy(s->buffer, old_buf, old_buf_size);
1704 s->buf_ptr = s->buffer;
1705 s->buf_end = s->buffer + old_buf_size;
1710 av_dict_free(&options);
1711 ffurl_close(old_hd);
1715 static int64_t http_seek(URLContext *h, int64_t off, int whence)
1717 return http_seek_internal(h, off, whence, 0);
1720 static int http_get_file_handle(URLContext *h)
1722 HTTPContext *s = h->priv_data;
1723 return ffurl_get_file_handle(s->hd);
1726 static int http_get_short_seek(URLContext *h)
1728 HTTPContext *s = h->priv_data;
1729 return ffurl_get_short_seek(s->hd);
1732 #define HTTP_CLASS(flavor) \
1733 static const AVClass flavor ## _context_class = { \
1734 .class_name = # flavor, \
1735 .item_name = av_default_item_name, \
1736 .option = options, \
1737 .version = LIBAVUTIL_VERSION_INT, \
1740 #if CONFIG_HTTP_PROTOCOL
1743 const URLProtocol ff_http_protocol = {
1745 .url_open2 = http_open,
1746 .url_accept = http_accept,
1747 .url_handshake = http_handshake,
1748 .url_read = http_read,
1749 .url_write = http_write,
1750 .url_seek = http_seek,
1751 .url_close = http_close,
1752 .url_get_file_handle = http_get_file_handle,
1753 .url_get_short_seek = http_get_short_seek,
1754 .url_shutdown = http_shutdown,
1755 .priv_data_size = sizeof(HTTPContext),
1756 .priv_data_class = &http_context_class,
1757 .flags = URL_PROTOCOL_FLAG_NETWORK,
1758 .default_whitelist = "http,https,tls,rtp,tcp,udp,crypto,httpproxy"
1760 #endif /* CONFIG_HTTP_PROTOCOL */
1762 #if CONFIG_HTTPS_PROTOCOL
1765 const URLProtocol ff_https_protocol = {
1767 .url_open2 = http_open,
1768 .url_read = http_read,
1769 .url_write = http_write,
1770 .url_seek = http_seek,
1771 .url_close = http_close,
1772 .url_get_file_handle = http_get_file_handle,
1773 .url_get_short_seek = http_get_short_seek,
1774 .url_shutdown = http_shutdown,
1775 .priv_data_size = sizeof(HTTPContext),
1776 .priv_data_class = &https_context_class,
1777 .flags = URL_PROTOCOL_FLAG_NETWORK,
1778 .default_whitelist = "http,https,tls,rtp,tcp,udp,crypto,httpproxy"
1780 #endif /* CONFIG_HTTPS_PROTOCOL */
1782 #if CONFIG_HTTPPROXY_PROTOCOL
1783 static int http_proxy_close(URLContext *h)
1785 HTTPContext *s = h->priv_data;
1787 ffurl_closep(&s->hd);
1791 static int http_proxy_open(URLContext *h, const char *uri, int flags)
1793 HTTPContext *s = h->priv_data;
1794 char hostname[1024], hoststr[1024];
1795 char auth[1024], pathbuf[1024], *path;
1796 char lower_url[100];
1797 int port, ret = 0, attempts = 0;
1798 HTTPAuthType cur_auth_type;
1802 if( s->seekable == 1 )
1807 av_url_split(NULL, 0, auth, sizeof(auth), hostname, sizeof(hostname), &port,
1808 pathbuf, sizeof(pathbuf), uri);
1809 ff_url_join(hoststr, sizeof(hoststr), NULL, NULL, hostname, port, NULL);
1814 ff_url_join(lower_url, sizeof(lower_url), "tcp", NULL, hostname, port,
1817 ret = ffurl_open_whitelist(&s->hd, lower_url, AVIO_FLAG_READ_WRITE,
1818 &h->interrupt_callback, NULL,
1819 h->protocol_whitelist, h->protocol_blacklist, h);
1823 authstr = ff_http_auth_create_response(&s->proxy_auth_state, auth,
1825 snprintf(s->buffer, sizeof(s->buffer),
1826 "CONNECT %s HTTP/1.1\r\n"
1828 "Connection: close\r\n"
1833 authstr ? "Proxy-" : "", authstr ? authstr : "");
1836 if ((ret = ffurl_write(s->hd, s->buffer, strlen(s->buffer))) < 0)
1839 s->buf_ptr = s->buffer;
1840 s->buf_end = s->buffer;
1842 s->filesize = UINT64_MAX;
1843 cur_auth_type = s->proxy_auth_state.auth_type;
1845 /* Note: This uses buffering, potentially reading more than the
1846 * HTTP header. If tunneling a protocol where the server starts
1847 * the conversation, we might buffer part of that here, too.
1848 * Reading that requires using the proper ffurl_read() function
1849 * on this URLContext, not using the fd directly (as the tls
1850 * protocol does). This shouldn't be an issue for tls though,
1851 * since the client starts the conversation there, so there
1852 * is no extra data that we might buffer up here.
1854 ret = http_read_header(h, &new_loc);
1859 if (s->http_code == 407 &&
1860 (cur_auth_type == HTTP_AUTH_NONE || s->proxy_auth_state.stale) &&
1861 s->proxy_auth_state.auth_type != HTTP_AUTH_NONE && attempts < 2) {
1862 ffurl_closep(&s->hd);
1866 if (s->http_code < 400)
1868 ret = ff_http_averror(s->http_code, AVERROR(EIO));
1871 http_proxy_close(h);
1875 static int http_proxy_write(URLContext *h, const uint8_t *buf, int size)
1877 HTTPContext *s = h->priv_data;
1878 return ffurl_write(s->hd, buf, size);
1881 const URLProtocol ff_httpproxy_protocol = {
1882 .name = "httpproxy",
1883 .url_open = http_proxy_open,
1884 .url_read = http_buf_read,
1885 .url_write = http_proxy_write,
1886 .url_close = http_proxy_close,
1887 .url_get_file_handle = http_get_file_handle,
1888 .priv_data_size = sizeof(HTTPContext),
1889 .flags = URL_PROTOCOL_FLAG_NETWORK,
1891 #endif /* CONFIG_HTTPPROXY_PROTOCOL */