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;
79 #if FF_API_HTTP_USER_AGENT
80 char *user_agent_deprecated;
83 /* Set if the server correctly handles Connection: close and will close
84 * the connection after feeding us the content. */
86 int seekable; /**< Control seekability, 0 = disable, 1 = enable, -1 = probe. */
88 /* A flag which indicates if the end of chunked encoding has been sent. */
90 /* A flag which indicates we have finished to read POST reply. */
92 /* A flag which indicates if we use persistent connections. */
93 int multiple_requests;
98 char *cookies; ///< holds newline (\n) delimited Set-Cookie header field values (without the "Set-Cookie: " field name)
99 /* A dictionary containing cookies keyed by cookie name */
100 AVDictionary *cookie_dict;
102 /* how much data was read since the last ICY metadata packet */
103 uint64_t icy_data_read;
104 /* after how many bytes of read data a new metadata packet will be found */
105 uint64_t icy_metaint;
106 char *icy_metadata_headers;
107 char *icy_metadata_packet;
108 AVDictionary *metadata;
111 z_stream inflate_stream;
112 uint8_t *inflate_buffer;
113 #endif /* CONFIG_ZLIB */
114 AVDictionary *chained_options;
118 int reconnect_at_eof;
119 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 #if FF_API_HTTP_USER_AGENT
143 { "user-agent", "override User-Agent header", OFFSET(user_agent_deprecated), AV_OPT_TYPE_STRING, { .str = DEFAULT_USER_AGENT }, 0, 0, D },
145 { "multiple_requests", "use persistent connections", OFFSET(multiple_requests), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, D | E },
146 { "post_data", "set custom HTTP post data", OFFSET(post_data), AV_OPT_TYPE_BINARY, .flags = D | E },
147 { "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 },
148 { "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 },
149 { "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 },
150 { "icy", "request ICY metadata", OFFSET(icy), AV_OPT_TYPE_BOOL, { .i64 = 1 }, 0, 1, D },
151 { "icy_metadata_headers", "return ICY metadata headers", OFFSET(icy_metadata_headers), AV_OPT_TYPE_STRING, { .str = NULL }, 0, 0, AV_OPT_FLAG_EXPORT },
152 { "icy_metadata_packet", "return current ICY metadata packet", OFFSET(icy_metadata_packet), AV_OPT_TYPE_STRING, { .str = NULL }, 0, 0, AV_OPT_FLAG_EXPORT },
153 { "metadata", "metadata read from the bitstream", OFFSET(metadata), AV_OPT_TYPE_DICT, {0}, 0, 0, AV_OPT_FLAG_EXPORT },
154 { "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"},
155 { "none", "No auth method set, autodetect", 0, AV_OPT_TYPE_CONST, { .i64 = HTTP_AUTH_NONE }, 0, 0, D | E, "auth_type"},
156 { "basic", "HTTP basic authentication", 0, AV_OPT_TYPE_CONST, { .i64 = HTTP_AUTH_BASIC }, 0, 0, D | E, "auth_type"},
157 { "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 },
158 { "location", "The actual location of the data received", OFFSET(location), AV_OPT_TYPE_STRING, { .str = NULL }, 0, 0, D | E },
159 { "offset", "initial byte offset", OFFSET(off), AV_OPT_TYPE_INT64, { .i64 = 0 }, 0, INT64_MAX, D },
160 { "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 },
161 { "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 },
162 { "reconnect", "auto reconnect after disconnect before EOF", OFFSET(reconnect), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, D },
163 { "reconnect_at_eof", "auto reconnect at EOF", OFFSET(reconnect_at_eof), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, D },
164 { "reconnect_streamed", "auto reconnect streamed / non seekable streams", OFFSET(reconnect_streamed), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, D },
165 { "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 },
166 { "listen", "listen on HTTP", OFFSET(listen), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 2, D | E },
167 { "resource", "The resource requested by a client", OFFSET(resource), AV_OPT_TYPE_STRING, { .str = NULL }, 0, 0, E },
168 { "reply_code", "The http status code to return to a client", OFFSET(reply_code), AV_OPT_TYPE_INT, { .i64 = 200}, INT_MIN, 599, E},
172 static int http_connect(URLContext *h, const char *path, const char *local_path,
173 const char *hoststr, const char *auth,
174 const char *proxyauth, int *new_location);
175 static int http_read_header(URLContext *h, int *new_location);
176 static int http_shutdown(URLContext *h, int flags);
178 void ff_http_init_auth_state(URLContext *dest, const URLContext *src)
180 memcpy(&((HTTPContext *)dest->priv_data)->auth_state,
181 &((HTTPContext *)src->priv_data)->auth_state,
182 sizeof(HTTPAuthState));
183 memcpy(&((HTTPContext *)dest->priv_data)->proxy_auth_state,
184 &((HTTPContext *)src->priv_data)->proxy_auth_state,
185 sizeof(HTTPAuthState));
188 static int http_open_cnx_internal(URLContext *h, AVDictionary **options)
190 const char *path, *proxy_path, *lower_proto = "tcp", *local_path;
191 char hostname[1024], hoststr[1024], proto[10];
192 char auth[1024], proxyauth[1024] = "";
193 char path1[MAX_URL_SIZE];
194 char buf[1024], urlbuf[MAX_URL_SIZE];
195 int port, use_proxy, err, location_changed = 0;
196 HTTPContext *s = h->priv_data;
198 av_url_split(proto, sizeof(proto), auth, sizeof(auth),
199 hostname, sizeof(hostname), &port,
200 path1, sizeof(path1), s->location);
201 ff_url_join(hoststr, sizeof(hoststr), NULL, NULL, hostname, port, NULL);
203 proxy_path = s->http_proxy ? s->http_proxy : getenv("http_proxy");
204 use_proxy = !ff_http_match_no_proxy(getenv("no_proxy"), hostname) &&
205 proxy_path && av_strstart(proxy_path, "http://", NULL);
207 if (!strcmp(proto, "https")) {
216 if (path1[0] == '\0')
222 /* Reassemble the request URL without auth string - we don't
223 * want to leak the auth to the proxy. */
224 ff_url_join(urlbuf, sizeof(urlbuf), proto, NULL, hostname, port, "%s",
227 av_url_split(NULL, 0, proxyauth, sizeof(proxyauth),
228 hostname, sizeof(hostname), &port, NULL, 0, proxy_path);
231 ff_url_join(buf, sizeof(buf), lower_proto, NULL, hostname, port, NULL);
234 err = ffurl_open_whitelist(&s->hd, buf, AVIO_FLAG_READ_WRITE,
235 &h->interrupt_callback, options,
236 h->protocol_whitelist, h->protocol_blacklist, h);
241 err = http_connect(h, path, local_path, hoststr,
242 auth, proxyauth, &location_changed);
246 return location_changed;
249 /* return non zero if error */
250 static int http_open_cnx(URLContext *h, AVDictionary **options)
252 HTTPAuthType cur_auth_type, cur_proxy_auth_type;
253 HTTPContext *s = h->priv_data;
254 int location_changed, attempts = 0, redirects = 0;
256 av_dict_copy(options, s->chained_options, 0);
258 cur_auth_type = s->auth_state.auth_type;
259 cur_proxy_auth_type = s->auth_state.auth_type;
261 location_changed = http_open_cnx_internal(h, options);
262 if (location_changed < 0)
266 if (s->http_code == 401) {
267 if ((cur_auth_type == HTTP_AUTH_NONE || s->auth_state.stale) &&
268 s->auth_state.auth_type != HTTP_AUTH_NONE && attempts < 4) {
269 ffurl_closep(&s->hd);
274 if (s->http_code == 407) {
275 if ((cur_proxy_auth_type == HTTP_AUTH_NONE || s->proxy_auth_state.stale) &&
276 s->proxy_auth_state.auth_type != HTTP_AUTH_NONE && attempts < 4) {
277 ffurl_closep(&s->hd);
282 if ((s->http_code == 301 || s->http_code == 302 ||
283 s->http_code == 303 || s->http_code == 307) &&
284 location_changed == 1) {
285 /* url moved, get next */
286 ffurl_closep(&s->hd);
287 if (redirects++ >= MAX_REDIRECTS)
289 /* Restart the authentication process with the new target, which
290 * might use a different auth mechanism. */
291 memset(&s->auth_state, 0, sizeof(s->auth_state));
293 location_changed = 0;
300 ffurl_closep(&s->hd);
301 if (location_changed < 0)
302 return location_changed;
303 return ff_http_averror(s->http_code, AVERROR(EIO));
306 int ff_http_do_new_request(URLContext *h, const char *uri)
308 HTTPContext *s = h->priv_data;
309 AVDictionary *options = NULL;
311 char hostname1[1024], hostname2[1024], proto1[10], proto2[10];
314 av_url_split(proto1, sizeof(proto1), NULL, 0,
315 hostname1, sizeof(hostname1), &port1,
316 NULL, 0, s->location);
317 av_url_split(proto2, sizeof(proto2), NULL, 0,
318 hostname2, sizeof(hostname2), &port2,
320 if (port1 != port2 || strncmp(hostname1, hostname2, sizeof(hostname2)) != 0) {
321 av_log(h, AV_LOG_ERROR, "Cannot reuse HTTP connection for different host: %s:%d != %s:%d\n",
325 return AVERROR(EINVAL);
328 if (!s->end_chunked_post) {
329 ret = http_shutdown(h, h->flags);
337 s->end_chunked_post = 0;
340 s->icy_data_read = 0;
341 av_free(s->location);
342 s->location = av_strdup(uri);
344 return AVERROR(ENOMEM);
346 av_log(s, AV_LOG_INFO, "Opening \'%s\' for %s\n", uri, h->flags & AVIO_FLAG_WRITE ? "writing" : "reading");
347 ret = http_open_cnx(h, &options);
348 av_dict_free(&options);
352 int ff_http_averror(int status_code, int default_averror)
354 switch (status_code) {
355 case 400: return AVERROR_HTTP_BAD_REQUEST;
356 case 401: return AVERROR_HTTP_UNAUTHORIZED;
357 case 403: return AVERROR_HTTP_FORBIDDEN;
358 case 404: return AVERROR_HTTP_NOT_FOUND;
361 if (status_code >= 400 && status_code <= 499)
362 return AVERROR_HTTP_OTHER_4XX;
363 else if (status_code >= 500)
364 return AVERROR_HTTP_SERVER_ERROR;
366 return default_averror;
369 static int http_write_reply(URLContext* h, int status_code)
371 int ret, body = 0, reply_code, message_len;
372 const char *reply_text, *content_type;
373 HTTPContext *s = h->priv_data;
374 char message[BUFFER_SIZE];
375 content_type = "text/plain";
379 switch (status_code) {
380 case AVERROR_HTTP_BAD_REQUEST:
383 reply_text = "Bad Request";
385 case AVERROR_HTTP_FORBIDDEN:
388 reply_text = "Forbidden";
390 case AVERROR_HTTP_NOT_FOUND:
393 reply_text = "Not Found";
398 content_type = s->content_type ? s->content_type : "application/octet-stream";
400 case AVERROR_HTTP_SERVER_ERROR:
403 reply_text = "Internal server error";
406 return AVERROR(EINVAL);
410 message_len = snprintf(message, sizeof(message),
411 "HTTP/1.1 %03d %s\r\n"
412 "Content-Type: %s\r\n"
413 "Content-Length: %"SIZE_SPECIFIER"\r\n"
420 strlen(reply_text) + 6, // 3 digit status code + space + \r\n
421 s->headers ? s->headers : "",
426 message_len = snprintf(message, sizeof(message),
427 "HTTP/1.1 %03d %s\r\n"
428 "Content-Type: %s\r\n"
429 "Transfer-Encoding: chunked\r\n"
435 s->headers ? s->headers : "");
437 av_log(h, AV_LOG_TRACE, "HTTP reply header: \n%s----\n", message);
438 if ((ret = ffurl_write(s->hd, message, message_len)) < 0)
443 static void handle_http_errors(URLContext *h, int error)
445 av_assert0(error < 0);
446 http_write_reply(h, error);
449 static int http_handshake(URLContext *c)
451 int ret, err, new_location;
452 HTTPContext *ch = c->priv_data;
453 URLContext *cl = ch->hd;
454 switch (ch->handshake_step) {
456 av_log(c, AV_LOG_TRACE, "Lower protocol\n");
457 if ((ret = ffurl_handshake(cl)) > 0)
461 ch->handshake_step = READ_HEADERS;
462 ch->is_connected_server = 1;
465 av_log(c, AV_LOG_TRACE, "Read headers\n");
466 if ((err = http_read_header(c, &new_location)) < 0) {
467 handle_http_errors(c, err);
470 ch->handshake_step = WRITE_REPLY_HEADERS;
472 case WRITE_REPLY_HEADERS:
473 av_log(c, AV_LOG_TRACE, "Reply code: %d\n", ch->reply_code);
474 if ((err = http_write_reply(c, ch->reply_code)) < 0)
476 ch->handshake_step = FINISH;
481 // this should never be reached.
482 return AVERROR(EINVAL);
485 static int http_listen(URLContext *h, const char *uri, int flags,
486 AVDictionary **options) {
487 HTTPContext *s = h->priv_data;
489 char hostname[1024], proto[10];
491 const char *lower_proto = "tcp";
493 av_url_split(proto, sizeof(proto), NULL, 0, hostname, sizeof(hostname), &port,
495 if (!strcmp(proto, "https"))
497 ff_url_join(lower_url, sizeof(lower_url), lower_proto, NULL, hostname, port,
499 if ((ret = av_dict_set_int(options, "listen", s->listen, 0)) < 0)
501 if ((ret = ffurl_open_whitelist(&s->hd, lower_url, AVIO_FLAG_READ_WRITE,
502 &h->interrupt_callback, options,
503 h->protocol_whitelist, h->protocol_blacklist, h
506 s->handshake_step = LOWER_PROTO;
507 if (s->listen == HTTP_SINGLE) { /* single client */
509 while ((ret = http_handshake(h)) > 0);
512 av_dict_free(&s->chained_options);
516 static int http_open(URLContext *h, const char *uri, int flags,
517 AVDictionary **options)
519 HTTPContext *s = h->priv_data;
522 if( s->seekable == 1 )
527 s->filesize = UINT64_MAX;
528 s->location = av_strdup(uri);
530 return AVERROR(ENOMEM);
532 av_dict_copy(&s->chained_options, *options, 0);
535 int len = strlen(s->headers);
536 if (len < 2 || strcmp("\r\n", s->headers + len - 2)) {
537 av_log(h, AV_LOG_WARNING,
538 "No trailing CRLF found in HTTP header.\n");
539 ret = av_reallocp(&s->headers, len + 3);
542 s->headers[len] = '\r';
543 s->headers[len + 1] = '\n';
544 s->headers[len + 2] = '\0';
549 return http_listen(h, uri, flags, options);
551 ret = http_open_cnx(h, options);
553 av_dict_free(&s->chained_options);
557 static int http_accept(URLContext *s, URLContext **c)
560 HTTPContext *sc = s->priv_data;
562 URLContext *sl = sc->hd;
563 URLContext *cl = NULL;
565 av_assert0(sc->listen);
566 if ((ret = ffurl_alloc(c, s->filename, s->flags, &sl->interrupt_callback)) < 0)
568 cc = (*c)->priv_data;
569 if ((ret = ffurl_accept(sl, &cl)) < 0)
572 cc->is_multi_client = 1;
577 static int http_getc(HTTPContext *s)
580 if (s->buf_ptr >= s->buf_end) {
581 len = ffurl_read(s->hd, s->buffer, BUFFER_SIZE);
584 } else if (len == 0) {
587 s->buf_ptr = s->buffer;
588 s->buf_end = s->buffer + len;
591 return *s->buf_ptr++;
594 static int http_get_line(HTTPContext *s, char *line, int line_size)
606 if (q > line && q[-1] == '\r')
612 if ((q - line) < line_size - 1)
618 static int check_http_code(URLContext *h, int http_code, const char *end)
620 HTTPContext *s = h->priv_data;
621 /* error codes are 4xx and 5xx, but regard 401 as a success, so we
622 * don't abort until all headers have been parsed. */
623 if (http_code >= 400 && http_code < 600 &&
624 (http_code != 401 || s->auth_state.auth_type != HTTP_AUTH_NONE) &&
625 (http_code != 407 || s->proxy_auth_state.auth_type != HTTP_AUTH_NONE)) {
626 end += strspn(end, SPACE_CHARS);
627 av_log(h, AV_LOG_WARNING, "HTTP error %d %s\n", http_code, end);
628 return ff_http_averror(http_code, AVERROR(EIO));
633 static int parse_location(HTTPContext *s, const char *p)
635 char redirected_location[MAX_URL_SIZE], *new_loc;
636 ff_make_absolute_url(redirected_location, sizeof(redirected_location),
638 new_loc = av_strdup(redirected_location);
640 return AVERROR(ENOMEM);
641 av_free(s->location);
642 s->location = new_loc;
646 /* "bytes $from-$to/$document_size" */
647 static void parse_content_range(URLContext *h, const char *p)
649 HTTPContext *s = h->priv_data;
652 if (!strncmp(p, "bytes ", 6)) {
654 s->off = strtoull(p, NULL, 10);
655 if ((slash = strchr(p, '/')) && strlen(slash) > 0)
656 s->filesize = strtoull(slash + 1, NULL, 10);
658 if (s->seekable == -1 && (!s->is_akamai || s->filesize != 2147483647))
659 h->is_streamed = 0; /* we _can_ in fact seek */
662 static int parse_content_encoding(URLContext *h, const char *p)
664 if (!av_strncasecmp(p, "gzip", 4) ||
665 !av_strncasecmp(p, "deflate", 7)) {
667 HTTPContext *s = h->priv_data;
670 inflateEnd(&s->inflate_stream);
671 if (inflateInit2(&s->inflate_stream, 32 + 15) != Z_OK) {
672 av_log(h, AV_LOG_WARNING, "Error during zlib initialisation: %s\n",
673 s->inflate_stream.msg);
674 return AVERROR(ENOSYS);
676 if (zlibCompileFlags() & (1 << 17)) {
677 av_log(h, AV_LOG_WARNING,
678 "Your zlib was compiled without gzip support.\n");
679 return AVERROR(ENOSYS);
682 av_log(h, AV_LOG_WARNING,
683 "Compressed (%s) content, need zlib with gzip support\n", p);
684 return AVERROR(ENOSYS);
685 #endif /* CONFIG_ZLIB */
686 } else if (!av_strncasecmp(p, "identity", 8)) {
687 // The normal, no-encoding case (although servers shouldn't include
688 // the header at all if this is the case).
690 av_log(h, AV_LOG_WARNING, "Unknown content coding: %s\n", p);
695 // Concat all Icy- header lines
696 static int parse_icy(HTTPContext *s, const char *tag, const char *p)
698 int len = 4 + strlen(p) + strlen(tag);
699 int is_first = !s->icy_metadata_headers;
702 av_dict_set(&s->metadata, tag, p, 0);
704 if (s->icy_metadata_headers)
705 len += strlen(s->icy_metadata_headers);
707 if ((ret = av_reallocp(&s->icy_metadata_headers, len)) < 0)
711 *s->icy_metadata_headers = '\0';
713 av_strlcatf(s->icy_metadata_headers, len, "%s: %s\n", tag, p);
718 static int parse_set_cookie_expiry_time(const char *exp_str, struct tm *buf)
720 char exp_buf[MAX_EXPIRY];
721 int i, j, exp_buf_len = MAX_EXPIRY-1;
724 // strip off any punctuation or whitespace
725 for (i = 0, j = 0; exp_str[i] != '\0' && j < exp_buf_len; i++) {
726 if ((exp_str[i] >= '0' && exp_str[i] <= '9') ||
727 (exp_str[i] >= 'A' && exp_str[i] <= 'Z') ||
728 (exp_str[i] >= 'a' && exp_str[i] <= 'z')) {
729 exp_buf[j] = exp_str[i];
736 // move the string beyond the day of week
737 while ((*expiry < '0' || *expiry > '9') && *expiry != '\0')
740 return av_small_strptime(expiry, "%d%b%Y%H%M%S", buf) ? 0 : AVERROR(EINVAL);
743 static int parse_set_cookie(const char *set_cookie, AVDictionary **dict)
745 char *param, *next_param, *cstr, *back;
747 if (!(cstr = av_strdup(set_cookie)))
748 return AVERROR(EINVAL);
750 // strip any trailing whitespace
751 back = &cstr[strlen(cstr)-1];
752 while (strchr(WHITESPACES, *back)) {
758 while ((param = av_strtok(next_param, ";", &next_param))) {
760 param += strspn(param, WHITESPACES);
761 if ((name = av_strtok(param, "=", &value))) {
762 if (av_dict_set(dict, name, value, 0) < 0) {
773 static int parse_cookie(HTTPContext *s, const char *p, AVDictionary **cookies)
775 AVDictionary *new_params = NULL;
776 AVDictionaryEntry *e, *cookie_entry;
779 // ensure the cookie is parsable
780 if (parse_set_cookie(p, &new_params))
783 // if there is no cookie value there is nothing to parse
784 cookie_entry = av_dict_get(new_params, "", NULL, AV_DICT_IGNORE_SUFFIX);
785 if (!cookie_entry || !cookie_entry->value) {
786 av_dict_free(&new_params);
790 // ensure the cookie is not expired or older than an existing value
791 if ((e = av_dict_get(new_params, "expires", NULL, 0)) && e->value) {
792 struct tm new_tm = {0};
793 if (!parse_set_cookie_expiry_time(e->value, &new_tm)) {
794 AVDictionaryEntry *e2;
796 // if the cookie has already expired ignore it
797 if (av_timegm(&new_tm) < av_gettime() / 1000000) {
798 av_dict_free(&new_params);
802 // only replace an older cookie with the same name
803 e2 = av_dict_get(*cookies, cookie_entry->key, NULL, 0);
804 if (e2 && e2->value) {
805 AVDictionary *old_params = NULL;
806 if (!parse_set_cookie(p, &old_params)) {
807 e2 = av_dict_get(old_params, "expires", NULL, 0);
808 if (e2 && e2->value) {
809 struct tm old_tm = {0};
810 if (!parse_set_cookie_expiry_time(e->value, &old_tm)) {
811 if (av_timegm(&new_tm) < av_timegm(&old_tm)) {
812 av_dict_free(&new_params);
813 av_dict_free(&old_params);
819 av_dict_free(&old_params);
824 // duplicate the cookie name (dict will dupe the value)
825 if (!(eql = strchr(p, '='))) return AVERROR(EINVAL);
826 if (!(name = av_strndup(p, eql - p))) return AVERROR(ENOMEM);
828 // add the cookie to the dictionary
829 av_dict_set(cookies, name, eql, AV_DICT_DONT_STRDUP_KEY);
834 static int cookie_string(AVDictionary *dict, char **cookies)
836 AVDictionaryEntry *e = NULL;
839 // determine how much memory is needed for the cookies string
840 while (e = av_dict_get(dict, "", e, AV_DICT_IGNORE_SUFFIX))
841 len += strlen(e->key) + strlen(e->value) + 1;
843 // reallocate the cookies
845 if (*cookies) av_free(*cookies);
846 *cookies = av_malloc(len);
847 if (!*cookies) return AVERROR(ENOMEM);
850 // write out the cookies
851 while (e = av_dict_get(dict, "", e, AV_DICT_IGNORE_SUFFIX))
852 av_strlcatf(*cookies, len, "%s%s\n", e->key, e->value);
857 static int process_line(URLContext *h, char *line, int line_count,
860 HTTPContext *s = h->priv_data;
861 const char *auto_method = h->flags & AVIO_FLAG_READ ? "POST" : "GET";
862 char *tag, *p, *end, *method, *resource, *version;
866 if (line[0] == '\0') {
872 if (line_count == 0) {
873 if (s->is_connected_server) {
876 while (*p && !av_isspace(*p))
879 av_log(h, AV_LOG_TRACE, "Received method: %s\n", method);
881 if (av_strcasecmp(s->method, method)) {
882 av_log(h, AV_LOG_ERROR, "Received and expected HTTP method do not match. (%s expected, %s received)\n",
884 return ff_http_averror(400, AVERROR(EIO));
887 // use autodetected HTTP method to expect
888 av_log(h, AV_LOG_TRACE, "Autodetected %s HTTP method\n", auto_method);
889 if (av_strcasecmp(auto_method, method)) {
890 av_log(h, AV_LOG_ERROR, "Received and autodetected HTTP method did not match "
891 "(%s autodetected %s received)\n", auto_method, method);
892 return ff_http_averror(400, AVERROR(EIO));
894 if (!(s->method = av_strdup(method)))
895 return AVERROR(ENOMEM);
899 while (av_isspace(*p))
902 while (!av_isspace(*p))
905 av_log(h, AV_LOG_TRACE, "Requested resource: %s\n", resource);
906 if (!(s->resource = av_strdup(resource)))
907 return AVERROR(ENOMEM);
910 while (av_isspace(*p))
913 while (*p && !av_isspace(*p))
916 if (av_strncasecmp(version, "HTTP/", 5)) {
917 av_log(h, AV_LOG_ERROR, "Malformed HTTP version string.\n");
918 return ff_http_averror(400, AVERROR(EIO));
920 av_log(h, AV_LOG_TRACE, "HTTP version string: %s\n", version);
922 if (av_strncasecmp(p, "HTTP/1.0", 8) == 0)
924 while (*p != '/' && *p != '\0')
928 av_freep(&s->http_version);
929 s->http_version = av_strndup(p, 3);
930 while (!av_isspace(*p) && *p != '\0')
932 while (av_isspace(*p))
934 s->http_code = strtol(p, &end, 10);
936 av_log(h, AV_LOG_TRACE, "http_code=%d\n", s->http_code);
938 if ((ret = check_http_code(h, s->http_code, end)) < 0)
942 while (*p != '\0' && *p != ':')
950 while (av_isspace(*p))
952 if (!av_strcasecmp(tag, "Location")) {
953 if ((ret = parse_location(s, p)) < 0)
956 } else if (!av_strcasecmp(tag, "Content-Length") &&
957 s->filesize == UINT64_MAX) {
958 s->filesize = strtoull(p, NULL, 10);
959 } else if (!av_strcasecmp(tag, "Content-Range")) {
960 parse_content_range(h, p);
961 } else if (!av_strcasecmp(tag, "Accept-Ranges") &&
962 !strncmp(p, "bytes", 5) &&
965 } else if (!av_strcasecmp(tag, "Transfer-Encoding") &&
966 !av_strncasecmp(p, "chunked", 7)) {
967 s->filesize = UINT64_MAX;
969 } else if (!av_strcasecmp(tag, "WWW-Authenticate")) {
970 ff_http_auth_handle_header(&s->auth_state, tag, p);
971 } else if (!av_strcasecmp(tag, "Authentication-Info")) {
972 ff_http_auth_handle_header(&s->auth_state, tag, p);
973 } else if (!av_strcasecmp(tag, "Proxy-Authenticate")) {
974 ff_http_auth_handle_header(&s->proxy_auth_state, tag, p);
975 } else if (!av_strcasecmp(tag, "Connection")) {
976 if (!strcmp(p, "close"))
978 } else if (!av_strcasecmp(tag, "Server")) {
979 if (!av_strcasecmp(p, "AkamaiGHost")) {
981 } else if (!av_strncasecmp(p, "MediaGateway", 12)) {
982 s->is_mediagateway = 1;
984 } else if (!av_strcasecmp(tag, "Content-Type")) {
985 av_free(s->mime_type);
986 s->mime_type = av_strdup(p);
987 } else if (!av_strcasecmp(tag, "Set-Cookie")) {
988 if (parse_cookie(s, p, &s->cookie_dict))
989 av_log(h, AV_LOG_WARNING, "Unable to parse '%s'\n", p);
990 } else if (!av_strcasecmp(tag, "Icy-MetaInt")) {
991 s->icy_metaint = strtoull(p, NULL, 10);
992 } else if (!av_strncasecmp(tag, "Icy-", 4)) {
993 if ((ret = parse_icy(s, tag, p)) < 0)
995 } else if (!av_strcasecmp(tag, "Content-Encoding")) {
996 if ((ret = parse_content_encoding(h, p)) < 0)
1004 * Create a string containing cookie values for use as a HTTP cookie header
1005 * field value for a particular path and domain from the cookie values stored in
1006 * the HTTP protocol context. The cookie string is stored in *cookies.
1008 * @return a negative value if an error condition occurred, 0 otherwise
1010 static int get_cookies(HTTPContext *s, char **cookies, const char *path,
1013 // cookie strings will look like Set-Cookie header field values. Multiple
1014 // Set-Cookie fields will result in multiple values delimited by a newline
1016 char *cookie, *set_cookies = av_strdup(s->cookies), *next = set_cookies;
1018 if (!set_cookies) return AVERROR(EINVAL);
1020 // destroy any cookies in the dictionary.
1021 av_dict_free(&s->cookie_dict);
1024 while ((cookie = av_strtok(next, "\n", &next))) {
1025 AVDictionary *cookie_params = NULL;
1026 AVDictionaryEntry *cookie_entry, *e;
1028 // store the cookie in a dict in case it is updated in the response
1029 if (parse_cookie(s, cookie, &s->cookie_dict))
1030 av_log(s, AV_LOG_WARNING, "Unable to parse '%s'\n", cookie);
1032 // continue on to the next cookie if this one cannot be parsed
1033 if (parse_set_cookie(cookie, &cookie_params))
1036 // if the cookie has no value, skip it
1037 cookie_entry = av_dict_get(cookie_params, "", NULL, AV_DICT_IGNORE_SUFFIX);
1038 if (!cookie_entry || !cookie_entry->value) {
1039 av_dict_free(&cookie_params);
1043 // if the cookie has expired, don't add it
1044 if ((e = av_dict_get(cookie_params, "expires", NULL, 0)) && e->value) {
1045 struct tm tm_buf = {0};
1046 if (!parse_set_cookie_expiry_time(e->value, &tm_buf)) {
1047 if (av_timegm(&tm_buf) < av_gettime() / 1000000) {
1048 av_dict_free(&cookie_params);
1054 // if no domain in the cookie assume it appied to this request
1055 if ((e = av_dict_get(cookie_params, "domain", NULL, 0)) && e->value) {
1056 // find the offset comparison is on the min domain (b.com, not a.b.com)
1057 int domain_offset = strlen(domain) - strlen(e->value);
1058 if (domain_offset < 0) {
1059 av_dict_free(&cookie_params);
1063 // match the cookie domain
1064 if (av_strcasecmp(&domain[domain_offset], e->value)) {
1065 av_dict_free(&cookie_params);
1070 // ensure this cookie matches the path
1071 e = av_dict_get(cookie_params, "path", NULL, 0);
1072 if (!e || av_strncasecmp(path, e->value, strlen(e->value))) {
1073 av_dict_free(&cookie_params);
1077 // cookie parameters match, so copy the value
1079 if (!(*cookies = av_asprintf("%s=%s", cookie_entry->key, cookie_entry->value))) {
1080 ret = AVERROR(ENOMEM);
1084 char *tmp = *cookies;
1085 size_t str_size = strlen(cookie_entry->key) + strlen(cookie_entry->value) + strlen(*cookies) + 4;
1086 if (!(*cookies = av_malloc(str_size))) {
1087 ret = AVERROR(ENOMEM);
1091 snprintf(*cookies, str_size, "%s; %s=%s", tmp, cookie_entry->key, cookie_entry->value);
1096 av_free(set_cookies);
1101 static inline int has_header(const char *str, const char *header)
1103 /* header + 2 to skip over CRLF prefix. (make sure you have one!) */
1106 return av_stristart(str, header + 2, NULL) || av_stristr(str, header);
1109 static int http_read_header(URLContext *h, int *new_location)
1111 HTTPContext *s = h->priv_data;
1112 char line[MAX_URL_SIZE];
1115 s->chunksize = UINT64_MAX;
1118 if ((err = http_get_line(s, line, sizeof(line))) < 0)
1121 av_log(h, AV_LOG_TRACE, "header='%s'\n", line);
1123 err = process_line(h, line, s->line_count, new_location);
1131 if (s->seekable == -1 && s->is_mediagateway && s->filesize == 2000000000)
1132 h->is_streamed = 1; /* we can in fact _not_ seek */
1134 // add any new cookies into the existing cookie string
1135 cookie_string(s->cookie_dict, &s->cookies);
1136 av_dict_free(&s->cookie_dict);
1141 static int http_connect(URLContext *h, const char *path, const char *local_path,
1142 const char *hoststr, const char *auth,
1143 const char *proxyauth, int *new_location)
1145 HTTPContext *s = h->priv_data;
1147 char headers[HTTP_HEADERS_SIZE] = "";
1148 char *authstr = NULL, *proxyauthstr = NULL;
1149 uint64_t off = s->off;
1152 int send_expect_100 = 0;
1155 /* send http header */
1156 post = h->flags & AVIO_FLAG_WRITE;
1159 /* force POST method and disable chunked encoding when
1160 * custom HTTP post data is set */
1162 s->chunked_post = 0;
1168 method = post ? "POST" : "GET";
1170 authstr = ff_http_auth_create_response(&s->auth_state, auth,
1171 local_path, method);
1172 proxyauthstr = ff_http_auth_create_response(&s->proxy_auth_state, proxyauth,
1173 local_path, method);
1174 if (post && !s->post_data) {
1175 send_expect_100 = s->send_expect_100;
1176 /* The user has supplied authentication but we don't know the auth type,
1177 * send Expect: 100-continue to get the 401 response including the
1178 * WWW-Authenticate header, or an 100 continue if no auth actually
1180 if (auth && *auth &&
1181 s->auth_state.auth_type == HTTP_AUTH_NONE &&
1182 s->http_code != 401)
1183 send_expect_100 = 1;
1186 #if FF_API_HTTP_USER_AGENT
1187 if (strcmp(s->user_agent_deprecated, DEFAULT_USER_AGENT)) {
1188 av_log(s, AV_LOG_WARNING, "the user-agent option is deprecated, please use user_agent option\n");
1189 s->user_agent = av_strdup(s->user_agent_deprecated);
1192 /* set default headers if needed */
1193 if (!has_header(s->headers, "\r\nUser-Agent: "))
1194 len += av_strlcatf(headers + len, sizeof(headers) - len,
1195 "User-Agent: %s\r\n", s->user_agent);
1196 if (!has_header(s->headers, "\r\nAccept: "))
1197 len += av_strlcpy(headers + len, "Accept: */*\r\n",
1198 sizeof(headers) - len);
1199 // Note: we send this on purpose even when s->off is 0 when we're probing,
1200 // since it allows us to detect more reliably if a (non-conforming)
1201 // server supports seeking by analysing the reply headers.
1202 if (!has_header(s->headers, "\r\nRange: ") && !post && (s->off > 0 || s->end_off || s->seekable == -1)) {
1203 len += av_strlcatf(headers + len, sizeof(headers) - len,
1204 "Range: bytes=%"PRIu64"-", s->off);
1206 len += av_strlcatf(headers + len, sizeof(headers) - len,
1207 "%"PRId64, s->end_off - 1);
1208 len += av_strlcpy(headers + len, "\r\n",
1209 sizeof(headers) - len);
1211 if (send_expect_100 && !has_header(s->headers, "\r\nExpect: "))
1212 len += av_strlcatf(headers + len, sizeof(headers) - len,
1213 "Expect: 100-continue\r\n");
1215 if (!has_header(s->headers, "\r\nConnection: ")) {
1216 if (s->multiple_requests)
1217 len += av_strlcpy(headers + len, "Connection: keep-alive\r\n",
1218 sizeof(headers) - len);
1220 len += av_strlcpy(headers + len, "Connection: close\r\n",
1221 sizeof(headers) - len);
1224 if (!has_header(s->headers, "\r\nHost: "))
1225 len += av_strlcatf(headers + len, sizeof(headers) - len,
1226 "Host: %s\r\n", hoststr);
1227 if (!has_header(s->headers, "\r\nContent-Length: ") && s->post_data)
1228 len += av_strlcatf(headers + len, sizeof(headers) - len,
1229 "Content-Length: %d\r\n", s->post_datalen);
1231 if (!has_header(s->headers, "\r\nContent-Type: ") && s->content_type)
1232 len += av_strlcatf(headers + len, sizeof(headers) - len,
1233 "Content-Type: %s\r\n", s->content_type);
1234 if (!has_header(s->headers, "\r\nCookie: ") && s->cookies) {
1235 char *cookies = NULL;
1236 if (!get_cookies(s, &cookies, path, hoststr) && cookies) {
1237 len += av_strlcatf(headers + len, sizeof(headers) - len,
1238 "Cookie: %s\r\n", cookies);
1242 if (!has_header(s->headers, "\r\nIcy-MetaData: ") && s->icy)
1243 len += av_strlcatf(headers + len, sizeof(headers) - len,
1244 "Icy-MetaData: %d\r\n", 1);
1246 /* now add in custom headers */
1248 av_strlcpy(headers + len, s->headers, sizeof(headers) - len);
1250 ret = snprintf(s->buffer, sizeof(s->buffer),
1251 "%s %s HTTP/1.1\r\n"
1259 post && s->chunked_post ? "Transfer-Encoding: chunked\r\n" : "",
1261 authstr ? authstr : "",
1262 proxyauthstr ? "Proxy-" : "", proxyauthstr ? proxyauthstr : "");
1264 av_log(h, AV_LOG_DEBUG, "request: %s\n", s->buffer);
1266 if (strlen(headers) + 1 == sizeof(headers) ||
1267 ret >= sizeof(s->buffer)) {
1268 av_log(h, AV_LOG_ERROR, "overlong headers\n");
1269 err = AVERROR(EINVAL);
1274 if ((err = ffurl_write(s->hd, s->buffer, strlen(s->buffer))) < 0)
1278 if ((err = ffurl_write(s->hd, s->post_data, s->post_datalen)) < 0)
1281 /* init input buffer */
1282 s->buf_ptr = s->buffer;
1283 s->buf_end = s->buffer;
1286 s->icy_data_read = 0;
1287 s->filesize = UINT64_MAX;
1289 s->end_chunked_post = 0;
1294 if (post && !s->post_data && !send_expect_100) {
1295 /* Pretend that it did work. We didn't read any header yet, since
1296 * we've still to send the POST data, but the code calling this
1297 * function will check http_code after we return. */
1303 /* wait for header */
1304 err = http_read_header(h, new_location);
1311 err = (off == s->off) ? 0 : -1;
1314 av_freep(&proxyauthstr);
1318 static int http_buf_read(URLContext *h, uint8_t *buf, int size)
1320 HTTPContext *s = h->priv_data;
1323 if (s->chunksize != UINT64_MAX) {
1327 if (!s->chunksize) {
1332 if ((err = http_get_line(s, line, sizeof(line))) < 0)
1334 } while (!*line); /* skip CR LF from last chunk */
1336 s->chunksize = strtoull(line, NULL, 16);
1338 av_log(h, AV_LOG_TRACE,
1339 "Chunked encoding data size: %"PRIu64"\n",
1342 if (!s->chunksize && s->multiple_requests) {
1343 http_get_line(s, line, sizeof(line)); // read empty chunk
1347 else if (!s->chunksize) {
1348 av_log(h, AV_LOG_DEBUG, "Last chunk received, closing conn\n");
1349 ffurl_closep(&s->hd);
1352 else if (s->chunksize == UINT64_MAX) {
1353 av_log(h, AV_LOG_ERROR, "Invalid chunk size %"PRIu64"\n",
1355 return AVERROR(EINVAL);
1358 size = FFMIN(size, s->chunksize);
1361 /* read bytes from input buffer first */
1362 len = s->buf_end - s->buf_ptr;
1366 memcpy(buf, s->buf_ptr, len);
1369 uint64_t target_end = s->end_off ? s->end_off : s->filesize;
1370 if ((!s->willclose || s->chunksize == UINT64_MAX) && s->off >= target_end)
1372 len = ffurl_read(s->hd, buf, size);
1373 if (!len && (!s->willclose || s->chunksize == UINT64_MAX) && s->off < target_end) {
1374 av_log(h, AV_LOG_ERROR,
1375 "Stream ends prematurely at %"PRIu64", should be %"PRIu64"\n",
1378 return AVERROR(EIO);
1383 if (s->chunksize > 0 && s->chunksize != UINT64_MAX) {
1384 av_assert0(s->chunksize >= len);
1385 s->chunksize -= len;
1392 #define DECOMPRESS_BUF_SIZE (256 * 1024)
1393 static int http_buf_read_compressed(URLContext *h, uint8_t *buf, int size)
1395 HTTPContext *s = h->priv_data;
1398 if (!s->inflate_buffer) {
1399 s->inflate_buffer = av_malloc(DECOMPRESS_BUF_SIZE);
1400 if (!s->inflate_buffer)
1401 return AVERROR(ENOMEM);
1404 if (s->inflate_stream.avail_in == 0) {
1405 int read = http_buf_read(h, s->inflate_buffer, DECOMPRESS_BUF_SIZE);
1408 s->inflate_stream.next_in = s->inflate_buffer;
1409 s->inflate_stream.avail_in = read;
1412 s->inflate_stream.avail_out = size;
1413 s->inflate_stream.next_out = buf;
1415 ret = inflate(&s->inflate_stream, Z_SYNC_FLUSH);
1416 if (ret != Z_OK && ret != Z_STREAM_END)
1417 av_log(h, AV_LOG_WARNING, "inflate return value: %d, %s\n",
1418 ret, s->inflate_stream.msg);
1420 return size - s->inflate_stream.avail_out;
1422 #endif /* CONFIG_ZLIB */
1424 static int64_t http_seek_internal(URLContext *h, int64_t off, int whence, int force_reconnect);
1426 static int http_read_stream(URLContext *h, uint8_t *buf, int size)
1428 HTTPContext *s = h->priv_data;
1429 int err, new_location, read_ret;
1435 if (s->end_chunked_post && !s->end_header) {
1436 err = http_read_header(h, &new_location);
1443 return http_buf_read_compressed(h, buf, size);
1444 #endif /* CONFIG_ZLIB */
1445 read_ret = http_buf_read(h, buf, size);
1446 if ( (read_ret < 0 && s->reconnect && (!h->is_streamed || s->reconnect_streamed) && s->filesize > 0 && s->off < s->filesize)
1447 || (read_ret == 0 && s->reconnect_at_eof && (!h->is_streamed || s->reconnect_streamed))) {
1448 uint64_t target = h->is_streamed ? 0 : s->off;
1450 if (s->reconnect_delay > s->reconnect_delay_max)
1451 return AVERROR(EIO);
1453 av_log(h, AV_LOG_INFO, "Will reconnect at %"PRIu64" error=%s.\n", s->off, av_err2str(read_ret));
1454 av_usleep(1000U*1000*s->reconnect_delay);
1455 s->reconnect_delay = 1 + 2*s->reconnect_delay;
1456 seek_ret = http_seek_internal(h, target, SEEK_SET, 1);
1457 if (seek_ret != target) {
1458 av_log(h, AV_LOG_ERROR, "Failed to reconnect at %"PRIu64".\n", target);
1462 read_ret = http_buf_read(h, buf, size);
1464 s->reconnect_delay = 0;
1469 // Like http_read_stream(), but no short reads.
1470 // Assumes partial reads are an error.
1471 static int http_read_stream_all(URLContext *h, uint8_t *buf, int size)
1474 while (pos < size) {
1475 int len = http_read_stream(h, buf + pos, size - pos);
1483 static void update_metadata(HTTPContext *s, char *data)
1492 val = strstr(key, "='");
1495 end = strstr(val, "';");
1503 av_dict_set(&s->metadata, key, val, 0);
1509 static int store_icy(URLContext *h, int size)
1511 HTTPContext *s = h->priv_data;
1512 /* until next metadata packet */
1515 if (s->icy_metaint < s->icy_data_read)
1516 return AVERROR_INVALIDDATA;
1517 remaining = s->icy_metaint - s->icy_data_read;
1520 /* The metadata packet is variable sized. It has a 1 byte header
1521 * which sets the length of the packet (divided by 16). If it's 0,
1522 * the metadata doesn't change. After the packet, icy_metaint bytes
1523 * of normal data follows. */
1525 int len = http_read_stream_all(h, &ch, 1);
1529 char data[255 * 16 + 1];
1532 ret = http_read_stream_all(h, data, len);
1536 if ((ret = av_opt_set(s, "icy_metadata_packet", data, 0)) < 0)
1538 update_metadata(s, data);
1540 s->icy_data_read = 0;
1541 remaining = s->icy_metaint;
1544 return FFMIN(size, remaining);
1547 static int http_read(URLContext *h, uint8_t *buf, int size)
1549 HTTPContext *s = h->priv_data;
1551 if (s->icy_metaint > 0) {
1552 size = store_icy(h, size);
1557 size = http_read_stream(h, buf, size);
1559 s->icy_data_read += size;
1563 /* used only when posting data */
1564 static int http_write(URLContext *h, const uint8_t *buf, int size)
1566 char temp[11] = ""; /* 32-bit hex + CRLF + nul */
1568 char crlf[] = "\r\n";
1569 HTTPContext *s = h->priv_data;
1571 if (!s->chunked_post) {
1572 /* non-chunked data is sent without any special encoding */
1573 return ffurl_write(s->hd, buf, size);
1576 /* silently ignore zero-size data since chunk encoding that would
1579 /* upload data using chunked encoding */
1580 snprintf(temp, sizeof(temp), "%x\r\n", size);
1582 if ((ret = ffurl_write(s->hd, temp, strlen(temp))) < 0 ||
1583 (ret = ffurl_write(s->hd, buf, size)) < 0 ||
1584 (ret = ffurl_write(s->hd, crlf, sizeof(crlf) - 1)) < 0)
1590 static int http_shutdown(URLContext *h, int flags)
1593 char footer[] = "0\r\n\r\n";
1594 HTTPContext *s = h->priv_data;
1596 /* signal end of chunked encoding if used */
1597 if (((flags & AVIO_FLAG_WRITE) && s->chunked_post) ||
1598 ((flags & AVIO_FLAG_READ) && s->chunked_post && s->listen)) {
1599 ret = ffurl_write(s->hd, footer, sizeof(footer) - 1);
1600 ret = ret > 0 ? 0 : ret;
1601 s->end_chunked_post = 1;
1607 static int http_close(URLContext *h)
1610 HTTPContext *s = h->priv_data;
1613 inflateEnd(&s->inflate_stream);
1614 av_freep(&s->inflate_buffer);
1615 #endif /* CONFIG_ZLIB */
1617 if (!s->end_chunked_post)
1618 /* Close the write direction by sending the end of chunked encoding. */
1619 ret = http_shutdown(h, h->flags);
1622 ffurl_closep(&s->hd);
1623 av_dict_free(&s->chained_options);
1627 static int64_t http_seek_internal(URLContext *h, int64_t off, int whence, int force_reconnect)
1629 HTTPContext *s = h->priv_data;
1630 URLContext *old_hd = s->hd;
1631 uint64_t old_off = s->off;
1632 uint8_t old_buf[BUFFER_SIZE];
1633 int old_buf_size, ret;
1634 AVDictionary *options = NULL;
1636 if (whence == AVSEEK_SIZE)
1638 else if (!force_reconnect &&
1639 ((whence == SEEK_CUR && off == 0) ||
1640 (whence == SEEK_SET && off == s->off)))
1642 else if ((s->filesize == UINT64_MAX && whence == SEEK_END))
1643 return AVERROR(ENOSYS);
1645 if (whence == SEEK_CUR)
1647 else if (whence == SEEK_END)
1649 else if (whence != SEEK_SET)
1650 return AVERROR(EINVAL);
1652 return AVERROR(EINVAL);
1655 if (s->off && h->is_streamed)
1656 return AVERROR(ENOSYS);
1658 /* we save the old context in case the seek fails */
1659 old_buf_size = s->buf_end - s->buf_ptr;
1660 memcpy(old_buf, s->buf_ptr, old_buf_size);
1663 /* if it fails, continue on old connection */
1664 if ((ret = http_open_cnx(h, &options)) < 0) {
1665 av_dict_free(&options);
1666 memcpy(s->buffer, old_buf, old_buf_size);
1667 s->buf_ptr = s->buffer;
1668 s->buf_end = s->buffer + old_buf_size;
1673 av_dict_free(&options);
1674 ffurl_close(old_hd);
1678 static int64_t http_seek(URLContext *h, int64_t off, int whence)
1680 return http_seek_internal(h, off, whence, 0);
1683 static int http_get_file_handle(URLContext *h)
1685 HTTPContext *s = h->priv_data;
1686 return ffurl_get_file_handle(s->hd);
1689 static int http_get_short_seek(URLContext *h)
1691 HTTPContext *s = h->priv_data;
1692 return ffurl_get_short_seek(s->hd);
1695 #define HTTP_CLASS(flavor) \
1696 static const AVClass flavor ## _context_class = { \
1697 .class_name = # flavor, \
1698 .item_name = av_default_item_name, \
1699 .option = options, \
1700 .version = LIBAVUTIL_VERSION_INT, \
1703 #if CONFIG_HTTP_PROTOCOL
1706 const URLProtocol ff_http_protocol = {
1708 .url_open2 = http_open,
1709 .url_accept = http_accept,
1710 .url_handshake = http_handshake,
1711 .url_read = http_read,
1712 .url_write = http_write,
1713 .url_seek = http_seek,
1714 .url_close = http_close,
1715 .url_get_file_handle = http_get_file_handle,
1716 .url_get_short_seek = http_get_short_seek,
1717 .url_shutdown = http_shutdown,
1718 .priv_data_size = sizeof(HTTPContext),
1719 .priv_data_class = &http_context_class,
1720 .flags = URL_PROTOCOL_FLAG_NETWORK,
1721 .default_whitelist = "http,https,tls,rtp,tcp,udp,crypto,httpproxy"
1723 #endif /* CONFIG_HTTP_PROTOCOL */
1725 #if CONFIG_HTTPS_PROTOCOL
1728 const URLProtocol ff_https_protocol = {
1730 .url_open2 = http_open,
1731 .url_read = http_read,
1732 .url_write = http_write,
1733 .url_seek = http_seek,
1734 .url_close = http_close,
1735 .url_get_file_handle = http_get_file_handle,
1736 .url_get_short_seek = http_get_short_seek,
1737 .url_shutdown = http_shutdown,
1738 .priv_data_size = sizeof(HTTPContext),
1739 .priv_data_class = &https_context_class,
1740 .flags = URL_PROTOCOL_FLAG_NETWORK,
1741 .default_whitelist = "http,https,tls,rtp,tcp,udp,crypto,httpproxy"
1743 #endif /* CONFIG_HTTPS_PROTOCOL */
1745 #if CONFIG_HTTPPROXY_PROTOCOL
1746 static int http_proxy_close(URLContext *h)
1748 HTTPContext *s = h->priv_data;
1750 ffurl_closep(&s->hd);
1754 static int http_proxy_open(URLContext *h, const char *uri, int flags)
1756 HTTPContext *s = h->priv_data;
1757 char hostname[1024], hoststr[1024];
1758 char auth[1024], pathbuf[1024], *path;
1759 char lower_url[100];
1760 int port, ret = 0, attempts = 0;
1761 HTTPAuthType cur_auth_type;
1765 if( s->seekable == 1 )
1770 av_url_split(NULL, 0, auth, sizeof(auth), hostname, sizeof(hostname), &port,
1771 pathbuf, sizeof(pathbuf), uri);
1772 ff_url_join(hoststr, sizeof(hoststr), NULL, NULL, hostname, port, NULL);
1777 ff_url_join(lower_url, sizeof(lower_url), "tcp", NULL, hostname, port,
1780 ret = ffurl_open_whitelist(&s->hd, lower_url, AVIO_FLAG_READ_WRITE,
1781 &h->interrupt_callback, NULL,
1782 h->protocol_whitelist, h->protocol_blacklist, h);
1786 authstr = ff_http_auth_create_response(&s->proxy_auth_state, auth,
1788 snprintf(s->buffer, sizeof(s->buffer),
1789 "CONNECT %s HTTP/1.1\r\n"
1791 "Connection: close\r\n"
1796 authstr ? "Proxy-" : "", authstr ? authstr : "");
1799 if ((ret = ffurl_write(s->hd, s->buffer, strlen(s->buffer))) < 0)
1802 s->buf_ptr = s->buffer;
1803 s->buf_end = s->buffer;
1805 s->filesize = UINT64_MAX;
1806 cur_auth_type = s->proxy_auth_state.auth_type;
1808 /* Note: This uses buffering, potentially reading more than the
1809 * HTTP header. If tunneling a protocol where the server starts
1810 * the conversation, we might buffer part of that here, too.
1811 * Reading that requires using the proper ffurl_read() function
1812 * on this URLContext, not using the fd directly (as the tls
1813 * protocol does). This shouldn't be an issue for tls though,
1814 * since the client starts the conversation there, so there
1815 * is no extra data that we might buffer up here.
1817 ret = http_read_header(h, &new_loc);
1822 if (s->http_code == 407 &&
1823 (cur_auth_type == HTTP_AUTH_NONE || s->proxy_auth_state.stale) &&
1824 s->proxy_auth_state.auth_type != HTTP_AUTH_NONE && attempts < 2) {
1825 ffurl_closep(&s->hd);
1829 if (s->http_code < 400)
1831 ret = ff_http_averror(s->http_code, AVERROR(EIO));
1834 http_proxy_close(h);
1838 static int http_proxy_write(URLContext *h, const uint8_t *buf, int size)
1840 HTTPContext *s = h->priv_data;
1841 return ffurl_write(s->hd, buf, size);
1844 const URLProtocol ff_httpproxy_protocol = {
1845 .name = "httpproxy",
1846 .url_open = http_proxy_open,
1847 .url_read = http_buf_read,
1848 .url_write = http_proxy_write,
1849 .url_close = http_proxy_close,
1850 .url_get_file_handle = http_get_file_handle,
1851 .priv_data_size = sizeof(HTTPContext),
1852 .flags = URL_PROTOCOL_FLAG_NETWORK,
1854 #endif /* CONFIG_HTTPPROXY_PROTOCOL */