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. */
69 uint64_t off, end_off, filesize;
71 HTTPAuthState auth_state;
72 HTTPAuthState proxy_auth_state;
77 #if FF_API_HTTP_USER_AGENT
78 char *user_agent_deprecated;
81 /* Set if the server correctly handles Connection: close and will close
82 * the connection after feeding us the content. */
84 int seekable; /**< Control seekability, 0 = disable, 1 = enable, -1 = probe. */
86 /* A flag which indicates if the end of chunked encoding has been sent. */
88 /* A flag which indicates we have finished to read POST reply. */
90 /* A flag which indicates if we use persistent connections. */
91 int multiple_requests;
96 char *cookies; ///< holds newline (\n) delimited Set-Cookie header field values (without the "Set-Cookie: " field name)
97 /* A dictionary containing cookies keyed by cookie name */
98 AVDictionary *cookie_dict;
100 /* how much data was read since the last ICY metadata packet */
101 uint64_t icy_data_read;
102 /* after how many bytes of read data a new metadata packet will be found */
103 uint64_t icy_metaint;
104 char *icy_metadata_headers;
105 char *icy_metadata_packet;
106 AVDictionary *metadata;
109 z_stream inflate_stream;
110 uint8_t *inflate_buffer;
111 #endif /* CONFIG_ZLIB */
112 AVDictionary *chained_options;
116 int reconnect_at_eof;
117 int reconnect_streamed;
119 int reconnect_delay_max;
124 HandshakeState handshake_step;
125 int is_connected_server;
128 #define OFFSET(x) offsetof(HTTPContext, x)
129 #define D AV_OPT_FLAG_DECODING_PARAM
130 #define E AV_OPT_FLAG_ENCODING_PARAM
131 #define DEFAULT_USER_AGENT "Lavf/" AV_STRINGIFY(LIBAVFORMAT_VERSION)
133 static const AVOption options[] = {
134 { "seekable", "control seekability of connection", OFFSET(seekable), AV_OPT_TYPE_BOOL, { .i64 = -1 }, -1, 1, D },
135 { "chunked_post", "use chunked transfer-encoding for posts", OFFSET(chunked_post), AV_OPT_TYPE_BOOL, { .i64 = 1 }, 0, 1, E },
136 { "http_proxy", "set HTTP proxy to tunnel through", OFFSET(http_proxy), AV_OPT_TYPE_STRING, { .str = NULL }, 0, 0, D | E },
137 { "headers", "set custom HTTP headers, can override built in default headers", OFFSET(headers), AV_OPT_TYPE_STRING, { .str = NULL }, 0, 0, D | E },
138 { "content_type", "set a specific content type for the POST messages", OFFSET(content_type), AV_OPT_TYPE_STRING, { .str = NULL }, 0, 0, D | E },
139 { "user_agent", "override User-Agent header", OFFSET(user_agent), AV_OPT_TYPE_STRING, { .str = DEFAULT_USER_AGENT }, 0, 0, D },
140 #if FF_API_HTTP_USER_AGENT
141 { "user-agent", "override User-Agent header", OFFSET(user_agent_deprecated), AV_OPT_TYPE_STRING, { .str = DEFAULT_USER_AGENT }, 0, 0, D },
143 { "multiple_requests", "use persistent connections", OFFSET(multiple_requests), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, D | E },
144 { "post_data", "set custom HTTP post data", OFFSET(post_data), AV_OPT_TYPE_BINARY, .flags = D | E },
145 { "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 },
146 { "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 },
147 { "icy", "request ICY metadata", OFFSET(icy), AV_OPT_TYPE_BOOL, { .i64 = 1 }, 0, 1, D },
148 { "icy_metadata_headers", "return ICY metadata headers", OFFSET(icy_metadata_headers), AV_OPT_TYPE_STRING, { .str = NULL }, 0, 0, AV_OPT_FLAG_EXPORT },
149 { "icy_metadata_packet", "return current ICY metadata packet", OFFSET(icy_metadata_packet), AV_OPT_TYPE_STRING, { .str = NULL }, 0, 0, AV_OPT_FLAG_EXPORT },
150 { "metadata", "metadata read from the bitstream", OFFSET(metadata), AV_OPT_TYPE_DICT, {0}, 0, 0, AV_OPT_FLAG_EXPORT },
151 { "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"},
152 { "none", "No auth method set, autodetect", 0, AV_OPT_TYPE_CONST, { .i64 = HTTP_AUTH_NONE }, 0, 0, D | E, "auth_type"},
153 { "basic", "HTTP basic authentication", 0, AV_OPT_TYPE_CONST, { .i64 = HTTP_AUTH_BASIC }, 0, 0, D | E, "auth_type"},
154 { "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 },
155 { "location", "The actual location of the data received", OFFSET(location), AV_OPT_TYPE_STRING, { .str = NULL }, 0, 0, D | E },
156 { "offset", "initial byte offset", OFFSET(off), AV_OPT_TYPE_INT64, { .i64 = 0 }, 0, INT64_MAX, D },
157 { "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 },
158 { "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 },
159 { "reconnect", "auto reconnect after disconnect before EOF", OFFSET(reconnect), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, D },
160 { "reconnect_at_eof", "auto reconnect at EOF", OFFSET(reconnect_at_eof), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, D },
161 { "reconnect_streamed", "auto reconnect streamed / non seekable streams", OFFSET(reconnect_streamed), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, D },
162 { "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 },
163 { "listen", "listen on HTTP", OFFSET(listen), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 2, D | E },
164 { "resource", "The resource requested by a client", OFFSET(resource), AV_OPT_TYPE_STRING, { .str = NULL }, 0, 0, E },
165 { "reply_code", "The http status code to return to a client", OFFSET(reply_code), AV_OPT_TYPE_INT, { .i64 = 200}, INT_MIN, 599, E},
169 static int http_connect(URLContext *h, const char *path, const char *local_path,
170 const char *hoststr, const char *auth,
171 const char *proxyauth, int *new_location);
172 static int http_read_header(URLContext *h, int *new_location);
174 void ff_http_init_auth_state(URLContext *dest, const URLContext *src)
176 memcpy(&((HTTPContext *)dest->priv_data)->auth_state,
177 &((HTTPContext *)src->priv_data)->auth_state,
178 sizeof(HTTPAuthState));
179 memcpy(&((HTTPContext *)dest->priv_data)->proxy_auth_state,
180 &((HTTPContext *)src->priv_data)->proxy_auth_state,
181 sizeof(HTTPAuthState));
184 static int http_open_cnx_internal(URLContext *h, AVDictionary **options)
186 const char *path, *proxy_path, *lower_proto = "tcp", *local_path;
187 char hostname[1024], hoststr[1024], proto[10];
188 char auth[1024], proxyauth[1024] = "";
189 char path1[MAX_URL_SIZE];
190 char buf[1024], urlbuf[MAX_URL_SIZE];
191 int port, use_proxy, err, location_changed = 0;
192 HTTPContext *s = h->priv_data;
194 av_url_split(proto, sizeof(proto), auth, sizeof(auth),
195 hostname, sizeof(hostname), &port,
196 path1, sizeof(path1), s->location);
197 ff_url_join(hoststr, sizeof(hoststr), NULL, NULL, hostname, port, NULL);
199 proxy_path = s->http_proxy ? s->http_proxy : getenv("http_proxy");
200 use_proxy = !ff_http_match_no_proxy(getenv("no_proxy"), hostname) &&
201 proxy_path && av_strstart(proxy_path, "http://", NULL);
203 if (!strcmp(proto, "https")) {
212 if (path1[0] == '\0')
218 /* Reassemble the request URL without auth string - we don't
219 * want to leak the auth to the proxy. */
220 ff_url_join(urlbuf, sizeof(urlbuf), proto, NULL, hostname, port, "%s",
223 av_url_split(NULL, 0, proxyauth, sizeof(proxyauth),
224 hostname, sizeof(hostname), &port, NULL, 0, proxy_path);
227 ff_url_join(buf, sizeof(buf), lower_proto, NULL, hostname, port, NULL);
230 err = ffurl_open_whitelist(&s->hd, buf, AVIO_FLAG_READ_WRITE,
231 &h->interrupt_callback, options,
232 h->protocol_whitelist, h->protocol_blacklist, h);
237 err = http_connect(h, path, local_path, hoststr,
238 auth, proxyauth, &location_changed);
242 return location_changed;
245 /* return non zero if error */
246 static int http_open_cnx(URLContext *h, AVDictionary **options)
248 HTTPAuthType cur_auth_type, cur_proxy_auth_type;
249 HTTPContext *s = h->priv_data;
250 int location_changed, attempts = 0, redirects = 0;
252 av_dict_copy(options, s->chained_options, 0);
254 cur_auth_type = s->auth_state.auth_type;
255 cur_proxy_auth_type = s->auth_state.auth_type;
257 location_changed = http_open_cnx_internal(h, options);
258 if (location_changed < 0)
262 if (s->http_code == 401) {
263 if ((cur_auth_type == HTTP_AUTH_NONE || s->auth_state.stale) &&
264 s->auth_state.auth_type != HTTP_AUTH_NONE && attempts < 4) {
265 ffurl_closep(&s->hd);
270 if (s->http_code == 407) {
271 if ((cur_proxy_auth_type == HTTP_AUTH_NONE || s->proxy_auth_state.stale) &&
272 s->proxy_auth_state.auth_type != HTTP_AUTH_NONE && attempts < 4) {
273 ffurl_closep(&s->hd);
278 if ((s->http_code == 301 || s->http_code == 302 ||
279 s->http_code == 303 || s->http_code == 307) &&
280 location_changed == 1) {
281 /* url moved, get next */
282 ffurl_closep(&s->hd);
283 if (redirects++ >= MAX_REDIRECTS)
285 /* Restart the authentication process with the new target, which
286 * might use a different auth mechanism. */
287 memset(&s->auth_state, 0, sizeof(s->auth_state));
289 location_changed = 0;
296 ffurl_closep(&s->hd);
297 if (location_changed < 0)
298 return location_changed;
299 return ff_http_averror(s->http_code, AVERROR(EIO));
302 int ff_http_do_new_request(URLContext *h, const char *uri)
304 HTTPContext *s = h->priv_data;
305 AVDictionary *options = NULL;
309 s->icy_data_read = 0;
310 av_free(s->location);
311 s->location = av_strdup(uri);
313 return AVERROR(ENOMEM);
315 ret = http_open_cnx(h, &options);
316 av_dict_free(&options);
320 int ff_http_averror(int status_code, int default_averror)
322 switch (status_code) {
323 case 400: return AVERROR_HTTP_BAD_REQUEST;
324 case 401: return AVERROR_HTTP_UNAUTHORIZED;
325 case 403: return AVERROR_HTTP_FORBIDDEN;
326 case 404: return AVERROR_HTTP_NOT_FOUND;
329 if (status_code >= 400 && status_code <= 499)
330 return AVERROR_HTTP_OTHER_4XX;
331 else if (status_code >= 500)
332 return AVERROR_HTTP_SERVER_ERROR;
334 return default_averror;
337 static int http_write_reply(URLContext* h, int status_code)
339 int ret, body = 0, reply_code, message_len;
340 const char *reply_text, *content_type;
341 HTTPContext *s = h->priv_data;
342 char message[BUFFER_SIZE];
343 content_type = "text/plain";
347 switch (status_code) {
348 case AVERROR_HTTP_BAD_REQUEST:
351 reply_text = "Bad Request";
353 case AVERROR_HTTP_FORBIDDEN:
356 reply_text = "Forbidden";
358 case AVERROR_HTTP_NOT_FOUND:
361 reply_text = "Not Found";
366 content_type = s->content_type ? s->content_type : "application/octet-stream";
368 case AVERROR_HTTP_SERVER_ERROR:
371 reply_text = "Internal server error";
374 return AVERROR(EINVAL);
378 message_len = snprintf(message, sizeof(message),
379 "HTTP/1.1 %03d %s\r\n"
380 "Content-Type: %s\r\n"
381 "Content-Length: %"SIZE_SPECIFIER"\r\n"
388 strlen(reply_text) + 6, // 3 digit status code + space + \r\n
389 s->headers ? s->headers : "",
394 message_len = snprintf(message, sizeof(message),
395 "HTTP/1.1 %03d %s\r\n"
396 "Content-Type: %s\r\n"
397 "Transfer-Encoding: chunked\r\n"
403 s->headers ? s->headers : "");
405 av_log(h, AV_LOG_TRACE, "HTTP reply header: \n%s----\n", message);
406 if ((ret = ffurl_write(s->hd, message, message_len)) < 0)
411 static void handle_http_errors(URLContext *h, int error)
413 av_assert0(error < 0);
414 http_write_reply(h, error);
417 static int http_handshake(URLContext *c)
419 int ret, err, new_location;
420 HTTPContext *ch = c->priv_data;
421 URLContext *cl = ch->hd;
422 switch (ch->handshake_step) {
424 av_log(c, AV_LOG_TRACE, "Lower protocol\n");
425 if ((ret = ffurl_handshake(cl)) > 0)
429 ch->handshake_step = READ_HEADERS;
430 ch->is_connected_server = 1;
433 av_log(c, AV_LOG_TRACE, "Read headers\n");
434 if ((err = http_read_header(c, &new_location)) < 0) {
435 handle_http_errors(c, err);
438 ch->handshake_step = WRITE_REPLY_HEADERS;
440 case WRITE_REPLY_HEADERS:
441 av_log(c, AV_LOG_TRACE, "Reply code: %d\n", ch->reply_code);
442 if ((err = http_write_reply(c, ch->reply_code)) < 0)
444 ch->handshake_step = FINISH;
449 // this should never be reached.
450 return AVERROR(EINVAL);
453 static int http_listen(URLContext *h, const char *uri, int flags,
454 AVDictionary **options) {
455 HTTPContext *s = h->priv_data;
457 char hostname[1024], proto[10];
459 const char *lower_proto = "tcp";
461 av_url_split(proto, sizeof(proto), NULL, 0, hostname, sizeof(hostname), &port,
463 if (!strcmp(proto, "https"))
465 ff_url_join(lower_url, sizeof(lower_url), lower_proto, NULL, hostname, port,
467 if ((ret = av_dict_set_int(options, "listen", s->listen, 0)) < 0)
469 if ((ret = ffurl_open_whitelist(&s->hd, lower_url, AVIO_FLAG_READ_WRITE,
470 &h->interrupt_callback, options,
471 h->protocol_whitelist, h->protocol_blacklist, h
474 s->handshake_step = LOWER_PROTO;
475 if (s->listen == HTTP_SINGLE) { /* single client */
477 while ((ret = http_handshake(h)) > 0);
480 av_dict_free(&s->chained_options);
484 static int http_open(URLContext *h, const char *uri, int flags,
485 AVDictionary **options)
487 HTTPContext *s = h->priv_data;
490 if( s->seekable == 1 )
495 s->filesize = UINT64_MAX;
496 s->location = av_strdup(uri);
498 return AVERROR(ENOMEM);
500 av_dict_copy(&s->chained_options, *options, 0);
503 int len = strlen(s->headers);
504 if (len < 2 || strcmp("\r\n", s->headers + len - 2)) {
505 av_log(h, AV_LOG_WARNING,
506 "No trailing CRLF found in HTTP header.\n");
507 ret = av_reallocp(&s->headers, len + 3);
510 s->headers[len] = '\r';
511 s->headers[len + 1] = '\n';
512 s->headers[len + 2] = '\0';
517 return http_listen(h, uri, flags, options);
519 ret = http_open_cnx(h, options);
521 av_dict_free(&s->chained_options);
525 static int http_accept(URLContext *s, URLContext **c)
528 HTTPContext *sc = s->priv_data;
530 URLContext *sl = sc->hd;
531 URLContext *cl = NULL;
533 av_assert0(sc->listen);
534 if ((ret = ffurl_alloc(c, s->filename, s->flags, &sl->interrupt_callback)) < 0)
536 cc = (*c)->priv_data;
537 if ((ret = ffurl_accept(sl, &cl)) < 0)
540 cc->is_multi_client = 1;
545 static int http_getc(HTTPContext *s)
548 if (s->buf_ptr >= s->buf_end) {
549 len = ffurl_read(s->hd, s->buffer, BUFFER_SIZE);
552 } else if (len == 0) {
555 s->buf_ptr = s->buffer;
556 s->buf_end = s->buffer + len;
559 return *s->buf_ptr++;
562 static int http_get_line(HTTPContext *s, char *line, int line_size)
574 if (q > line && q[-1] == '\r')
580 if ((q - line) < line_size - 1)
586 static int check_http_code(URLContext *h, int http_code, const char *end)
588 HTTPContext *s = h->priv_data;
589 /* error codes are 4xx and 5xx, but regard 401 as a success, so we
590 * don't abort until all headers have been parsed. */
591 if (http_code >= 400 && http_code < 600 &&
592 (http_code != 401 || s->auth_state.auth_type != HTTP_AUTH_NONE) &&
593 (http_code != 407 || s->proxy_auth_state.auth_type != HTTP_AUTH_NONE)) {
594 end += strspn(end, SPACE_CHARS);
595 av_log(h, AV_LOG_WARNING, "HTTP error %d %s\n", http_code, end);
596 return ff_http_averror(http_code, AVERROR(EIO));
601 static int parse_location(HTTPContext *s, const char *p)
603 char redirected_location[MAX_URL_SIZE], *new_loc;
604 ff_make_absolute_url(redirected_location, sizeof(redirected_location),
606 new_loc = av_strdup(redirected_location);
608 return AVERROR(ENOMEM);
609 av_free(s->location);
610 s->location = new_loc;
614 /* "bytes $from-$to/$document_size" */
615 static void parse_content_range(URLContext *h, const char *p)
617 HTTPContext *s = h->priv_data;
620 if (!strncmp(p, "bytes ", 6)) {
622 s->off = strtoull(p, NULL, 10);
623 if ((slash = strchr(p, '/')) && strlen(slash) > 0)
624 s->filesize = strtoull(slash + 1, NULL, 10);
626 if (s->seekable == -1 && (!s->is_akamai || s->filesize != 2147483647))
627 h->is_streamed = 0; /* we _can_ in fact seek */
630 static int parse_content_encoding(URLContext *h, const char *p)
632 if (!av_strncasecmp(p, "gzip", 4) ||
633 !av_strncasecmp(p, "deflate", 7)) {
635 HTTPContext *s = h->priv_data;
638 inflateEnd(&s->inflate_stream);
639 if (inflateInit2(&s->inflate_stream, 32 + 15) != Z_OK) {
640 av_log(h, AV_LOG_WARNING, "Error during zlib initialisation: %s\n",
641 s->inflate_stream.msg);
642 return AVERROR(ENOSYS);
644 if (zlibCompileFlags() & (1 << 17)) {
645 av_log(h, AV_LOG_WARNING,
646 "Your zlib was compiled without gzip support.\n");
647 return AVERROR(ENOSYS);
650 av_log(h, AV_LOG_WARNING,
651 "Compressed (%s) content, need zlib with gzip support\n", p);
652 return AVERROR(ENOSYS);
653 #endif /* CONFIG_ZLIB */
654 } else if (!av_strncasecmp(p, "identity", 8)) {
655 // The normal, no-encoding case (although servers shouldn't include
656 // the header at all if this is the case).
658 av_log(h, AV_LOG_WARNING, "Unknown content coding: %s\n", p);
663 // Concat all Icy- header lines
664 static int parse_icy(HTTPContext *s, const char *tag, const char *p)
666 int len = 4 + strlen(p) + strlen(tag);
667 int is_first = !s->icy_metadata_headers;
670 av_dict_set(&s->metadata, tag, p, 0);
672 if (s->icy_metadata_headers)
673 len += strlen(s->icy_metadata_headers);
675 if ((ret = av_reallocp(&s->icy_metadata_headers, len)) < 0)
679 *s->icy_metadata_headers = '\0';
681 av_strlcatf(s->icy_metadata_headers, len, "%s: %s\n", tag, p);
686 static int parse_set_cookie_expiry_time(const char *exp_str, struct tm *buf)
688 char exp_buf[MAX_EXPIRY];
689 int i, j, exp_buf_len = MAX_EXPIRY-1;
692 // strip off any punctuation or whitespace
693 for (i = 0, j = 0; exp_str[i] != '\0' && j < exp_buf_len; i++) {
694 if ((exp_str[i] >= '0' && exp_str[i] <= '9') ||
695 (exp_str[i] >= 'A' && exp_str[i] <= 'Z') ||
696 (exp_str[i] >= 'a' && exp_str[i] <= 'z')) {
697 exp_buf[j] = exp_str[i];
704 // move the string beyond the day of week
705 while ((*expiry < '0' || *expiry > '9') && *expiry != '\0')
708 return av_small_strptime(expiry, "%d%b%Y%H%M%S", buf) ? 0 : AVERROR(EINVAL);
711 static int parse_set_cookie(const char *set_cookie, AVDictionary **dict)
713 char *param, *next_param, *cstr, *back;
715 if (!(cstr = av_strdup(set_cookie)))
716 return AVERROR(EINVAL);
718 // strip any trailing whitespace
719 back = &cstr[strlen(cstr)-1];
720 while (strchr(WHITESPACES, *back)) {
726 while ((param = av_strtok(next_param, ";", &next_param))) {
728 param += strspn(param, WHITESPACES);
729 if ((name = av_strtok(param, "=", &value))) {
730 if (av_dict_set(dict, name, value, 0) < 0) {
741 static int parse_cookie(HTTPContext *s, const char *p, AVDictionary **cookies)
743 AVDictionary *new_params = NULL;
744 AVDictionaryEntry *e, *cookie_entry;
747 // ensure the cookie is parsable
748 if (parse_set_cookie(p, &new_params))
751 // if there is no cookie value there is nothing to parse
752 cookie_entry = av_dict_get(new_params, "", NULL, AV_DICT_IGNORE_SUFFIX);
753 if (!cookie_entry || !cookie_entry->value) {
754 av_dict_free(&new_params);
758 // ensure the cookie is not expired or older than an existing value
759 if ((e = av_dict_get(new_params, "expires", NULL, 0)) && e->value) {
760 struct tm new_tm = {0};
761 if (!parse_set_cookie_expiry_time(e->value, &new_tm)) {
762 AVDictionaryEntry *e2;
764 // if the cookie has already expired ignore it
765 if (av_timegm(&new_tm) < av_gettime() / 1000000) {
766 av_dict_free(&new_params);
770 // only replace an older cookie with the same name
771 e2 = av_dict_get(*cookies, cookie_entry->key, NULL, 0);
772 if (e2 && e2->value) {
773 AVDictionary *old_params = NULL;
774 if (!parse_set_cookie(p, &old_params)) {
775 e2 = av_dict_get(old_params, "expires", NULL, 0);
776 if (e2 && e2->value) {
777 struct tm old_tm = {0};
778 if (!parse_set_cookie_expiry_time(e->value, &old_tm)) {
779 if (av_timegm(&new_tm) < av_timegm(&old_tm)) {
780 av_dict_free(&new_params);
781 av_dict_free(&old_params);
787 av_dict_free(&old_params);
792 // duplicate the cookie name (dict will dupe the value)
793 if (!(eql = strchr(p, '='))) return AVERROR(EINVAL);
794 if (!(name = av_strndup(p, eql - p))) return AVERROR(ENOMEM);
796 // add the cookie to the dictionary
797 av_dict_set(cookies, name, eql, AV_DICT_DONT_STRDUP_KEY);
802 static int cookie_string(AVDictionary *dict, char **cookies)
804 AVDictionaryEntry *e = NULL;
807 // determine how much memory is needed for the cookies string
808 while (e = av_dict_get(dict, "", e, AV_DICT_IGNORE_SUFFIX))
809 len += strlen(e->key) + strlen(e->value) + 1;
811 // reallocate the cookies
813 if (*cookies) av_free(*cookies);
814 *cookies = av_malloc(len);
815 if (!*cookies) return AVERROR(ENOMEM);
818 // write out the cookies
819 while (e = av_dict_get(dict, "", e, AV_DICT_IGNORE_SUFFIX))
820 av_strlcatf(*cookies, len, "%s%s\n", e->key, e->value);
825 static int process_line(URLContext *h, char *line, int line_count,
828 HTTPContext *s = h->priv_data;
829 const char *auto_method = h->flags & AVIO_FLAG_READ ? "POST" : "GET";
830 char *tag, *p, *end, *method, *resource, *version;
834 if (line[0] == '\0') {
840 if (line_count == 0) {
841 if (s->is_connected_server) {
844 while (*p && !av_isspace(*p))
847 av_log(h, AV_LOG_TRACE, "Received method: %s\n", method);
849 if (av_strcasecmp(s->method, method)) {
850 av_log(h, AV_LOG_ERROR, "Received and expected HTTP method do not match. (%s expected, %s received)\n",
852 return ff_http_averror(400, AVERROR(EIO));
855 // use autodetected HTTP method to expect
856 av_log(h, AV_LOG_TRACE, "Autodetected %s HTTP method\n", auto_method);
857 if (av_strcasecmp(auto_method, method)) {
858 av_log(h, AV_LOG_ERROR, "Received and autodetected HTTP method did not match "
859 "(%s autodetected %s received)\n", auto_method, method);
860 return ff_http_averror(400, AVERROR(EIO));
862 if (!(s->method = av_strdup(method)))
863 return AVERROR(ENOMEM);
867 while (av_isspace(*p))
870 while (!av_isspace(*p))
873 av_log(h, AV_LOG_TRACE, "Requested resource: %s\n", resource);
874 if (!(s->resource = av_strdup(resource)))
875 return AVERROR(ENOMEM);
878 while (av_isspace(*p))
881 while (*p && !av_isspace(*p))
884 if (av_strncasecmp(version, "HTTP/", 5)) {
885 av_log(h, AV_LOG_ERROR, "Malformed HTTP version string.\n");
886 return ff_http_averror(400, AVERROR(EIO));
888 av_log(h, AV_LOG_TRACE, "HTTP version string: %s\n", version);
890 while (!av_isspace(*p) && *p != '\0')
892 while (av_isspace(*p))
894 s->http_code = strtol(p, &end, 10);
896 av_log(h, AV_LOG_TRACE, "http_code=%d\n", s->http_code);
898 if ((ret = check_http_code(h, s->http_code, end)) < 0)
902 while (*p != '\0' && *p != ':')
910 while (av_isspace(*p))
912 if (!av_strcasecmp(tag, "Location")) {
913 if ((ret = parse_location(s, p)) < 0)
916 } else if (!av_strcasecmp(tag, "Content-Length") &&
917 s->filesize == UINT64_MAX) {
918 s->filesize = strtoull(p, NULL, 10);
919 } else if (!av_strcasecmp(tag, "Content-Range")) {
920 parse_content_range(h, p);
921 } else if (!av_strcasecmp(tag, "Accept-Ranges") &&
922 !strncmp(p, "bytes", 5) &&
925 } else if (!av_strcasecmp(tag, "Transfer-Encoding") &&
926 !av_strncasecmp(p, "chunked", 7)) {
927 s->filesize = UINT64_MAX;
929 } else if (!av_strcasecmp(tag, "WWW-Authenticate")) {
930 ff_http_auth_handle_header(&s->auth_state, tag, p);
931 } else if (!av_strcasecmp(tag, "Authentication-Info")) {
932 ff_http_auth_handle_header(&s->auth_state, tag, p);
933 } else if (!av_strcasecmp(tag, "Proxy-Authenticate")) {
934 ff_http_auth_handle_header(&s->proxy_auth_state, tag, p);
935 } else if (!av_strcasecmp(tag, "Connection")) {
936 if (!strcmp(p, "close"))
938 } else if (!av_strcasecmp(tag, "Server")) {
939 if (!av_strcasecmp(p, "AkamaiGHost")) {
941 } else if (!av_strncasecmp(p, "MediaGateway", 12)) {
942 s->is_mediagateway = 1;
944 } else if (!av_strcasecmp(tag, "Content-Type")) {
945 av_free(s->mime_type);
946 s->mime_type = av_strdup(p);
947 } else if (!av_strcasecmp(tag, "Set-Cookie")) {
948 if (parse_cookie(s, p, &s->cookie_dict))
949 av_log(h, AV_LOG_WARNING, "Unable to parse '%s'\n", p);
950 } else if (!av_strcasecmp(tag, "Icy-MetaInt")) {
951 s->icy_metaint = strtoull(p, NULL, 10);
952 } else if (!av_strncasecmp(tag, "Icy-", 4)) {
953 if ((ret = parse_icy(s, tag, p)) < 0)
955 } else if (!av_strcasecmp(tag, "Content-Encoding")) {
956 if ((ret = parse_content_encoding(h, p)) < 0)
964 * Create a string containing cookie values for use as a HTTP cookie header
965 * field value for a particular path and domain from the cookie values stored in
966 * the HTTP protocol context. The cookie string is stored in *cookies.
968 * @return a negative value if an error condition occurred, 0 otherwise
970 static int get_cookies(HTTPContext *s, char **cookies, const char *path,
973 // cookie strings will look like Set-Cookie header field values. Multiple
974 // Set-Cookie fields will result in multiple values delimited by a newline
976 char *cookie, *set_cookies = av_strdup(s->cookies), *next = set_cookies;
978 if (!set_cookies) return AVERROR(EINVAL);
980 // destroy any cookies in the dictionary.
981 av_dict_free(&s->cookie_dict);
984 while ((cookie = av_strtok(next, "\n", &next))) {
985 AVDictionary *cookie_params = NULL;
986 AVDictionaryEntry *cookie_entry, *e;
988 // store the cookie in a dict in case it is updated in the response
989 if (parse_cookie(s, cookie, &s->cookie_dict))
990 av_log(s, AV_LOG_WARNING, "Unable to parse '%s'\n", cookie);
992 // continue on to the next cookie if this one cannot be parsed
993 if (parse_set_cookie(cookie, &cookie_params))
996 // if the cookie has no value, skip it
997 cookie_entry = av_dict_get(cookie_params, "", NULL, AV_DICT_IGNORE_SUFFIX);
998 if (!cookie_entry || !cookie_entry->value) {
999 av_dict_free(&cookie_params);
1003 // if the cookie has expired, don't add it
1004 if ((e = av_dict_get(cookie_params, "expires", NULL, 0)) && e->value) {
1005 struct tm tm_buf = {0};
1006 if (!parse_set_cookie_expiry_time(e->value, &tm_buf)) {
1007 if (av_timegm(&tm_buf) < av_gettime() / 1000000) {
1008 av_dict_free(&cookie_params);
1014 // if no domain in the cookie assume it appied to this request
1015 if ((e = av_dict_get(cookie_params, "domain", NULL, 0)) && e->value) {
1016 // find the offset comparison is on the min domain (b.com, not a.b.com)
1017 int domain_offset = strlen(domain) - strlen(e->value);
1018 if (domain_offset < 0) {
1019 av_dict_free(&cookie_params);
1023 // match the cookie domain
1024 if (av_strcasecmp(&domain[domain_offset], e->value)) {
1025 av_dict_free(&cookie_params);
1030 // ensure this cookie matches the path
1031 e = av_dict_get(cookie_params, "path", NULL, 0);
1032 if (!e || av_strncasecmp(path, e->value, strlen(e->value))) {
1033 av_dict_free(&cookie_params);
1037 // cookie parameters match, so copy the value
1039 if (!(*cookies = av_asprintf("%s=%s", cookie_entry->key, cookie_entry->value))) {
1040 ret = AVERROR(ENOMEM);
1044 char *tmp = *cookies;
1045 size_t str_size = strlen(cookie_entry->key) + strlen(cookie_entry->value) + strlen(*cookies) + 4;
1046 if (!(*cookies = av_malloc(str_size))) {
1047 ret = AVERROR(ENOMEM);
1051 snprintf(*cookies, str_size, "%s; %s=%s", tmp, cookie_entry->key, cookie_entry->value);
1056 av_free(set_cookies);
1061 static inline int has_header(const char *str, const char *header)
1063 /* header + 2 to skip over CRLF prefix. (make sure you have one!) */
1066 return av_stristart(str, header + 2, NULL) || av_stristr(str, header);
1069 static int http_read_header(URLContext *h, int *new_location)
1071 HTTPContext *s = h->priv_data;
1072 char line[MAX_URL_SIZE];
1075 s->chunksize = UINT64_MAX;
1078 if ((err = http_get_line(s, line, sizeof(line))) < 0)
1081 av_log(h, AV_LOG_TRACE, "header='%s'\n", line);
1083 err = process_line(h, line, s->line_count, new_location);
1091 if (s->seekable == -1 && s->is_mediagateway && s->filesize == 2000000000)
1092 h->is_streamed = 1; /* we can in fact _not_ seek */
1094 // add any new cookies into the existing cookie string
1095 cookie_string(s->cookie_dict, &s->cookies);
1096 av_dict_free(&s->cookie_dict);
1101 static int http_connect(URLContext *h, const char *path, const char *local_path,
1102 const char *hoststr, const char *auth,
1103 const char *proxyauth, int *new_location)
1105 HTTPContext *s = h->priv_data;
1107 char headers[HTTP_HEADERS_SIZE] = "";
1108 char *authstr = NULL, *proxyauthstr = NULL;
1109 uint64_t off = s->off;
1112 int send_expect_100 = 0;
1115 /* send http header */
1116 post = h->flags & AVIO_FLAG_WRITE;
1119 /* force POST method and disable chunked encoding when
1120 * custom HTTP post data is set */
1122 s->chunked_post = 0;
1128 method = post ? "POST" : "GET";
1130 authstr = ff_http_auth_create_response(&s->auth_state, auth,
1131 local_path, method);
1132 proxyauthstr = ff_http_auth_create_response(&s->proxy_auth_state, proxyauth,
1133 local_path, method);
1134 if (post && !s->post_data) {
1135 send_expect_100 = s->send_expect_100;
1136 /* The user has supplied authentication but we don't know the auth type,
1137 * send Expect: 100-continue to get the 401 response including the
1138 * WWW-Authenticate header, or an 100 continue if no auth actually
1140 if (auth && *auth &&
1141 s->auth_state.auth_type == HTTP_AUTH_NONE &&
1142 s->http_code != 401)
1143 send_expect_100 = 1;
1146 #if FF_API_HTTP_USER_AGENT
1147 if (strcmp(s->user_agent_deprecated, DEFAULT_USER_AGENT)) {
1148 av_log(s, AV_LOG_WARNING, "the user-agent option is deprecated, please use user_agent option\n");
1149 s->user_agent = av_strdup(s->user_agent_deprecated);
1152 /* set default headers if needed */
1153 if (!has_header(s->headers, "\r\nUser-Agent: "))
1154 len += av_strlcatf(headers + len, sizeof(headers) - len,
1155 "User-Agent: %s\r\n", s->user_agent);
1156 if (!has_header(s->headers, "\r\nAccept: "))
1157 len += av_strlcpy(headers + len, "Accept: */*\r\n",
1158 sizeof(headers) - len);
1159 // Note: we send this on purpose even when s->off is 0 when we're probing,
1160 // since it allows us to detect more reliably if a (non-conforming)
1161 // server supports seeking by analysing the reply headers.
1162 if (!has_header(s->headers, "\r\nRange: ") && !post && (s->off > 0 || s->end_off || s->seekable == -1)) {
1163 len += av_strlcatf(headers + len, sizeof(headers) - len,
1164 "Range: bytes=%"PRIu64"-", s->off);
1166 len += av_strlcatf(headers + len, sizeof(headers) - len,
1167 "%"PRId64, s->end_off - 1);
1168 len += av_strlcpy(headers + len, "\r\n",
1169 sizeof(headers) - len);
1171 if (send_expect_100 && !has_header(s->headers, "\r\nExpect: "))
1172 len += av_strlcatf(headers + len, sizeof(headers) - len,
1173 "Expect: 100-continue\r\n");
1175 if (!has_header(s->headers, "\r\nConnection: ")) {
1176 if (s->multiple_requests)
1177 len += av_strlcpy(headers + len, "Connection: keep-alive\r\n",
1178 sizeof(headers) - len);
1180 len += av_strlcpy(headers + len, "Connection: close\r\n",
1181 sizeof(headers) - len);
1184 if (!has_header(s->headers, "\r\nHost: "))
1185 len += av_strlcatf(headers + len, sizeof(headers) - len,
1186 "Host: %s\r\n", hoststr);
1187 if (!has_header(s->headers, "\r\nContent-Length: ") && s->post_data)
1188 len += av_strlcatf(headers + len, sizeof(headers) - len,
1189 "Content-Length: %d\r\n", s->post_datalen);
1191 if (!has_header(s->headers, "\r\nContent-Type: ") && s->content_type)
1192 len += av_strlcatf(headers + len, sizeof(headers) - len,
1193 "Content-Type: %s\r\n", s->content_type);
1194 if (!has_header(s->headers, "\r\nCookie: ") && s->cookies) {
1195 char *cookies = NULL;
1196 if (!get_cookies(s, &cookies, path, hoststr) && cookies) {
1197 len += av_strlcatf(headers + len, sizeof(headers) - len,
1198 "Cookie: %s\r\n", cookies);
1202 if (!has_header(s->headers, "\r\nIcy-MetaData: ") && s->icy)
1203 len += av_strlcatf(headers + len, sizeof(headers) - len,
1204 "Icy-MetaData: %d\r\n", 1);
1206 /* now add in custom headers */
1208 av_strlcpy(headers + len, s->headers, sizeof(headers) - len);
1210 ret = snprintf(s->buffer, sizeof(s->buffer),
1211 "%s %s HTTP/1.1\r\n"
1219 post && s->chunked_post ? "Transfer-Encoding: chunked\r\n" : "",
1221 authstr ? authstr : "",
1222 proxyauthstr ? "Proxy-" : "", proxyauthstr ? proxyauthstr : "");
1224 av_log(h, AV_LOG_DEBUG, "request: %s\n", s->buffer);
1226 if (strlen(headers) + 1 == sizeof(headers) ||
1227 ret >= sizeof(s->buffer)) {
1228 av_log(h, AV_LOG_ERROR, "overlong headers\n");
1229 err = AVERROR(EINVAL);
1234 if ((err = ffurl_write(s->hd, s->buffer, strlen(s->buffer))) < 0)
1238 if ((err = ffurl_write(s->hd, s->post_data, s->post_datalen)) < 0)
1241 /* init input buffer */
1242 s->buf_ptr = s->buffer;
1243 s->buf_end = s->buffer;
1246 s->icy_data_read = 0;
1247 s->filesize = UINT64_MAX;
1249 s->end_chunked_post = 0;
1254 if (post && !s->post_data && !send_expect_100) {
1255 /* Pretend that it did work. We didn't read any header yet, since
1256 * we've still to send the POST data, but the code calling this
1257 * function will check http_code after we return. */
1263 /* wait for header */
1264 err = http_read_header(h, new_location);
1271 err = (off == s->off) ? 0 : -1;
1274 av_freep(&proxyauthstr);
1278 static int http_buf_read(URLContext *h, uint8_t *buf, int size)
1280 HTTPContext *s = h->priv_data;
1283 if (s->chunksize != UINT64_MAX) {
1284 if (!s->chunksize) {
1289 if ((err = http_get_line(s, line, sizeof(line))) < 0)
1291 } while (!*line); /* skip CR LF from last chunk */
1293 s->chunksize = strtoull(line, NULL, 16);
1295 av_log(h, AV_LOG_TRACE,
1296 "Chunked encoding data size: %"PRIu64"'\n",
1301 else if (s->chunksize == UINT64_MAX) {
1302 av_log(h, AV_LOG_ERROR, "Invalid chunk size %"PRIu64"\n",
1304 return AVERROR(EINVAL);
1307 size = FFMIN(size, s->chunksize);
1310 /* read bytes from input buffer first */
1311 len = s->buf_end - s->buf_ptr;
1315 memcpy(buf, s->buf_ptr, len);
1318 uint64_t target_end = s->end_off ? s->end_off : s->filesize;
1319 if ((!s->willclose || s->chunksize == UINT64_MAX) && s->off >= target_end)
1321 len = ffurl_read(s->hd, buf, size);
1322 if (!len && (!s->willclose || s->chunksize == UINT64_MAX) && s->off < target_end) {
1323 av_log(h, AV_LOG_ERROR,
1324 "Stream ends prematurely at %"PRIu64", should be %"PRIu64"\n",
1327 return AVERROR(EIO);
1332 if (s->chunksize > 0 && s->chunksize != UINT64_MAX) {
1333 av_assert0(s->chunksize >= len);
1334 s->chunksize -= len;
1341 #define DECOMPRESS_BUF_SIZE (256 * 1024)
1342 static int http_buf_read_compressed(URLContext *h, uint8_t *buf, int size)
1344 HTTPContext *s = h->priv_data;
1347 if (!s->inflate_buffer) {
1348 s->inflate_buffer = av_malloc(DECOMPRESS_BUF_SIZE);
1349 if (!s->inflate_buffer)
1350 return AVERROR(ENOMEM);
1353 if (s->inflate_stream.avail_in == 0) {
1354 int read = http_buf_read(h, s->inflate_buffer, DECOMPRESS_BUF_SIZE);
1357 s->inflate_stream.next_in = s->inflate_buffer;
1358 s->inflate_stream.avail_in = read;
1361 s->inflate_stream.avail_out = size;
1362 s->inflate_stream.next_out = buf;
1364 ret = inflate(&s->inflate_stream, Z_SYNC_FLUSH);
1365 if (ret != Z_OK && ret != Z_STREAM_END)
1366 av_log(h, AV_LOG_WARNING, "inflate return value: %d, %s\n",
1367 ret, s->inflate_stream.msg);
1369 return size - s->inflate_stream.avail_out;
1371 #endif /* CONFIG_ZLIB */
1373 static int64_t http_seek_internal(URLContext *h, int64_t off, int whence, int force_reconnect);
1375 static int http_read_stream(URLContext *h, uint8_t *buf, int size)
1377 HTTPContext *s = h->priv_data;
1378 int err, new_location, read_ret;
1384 if (s->end_chunked_post && !s->end_header) {
1385 err = http_read_header(h, &new_location);
1392 return http_buf_read_compressed(h, buf, size);
1393 #endif /* CONFIG_ZLIB */
1394 read_ret = http_buf_read(h, buf, size);
1395 if ( (read_ret < 0 && s->reconnect && (!h->is_streamed || s->reconnect_streamed) && s->filesize > 0 && s->off < s->filesize)
1396 || (read_ret == 0 && s->reconnect_at_eof && (!h->is_streamed || s->reconnect_streamed))) {
1397 uint64_t target = h->is_streamed ? 0 : s->off;
1399 if (s->reconnect_delay > s->reconnect_delay_max)
1400 return AVERROR(EIO);
1402 av_log(h, AV_LOG_INFO, "Will reconnect at %"PRIu64" error=%s.\n", s->off, av_err2str(read_ret));
1403 av_usleep(1000U*1000*s->reconnect_delay);
1404 s->reconnect_delay = 1 + 2*s->reconnect_delay;
1405 seek_ret = http_seek_internal(h, target, SEEK_SET, 1);
1406 if (seek_ret != target) {
1407 av_log(h, AV_LOG_ERROR, "Failed to reconnect at %"PRIu64".\n", target);
1411 read_ret = http_buf_read(h, buf, size);
1413 s->reconnect_delay = 0;
1418 // Like http_read_stream(), but no short reads.
1419 // Assumes partial reads are an error.
1420 static int http_read_stream_all(URLContext *h, uint8_t *buf, int size)
1423 while (pos < size) {
1424 int len = http_read_stream(h, buf + pos, size - pos);
1432 static void update_metadata(HTTPContext *s, char *data)
1441 val = strstr(key, "='");
1444 end = strstr(val, "';");
1452 av_dict_set(&s->metadata, key, val, 0);
1458 static int store_icy(URLContext *h, int size)
1460 HTTPContext *s = h->priv_data;
1461 /* until next metadata packet */
1464 if (s->icy_metaint < s->icy_data_read)
1465 return AVERROR_INVALIDDATA;
1466 remaining = s->icy_metaint - s->icy_data_read;
1469 /* The metadata packet is variable sized. It has a 1 byte header
1470 * which sets the length of the packet (divided by 16). If it's 0,
1471 * the metadata doesn't change. After the packet, icy_metaint bytes
1472 * of normal data follows. */
1474 int len = http_read_stream_all(h, &ch, 1);
1478 char data[255 * 16 + 1];
1481 ret = http_read_stream_all(h, data, len);
1485 if ((ret = av_opt_set(s, "icy_metadata_packet", data, 0)) < 0)
1487 update_metadata(s, data);
1489 s->icy_data_read = 0;
1490 remaining = s->icy_metaint;
1493 return FFMIN(size, remaining);
1496 static int http_read(URLContext *h, uint8_t *buf, int size)
1498 HTTPContext *s = h->priv_data;
1500 if (s->icy_metaint > 0) {
1501 size = store_icy(h, size);
1506 size = http_read_stream(h, buf, size);
1508 s->icy_data_read += size;
1512 /* used only when posting data */
1513 static int http_write(URLContext *h, const uint8_t *buf, int size)
1515 char temp[11] = ""; /* 32-bit hex + CRLF + nul */
1517 char crlf[] = "\r\n";
1518 HTTPContext *s = h->priv_data;
1520 if (!s->chunked_post) {
1521 /* non-chunked data is sent without any special encoding */
1522 return ffurl_write(s->hd, buf, size);
1525 /* silently ignore zero-size data since chunk encoding that would
1528 /* upload data using chunked encoding */
1529 snprintf(temp, sizeof(temp), "%x\r\n", size);
1531 if ((ret = ffurl_write(s->hd, temp, strlen(temp))) < 0 ||
1532 (ret = ffurl_write(s->hd, buf, size)) < 0 ||
1533 (ret = ffurl_write(s->hd, crlf, sizeof(crlf) - 1)) < 0)
1539 static int http_shutdown(URLContext *h, int flags)
1542 char footer[] = "0\r\n\r\n";
1543 HTTPContext *s = h->priv_data;
1545 /* signal end of chunked encoding if used */
1546 if (((flags & AVIO_FLAG_WRITE) && s->chunked_post) ||
1547 ((flags & AVIO_FLAG_READ) && s->chunked_post && s->listen)) {
1548 ret = ffurl_write(s->hd, footer, sizeof(footer) - 1);
1549 ret = ret > 0 ? 0 : ret;
1550 s->end_chunked_post = 1;
1556 static int http_close(URLContext *h)
1559 HTTPContext *s = h->priv_data;
1562 inflateEnd(&s->inflate_stream);
1563 av_freep(&s->inflate_buffer);
1564 #endif /* CONFIG_ZLIB */
1566 if (!s->end_chunked_post)
1567 /* Close the write direction by sending the end of chunked encoding. */
1568 ret = http_shutdown(h, h->flags);
1571 ffurl_closep(&s->hd);
1572 av_dict_free(&s->chained_options);
1576 static int64_t http_seek_internal(URLContext *h, int64_t off, int whence, int force_reconnect)
1578 HTTPContext *s = h->priv_data;
1579 URLContext *old_hd = s->hd;
1580 uint64_t old_off = s->off;
1581 uint8_t old_buf[BUFFER_SIZE];
1582 int old_buf_size, ret;
1583 AVDictionary *options = NULL;
1585 if (whence == AVSEEK_SIZE)
1587 else if (!force_reconnect &&
1588 ((whence == SEEK_CUR && off == 0) ||
1589 (whence == SEEK_SET && off == s->off)))
1591 else if ((s->filesize == UINT64_MAX && whence == SEEK_END))
1592 return AVERROR(ENOSYS);
1594 if (whence == SEEK_CUR)
1596 else if (whence == SEEK_END)
1598 else if (whence != SEEK_SET)
1599 return AVERROR(EINVAL);
1601 return AVERROR(EINVAL);
1604 if (s->off && h->is_streamed)
1605 return AVERROR(ENOSYS);
1607 /* we save the old context in case the seek fails */
1608 old_buf_size = s->buf_end - s->buf_ptr;
1609 memcpy(old_buf, s->buf_ptr, old_buf_size);
1612 /* if it fails, continue on old connection */
1613 if ((ret = http_open_cnx(h, &options)) < 0) {
1614 av_dict_free(&options);
1615 memcpy(s->buffer, old_buf, old_buf_size);
1616 s->buf_ptr = s->buffer;
1617 s->buf_end = s->buffer + old_buf_size;
1622 av_dict_free(&options);
1623 ffurl_close(old_hd);
1627 static int64_t http_seek(URLContext *h, int64_t off, int whence)
1629 return http_seek_internal(h, off, whence, 0);
1632 static int http_get_file_handle(URLContext *h)
1634 HTTPContext *s = h->priv_data;
1635 return ffurl_get_file_handle(s->hd);
1638 static int http_get_short_seek(URLContext *h)
1640 HTTPContext *s = h->priv_data;
1641 return ffurl_get_short_seek(s->hd);
1644 #define HTTP_CLASS(flavor) \
1645 static const AVClass flavor ## _context_class = { \
1646 .class_name = # flavor, \
1647 .item_name = av_default_item_name, \
1648 .option = options, \
1649 .version = LIBAVUTIL_VERSION_INT, \
1652 #if CONFIG_HTTP_PROTOCOL
1655 const URLProtocol ff_http_protocol = {
1657 .url_open2 = http_open,
1658 .url_accept = http_accept,
1659 .url_handshake = http_handshake,
1660 .url_read = http_read,
1661 .url_write = http_write,
1662 .url_seek = http_seek,
1663 .url_close = http_close,
1664 .url_get_file_handle = http_get_file_handle,
1665 .url_get_short_seek = http_get_short_seek,
1666 .url_shutdown = http_shutdown,
1667 .priv_data_size = sizeof(HTTPContext),
1668 .priv_data_class = &http_context_class,
1669 .flags = URL_PROTOCOL_FLAG_NETWORK,
1670 .default_whitelist = "http,https,tls,rtp,tcp,udp,crypto,httpproxy"
1672 #endif /* CONFIG_HTTP_PROTOCOL */
1674 #if CONFIG_HTTPS_PROTOCOL
1677 const URLProtocol ff_https_protocol = {
1679 .url_open2 = http_open,
1680 .url_read = http_read,
1681 .url_write = http_write,
1682 .url_seek = http_seek,
1683 .url_close = http_close,
1684 .url_get_file_handle = http_get_file_handle,
1685 .url_get_short_seek = http_get_short_seek,
1686 .url_shutdown = http_shutdown,
1687 .priv_data_size = sizeof(HTTPContext),
1688 .priv_data_class = &https_context_class,
1689 .flags = URL_PROTOCOL_FLAG_NETWORK,
1690 .default_whitelist = "http,https,tls,rtp,tcp,udp,crypto,httpproxy"
1692 #endif /* CONFIG_HTTPS_PROTOCOL */
1694 #if CONFIG_HTTPPROXY_PROTOCOL
1695 static int http_proxy_close(URLContext *h)
1697 HTTPContext *s = h->priv_data;
1699 ffurl_closep(&s->hd);
1703 static int http_proxy_open(URLContext *h, const char *uri, int flags)
1705 HTTPContext *s = h->priv_data;
1706 char hostname[1024], hoststr[1024];
1707 char auth[1024], pathbuf[1024], *path;
1708 char lower_url[100];
1709 int port, ret = 0, attempts = 0;
1710 HTTPAuthType cur_auth_type;
1714 if( s->seekable == 1 )
1719 av_url_split(NULL, 0, auth, sizeof(auth), hostname, sizeof(hostname), &port,
1720 pathbuf, sizeof(pathbuf), uri);
1721 ff_url_join(hoststr, sizeof(hoststr), NULL, NULL, hostname, port, NULL);
1726 ff_url_join(lower_url, sizeof(lower_url), "tcp", NULL, hostname, port,
1729 ret = ffurl_open_whitelist(&s->hd, lower_url, AVIO_FLAG_READ_WRITE,
1730 &h->interrupt_callback, NULL,
1731 h->protocol_whitelist, h->protocol_blacklist, h);
1735 authstr = ff_http_auth_create_response(&s->proxy_auth_state, auth,
1737 snprintf(s->buffer, sizeof(s->buffer),
1738 "CONNECT %s HTTP/1.1\r\n"
1740 "Connection: close\r\n"
1745 authstr ? "Proxy-" : "", authstr ? authstr : "");
1748 if ((ret = ffurl_write(s->hd, s->buffer, strlen(s->buffer))) < 0)
1751 s->buf_ptr = s->buffer;
1752 s->buf_end = s->buffer;
1754 s->filesize = UINT64_MAX;
1755 cur_auth_type = s->proxy_auth_state.auth_type;
1757 /* Note: This uses buffering, potentially reading more than the
1758 * HTTP header. If tunneling a protocol where the server starts
1759 * the conversation, we might buffer part of that here, too.
1760 * Reading that requires using the proper ffurl_read() function
1761 * on this URLContext, not using the fd directly (as the tls
1762 * protocol does). This shouldn't be an issue for tls though,
1763 * since the client starts the conversation there, so there
1764 * is no extra data that we might buffer up here.
1766 ret = http_read_header(h, &new_loc);
1771 if (s->http_code == 407 &&
1772 (cur_auth_type == HTTP_AUTH_NONE || s->proxy_auth_state.stale) &&
1773 s->proxy_auth_state.auth_type != HTTP_AUTH_NONE && attempts < 2) {
1774 ffurl_closep(&s->hd);
1778 if (s->http_code < 400)
1780 ret = ff_http_averror(s->http_code, AVERROR(EIO));
1783 http_proxy_close(h);
1787 static int http_proxy_write(URLContext *h, const uint8_t *buf, int size)
1789 HTTPContext *s = h->priv_data;
1790 return ffurl_write(s->hd, buf, size);
1793 const URLProtocol ff_httpproxy_protocol = {
1794 .name = "httpproxy",
1795 .url_open = http_proxy_open,
1796 .url_read = http_buf_read,
1797 .url_write = http_proxy_write,
1798 .url_close = http_proxy_close,
1799 .url_get_file_handle = http_get_file_handle,
1800 .priv_data_size = sizeof(HTTPContext),
1801 .flags = URL_PROTOCOL_FLAG_NETWORK,
1803 #endif /* CONFIG_HTTPPROXY_PROTOCOL */