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;
78 #if FF_API_HTTP_USER_AGENT
79 char *user_agent_deprecated;
82 /* Set if the server correctly handles Connection: close and will close
83 * the connection after feeding us the content. */
85 int seekable; /**< Control seekability, 0 = disable, 1 = enable, -1 = probe. */
87 /* A flag which indicates if the end of chunked encoding has been sent. */
89 /* A flag which indicates we have finished to read POST reply. */
91 /* A flag which indicates if we use persistent connections. */
92 int multiple_requests;
97 char *cookies; ///< holds newline (\n) delimited Set-Cookie header field values (without the "Set-Cookie: " field name)
98 /* A dictionary containing cookies keyed by cookie name */
99 AVDictionary *cookie_dict;
101 /* how much data was read since the last ICY metadata packet */
102 uint64_t icy_data_read;
103 /* after how many bytes of read data a new metadata packet will be found */
104 uint64_t icy_metaint;
105 char *icy_metadata_headers;
106 char *icy_metadata_packet;
107 AVDictionary *metadata;
110 z_stream inflate_stream;
111 uint8_t *inflate_buffer;
112 #endif /* CONFIG_ZLIB */
113 AVDictionary *chained_options;
117 int reconnect_at_eof;
118 int reconnect_streamed;
120 int reconnect_delay_max;
125 HandshakeState handshake_step;
126 int is_connected_server;
129 #define OFFSET(x) offsetof(HTTPContext, x)
130 #define D AV_OPT_FLAG_DECODING_PARAM
131 #define E AV_OPT_FLAG_ENCODING_PARAM
132 #define DEFAULT_USER_AGENT "Lavf/" AV_STRINGIFY(LIBAVFORMAT_VERSION)
134 static const AVOption options[] = {
135 { "seekable", "control seekability of connection", OFFSET(seekable), AV_OPT_TYPE_BOOL, { .i64 = -1 }, -1, 1, D },
136 { "chunked_post", "use chunked transfer-encoding for posts", OFFSET(chunked_post), AV_OPT_TYPE_BOOL, { .i64 = 1 }, 0, 1, E },
137 { "http_proxy", "set HTTP proxy to tunnel through", OFFSET(http_proxy), AV_OPT_TYPE_STRING, { .str = NULL }, 0, 0, D | E },
138 { "headers", "set custom HTTP headers, can override built in default headers", OFFSET(headers), AV_OPT_TYPE_STRING, { .str = NULL }, 0, 0, D | E },
139 { "content_type", "set a specific content type for the POST messages", OFFSET(content_type), AV_OPT_TYPE_STRING, { .str = NULL }, 0, 0, D | E },
140 { "user_agent", "override User-Agent header", OFFSET(user_agent), AV_OPT_TYPE_STRING, { .str = DEFAULT_USER_AGENT }, 0, 0, D },
141 #if FF_API_HTTP_USER_AGENT
142 { "user-agent", "override User-Agent header", OFFSET(user_agent_deprecated), AV_OPT_TYPE_STRING, { .str = DEFAULT_USER_AGENT }, 0, 0, D },
144 { "multiple_requests", "use persistent connections", OFFSET(multiple_requests), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, D | E },
145 { "post_data", "set custom HTTP post data", OFFSET(post_data), AV_OPT_TYPE_BINARY, .flags = D | E },
146 { "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 },
147 { "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 },
148 { "icy", "request ICY metadata", OFFSET(icy), AV_OPT_TYPE_BOOL, { .i64 = 1 }, 0, 1, D },
149 { "icy_metadata_headers", "return ICY metadata headers", OFFSET(icy_metadata_headers), AV_OPT_TYPE_STRING, { .str = NULL }, 0, 0, AV_OPT_FLAG_EXPORT },
150 { "icy_metadata_packet", "return current ICY metadata packet", OFFSET(icy_metadata_packet), AV_OPT_TYPE_STRING, { .str = NULL }, 0, 0, AV_OPT_FLAG_EXPORT },
151 { "metadata", "metadata read from the bitstream", OFFSET(metadata), AV_OPT_TYPE_DICT, {0}, 0, 0, AV_OPT_FLAG_EXPORT },
152 { "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"},
153 { "none", "No auth method set, autodetect", 0, AV_OPT_TYPE_CONST, { .i64 = HTTP_AUTH_NONE }, 0, 0, D | E, "auth_type"},
154 { "basic", "HTTP basic authentication", 0, AV_OPT_TYPE_CONST, { .i64 = HTTP_AUTH_BASIC }, 0, 0, D | E, "auth_type"},
155 { "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 },
156 { "location", "The actual location of the data received", OFFSET(location), AV_OPT_TYPE_STRING, { .str = NULL }, 0, 0, D | E },
157 { "offset", "initial byte offset", OFFSET(off), AV_OPT_TYPE_INT64, { .i64 = 0 }, 0, INT64_MAX, D },
158 { "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 },
159 { "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 },
160 { "reconnect", "auto reconnect after disconnect before EOF", OFFSET(reconnect), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, D },
161 { "reconnect_at_eof", "auto reconnect at EOF", OFFSET(reconnect_at_eof), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, D },
162 { "reconnect_streamed", "auto reconnect streamed / non seekable streams", OFFSET(reconnect_streamed), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, D },
163 { "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 },
164 { "listen", "listen on HTTP", OFFSET(listen), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 2, D | E },
165 { "resource", "The resource requested by a client", OFFSET(resource), AV_OPT_TYPE_STRING, { .str = NULL }, 0, 0, E },
166 { "reply_code", "The http status code to return to a client", OFFSET(reply_code), AV_OPT_TYPE_INT, { .i64 = 200}, INT_MIN, 599, E},
170 static int http_connect(URLContext *h, const char *path, const char *local_path,
171 const char *hoststr, const char *auth,
172 const char *proxyauth, int *new_location);
173 static int http_read_header(URLContext *h, int *new_location);
174 static int http_shutdown(URLContext *h, int flags);
176 void ff_http_init_auth_state(URLContext *dest, const URLContext *src)
178 memcpy(&((HTTPContext *)dest->priv_data)->auth_state,
179 &((HTTPContext *)src->priv_data)->auth_state,
180 sizeof(HTTPAuthState));
181 memcpy(&((HTTPContext *)dest->priv_data)->proxy_auth_state,
182 &((HTTPContext *)src->priv_data)->proxy_auth_state,
183 sizeof(HTTPAuthState));
186 static int http_open_cnx_internal(URLContext *h, AVDictionary **options)
188 const char *path, *proxy_path, *lower_proto = "tcp", *local_path;
189 char hostname[1024], hoststr[1024], proto[10];
190 char auth[1024], proxyauth[1024] = "";
191 char path1[MAX_URL_SIZE];
192 char buf[1024], urlbuf[MAX_URL_SIZE];
193 int port, use_proxy, err, location_changed = 0;
194 HTTPContext *s = h->priv_data;
196 av_url_split(proto, sizeof(proto), auth, sizeof(auth),
197 hostname, sizeof(hostname), &port,
198 path1, sizeof(path1), s->location);
199 ff_url_join(hoststr, sizeof(hoststr), NULL, NULL, hostname, port, NULL);
201 proxy_path = s->http_proxy ? s->http_proxy : getenv("http_proxy");
202 use_proxy = !ff_http_match_no_proxy(getenv("no_proxy"), hostname) &&
203 proxy_path && av_strstart(proxy_path, "http://", NULL);
205 if (!strcmp(proto, "https")) {
214 if (path1[0] == '\0')
220 /* Reassemble the request URL without auth string - we don't
221 * want to leak the auth to the proxy. */
222 ff_url_join(urlbuf, sizeof(urlbuf), proto, NULL, hostname, port, "%s",
225 av_url_split(NULL, 0, proxyauth, sizeof(proxyauth),
226 hostname, sizeof(hostname), &port, NULL, 0, proxy_path);
229 ff_url_join(buf, sizeof(buf), lower_proto, NULL, hostname, port, NULL);
232 err = ffurl_open_whitelist(&s->hd, buf, AVIO_FLAG_READ_WRITE,
233 &h->interrupt_callback, options,
234 h->protocol_whitelist, h->protocol_blacklist, h);
239 err = http_connect(h, path, local_path, hoststr,
240 auth, proxyauth, &location_changed);
244 return location_changed;
247 /* return non zero if error */
248 static int http_open_cnx(URLContext *h, AVDictionary **options)
250 HTTPAuthType cur_auth_type, cur_proxy_auth_type;
251 HTTPContext *s = h->priv_data;
252 int location_changed, attempts = 0, redirects = 0;
254 av_dict_copy(options, s->chained_options, 0);
256 cur_auth_type = s->auth_state.auth_type;
257 cur_proxy_auth_type = s->auth_state.auth_type;
259 location_changed = http_open_cnx_internal(h, options);
260 if (location_changed < 0)
264 if (s->http_code == 401) {
265 if ((cur_auth_type == HTTP_AUTH_NONE || s->auth_state.stale) &&
266 s->auth_state.auth_type != HTTP_AUTH_NONE && attempts < 4) {
267 ffurl_closep(&s->hd);
272 if (s->http_code == 407) {
273 if ((cur_proxy_auth_type == HTTP_AUTH_NONE || s->proxy_auth_state.stale) &&
274 s->proxy_auth_state.auth_type != HTTP_AUTH_NONE && attempts < 4) {
275 ffurl_closep(&s->hd);
280 if ((s->http_code == 301 || s->http_code == 302 ||
281 s->http_code == 303 || s->http_code == 307) &&
282 location_changed == 1) {
283 /* url moved, get next */
284 ffurl_closep(&s->hd);
285 if (redirects++ >= MAX_REDIRECTS)
287 /* Restart the authentication process with the new target, which
288 * might use a different auth mechanism. */
289 memset(&s->auth_state, 0, sizeof(s->auth_state));
291 location_changed = 0;
298 ffurl_closep(&s->hd);
299 if (location_changed < 0)
300 return location_changed;
301 return ff_http_averror(s->http_code, AVERROR(EIO));
304 int ff_http_do_new_request(URLContext *h, const char *uri)
306 HTTPContext *s = h->priv_data;
307 AVDictionary *options = NULL;
310 ret = http_shutdown(h, h->flags);
314 s->end_chunked_post = 0;
317 s->icy_data_read = 0;
318 av_free(s->location);
319 s->location = av_strdup(uri);
321 return AVERROR(ENOMEM);
323 ret = http_open_cnx(h, &options);
324 av_dict_free(&options);
328 int ff_http_averror(int status_code, int default_averror)
330 switch (status_code) {
331 case 400: return AVERROR_HTTP_BAD_REQUEST;
332 case 401: return AVERROR_HTTP_UNAUTHORIZED;
333 case 403: return AVERROR_HTTP_FORBIDDEN;
334 case 404: return AVERROR_HTTP_NOT_FOUND;
337 if (status_code >= 400 && status_code <= 499)
338 return AVERROR_HTTP_OTHER_4XX;
339 else if (status_code >= 500)
340 return AVERROR_HTTP_SERVER_ERROR;
342 return default_averror;
345 static int http_write_reply(URLContext* h, int status_code)
347 int ret, body = 0, reply_code, message_len;
348 const char *reply_text, *content_type;
349 HTTPContext *s = h->priv_data;
350 char message[BUFFER_SIZE];
351 content_type = "text/plain";
355 switch (status_code) {
356 case AVERROR_HTTP_BAD_REQUEST:
359 reply_text = "Bad Request";
361 case AVERROR_HTTP_FORBIDDEN:
364 reply_text = "Forbidden";
366 case AVERROR_HTTP_NOT_FOUND:
369 reply_text = "Not Found";
374 content_type = s->content_type ? s->content_type : "application/octet-stream";
376 case AVERROR_HTTP_SERVER_ERROR:
379 reply_text = "Internal server error";
382 return AVERROR(EINVAL);
386 message_len = snprintf(message, sizeof(message),
387 "HTTP/1.1 %03d %s\r\n"
388 "Content-Type: %s\r\n"
389 "Content-Length: %"SIZE_SPECIFIER"\r\n"
396 strlen(reply_text) + 6, // 3 digit status code + space + \r\n
397 s->headers ? s->headers : "",
402 message_len = snprintf(message, sizeof(message),
403 "HTTP/1.1 %03d %s\r\n"
404 "Content-Type: %s\r\n"
405 "Transfer-Encoding: chunked\r\n"
411 s->headers ? s->headers : "");
413 av_log(h, AV_LOG_TRACE, "HTTP reply header: \n%s----\n", message);
414 if ((ret = ffurl_write(s->hd, message, message_len)) < 0)
419 static void handle_http_errors(URLContext *h, int error)
421 av_assert0(error < 0);
422 http_write_reply(h, error);
425 static int http_handshake(URLContext *c)
427 int ret, err, new_location;
428 HTTPContext *ch = c->priv_data;
429 URLContext *cl = ch->hd;
430 switch (ch->handshake_step) {
432 av_log(c, AV_LOG_TRACE, "Lower protocol\n");
433 if ((ret = ffurl_handshake(cl)) > 0)
437 ch->handshake_step = READ_HEADERS;
438 ch->is_connected_server = 1;
441 av_log(c, AV_LOG_TRACE, "Read headers\n");
442 if ((err = http_read_header(c, &new_location)) < 0) {
443 handle_http_errors(c, err);
446 ch->handshake_step = WRITE_REPLY_HEADERS;
448 case WRITE_REPLY_HEADERS:
449 av_log(c, AV_LOG_TRACE, "Reply code: %d\n", ch->reply_code);
450 if ((err = http_write_reply(c, ch->reply_code)) < 0)
452 ch->handshake_step = FINISH;
457 // this should never be reached.
458 return AVERROR(EINVAL);
461 static int http_listen(URLContext *h, const char *uri, int flags,
462 AVDictionary **options) {
463 HTTPContext *s = h->priv_data;
465 char hostname[1024], proto[10];
467 const char *lower_proto = "tcp";
469 av_url_split(proto, sizeof(proto), NULL, 0, hostname, sizeof(hostname), &port,
471 if (!strcmp(proto, "https"))
473 ff_url_join(lower_url, sizeof(lower_url), lower_proto, NULL, hostname, port,
475 if ((ret = av_dict_set_int(options, "listen", s->listen, 0)) < 0)
477 if ((ret = ffurl_open_whitelist(&s->hd, lower_url, AVIO_FLAG_READ_WRITE,
478 &h->interrupt_callback, options,
479 h->protocol_whitelist, h->protocol_blacklist, h
482 s->handshake_step = LOWER_PROTO;
483 if (s->listen == HTTP_SINGLE) { /* single client */
485 while ((ret = http_handshake(h)) > 0);
488 av_dict_free(&s->chained_options);
492 static int http_open(URLContext *h, const char *uri, int flags,
493 AVDictionary **options)
495 HTTPContext *s = h->priv_data;
498 if( s->seekable == 1 )
503 s->filesize = UINT64_MAX;
504 s->location = av_strdup(uri);
506 return AVERROR(ENOMEM);
508 av_dict_copy(&s->chained_options, *options, 0);
511 int len = strlen(s->headers);
512 if (len < 2 || strcmp("\r\n", s->headers + len - 2)) {
513 av_log(h, AV_LOG_WARNING,
514 "No trailing CRLF found in HTTP header.\n");
515 ret = av_reallocp(&s->headers, len + 3);
518 s->headers[len] = '\r';
519 s->headers[len + 1] = '\n';
520 s->headers[len + 2] = '\0';
525 return http_listen(h, uri, flags, options);
527 ret = http_open_cnx(h, options);
529 av_dict_free(&s->chained_options);
533 static int http_accept(URLContext *s, URLContext **c)
536 HTTPContext *sc = s->priv_data;
538 URLContext *sl = sc->hd;
539 URLContext *cl = NULL;
541 av_assert0(sc->listen);
542 if ((ret = ffurl_alloc(c, s->filename, s->flags, &sl->interrupt_callback)) < 0)
544 cc = (*c)->priv_data;
545 if ((ret = ffurl_accept(sl, &cl)) < 0)
548 cc->is_multi_client = 1;
553 static int http_getc(HTTPContext *s)
556 if (s->buf_ptr >= s->buf_end) {
557 len = ffurl_read(s->hd, s->buffer, BUFFER_SIZE);
560 } else if (len == 0) {
563 s->buf_ptr = s->buffer;
564 s->buf_end = s->buffer + len;
567 return *s->buf_ptr++;
570 static int http_get_line(HTTPContext *s, char *line, int line_size)
582 if (q > line && q[-1] == '\r')
588 if ((q - line) < line_size - 1)
594 static int check_http_code(URLContext *h, int http_code, const char *end)
596 HTTPContext *s = h->priv_data;
597 /* error codes are 4xx and 5xx, but regard 401 as a success, so we
598 * don't abort until all headers have been parsed. */
599 if (http_code >= 400 && http_code < 600 &&
600 (http_code != 401 || s->auth_state.auth_type != HTTP_AUTH_NONE) &&
601 (http_code != 407 || s->proxy_auth_state.auth_type != HTTP_AUTH_NONE)) {
602 end += strspn(end, SPACE_CHARS);
603 av_log(h, AV_LOG_WARNING, "HTTP error %d %s\n", http_code, end);
604 return ff_http_averror(http_code, AVERROR(EIO));
609 static int parse_location(HTTPContext *s, const char *p)
611 char redirected_location[MAX_URL_SIZE], *new_loc;
612 ff_make_absolute_url(redirected_location, sizeof(redirected_location),
614 new_loc = av_strdup(redirected_location);
616 return AVERROR(ENOMEM);
617 av_free(s->location);
618 s->location = new_loc;
622 /* "bytes $from-$to/$document_size" */
623 static void parse_content_range(URLContext *h, const char *p)
625 HTTPContext *s = h->priv_data;
628 if (!strncmp(p, "bytes ", 6)) {
630 s->off = strtoull(p, NULL, 10);
631 if ((slash = strchr(p, '/')) && strlen(slash) > 0)
632 s->filesize = strtoull(slash + 1, NULL, 10);
634 if (s->seekable == -1 && (!s->is_akamai || s->filesize != 2147483647))
635 h->is_streamed = 0; /* we _can_ in fact seek */
638 static int parse_content_encoding(URLContext *h, const char *p)
640 if (!av_strncasecmp(p, "gzip", 4) ||
641 !av_strncasecmp(p, "deflate", 7)) {
643 HTTPContext *s = h->priv_data;
646 inflateEnd(&s->inflate_stream);
647 if (inflateInit2(&s->inflate_stream, 32 + 15) != Z_OK) {
648 av_log(h, AV_LOG_WARNING, "Error during zlib initialisation: %s\n",
649 s->inflate_stream.msg);
650 return AVERROR(ENOSYS);
652 if (zlibCompileFlags() & (1 << 17)) {
653 av_log(h, AV_LOG_WARNING,
654 "Your zlib was compiled without gzip support.\n");
655 return AVERROR(ENOSYS);
658 av_log(h, AV_LOG_WARNING,
659 "Compressed (%s) content, need zlib with gzip support\n", p);
660 return AVERROR(ENOSYS);
661 #endif /* CONFIG_ZLIB */
662 } else if (!av_strncasecmp(p, "identity", 8)) {
663 // The normal, no-encoding case (although servers shouldn't include
664 // the header at all if this is the case).
666 av_log(h, AV_LOG_WARNING, "Unknown content coding: %s\n", p);
671 // Concat all Icy- header lines
672 static int parse_icy(HTTPContext *s, const char *tag, const char *p)
674 int len = 4 + strlen(p) + strlen(tag);
675 int is_first = !s->icy_metadata_headers;
678 av_dict_set(&s->metadata, tag, p, 0);
680 if (s->icy_metadata_headers)
681 len += strlen(s->icy_metadata_headers);
683 if ((ret = av_reallocp(&s->icy_metadata_headers, len)) < 0)
687 *s->icy_metadata_headers = '\0';
689 av_strlcatf(s->icy_metadata_headers, len, "%s: %s\n", tag, p);
694 static int parse_set_cookie_expiry_time(const char *exp_str, struct tm *buf)
696 char exp_buf[MAX_EXPIRY];
697 int i, j, exp_buf_len = MAX_EXPIRY-1;
700 // strip off any punctuation or whitespace
701 for (i = 0, j = 0; exp_str[i] != '\0' && j < exp_buf_len; i++) {
702 if ((exp_str[i] >= '0' && exp_str[i] <= '9') ||
703 (exp_str[i] >= 'A' && exp_str[i] <= 'Z') ||
704 (exp_str[i] >= 'a' && exp_str[i] <= 'z')) {
705 exp_buf[j] = exp_str[i];
712 // move the string beyond the day of week
713 while ((*expiry < '0' || *expiry > '9') && *expiry != '\0')
716 return av_small_strptime(expiry, "%d%b%Y%H%M%S", buf) ? 0 : AVERROR(EINVAL);
719 static int parse_set_cookie(const char *set_cookie, AVDictionary **dict)
721 char *param, *next_param, *cstr, *back;
723 if (!(cstr = av_strdup(set_cookie)))
724 return AVERROR(EINVAL);
726 // strip any trailing whitespace
727 back = &cstr[strlen(cstr)-1];
728 while (strchr(WHITESPACES, *back)) {
734 while ((param = av_strtok(next_param, ";", &next_param))) {
736 param += strspn(param, WHITESPACES);
737 if ((name = av_strtok(param, "=", &value))) {
738 if (av_dict_set(dict, name, value, 0) < 0) {
749 static int parse_cookie(HTTPContext *s, const char *p, AVDictionary **cookies)
751 AVDictionary *new_params = NULL;
752 AVDictionaryEntry *e, *cookie_entry;
755 // ensure the cookie is parsable
756 if (parse_set_cookie(p, &new_params))
759 // if there is no cookie value there is nothing to parse
760 cookie_entry = av_dict_get(new_params, "", NULL, AV_DICT_IGNORE_SUFFIX);
761 if (!cookie_entry || !cookie_entry->value) {
762 av_dict_free(&new_params);
766 // ensure the cookie is not expired or older than an existing value
767 if ((e = av_dict_get(new_params, "expires", NULL, 0)) && e->value) {
768 struct tm new_tm = {0};
769 if (!parse_set_cookie_expiry_time(e->value, &new_tm)) {
770 AVDictionaryEntry *e2;
772 // if the cookie has already expired ignore it
773 if (av_timegm(&new_tm) < av_gettime() / 1000000) {
774 av_dict_free(&new_params);
778 // only replace an older cookie with the same name
779 e2 = av_dict_get(*cookies, cookie_entry->key, NULL, 0);
780 if (e2 && e2->value) {
781 AVDictionary *old_params = NULL;
782 if (!parse_set_cookie(p, &old_params)) {
783 e2 = av_dict_get(old_params, "expires", NULL, 0);
784 if (e2 && e2->value) {
785 struct tm old_tm = {0};
786 if (!parse_set_cookie_expiry_time(e->value, &old_tm)) {
787 if (av_timegm(&new_tm) < av_timegm(&old_tm)) {
788 av_dict_free(&new_params);
789 av_dict_free(&old_params);
795 av_dict_free(&old_params);
800 // duplicate the cookie name (dict will dupe the value)
801 if (!(eql = strchr(p, '='))) return AVERROR(EINVAL);
802 if (!(name = av_strndup(p, eql - p))) return AVERROR(ENOMEM);
804 // add the cookie to the dictionary
805 av_dict_set(cookies, name, eql, AV_DICT_DONT_STRDUP_KEY);
810 static int cookie_string(AVDictionary *dict, char **cookies)
812 AVDictionaryEntry *e = NULL;
815 // determine how much memory is needed for the cookies string
816 while (e = av_dict_get(dict, "", e, AV_DICT_IGNORE_SUFFIX))
817 len += strlen(e->key) + strlen(e->value) + 1;
819 // reallocate the cookies
821 if (*cookies) av_free(*cookies);
822 *cookies = av_malloc(len);
823 if (!*cookies) return AVERROR(ENOMEM);
826 // write out the cookies
827 while (e = av_dict_get(dict, "", e, AV_DICT_IGNORE_SUFFIX))
828 av_strlcatf(*cookies, len, "%s%s\n", e->key, e->value);
833 static int process_line(URLContext *h, char *line, int line_count,
836 HTTPContext *s = h->priv_data;
837 const char *auto_method = h->flags & AVIO_FLAG_READ ? "POST" : "GET";
838 char *tag, *p, *end, *method, *resource, *version;
842 if (line[0] == '\0') {
848 if (line_count == 0) {
849 if (s->is_connected_server) {
852 while (*p && !av_isspace(*p))
855 av_log(h, AV_LOG_TRACE, "Received method: %s\n", method);
857 if (av_strcasecmp(s->method, method)) {
858 av_log(h, AV_LOG_ERROR, "Received and expected HTTP method do not match. (%s expected, %s received)\n",
860 return ff_http_averror(400, AVERROR(EIO));
863 // use autodetected HTTP method to expect
864 av_log(h, AV_LOG_TRACE, "Autodetected %s HTTP method\n", auto_method);
865 if (av_strcasecmp(auto_method, method)) {
866 av_log(h, AV_LOG_ERROR, "Received and autodetected HTTP method did not match "
867 "(%s autodetected %s received)\n", auto_method, method);
868 return ff_http_averror(400, AVERROR(EIO));
870 if (!(s->method = av_strdup(method)))
871 return AVERROR(ENOMEM);
875 while (av_isspace(*p))
878 while (!av_isspace(*p))
881 av_log(h, AV_LOG_TRACE, "Requested resource: %s\n", resource);
882 if (!(s->resource = av_strdup(resource)))
883 return AVERROR(ENOMEM);
886 while (av_isspace(*p))
889 while (*p && !av_isspace(*p))
892 if (av_strncasecmp(version, "HTTP/", 5)) {
893 av_log(h, AV_LOG_ERROR, "Malformed HTTP version string.\n");
894 return ff_http_averror(400, AVERROR(EIO));
896 av_log(h, AV_LOG_TRACE, "HTTP version string: %s\n", version);
898 while (!av_isspace(*p) && *p != '\0')
900 while (av_isspace(*p))
902 s->http_code = strtol(p, &end, 10);
904 av_log(h, AV_LOG_TRACE, "http_code=%d\n", s->http_code);
906 if ((ret = check_http_code(h, s->http_code, end)) < 0)
910 while (*p != '\0' && *p != ':')
918 while (av_isspace(*p))
920 if (!av_strcasecmp(tag, "Location")) {
921 if ((ret = parse_location(s, p)) < 0)
924 } else if (!av_strcasecmp(tag, "Content-Length") &&
925 s->filesize == UINT64_MAX) {
926 s->filesize = strtoull(p, NULL, 10);
927 } else if (!av_strcasecmp(tag, "Content-Range")) {
928 parse_content_range(h, p);
929 } else if (!av_strcasecmp(tag, "Accept-Ranges") &&
930 !strncmp(p, "bytes", 5) &&
933 } else if (!av_strcasecmp(tag, "Transfer-Encoding") &&
934 !av_strncasecmp(p, "chunked", 7)) {
935 s->filesize = UINT64_MAX;
937 } else if (!av_strcasecmp(tag, "WWW-Authenticate")) {
938 ff_http_auth_handle_header(&s->auth_state, tag, p);
939 } else if (!av_strcasecmp(tag, "Authentication-Info")) {
940 ff_http_auth_handle_header(&s->auth_state, tag, p);
941 } else if (!av_strcasecmp(tag, "Proxy-Authenticate")) {
942 ff_http_auth_handle_header(&s->proxy_auth_state, tag, p);
943 } else if (!av_strcasecmp(tag, "Connection")) {
944 if (!strcmp(p, "close"))
946 } else if (!av_strcasecmp(tag, "Server")) {
947 if (!av_strcasecmp(p, "AkamaiGHost")) {
949 } else if (!av_strncasecmp(p, "MediaGateway", 12)) {
950 s->is_mediagateway = 1;
952 } else if (!av_strcasecmp(tag, "Content-Type")) {
953 av_free(s->mime_type);
954 s->mime_type = av_strdup(p);
955 } else if (!av_strcasecmp(tag, "Set-Cookie")) {
956 if (parse_cookie(s, p, &s->cookie_dict))
957 av_log(h, AV_LOG_WARNING, "Unable to parse '%s'\n", p);
958 } else if (!av_strcasecmp(tag, "Icy-MetaInt")) {
959 s->icy_metaint = strtoull(p, NULL, 10);
960 } else if (!av_strncasecmp(tag, "Icy-", 4)) {
961 if ((ret = parse_icy(s, tag, p)) < 0)
963 } else if (!av_strcasecmp(tag, "Content-Encoding")) {
964 if ((ret = parse_content_encoding(h, p)) < 0)
972 * Create a string containing cookie values for use as a HTTP cookie header
973 * field value for a particular path and domain from the cookie values stored in
974 * the HTTP protocol context. The cookie string is stored in *cookies.
976 * @return a negative value if an error condition occurred, 0 otherwise
978 static int get_cookies(HTTPContext *s, char **cookies, const char *path,
981 // cookie strings will look like Set-Cookie header field values. Multiple
982 // Set-Cookie fields will result in multiple values delimited by a newline
984 char *cookie, *set_cookies = av_strdup(s->cookies), *next = set_cookies;
986 if (!set_cookies) return AVERROR(EINVAL);
988 // destroy any cookies in the dictionary.
989 av_dict_free(&s->cookie_dict);
992 while ((cookie = av_strtok(next, "\n", &next))) {
993 AVDictionary *cookie_params = NULL;
994 AVDictionaryEntry *cookie_entry, *e;
996 // store the cookie in a dict in case it is updated in the response
997 if (parse_cookie(s, cookie, &s->cookie_dict))
998 av_log(s, AV_LOG_WARNING, "Unable to parse '%s'\n", cookie);
1000 // continue on to the next cookie if this one cannot be parsed
1001 if (parse_set_cookie(cookie, &cookie_params))
1004 // if the cookie has no value, skip it
1005 cookie_entry = av_dict_get(cookie_params, "", NULL, AV_DICT_IGNORE_SUFFIX);
1006 if (!cookie_entry || !cookie_entry->value) {
1007 av_dict_free(&cookie_params);
1011 // if the cookie has expired, don't add it
1012 if ((e = av_dict_get(cookie_params, "expires", NULL, 0)) && e->value) {
1013 struct tm tm_buf = {0};
1014 if (!parse_set_cookie_expiry_time(e->value, &tm_buf)) {
1015 if (av_timegm(&tm_buf) < av_gettime() / 1000000) {
1016 av_dict_free(&cookie_params);
1022 // if no domain in the cookie assume it appied to this request
1023 if ((e = av_dict_get(cookie_params, "domain", NULL, 0)) && e->value) {
1024 // find the offset comparison is on the min domain (b.com, not a.b.com)
1025 int domain_offset = strlen(domain) - strlen(e->value);
1026 if (domain_offset < 0) {
1027 av_dict_free(&cookie_params);
1031 // match the cookie domain
1032 if (av_strcasecmp(&domain[domain_offset], e->value)) {
1033 av_dict_free(&cookie_params);
1038 // ensure this cookie matches the path
1039 e = av_dict_get(cookie_params, "path", NULL, 0);
1040 if (!e || av_strncasecmp(path, e->value, strlen(e->value))) {
1041 av_dict_free(&cookie_params);
1045 // cookie parameters match, so copy the value
1047 if (!(*cookies = av_asprintf("%s=%s", cookie_entry->key, cookie_entry->value))) {
1048 ret = AVERROR(ENOMEM);
1052 char *tmp = *cookies;
1053 size_t str_size = strlen(cookie_entry->key) + strlen(cookie_entry->value) + strlen(*cookies) + 4;
1054 if (!(*cookies = av_malloc(str_size))) {
1055 ret = AVERROR(ENOMEM);
1059 snprintf(*cookies, str_size, "%s; %s=%s", tmp, cookie_entry->key, cookie_entry->value);
1064 av_free(set_cookies);
1069 static inline int has_header(const char *str, const char *header)
1071 /* header + 2 to skip over CRLF prefix. (make sure you have one!) */
1074 return av_stristart(str, header + 2, NULL) || av_stristr(str, header);
1077 static int http_read_header(URLContext *h, int *new_location)
1079 HTTPContext *s = h->priv_data;
1080 char line[MAX_URL_SIZE];
1083 s->chunksize = UINT64_MAX;
1086 if ((err = http_get_line(s, line, sizeof(line))) < 0)
1089 av_log(h, AV_LOG_TRACE, "header='%s'\n", line);
1091 err = process_line(h, line, s->line_count, new_location);
1099 if (s->seekable == -1 && s->is_mediagateway && s->filesize == 2000000000)
1100 h->is_streamed = 1; /* we can in fact _not_ seek */
1102 // add any new cookies into the existing cookie string
1103 cookie_string(s->cookie_dict, &s->cookies);
1104 av_dict_free(&s->cookie_dict);
1109 static int http_connect(URLContext *h, const char *path, const char *local_path,
1110 const char *hoststr, const char *auth,
1111 const char *proxyauth, int *new_location)
1113 HTTPContext *s = h->priv_data;
1115 char headers[HTTP_HEADERS_SIZE] = "";
1116 char *authstr = NULL, *proxyauthstr = NULL;
1117 uint64_t off = s->off;
1120 int send_expect_100 = 0;
1123 /* send http header */
1124 post = h->flags & AVIO_FLAG_WRITE;
1127 /* force POST method and disable chunked encoding when
1128 * custom HTTP post data is set */
1130 s->chunked_post = 0;
1136 method = post ? "POST" : "GET";
1138 authstr = ff_http_auth_create_response(&s->auth_state, auth,
1139 local_path, method);
1140 proxyauthstr = ff_http_auth_create_response(&s->proxy_auth_state, proxyauth,
1141 local_path, method);
1142 if (post && !s->post_data) {
1143 send_expect_100 = s->send_expect_100;
1144 /* The user has supplied authentication but we don't know the auth type,
1145 * send Expect: 100-continue to get the 401 response including the
1146 * WWW-Authenticate header, or an 100 continue if no auth actually
1148 if (auth && *auth &&
1149 s->auth_state.auth_type == HTTP_AUTH_NONE &&
1150 s->http_code != 401)
1151 send_expect_100 = 1;
1154 #if FF_API_HTTP_USER_AGENT
1155 if (strcmp(s->user_agent_deprecated, DEFAULT_USER_AGENT)) {
1156 av_log(s, AV_LOG_WARNING, "the user-agent option is deprecated, please use user_agent option\n");
1157 s->user_agent = av_strdup(s->user_agent_deprecated);
1160 /* set default headers if needed */
1161 if (!has_header(s->headers, "\r\nUser-Agent: "))
1162 len += av_strlcatf(headers + len, sizeof(headers) - len,
1163 "User-Agent: %s\r\n", s->user_agent);
1164 if (!has_header(s->headers, "\r\nAccept: "))
1165 len += av_strlcpy(headers + len, "Accept: */*\r\n",
1166 sizeof(headers) - len);
1167 // Note: we send this on purpose even when s->off is 0 when we're probing,
1168 // since it allows us to detect more reliably if a (non-conforming)
1169 // server supports seeking by analysing the reply headers.
1170 if (!has_header(s->headers, "\r\nRange: ") && !post && (s->off > 0 || s->end_off || s->seekable == -1)) {
1171 len += av_strlcatf(headers + len, sizeof(headers) - len,
1172 "Range: bytes=%"PRIu64"-", s->off);
1174 len += av_strlcatf(headers + len, sizeof(headers) - len,
1175 "%"PRId64, s->end_off - 1);
1176 len += av_strlcpy(headers + len, "\r\n",
1177 sizeof(headers) - len);
1179 if (send_expect_100 && !has_header(s->headers, "\r\nExpect: "))
1180 len += av_strlcatf(headers + len, sizeof(headers) - len,
1181 "Expect: 100-continue\r\n");
1183 if (!has_header(s->headers, "\r\nConnection: ")) {
1184 if (s->multiple_requests)
1185 len += av_strlcpy(headers + len, "Connection: keep-alive\r\n",
1186 sizeof(headers) - len);
1188 len += av_strlcpy(headers + len, "Connection: close\r\n",
1189 sizeof(headers) - len);
1192 if (!has_header(s->headers, "\r\nHost: "))
1193 len += av_strlcatf(headers + len, sizeof(headers) - len,
1194 "Host: %s\r\n", hoststr);
1195 if (!has_header(s->headers, "\r\nContent-Length: ") && s->post_data)
1196 len += av_strlcatf(headers + len, sizeof(headers) - len,
1197 "Content-Length: %d\r\n", s->post_datalen);
1199 if (!has_header(s->headers, "\r\nContent-Type: ") && s->content_type)
1200 len += av_strlcatf(headers + len, sizeof(headers) - len,
1201 "Content-Type: %s\r\n", s->content_type);
1202 if (!has_header(s->headers, "\r\nCookie: ") && s->cookies) {
1203 char *cookies = NULL;
1204 if (!get_cookies(s, &cookies, path, hoststr) && cookies) {
1205 len += av_strlcatf(headers + len, sizeof(headers) - len,
1206 "Cookie: %s\r\n", cookies);
1210 if (!has_header(s->headers, "\r\nIcy-MetaData: ") && s->icy)
1211 len += av_strlcatf(headers + len, sizeof(headers) - len,
1212 "Icy-MetaData: %d\r\n", 1);
1214 /* now add in custom headers */
1216 av_strlcpy(headers + len, s->headers, sizeof(headers) - len);
1218 ret = snprintf(s->buffer, sizeof(s->buffer),
1219 "%s %s HTTP/1.1\r\n"
1227 post && s->chunked_post ? "Transfer-Encoding: chunked\r\n" : "",
1229 authstr ? authstr : "",
1230 proxyauthstr ? "Proxy-" : "", proxyauthstr ? proxyauthstr : "");
1232 av_log(h, AV_LOG_DEBUG, "request: %s\n", s->buffer);
1234 if (strlen(headers) + 1 == sizeof(headers) ||
1235 ret >= sizeof(s->buffer)) {
1236 av_log(h, AV_LOG_ERROR, "overlong headers\n");
1237 err = AVERROR(EINVAL);
1242 if ((err = ffurl_write(s->hd, s->buffer, strlen(s->buffer))) < 0)
1246 if ((err = ffurl_write(s->hd, s->post_data, s->post_datalen)) < 0)
1249 /* init input buffer */
1250 s->buf_ptr = s->buffer;
1251 s->buf_end = s->buffer;
1254 s->icy_data_read = 0;
1255 s->filesize = UINT64_MAX;
1257 s->end_chunked_post = 0;
1262 if (post && !s->post_data && !send_expect_100) {
1263 /* Pretend that it did work. We didn't read any header yet, since
1264 * we've still to send the POST data, but the code calling this
1265 * function will check http_code after we return. */
1271 /* wait for header */
1272 err = http_read_header(h, new_location);
1279 err = (off == s->off) ? 0 : -1;
1282 av_freep(&proxyauthstr);
1286 static int http_buf_read(URLContext *h, uint8_t *buf, int size)
1288 HTTPContext *s = h->priv_data;
1291 if (s->chunksize != UINT64_MAX) {
1295 if (!s->chunksize) {
1300 if ((err = http_get_line(s, line, sizeof(line))) < 0)
1302 } while (!*line); /* skip CR LF from last chunk */
1304 s->chunksize = strtoull(line, NULL, 16);
1306 av_log(h, AV_LOG_TRACE,
1307 "Chunked encoding data size: %"PRIu64"\n",
1310 if (!s->chunksize && s->multiple_requests) {
1311 http_get_line(s, line, sizeof(line)); // read empty chunk
1315 else if (!s->chunksize) {
1316 av_log(h, AV_LOG_DEBUG, "Last chunk received, closing conn\n");
1317 ffurl_closep(&s->hd);
1320 else if (s->chunksize == UINT64_MAX) {
1321 av_log(h, AV_LOG_ERROR, "Invalid chunk size %"PRIu64"\n",
1323 return AVERROR(EINVAL);
1326 size = FFMIN(size, s->chunksize);
1329 /* read bytes from input buffer first */
1330 len = s->buf_end - s->buf_ptr;
1334 memcpy(buf, s->buf_ptr, len);
1337 uint64_t target_end = s->end_off ? s->end_off : s->filesize;
1338 if ((!s->willclose || s->chunksize == UINT64_MAX) && s->off >= target_end)
1340 len = ffurl_read(s->hd, buf, size);
1341 if (!len && (!s->willclose || s->chunksize == UINT64_MAX) && s->off < target_end) {
1342 av_log(h, AV_LOG_ERROR,
1343 "Stream ends prematurely at %"PRIu64", should be %"PRIu64"\n",
1346 return AVERROR(EIO);
1351 if (s->chunksize > 0 && s->chunksize != UINT64_MAX) {
1352 av_assert0(s->chunksize >= len);
1353 s->chunksize -= len;
1360 #define DECOMPRESS_BUF_SIZE (256 * 1024)
1361 static int http_buf_read_compressed(URLContext *h, uint8_t *buf, int size)
1363 HTTPContext *s = h->priv_data;
1366 if (!s->inflate_buffer) {
1367 s->inflate_buffer = av_malloc(DECOMPRESS_BUF_SIZE);
1368 if (!s->inflate_buffer)
1369 return AVERROR(ENOMEM);
1372 if (s->inflate_stream.avail_in == 0) {
1373 int read = http_buf_read(h, s->inflate_buffer, DECOMPRESS_BUF_SIZE);
1376 s->inflate_stream.next_in = s->inflate_buffer;
1377 s->inflate_stream.avail_in = read;
1380 s->inflate_stream.avail_out = size;
1381 s->inflate_stream.next_out = buf;
1383 ret = inflate(&s->inflate_stream, Z_SYNC_FLUSH);
1384 if (ret != Z_OK && ret != Z_STREAM_END)
1385 av_log(h, AV_LOG_WARNING, "inflate return value: %d, %s\n",
1386 ret, s->inflate_stream.msg);
1388 return size - s->inflate_stream.avail_out;
1390 #endif /* CONFIG_ZLIB */
1392 static int64_t http_seek_internal(URLContext *h, int64_t off, int whence, int force_reconnect);
1394 static int http_read_stream(URLContext *h, uint8_t *buf, int size)
1396 HTTPContext *s = h->priv_data;
1397 int err, new_location, read_ret;
1403 if (s->end_chunked_post && !s->end_header) {
1404 err = http_read_header(h, &new_location);
1411 return http_buf_read_compressed(h, buf, size);
1412 #endif /* CONFIG_ZLIB */
1413 read_ret = http_buf_read(h, buf, size);
1414 if ( (read_ret < 0 && s->reconnect && (!h->is_streamed || s->reconnect_streamed) && s->filesize > 0 && s->off < s->filesize)
1415 || (read_ret == 0 && s->reconnect_at_eof && (!h->is_streamed || s->reconnect_streamed))) {
1416 uint64_t target = h->is_streamed ? 0 : s->off;
1418 if (s->reconnect_delay > s->reconnect_delay_max)
1419 return AVERROR(EIO);
1421 av_log(h, AV_LOG_INFO, "Will reconnect at %"PRIu64" error=%s.\n", s->off, av_err2str(read_ret));
1422 av_usleep(1000U*1000*s->reconnect_delay);
1423 s->reconnect_delay = 1 + 2*s->reconnect_delay;
1424 seek_ret = http_seek_internal(h, target, SEEK_SET, 1);
1425 if (seek_ret != target) {
1426 av_log(h, AV_LOG_ERROR, "Failed to reconnect at %"PRIu64".\n", target);
1430 read_ret = http_buf_read(h, buf, size);
1432 s->reconnect_delay = 0;
1437 // Like http_read_stream(), but no short reads.
1438 // Assumes partial reads are an error.
1439 static int http_read_stream_all(URLContext *h, uint8_t *buf, int size)
1442 while (pos < size) {
1443 int len = http_read_stream(h, buf + pos, size - pos);
1451 static void update_metadata(HTTPContext *s, char *data)
1460 val = strstr(key, "='");
1463 end = strstr(val, "';");
1471 av_dict_set(&s->metadata, key, val, 0);
1477 static int store_icy(URLContext *h, int size)
1479 HTTPContext *s = h->priv_data;
1480 /* until next metadata packet */
1483 if (s->icy_metaint < s->icy_data_read)
1484 return AVERROR_INVALIDDATA;
1485 remaining = s->icy_metaint - s->icy_data_read;
1488 /* The metadata packet is variable sized. It has a 1 byte header
1489 * which sets the length of the packet (divided by 16). If it's 0,
1490 * the metadata doesn't change. After the packet, icy_metaint bytes
1491 * of normal data follows. */
1493 int len = http_read_stream_all(h, &ch, 1);
1497 char data[255 * 16 + 1];
1500 ret = http_read_stream_all(h, data, len);
1504 if ((ret = av_opt_set(s, "icy_metadata_packet", data, 0)) < 0)
1506 update_metadata(s, data);
1508 s->icy_data_read = 0;
1509 remaining = s->icy_metaint;
1512 return FFMIN(size, remaining);
1515 static int http_read(URLContext *h, uint8_t *buf, int size)
1517 HTTPContext *s = h->priv_data;
1519 if (s->icy_metaint > 0) {
1520 size = store_icy(h, size);
1525 size = http_read_stream(h, buf, size);
1527 s->icy_data_read += size;
1531 /* used only when posting data */
1532 static int http_write(URLContext *h, const uint8_t *buf, int size)
1534 char temp[11] = ""; /* 32-bit hex + CRLF + nul */
1536 char crlf[] = "\r\n";
1537 HTTPContext *s = h->priv_data;
1539 if (!s->chunked_post) {
1540 /* non-chunked data is sent without any special encoding */
1541 return ffurl_write(s->hd, buf, size);
1544 /* silently ignore zero-size data since chunk encoding that would
1547 /* upload data using chunked encoding */
1548 snprintf(temp, sizeof(temp), "%x\r\n", size);
1550 if ((ret = ffurl_write(s->hd, temp, strlen(temp))) < 0 ||
1551 (ret = ffurl_write(s->hd, buf, size)) < 0 ||
1552 (ret = ffurl_write(s->hd, crlf, sizeof(crlf) - 1)) < 0)
1558 static int http_shutdown(URLContext *h, int flags)
1561 char footer[] = "0\r\n\r\n";
1562 HTTPContext *s = h->priv_data;
1564 /* signal end of chunked encoding if used */
1565 if (((flags & AVIO_FLAG_WRITE) && s->chunked_post) ||
1566 ((flags & AVIO_FLAG_READ) && s->chunked_post && s->listen)) {
1567 ret = ffurl_write(s->hd, footer, sizeof(footer) - 1);
1568 ret = ret > 0 ? 0 : ret;
1569 s->end_chunked_post = 1;
1575 static int http_close(URLContext *h)
1578 HTTPContext *s = h->priv_data;
1581 inflateEnd(&s->inflate_stream);
1582 av_freep(&s->inflate_buffer);
1583 #endif /* CONFIG_ZLIB */
1585 if (!s->end_chunked_post)
1586 /* Close the write direction by sending the end of chunked encoding. */
1587 ret = http_shutdown(h, h->flags);
1590 ffurl_closep(&s->hd);
1591 av_dict_free(&s->chained_options);
1595 static int64_t http_seek_internal(URLContext *h, int64_t off, int whence, int force_reconnect)
1597 HTTPContext *s = h->priv_data;
1598 URLContext *old_hd = s->hd;
1599 uint64_t old_off = s->off;
1600 uint8_t old_buf[BUFFER_SIZE];
1601 int old_buf_size, ret;
1602 AVDictionary *options = NULL;
1604 if (whence == AVSEEK_SIZE)
1606 else if (!force_reconnect &&
1607 ((whence == SEEK_CUR && off == 0) ||
1608 (whence == SEEK_SET && off == s->off)))
1610 else if ((s->filesize == UINT64_MAX && whence == SEEK_END))
1611 return AVERROR(ENOSYS);
1613 if (whence == SEEK_CUR)
1615 else if (whence == SEEK_END)
1617 else if (whence != SEEK_SET)
1618 return AVERROR(EINVAL);
1620 return AVERROR(EINVAL);
1623 if (s->off && h->is_streamed)
1624 return AVERROR(ENOSYS);
1626 /* we save the old context in case the seek fails */
1627 old_buf_size = s->buf_end - s->buf_ptr;
1628 memcpy(old_buf, s->buf_ptr, old_buf_size);
1631 /* if it fails, continue on old connection */
1632 if ((ret = http_open_cnx(h, &options)) < 0) {
1633 av_dict_free(&options);
1634 memcpy(s->buffer, old_buf, old_buf_size);
1635 s->buf_ptr = s->buffer;
1636 s->buf_end = s->buffer + old_buf_size;
1641 av_dict_free(&options);
1642 ffurl_close(old_hd);
1646 static int64_t http_seek(URLContext *h, int64_t off, int whence)
1648 return http_seek_internal(h, off, whence, 0);
1651 static int http_get_file_handle(URLContext *h)
1653 HTTPContext *s = h->priv_data;
1654 return ffurl_get_file_handle(s->hd);
1657 static int http_get_short_seek(URLContext *h)
1659 HTTPContext *s = h->priv_data;
1660 return ffurl_get_short_seek(s->hd);
1663 #define HTTP_CLASS(flavor) \
1664 static const AVClass flavor ## _context_class = { \
1665 .class_name = # flavor, \
1666 .item_name = av_default_item_name, \
1667 .option = options, \
1668 .version = LIBAVUTIL_VERSION_INT, \
1671 #if CONFIG_HTTP_PROTOCOL
1674 const URLProtocol ff_http_protocol = {
1676 .url_open2 = http_open,
1677 .url_accept = http_accept,
1678 .url_handshake = http_handshake,
1679 .url_read = http_read,
1680 .url_write = http_write,
1681 .url_seek = http_seek,
1682 .url_close = http_close,
1683 .url_get_file_handle = http_get_file_handle,
1684 .url_get_short_seek = http_get_short_seek,
1685 .url_shutdown = http_shutdown,
1686 .priv_data_size = sizeof(HTTPContext),
1687 .priv_data_class = &http_context_class,
1688 .flags = URL_PROTOCOL_FLAG_NETWORK,
1689 .default_whitelist = "http,https,tls,rtp,tcp,udp,crypto,httpproxy"
1691 #endif /* CONFIG_HTTP_PROTOCOL */
1693 #if CONFIG_HTTPS_PROTOCOL
1696 const URLProtocol ff_https_protocol = {
1698 .url_open2 = http_open,
1699 .url_read = http_read,
1700 .url_write = http_write,
1701 .url_seek = http_seek,
1702 .url_close = http_close,
1703 .url_get_file_handle = http_get_file_handle,
1704 .url_get_short_seek = http_get_short_seek,
1705 .url_shutdown = http_shutdown,
1706 .priv_data_size = sizeof(HTTPContext),
1707 .priv_data_class = &https_context_class,
1708 .flags = URL_PROTOCOL_FLAG_NETWORK,
1709 .default_whitelist = "http,https,tls,rtp,tcp,udp,crypto,httpproxy"
1711 #endif /* CONFIG_HTTPS_PROTOCOL */
1713 #if CONFIG_HTTPPROXY_PROTOCOL
1714 static int http_proxy_close(URLContext *h)
1716 HTTPContext *s = h->priv_data;
1718 ffurl_closep(&s->hd);
1722 static int http_proxy_open(URLContext *h, const char *uri, int flags)
1724 HTTPContext *s = h->priv_data;
1725 char hostname[1024], hoststr[1024];
1726 char auth[1024], pathbuf[1024], *path;
1727 char lower_url[100];
1728 int port, ret = 0, attempts = 0;
1729 HTTPAuthType cur_auth_type;
1733 if( s->seekable == 1 )
1738 av_url_split(NULL, 0, auth, sizeof(auth), hostname, sizeof(hostname), &port,
1739 pathbuf, sizeof(pathbuf), uri);
1740 ff_url_join(hoststr, sizeof(hoststr), NULL, NULL, hostname, port, NULL);
1745 ff_url_join(lower_url, sizeof(lower_url), "tcp", NULL, hostname, port,
1748 ret = ffurl_open_whitelist(&s->hd, lower_url, AVIO_FLAG_READ_WRITE,
1749 &h->interrupt_callback, NULL,
1750 h->protocol_whitelist, h->protocol_blacklist, h);
1754 authstr = ff_http_auth_create_response(&s->proxy_auth_state, auth,
1756 snprintf(s->buffer, sizeof(s->buffer),
1757 "CONNECT %s HTTP/1.1\r\n"
1759 "Connection: close\r\n"
1764 authstr ? "Proxy-" : "", authstr ? authstr : "");
1767 if ((ret = ffurl_write(s->hd, s->buffer, strlen(s->buffer))) < 0)
1770 s->buf_ptr = s->buffer;
1771 s->buf_end = s->buffer;
1773 s->filesize = UINT64_MAX;
1774 cur_auth_type = s->proxy_auth_state.auth_type;
1776 /* Note: This uses buffering, potentially reading more than the
1777 * HTTP header. If tunneling a protocol where the server starts
1778 * the conversation, we might buffer part of that here, too.
1779 * Reading that requires using the proper ffurl_read() function
1780 * on this URLContext, not using the fd directly (as the tls
1781 * protocol does). This shouldn't be an issue for tls though,
1782 * since the client starts the conversation there, so there
1783 * is no extra data that we might buffer up here.
1785 ret = http_read_header(h, &new_loc);
1790 if (s->http_code == 407 &&
1791 (cur_auth_type == HTTP_AUTH_NONE || s->proxy_auth_state.stale) &&
1792 s->proxy_auth_state.auth_type != HTTP_AUTH_NONE && attempts < 2) {
1793 ffurl_closep(&s->hd);
1797 if (s->http_code < 400)
1799 ret = ff_http_averror(s->http_code, AVERROR(EIO));
1802 http_proxy_close(h);
1806 static int http_proxy_write(URLContext *h, const uint8_t *buf, int size)
1808 HTTPContext *s = h->priv_data;
1809 return ffurl_write(s->hd, buf, size);
1812 const URLProtocol ff_httpproxy_protocol = {
1813 .name = "httpproxy",
1814 .url_open = http_proxy_open,
1815 .url_read = http_buf_read,
1816 .url_write = http_proxy_write,
1817 .url_close = http_proxy_close,
1818 .url_get_file_handle = http_get_file_handle,
1819 .priv_data_size = sizeof(HTTPContext),
1820 .flags = URL_PROTOCOL_FLAG_NETWORK,
1822 #endif /* CONFIG_HTTPPROXY_PROTOCOL */