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"
38 #include "os_support.h"
41 /* XXX: POST protocol is not completely implemented because ffmpeg uses
42 * only a subset of it. */
44 /* The IO buffer size is unrelated to the max URL size in itself, but needs
45 * to be large enough to fit the full request headers (including long
47 #define BUFFER_SIZE MAX_URL_SIZE
48 #define MAX_REDIRECTS 8
58 typedef struct HTTPContext {
61 unsigned char buffer[BUFFER_SIZE], *buf_ptr, *buf_end;
64 /* Used if "Transfer-Encoding: chunked" otherwise -1. */
66 uint64_t off, end_off, filesize;
68 HTTPAuthState auth_state;
69 HTTPAuthState proxy_auth_state;
74 #if FF_API_HTTP_USER_AGENT
75 char *user_agent_deprecated;
78 /* Set if the server correctly handles Connection: close and will close
79 * the connection after feeding us the content. */
81 int seekable; /**< Control seekability, 0 = disable, 1 = enable, -1 = probe. */
83 /* A flag which indicates if the end of chunked encoding has been sent. */
85 /* A flag which indicates we have finished to read POST reply. */
87 /* A flag which indicates if we use persistent connections. */
88 int multiple_requests;
93 char *cookies; ///< holds newline (\n) delimited Set-Cookie header field values (without the "Set-Cookie: " field name)
94 /* A dictionary containing cookies keyed by cookie name */
95 AVDictionary *cookie_dict;
97 /* how much data was read since the last ICY metadata packet */
98 uint64_t icy_data_read;
99 /* after how many bytes of read data a new metadata packet will be found */
100 uint64_t icy_metaint;
101 char *icy_metadata_headers;
102 char *icy_metadata_packet;
103 AVDictionary *metadata;
106 z_stream inflate_stream;
107 uint8_t *inflate_buffer;
108 #endif /* CONFIG_ZLIB */
109 AVDictionary *chained_options;
113 int reconnect_at_eof;
114 int reconnect_streamed;
116 int reconnect_delay_max;
121 HandshakeState handshake_step;
122 int is_connected_server;
125 #define OFFSET(x) offsetof(HTTPContext, x)
126 #define D AV_OPT_FLAG_DECODING_PARAM
127 #define E AV_OPT_FLAG_ENCODING_PARAM
128 #define DEFAULT_USER_AGENT "Lavf/" AV_STRINGIFY(LIBAVFORMAT_VERSION)
130 static const AVOption options[] = {
131 { "seekable", "control seekability of connection", OFFSET(seekable), AV_OPT_TYPE_BOOL, { .i64 = -1 }, -1, 1, D },
132 { "chunked_post", "use chunked transfer-encoding for posts", OFFSET(chunked_post), AV_OPT_TYPE_BOOL, { .i64 = 1 }, 0, 1, E },
133 { "http_proxy", "set HTTP proxy to tunnel through", OFFSET(http_proxy), AV_OPT_TYPE_STRING, { .str = NULL }, 0, 0, D | E },
134 { "headers", "set custom HTTP headers, can override built in default headers", OFFSET(headers), AV_OPT_TYPE_STRING, { .str = NULL }, 0, 0, D | E },
135 { "content_type", "set a specific content type for the POST messages", OFFSET(content_type), AV_OPT_TYPE_STRING, { .str = NULL }, 0, 0, D | E },
136 { "user_agent", "override User-Agent header", OFFSET(user_agent), AV_OPT_TYPE_STRING, { .str = DEFAULT_USER_AGENT }, 0, 0, D },
137 #if FF_API_HTTP_USER_AGENT
138 { "user-agent", "override User-Agent header", OFFSET(user_agent_deprecated), AV_OPT_TYPE_STRING, { .str = DEFAULT_USER_AGENT }, 0, 0, D },
140 { "multiple_requests", "use persistent connections", OFFSET(multiple_requests), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, D | E },
141 { "post_data", "set custom HTTP post data", OFFSET(post_data), AV_OPT_TYPE_BINARY, .flags = D | E },
142 { "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 },
143 { "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 },
144 { "icy", "request ICY metadata", OFFSET(icy), AV_OPT_TYPE_BOOL, { .i64 = 1 }, 0, 1, D },
145 { "icy_metadata_headers", "return ICY metadata headers", OFFSET(icy_metadata_headers), AV_OPT_TYPE_STRING, { .str = NULL }, 0, 0, AV_OPT_FLAG_EXPORT },
146 { "icy_metadata_packet", "return current ICY metadata packet", OFFSET(icy_metadata_packet), AV_OPT_TYPE_STRING, { .str = NULL }, 0, 0, AV_OPT_FLAG_EXPORT },
147 { "metadata", "metadata read from the bitstream", OFFSET(metadata), AV_OPT_TYPE_DICT, {0}, 0, 0, AV_OPT_FLAG_EXPORT },
148 { "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"},
149 { "none", "No auth method set, autodetect", 0, AV_OPT_TYPE_CONST, { .i64 = HTTP_AUTH_NONE }, 0, 0, D | E, "auth_type"},
150 { "basic", "HTTP basic authentication", 0, AV_OPT_TYPE_CONST, { .i64 = HTTP_AUTH_BASIC }, 0, 0, D | E, "auth_type"},
151 { "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 },
152 { "location", "The actual location of the data received", OFFSET(location), AV_OPT_TYPE_STRING, { .str = NULL }, 0, 0, D | E },
153 { "offset", "initial byte offset", OFFSET(off), AV_OPT_TYPE_INT64, { .i64 = 0 }, 0, INT64_MAX, D },
154 { "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 },
155 { "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 },
156 { "reconnect", "auto reconnect after disconnect before EOF", OFFSET(reconnect), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, D },
157 { "reconnect_at_eof", "auto reconnect at EOF", OFFSET(reconnect_at_eof), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, D },
158 { "reconnect_streamed", "auto reconnect streamed / non seekable streams", OFFSET(reconnect_streamed), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, D },
159 { "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 },
160 { "listen", "listen on HTTP", OFFSET(listen), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 2, D | E },
161 { "resource", "The resource requested by a client", OFFSET(resource), AV_OPT_TYPE_STRING, { .str = NULL }, 0, 0, E },
162 { "reply_code", "The http status code to return to a client", OFFSET(reply_code), AV_OPT_TYPE_INT, { .i64 = 200}, INT_MIN, 599, E},
166 static int http_connect(URLContext *h, const char *path, const char *local_path,
167 const char *hoststr, const char *auth,
168 const char *proxyauth, int *new_location);
169 static int http_read_header(URLContext *h, int *new_location);
171 void ff_http_init_auth_state(URLContext *dest, const URLContext *src)
173 memcpy(&((HTTPContext *)dest->priv_data)->auth_state,
174 &((HTTPContext *)src->priv_data)->auth_state,
175 sizeof(HTTPAuthState));
176 memcpy(&((HTTPContext *)dest->priv_data)->proxy_auth_state,
177 &((HTTPContext *)src->priv_data)->proxy_auth_state,
178 sizeof(HTTPAuthState));
181 static int http_open_cnx_internal(URLContext *h, AVDictionary **options)
183 const char *path, *proxy_path, *lower_proto = "tcp", *local_path;
184 char hostname[1024], hoststr[1024], proto[10];
185 char auth[1024], proxyauth[1024] = "";
186 char path1[MAX_URL_SIZE];
187 char buf[1024], urlbuf[MAX_URL_SIZE];
188 int port, use_proxy, err, location_changed = 0;
189 HTTPContext *s = h->priv_data;
191 av_url_split(proto, sizeof(proto), auth, sizeof(auth),
192 hostname, sizeof(hostname), &port,
193 path1, sizeof(path1), s->location);
194 ff_url_join(hoststr, sizeof(hoststr), NULL, NULL, hostname, port, NULL);
196 proxy_path = s->http_proxy ? s->http_proxy : getenv("http_proxy");
197 use_proxy = !ff_http_match_no_proxy(getenv("no_proxy"), hostname) &&
198 proxy_path && av_strstart(proxy_path, "http://", NULL);
200 if (!strcmp(proto, "https")) {
209 if (path1[0] == '\0')
215 /* Reassemble the request URL without auth string - we don't
216 * want to leak the auth to the proxy. */
217 ff_url_join(urlbuf, sizeof(urlbuf), proto, NULL, hostname, port, "%s",
220 av_url_split(NULL, 0, proxyauth, sizeof(proxyauth),
221 hostname, sizeof(hostname), &port, NULL, 0, proxy_path);
224 ff_url_join(buf, sizeof(buf), lower_proto, NULL, hostname, port, NULL);
227 err = ffurl_open_whitelist(&s->hd, buf, AVIO_FLAG_READ_WRITE,
228 &h->interrupt_callback, options,
229 h->protocol_whitelist, h->protocol_blacklist, h);
234 err = http_connect(h, path, local_path, hoststr,
235 auth, proxyauth, &location_changed);
239 return location_changed;
242 /* return non zero if error */
243 static int http_open_cnx(URLContext *h, AVDictionary **options)
245 HTTPAuthType cur_auth_type, cur_proxy_auth_type;
246 HTTPContext *s = h->priv_data;
247 int location_changed, attempts = 0, redirects = 0;
249 av_dict_copy(options, s->chained_options, 0);
251 cur_auth_type = s->auth_state.auth_type;
252 cur_proxy_auth_type = s->auth_state.auth_type;
254 location_changed = http_open_cnx_internal(h, options);
255 if (location_changed < 0)
259 if (s->http_code == 401) {
260 if ((cur_auth_type == HTTP_AUTH_NONE || s->auth_state.stale) &&
261 s->auth_state.auth_type != HTTP_AUTH_NONE && attempts < 4) {
262 ffurl_closep(&s->hd);
267 if (s->http_code == 407) {
268 if ((cur_proxy_auth_type == HTTP_AUTH_NONE || s->proxy_auth_state.stale) &&
269 s->proxy_auth_state.auth_type != HTTP_AUTH_NONE && attempts < 4) {
270 ffurl_closep(&s->hd);
275 if ((s->http_code == 301 || s->http_code == 302 ||
276 s->http_code == 303 || s->http_code == 307) &&
277 location_changed == 1) {
278 /* url moved, get next */
279 ffurl_closep(&s->hd);
280 if (redirects++ >= MAX_REDIRECTS)
282 /* Restart the authentication process with the new target, which
283 * might use a different auth mechanism. */
284 memset(&s->auth_state, 0, sizeof(s->auth_state));
286 location_changed = 0;
293 ffurl_closep(&s->hd);
294 if (location_changed < 0)
295 return location_changed;
296 return ff_http_averror(s->http_code, AVERROR(EIO));
299 int ff_http_do_new_request(URLContext *h, const char *uri)
301 HTTPContext *s = h->priv_data;
302 AVDictionary *options = NULL;
306 s->icy_data_read = 0;
307 av_free(s->location);
308 s->location = av_strdup(uri);
310 return AVERROR(ENOMEM);
312 ret = http_open_cnx(h, &options);
313 av_dict_free(&options);
317 int ff_http_averror(int status_code, int default_averror)
319 switch (status_code) {
320 case 400: return AVERROR_HTTP_BAD_REQUEST;
321 case 401: return AVERROR_HTTP_UNAUTHORIZED;
322 case 403: return AVERROR_HTTP_FORBIDDEN;
323 case 404: return AVERROR_HTTP_NOT_FOUND;
326 if (status_code >= 400 && status_code <= 499)
327 return AVERROR_HTTP_OTHER_4XX;
328 else if (status_code >= 500)
329 return AVERROR_HTTP_SERVER_ERROR;
331 return default_averror;
334 static int http_write_reply(URLContext* h, int status_code)
336 int ret, body = 0, reply_code, message_len;
337 const char *reply_text, *content_type;
338 HTTPContext *s = h->priv_data;
339 char message[BUFFER_SIZE];
340 content_type = "text/plain";
344 switch (status_code) {
345 case AVERROR_HTTP_BAD_REQUEST:
348 reply_text = "Bad Request";
350 case AVERROR_HTTP_FORBIDDEN:
353 reply_text = "Forbidden";
355 case AVERROR_HTTP_NOT_FOUND:
358 reply_text = "Not Found";
363 content_type = s->content_type ? s->content_type : "application/octet-stream";
365 case AVERROR_HTTP_SERVER_ERROR:
368 reply_text = "Internal server error";
371 return AVERROR(EINVAL);
375 message_len = snprintf(message, sizeof(message),
376 "HTTP/1.1 %03d %s\r\n"
377 "Content-Type: %s\r\n"
378 "Content-Length: %"SIZE_SPECIFIER"\r\n"
385 strlen(reply_text) + 6, // 3 digit status code + space + \r\n
386 s->headers ? s->headers : "",
391 message_len = snprintf(message, sizeof(message),
392 "HTTP/1.1 %03d %s\r\n"
393 "Content-Type: %s\r\n"
394 "Transfer-Encoding: chunked\r\n"
400 s->headers ? s->headers : "");
402 av_log(h, AV_LOG_TRACE, "HTTP reply header: \n%s----\n", message);
403 if ((ret = ffurl_write(s->hd, message, message_len)) < 0)
408 static void handle_http_errors(URLContext *h, int error)
410 av_assert0(error < 0);
411 http_write_reply(h, error);
414 static int http_handshake(URLContext *c)
416 int ret, err, new_location;
417 HTTPContext *ch = c->priv_data;
418 URLContext *cl = ch->hd;
419 switch (ch->handshake_step) {
421 av_log(c, AV_LOG_TRACE, "Lower protocol\n");
422 if ((ret = ffurl_handshake(cl)) > 0)
426 ch->handshake_step = READ_HEADERS;
427 ch->is_connected_server = 1;
430 av_log(c, AV_LOG_TRACE, "Read headers\n");
431 if ((err = http_read_header(c, &new_location)) < 0) {
432 handle_http_errors(c, err);
435 ch->handshake_step = WRITE_REPLY_HEADERS;
437 case WRITE_REPLY_HEADERS:
438 av_log(c, AV_LOG_TRACE, "Reply code: %d\n", ch->reply_code);
439 if ((err = http_write_reply(c, ch->reply_code)) < 0)
441 ch->handshake_step = FINISH;
446 // this should never be reached.
447 return AVERROR(EINVAL);
450 static int http_listen(URLContext *h, const char *uri, int flags,
451 AVDictionary **options) {
452 HTTPContext *s = h->priv_data;
454 char hostname[1024], proto[10];
456 const char *lower_proto = "tcp";
458 av_url_split(proto, sizeof(proto), NULL, 0, hostname, sizeof(hostname), &port,
460 if (!strcmp(proto, "https"))
462 ff_url_join(lower_url, sizeof(lower_url), lower_proto, NULL, hostname, port,
464 if ((ret = av_dict_set_int(options, "listen", s->listen, 0)) < 0)
466 if ((ret = ffurl_open_whitelist(&s->hd, lower_url, AVIO_FLAG_READ_WRITE,
467 &h->interrupt_callback, options,
468 h->protocol_whitelist, h->protocol_blacklist, h
471 s->handshake_step = LOWER_PROTO;
472 if (s->listen == HTTP_SINGLE) { /* single client */
474 while ((ret = http_handshake(h)) > 0);
477 av_dict_free(&s->chained_options);
481 static int http_open(URLContext *h, const char *uri, int flags,
482 AVDictionary **options)
484 HTTPContext *s = h->priv_data;
487 if( s->seekable == 1 )
492 s->filesize = UINT64_MAX;
493 s->location = av_strdup(uri);
495 return AVERROR(ENOMEM);
497 av_dict_copy(&s->chained_options, *options, 0);
500 int len = strlen(s->headers);
501 if (len < 2 || strcmp("\r\n", s->headers + len - 2)) {
502 av_log(h, AV_LOG_WARNING,
503 "No trailing CRLF found in HTTP header.\n");
504 ret = av_reallocp(&s->headers, len + 3);
507 s->headers[len] = '\r';
508 s->headers[len + 1] = '\n';
509 s->headers[len + 2] = '\0';
514 return http_listen(h, uri, flags, options);
516 ret = http_open_cnx(h, options);
518 av_dict_free(&s->chained_options);
522 static int http_accept(URLContext *s, URLContext **c)
525 HTTPContext *sc = s->priv_data;
527 URLContext *sl = sc->hd;
528 URLContext *cl = NULL;
530 av_assert0(sc->listen);
531 if ((ret = ffurl_alloc(c, s->filename, s->flags, &sl->interrupt_callback)) < 0)
533 cc = (*c)->priv_data;
534 if ((ret = ffurl_accept(sl, &cl)) < 0)
537 cc->is_multi_client = 1;
542 static int http_getc(HTTPContext *s)
545 if (s->buf_ptr >= s->buf_end) {
546 len = ffurl_read(s->hd, s->buffer, BUFFER_SIZE);
549 } else if (len == 0) {
552 s->buf_ptr = s->buffer;
553 s->buf_end = s->buffer + len;
556 return *s->buf_ptr++;
559 static int http_get_line(HTTPContext *s, char *line, int line_size)
571 if (q > line && q[-1] == '\r')
577 if ((q - line) < line_size - 1)
583 static int check_http_code(URLContext *h, int http_code, const char *end)
585 HTTPContext *s = h->priv_data;
586 /* error codes are 4xx and 5xx, but regard 401 as a success, so we
587 * don't abort until all headers have been parsed. */
588 if (http_code >= 400 && http_code < 600 &&
589 (http_code != 401 || s->auth_state.auth_type != HTTP_AUTH_NONE) &&
590 (http_code != 407 || s->proxy_auth_state.auth_type != HTTP_AUTH_NONE)) {
591 end += strspn(end, SPACE_CHARS);
592 av_log(h, AV_LOG_WARNING, "HTTP error %d %s\n", http_code, end);
593 return ff_http_averror(http_code, AVERROR(EIO));
598 static int parse_location(HTTPContext *s, const char *p)
600 char redirected_location[MAX_URL_SIZE], *new_loc;
601 ff_make_absolute_url(redirected_location, sizeof(redirected_location),
603 new_loc = av_strdup(redirected_location);
605 return AVERROR(ENOMEM);
606 av_free(s->location);
607 s->location = new_loc;
611 /* "bytes $from-$to/$document_size" */
612 static void parse_content_range(URLContext *h, const char *p)
614 HTTPContext *s = h->priv_data;
617 if (!strncmp(p, "bytes ", 6)) {
619 s->off = strtoull(p, NULL, 10);
620 if ((slash = strchr(p, '/')) && strlen(slash) > 0)
621 s->filesize = strtoull(slash + 1, NULL, 10);
623 if (s->seekable == -1 && (!s->is_akamai || s->filesize != 2147483647))
624 h->is_streamed = 0; /* we _can_ in fact seek */
627 static int parse_content_encoding(URLContext *h, const char *p)
629 if (!av_strncasecmp(p, "gzip", 4) ||
630 !av_strncasecmp(p, "deflate", 7)) {
632 HTTPContext *s = h->priv_data;
635 inflateEnd(&s->inflate_stream);
636 if (inflateInit2(&s->inflate_stream, 32 + 15) != Z_OK) {
637 av_log(h, AV_LOG_WARNING, "Error during zlib initialisation: %s\n",
638 s->inflate_stream.msg);
639 return AVERROR(ENOSYS);
641 if (zlibCompileFlags() & (1 << 17)) {
642 av_log(h, AV_LOG_WARNING,
643 "Your zlib was compiled without gzip support.\n");
644 return AVERROR(ENOSYS);
647 av_log(h, AV_LOG_WARNING,
648 "Compressed (%s) content, need zlib with gzip support\n", p);
649 return AVERROR(ENOSYS);
650 #endif /* CONFIG_ZLIB */
651 } else if (!av_strncasecmp(p, "identity", 8)) {
652 // The normal, no-encoding case (although servers shouldn't include
653 // the header at all if this is the case).
655 av_log(h, AV_LOG_WARNING, "Unknown content coding: %s\n", p);
660 // Concat all Icy- header lines
661 static int parse_icy(HTTPContext *s, const char *tag, const char *p)
663 int len = 4 + strlen(p) + strlen(tag);
664 int is_first = !s->icy_metadata_headers;
667 av_dict_set(&s->metadata, tag, p, 0);
669 if (s->icy_metadata_headers)
670 len += strlen(s->icy_metadata_headers);
672 if ((ret = av_reallocp(&s->icy_metadata_headers, len)) < 0)
676 *s->icy_metadata_headers = '\0';
678 av_strlcatf(s->icy_metadata_headers, len, "%s: %s\n", tag, p);
683 static int parse_cookie(HTTPContext *s, const char *p, AVDictionary **cookies)
687 // duplicate the cookie name (dict will dupe the value)
688 if (!(eql = strchr(p, '='))) return AVERROR(EINVAL);
689 if (!(name = av_strndup(p, eql - p))) return AVERROR(ENOMEM);
691 // add the cookie to the dictionary
692 av_dict_set(cookies, name, eql, AV_DICT_DONT_STRDUP_KEY);
697 static int cookie_string(AVDictionary *dict, char **cookies)
699 AVDictionaryEntry *e = NULL;
702 // determine how much memory is needed for the cookies string
703 while (e = av_dict_get(dict, "", e, AV_DICT_IGNORE_SUFFIX))
704 len += strlen(e->key) + strlen(e->value) + 1;
706 // reallocate the cookies
708 if (*cookies) av_free(*cookies);
709 *cookies = av_malloc(len);
710 if (!*cookies) return AVERROR(ENOMEM);
713 // write out the cookies
714 while (e = av_dict_get(dict, "", e, AV_DICT_IGNORE_SUFFIX))
715 av_strlcatf(*cookies, len, "%s%s\n", e->key, e->value);
720 static int process_line(URLContext *h, char *line, int line_count,
723 HTTPContext *s = h->priv_data;
724 const char *auto_method = h->flags & AVIO_FLAG_READ ? "POST" : "GET";
725 char *tag, *p, *end, *method, *resource, *version;
729 if (line[0] == '\0') {
735 if (line_count == 0) {
736 if (s->is_connected_server) {
739 while (*p && !av_isspace(*p))
742 av_log(h, AV_LOG_TRACE, "Received method: %s\n", method);
744 if (av_strcasecmp(s->method, method)) {
745 av_log(h, AV_LOG_ERROR, "Received and expected HTTP method do not match. (%s expected, %s received)\n",
747 return ff_http_averror(400, AVERROR(EIO));
750 // use autodetected HTTP method to expect
751 av_log(h, AV_LOG_TRACE, "Autodetected %s HTTP method\n", auto_method);
752 if (av_strcasecmp(auto_method, method)) {
753 av_log(h, AV_LOG_ERROR, "Received and autodetected HTTP method did not match "
754 "(%s autodetected %s received)\n", auto_method, method);
755 return ff_http_averror(400, AVERROR(EIO));
757 if (!(s->method = av_strdup(method)))
758 return AVERROR(ENOMEM);
762 while (av_isspace(*p))
765 while (!av_isspace(*p))
768 av_log(h, AV_LOG_TRACE, "Requested resource: %s\n", resource);
769 if (!(s->resource = av_strdup(resource)))
770 return AVERROR(ENOMEM);
773 while (av_isspace(*p))
776 while (*p && !av_isspace(*p))
779 if (av_strncasecmp(version, "HTTP/", 5)) {
780 av_log(h, AV_LOG_ERROR, "Malformed HTTP version string.\n");
781 return ff_http_averror(400, AVERROR(EIO));
783 av_log(h, AV_LOG_TRACE, "HTTP version string: %s\n", version);
785 while (!av_isspace(*p) && *p != '\0')
787 while (av_isspace(*p))
789 s->http_code = strtol(p, &end, 10);
791 av_log(h, AV_LOG_TRACE, "http_code=%d\n", s->http_code);
793 if ((ret = check_http_code(h, s->http_code, end)) < 0)
797 while (*p != '\0' && *p != ':')
805 while (av_isspace(*p))
807 if (!av_strcasecmp(tag, "Location")) {
808 if ((ret = parse_location(s, p)) < 0)
811 } else if (!av_strcasecmp(tag, "Content-Length") &&
812 s->filesize == UINT64_MAX) {
813 s->filesize = strtoull(p, NULL, 10);
814 } else if (!av_strcasecmp(tag, "Content-Range")) {
815 parse_content_range(h, p);
816 } else if (!av_strcasecmp(tag, "Accept-Ranges") &&
817 !strncmp(p, "bytes", 5) &&
820 } else if (!av_strcasecmp(tag, "Transfer-Encoding") &&
821 !av_strncasecmp(p, "chunked", 7)) {
822 s->filesize = UINT64_MAX;
824 } else if (!av_strcasecmp(tag, "WWW-Authenticate")) {
825 ff_http_auth_handle_header(&s->auth_state, tag, p);
826 } else if (!av_strcasecmp(tag, "Authentication-Info")) {
827 ff_http_auth_handle_header(&s->auth_state, tag, p);
828 } else if (!av_strcasecmp(tag, "Proxy-Authenticate")) {
829 ff_http_auth_handle_header(&s->proxy_auth_state, tag, p);
830 } else if (!av_strcasecmp(tag, "Connection")) {
831 if (!strcmp(p, "close"))
833 } else if (!av_strcasecmp(tag, "Server")) {
834 if (!av_strcasecmp(p, "AkamaiGHost")) {
836 } else if (!av_strncasecmp(p, "MediaGateway", 12)) {
837 s->is_mediagateway = 1;
839 } else if (!av_strcasecmp(tag, "Content-Type")) {
840 av_free(s->mime_type);
841 s->mime_type = av_strdup(p);
842 } else if (!av_strcasecmp(tag, "Set-Cookie")) {
843 if (parse_cookie(s, p, &s->cookie_dict))
844 av_log(h, AV_LOG_WARNING, "Unable to parse '%s'\n", p);
845 } else if (!av_strcasecmp(tag, "Icy-MetaInt")) {
846 s->icy_metaint = strtoull(p, NULL, 10);
847 } else if (!av_strncasecmp(tag, "Icy-", 4)) {
848 if ((ret = parse_icy(s, tag, p)) < 0)
850 } else if (!av_strcasecmp(tag, "Content-Encoding")) {
851 if ((ret = parse_content_encoding(h, p)) < 0)
859 * Create a string containing cookie values for use as a HTTP cookie header
860 * field value for a particular path and domain from the cookie values stored in
861 * the HTTP protocol context. The cookie string is stored in *cookies.
863 * @return a negative value if an error condition occurred, 0 otherwise
865 static int get_cookies(HTTPContext *s, char **cookies, const char *path,
868 // cookie strings will look like Set-Cookie header field values. Multiple
869 // Set-Cookie fields will result in multiple values delimited by a newline
871 char *next, *cookie, *set_cookies = av_strdup(s->cookies), *cset_cookies = set_cookies;
873 if (!set_cookies) return AVERROR(EINVAL);
875 // destroy any cookies in the dictionary.
876 av_dict_free(&s->cookie_dict);
879 while ((cookie = av_strtok(set_cookies, "\n", &next))) {
880 int domain_offset = 0;
881 char *param, *next_param, *cdomain = NULL, *cpath = NULL, *cvalue = NULL;
884 // store the cookie in a dict in case it is updated in the response
885 if (parse_cookie(s, cookie, &s->cookie_dict))
886 av_log(s, AV_LOG_WARNING, "Unable to parse '%s'\n", cookie);
888 while ((param = av_strtok(cookie, "; ", &next_param))) {
890 // first key-value pair is the actual cookie value
891 cvalue = av_strdup(param);
893 } else if (!av_strncasecmp("path=", param, 5)) {
895 cpath = av_strdup(¶m[5]);
896 } else if (!av_strncasecmp("domain=", param, 7)) {
897 // if the cookie specifies a sub-domain, skip the leading dot thereby
898 // supporting URLs that point to sub-domains and the master domain
899 int leading_dot = (param[7] == '.');
901 cdomain = av_strdup(¶m[7+leading_dot]);
903 // ignore unknown attributes
907 cdomain = av_strdup(domain);
909 // ensure all of the necessary values are valid
910 if (!cdomain || !cpath || !cvalue) {
911 av_log(s, AV_LOG_WARNING,
912 "Invalid cookie found, no value, path or domain specified\n");
916 // check if the request path matches the cookie path
917 if (av_strncasecmp(path, cpath, strlen(cpath)))
920 // the domain should be at least the size of our cookie domain
921 domain_offset = strlen(domain) - strlen(cdomain);
922 if (domain_offset < 0)
925 // match the cookie domain
926 if (av_strcasecmp(&domain[domain_offset], cdomain))
929 // cookie parameters match, so copy the value
931 if (!(*cookies = av_strdup(cvalue))) {
932 ret = AVERROR(ENOMEM);
936 char *tmp = *cookies;
937 size_t str_size = strlen(cvalue) + strlen(*cookies) + 3;
938 if (!(*cookies = av_malloc(str_size))) {
939 ret = AVERROR(ENOMEM);
942 snprintf(*cookies, str_size, "%s; %s", tmp, cvalue);
951 if (*cookies) av_freep(cookies);
952 av_free(cset_cookies);
957 av_free(cset_cookies);
962 static inline int has_header(const char *str, const char *header)
964 /* header + 2 to skip over CRLF prefix. (make sure you have one!) */
967 return av_stristart(str, header + 2, NULL) || av_stristr(str, header);
970 static int http_read_header(URLContext *h, int *new_location)
972 HTTPContext *s = h->priv_data;
973 char line[MAX_URL_SIZE];
976 s->chunksize = UINT64_MAX;
979 if ((err = http_get_line(s, line, sizeof(line))) < 0)
982 av_log(h, AV_LOG_TRACE, "header='%s'\n", line);
984 err = process_line(h, line, s->line_count, new_location);
992 if (s->seekable == -1 && s->is_mediagateway && s->filesize == 2000000000)
993 h->is_streamed = 1; /* we can in fact _not_ seek */
995 // add any new cookies into the existing cookie string
996 cookie_string(s->cookie_dict, &s->cookies);
997 av_dict_free(&s->cookie_dict);
1002 static int http_connect(URLContext *h, const char *path, const char *local_path,
1003 const char *hoststr, const char *auth,
1004 const char *proxyauth, int *new_location)
1006 HTTPContext *s = h->priv_data;
1008 char headers[HTTP_HEADERS_SIZE] = "";
1009 char *authstr = NULL, *proxyauthstr = NULL;
1010 uint64_t off = s->off;
1013 int send_expect_100 = 0;
1016 /* send http header */
1017 post = h->flags & AVIO_FLAG_WRITE;
1020 /* force POST method and disable chunked encoding when
1021 * custom HTTP post data is set */
1023 s->chunked_post = 0;
1029 method = post ? "POST" : "GET";
1031 authstr = ff_http_auth_create_response(&s->auth_state, auth,
1032 local_path, method);
1033 proxyauthstr = ff_http_auth_create_response(&s->proxy_auth_state, proxyauth,
1034 local_path, method);
1035 if (post && !s->post_data) {
1036 send_expect_100 = s->send_expect_100;
1037 /* The user has supplied authentication but we don't know the auth type,
1038 * send Expect: 100-continue to get the 401 response including the
1039 * WWW-Authenticate header, or an 100 continue if no auth actually
1041 if (auth && *auth &&
1042 s->auth_state.auth_type == HTTP_AUTH_NONE &&
1043 s->http_code != 401)
1044 send_expect_100 = 1;
1047 #if FF_API_HTTP_USER_AGENT
1048 if (strcmp(s->user_agent_deprecated, DEFAULT_USER_AGENT)) {
1049 av_log(s, AV_LOG_WARNING, "the user-agent option is deprecated, please use user_agent option\n");
1050 s->user_agent = av_strdup(s->user_agent_deprecated);
1053 /* set default headers if needed */
1054 if (!has_header(s->headers, "\r\nUser-Agent: "))
1055 len += av_strlcatf(headers + len, sizeof(headers) - len,
1056 "User-Agent: %s\r\n", s->user_agent);
1057 if (!has_header(s->headers, "\r\nAccept: "))
1058 len += av_strlcpy(headers + len, "Accept: */*\r\n",
1059 sizeof(headers) - len);
1060 // Note: we send this on purpose even when s->off is 0 when we're probing,
1061 // since it allows us to detect more reliably if a (non-conforming)
1062 // server supports seeking by analysing the reply headers.
1063 if (!has_header(s->headers, "\r\nRange: ") && !post && (s->off > 0 || s->end_off || s->seekable == -1)) {
1064 len += av_strlcatf(headers + len, sizeof(headers) - len,
1065 "Range: bytes=%"PRIu64"-", s->off);
1067 len += av_strlcatf(headers + len, sizeof(headers) - len,
1068 "%"PRId64, s->end_off - 1);
1069 len += av_strlcpy(headers + len, "\r\n",
1070 sizeof(headers) - len);
1072 if (send_expect_100 && !has_header(s->headers, "\r\nExpect: "))
1073 len += av_strlcatf(headers + len, sizeof(headers) - len,
1074 "Expect: 100-continue\r\n");
1076 if (!has_header(s->headers, "\r\nConnection: ")) {
1077 if (s->multiple_requests)
1078 len += av_strlcpy(headers + len, "Connection: keep-alive\r\n",
1079 sizeof(headers) - len);
1081 len += av_strlcpy(headers + len, "Connection: close\r\n",
1082 sizeof(headers) - len);
1085 if (!has_header(s->headers, "\r\nHost: "))
1086 len += av_strlcatf(headers + len, sizeof(headers) - len,
1087 "Host: %s\r\n", hoststr);
1088 if (!has_header(s->headers, "\r\nContent-Length: ") && s->post_data)
1089 len += av_strlcatf(headers + len, sizeof(headers) - len,
1090 "Content-Length: %d\r\n", s->post_datalen);
1092 if (!has_header(s->headers, "\r\nContent-Type: ") && s->content_type)
1093 len += av_strlcatf(headers + len, sizeof(headers) - len,
1094 "Content-Type: %s\r\n", s->content_type);
1095 if (!has_header(s->headers, "\r\nCookie: ") && s->cookies) {
1096 char *cookies = NULL;
1097 if (!get_cookies(s, &cookies, path, hoststr) && cookies) {
1098 len += av_strlcatf(headers + len, sizeof(headers) - len,
1099 "Cookie: %s\r\n", cookies);
1103 if (!has_header(s->headers, "\r\nIcy-MetaData: ") && s->icy)
1104 len += av_strlcatf(headers + len, sizeof(headers) - len,
1105 "Icy-MetaData: %d\r\n", 1);
1107 /* now add in custom headers */
1109 av_strlcpy(headers + len, s->headers, sizeof(headers) - len);
1111 ret = snprintf(s->buffer, sizeof(s->buffer),
1112 "%s %s HTTP/1.1\r\n"
1120 post && s->chunked_post ? "Transfer-Encoding: chunked\r\n" : "",
1122 authstr ? authstr : "",
1123 proxyauthstr ? "Proxy-" : "", proxyauthstr ? proxyauthstr : "");
1125 av_log(h, AV_LOG_DEBUG, "request: %s\n", s->buffer);
1127 if (strlen(headers) + 1 == sizeof(headers) ||
1128 ret >= sizeof(s->buffer)) {
1129 av_log(h, AV_LOG_ERROR, "overlong headers\n");
1130 err = AVERROR(EINVAL);
1135 if ((err = ffurl_write(s->hd, s->buffer, strlen(s->buffer))) < 0)
1139 if ((err = ffurl_write(s->hd, s->post_data, s->post_datalen)) < 0)
1142 /* init input buffer */
1143 s->buf_ptr = s->buffer;
1144 s->buf_end = s->buffer;
1147 s->icy_data_read = 0;
1148 s->filesize = UINT64_MAX;
1150 s->end_chunked_post = 0;
1152 if (post && !s->post_data && !send_expect_100) {
1153 /* Pretend that it did work. We didn't read any header yet, since
1154 * we've still to send the POST data, but the code calling this
1155 * function will check http_code after we return. */
1161 /* wait for header */
1162 err = http_read_header(h, new_location);
1169 err = (off == s->off) ? 0 : -1;
1172 av_freep(&proxyauthstr);
1176 static int http_buf_read(URLContext *h, uint8_t *buf, int size)
1178 HTTPContext *s = h->priv_data;
1181 if (s->chunksize != UINT64_MAX) {
1182 if (!s->chunksize) {
1187 if ((err = http_get_line(s, line, sizeof(line))) < 0)
1189 } while (!*line); /* skip CR LF from last chunk */
1191 s->chunksize = strtoull(line, NULL, 16);
1193 av_log(h, AV_LOG_TRACE,
1194 "Chunked encoding data size: %"PRIu64"'\n",
1199 else if (s->chunksize == UINT64_MAX) {
1200 av_log(h, AV_LOG_ERROR, "Invalid chunk size %"PRIu64"\n",
1202 return AVERROR(EINVAL);
1205 size = FFMIN(size, s->chunksize);
1208 /* read bytes from input buffer first */
1209 len = s->buf_end - s->buf_ptr;
1213 memcpy(buf, s->buf_ptr, len);
1216 uint64_t target_end = s->end_off ? s->end_off : s->filesize;
1217 if ((!s->willclose || s->chunksize == UINT64_MAX) && s->off >= target_end)
1219 len = ffurl_read(s->hd, buf, size);
1220 if (!len && (!s->willclose || s->chunksize == UINT64_MAX) && s->off < target_end) {
1221 av_log(h, AV_LOG_ERROR,
1222 "Stream ends prematurely at %"PRIu64", should be %"PRIu64"\n",
1225 return AVERROR(EIO);
1230 if (s->chunksize > 0) {
1231 av_assert0(s->chunksize >= len);
1232 s->chunksize -= len;
1239 #define DECOMPRESS_BUF_SIZE (256 * 1024)
1240 static int http_buf_read_compressed(URLContext *h, uint8_t *buf, int size)
1242 HTTPContext *s = h->priv_data;
1245 if (!s->inflate_buffer) {
1246 s->inflate_buffer = av_malloc(DECOMPRESS_BUF_SIZE);
1247 if (!s->inflate_buffer)
1248 return AVERROR(ENOMEM);
1251 if (s->inflate_stream.avail_in == 0) {
1252 int read = http_buf_read(h, s->inflate_buffer, DECOMPRESS_BUF_SIZE);
1255 s->inflate_stream.next_in = s->inflate_buffer;
1256 s->inflate_stream.avail_in = read;
1259 s->inflate_stream.avail_out = size;
1260 s->inflate_stream.next_out = buf;
1262 ret = inflate(&s->inflate_stream, Z_SYNC_FLUSH);
1263 if (ret != Z_OK && ret != Z_STREAM_END)
1264 av_log(h, AV_LOG_WARNING, "inflate return value: %d, %s\n",
1265 ret, s->inflate_stream.msg);
1267 return size - s->inflate_stream.avail_out;
1269 #endif /* CONFIG_ZLIB */
1271 static int64_t http_seek_internal(URLContext *h, int64_t off, int whence, int force_reconnect);
1273 static int http_read_stream(URLContext *h, uint8_t *buf, int size)
1275 HTTPContext *s = h->priv_data;
1276 int err, new_location, read_ret;
1282 if (s->end_chunked_post && !s->end_header) {
1283 err = http_read_header(h, &new_location);
1290 return http_buf_read_compressed(h, buf, size);
1291 #endif /* CONFIG_ZLIB */
1292 read_ret = http_buf_read(h, buf, size);
1293 if ( (read_ret < 0 && s->reconnect && (!h->is_streamed || s->reconnect_streamed) && s->filesize > 0 && s->off < s->filesize)
1294 || (read_ret == 0 && s->reconnect_at_eof && (!h->is_streamed || s->reconnect_streamed))) {
1295 uint64_t target = h->is_streamed ? 0 : s->off;
1297 if (s->reconnect_delay > s->reconnect_delay_max)
1298 return AVERROR(EIO);
1300 av_log(h, AV_LOG_INFO, "Will reconnect at %"PRIu64" error=%s.\n", s->off, av_err2str(read_ret));
1301 av_usleep(1000U*1000*s->reconnect_delay);
1302 s->reconnect_delay = 1 + 2*s->reconnect_delay;
1303 seek_ret = http_seek_internal(h, target, SEEK_SET, 1);
1304 if (seek_ret != target) {
1305 av_log(h, AV_LOG_ERROR, "Failed to reconnect at %"PRIu64".\n", target);
1309 read_ret = http_buf_read(h, buf, size);
1311 s->reconnect_delay = 0;
1316 // Like http_read_stream(), but no short reads.
1317 // Assumes partial reads are an error.
1318 static int http_read_stream_all(URLContext *h, uint8_t *buf, int size)
1321 while (pos < size) {
1322 int len = http_read_stream(h, buf + pos, size - pos);
1330 static void update_metadata(HTTPContext *s, char *data)
1339 val = strstr(key, "='");
1342 end = strstr(val, "';");
1350 av_dict_set(&s->metadata, key, val, 0);
1356 static int store_icy(URLContext *h, int size)
1358 HTTPContext *s = h->priv_data;
1359 /* until next metadata packet */
1362 if (s->icy_metaint < s->icy_data_read)
1363 return AVERROR_INVALIDDATA;
1364 remaining = s->icy_metaint - s->icy_data_read;
1367 /* The metadata packet is variable sized. It has a 1 byte header
1368 * which sets the length of the packet (divided by 16). If it's 0,
1369 * the metadata doesn't change. After the packet, icy_metaint bytes
1370 * of normal data follows. */
1372 int len = http_read_stream_all(h, &ch, 1);
1376 char data[255 * 16 + 1];
1379 ret = http_read_stream_all(h, data, len);
1383 if ((ret = av_opt_set(s, "icy_metadata_packet", data, 0)) < 0)
1385 update_metadata(s, data);
1387 s->icy_data_read = 0;
1388 remaining = s->icy_metaint;
1391 return FFMIN(size, remaining);
1394 static int http_read(URLContext *h, uint8_t *buf, int size)
1396 HTTPContext *s = h->priv_data;
1398 if (s->icy_metaint > 0) {
1399 size = store_icy(h, size);
1404 size = http_read_stream(h, buf, size);
1406 s->icy_data_read += size;
1410 /* used only when posting data */
1411 static int http_write(URLContext *h, const uint8_t *buf, int size)
1413 char temp[11] = ""; /* 32-bit hex + CRLF + nul */
1415 char crlf[] = "\r\n";
1416 HTTPContext *s = h->priv_data;
1418 if (!s->chunked_post) {
1419 /* non-chunked data is sent without any special encoding */
1420 return ffurl_write(s->hd, buf, size);
1423 /* silently ignore zero-size data since chunk encoding that would
1426 /* upload data using chunked encoding */
1427 snprintf(temp, sizeof(temp), "%x\r\n", size);
1429 if ((ret = ffurl_write(s->hd, temp, strlen(temp))) < 0 ||
1430 (ret = ffurl_write(s->hd, buf, size)) < 0 ||
1431 (ret = ffurl_write(s->hd, crlf, sizeof(crlf) - 1)) < 0)
1437 static int http_shutdown(URLContext *h, int flags)
1440 char footer[] = "0\r\n\r\n";
1441 HTTPContext *s = h->priv_data;
1443 /* signal end of chunked encoding if used */
1444 if (((flags & AVIO_FLAG_WRITE) && s->chunked_post) ||
1445 ((flags & AVIO_FLAG_READ) && s->chunked_post && s->listen)) {
1446 ret = ffurl_write(s->hd, footer, sizeof(footer) - 1);
1447 ret = ret > 0 ? 0 : ret;
1448 s->end_chunked_post = 1;
1454 static int http_close(URLContext *h)
1457 HTTPContext *s = h->priv_data;
1460 inflateEnd(&s->inflate_stream);
1461 av_freep(&s->inflate_buffer);
1462 #endif /* CONFIG_ZLIB */
1464 if (!s->end_chunked_post)
1465 /* Close the write direction by sending the end of chunked encoding. */
1466 ret = http_shutdown(h, h->flags);
1469 ffurl_closep(&s->hd);
1470 av_dict_free(&s->chained_options);
1474 static int64_t http_seek_internal(URLContext *h, int64_t off, int whence, int force_reconnect)
1476 HTTPContext *s = h->priv_data;
1477 URLContext *old_hd = s->hd;
1478 uint64_t old_off = s->off;
1479 uint8_t old_buf[BUFFER_SIZE];
1480 int old_buf_size, ret;
1481 AVDictionary *options = NULL;
1483 if (whence == AVSEEK_SIZE)
1485 else if (!force_reconnect &&
1486 ((whence == SEEK_CUR && off == 0) ||
1487 (whence == SEEK_SET && off == s->off)))
1489 else if ((s->filesize == UINT64_MAX && whence == SEEK_END))
1490 return AVERROR(ENOSYS);
1492 if (whence == SEEK_CUR)
1494 else if (whence == SEEK_END)
1496 else if (whence != SEEK_SET)
1497 return AVERROR(EINVAL);
1499 return AVERROR(EINVAL);
1502 if (s->off && h->is_streamed)
1503 return AVERROR(ENOSYS);
1505 /* we save the old context in case the seek fails */
1506 old_buf_size = s->buf_end - s->buf_ptr;
1507 memcpy(old_buf, s->buf_ptr, old_buf_size);
1510 /* if it fails, continue on old connection */
1511 if ((ret = http_open_cnx(h, &options)) < 0) {
1512 av_dict_free(&options);
1513 memcpy(s->buffer, old_buf, old_buf_size);
1514 s->buf_ptr = s->buffer;
1515 s->buf_end = s->buffer + old_buf_size;
1520 av_dict_free(&options);
1521 ffurl_close(old_hd);
1525 static int64_t http_seek(URLContext *h, int64_t off, int whence)
1527 return http_seek_internal(h, off, whence, 0);
1530 static int http_get_file_handle(URLContext *h)
1532 HTTPContext *s = h->priv_data;
1533 return ffurl_get_file_handle(s->hd);
1536 static int http_get_short_seek(URLContext *h)
1538 HTTPContext *s = h->priv_data;
1539 return ffurl_get_short_seek(s->hd);
1542 #define HTTP_CLASS(flavor) \
1543 static const AVClass flavor ## _context_class = { \
1544 .class_name = # flavor, \
1545 .item_name = av_default_item_name, \
1546 .option = options, \
1547 .version = LIBAVUTIL_VERSION_INT, \
1550 #if CONFIG_HTTP_PROTOCOL
1553 const URLProtocol ff_http_protocol = {
1555 .url_open2 = http_open,
1556 .url_accept = http_accept,
1557 .url_handshake = http_handshake,
1558 .url_read = http_read,
1559 .url_write = http_write,
1560 .url_seek = http_seek,
1561 .url_close = http_close,
1562 .url_get_file_handle = http_get_file_handle,
1563 .url_get_short_seek = http_get_short_seek,
1564 .url_shutdown = http_shutdown,
1565 .priv_data_size = sizeof(HTTPContext),
1566 .priv_data_class = &http_context_class,
1567 .flags = URL_PROTOCOL_FLAG_NETWORK,
1568 .default_whitelist = "http,https,tls,rtp,tcp,udp,crypto,httpproxy"
1570 #endif /* CONFIG_HTTP_PROTOCOL */
1572 #if CONFIG_HTTPS_PROTOCOL
1575 const URLProtocol ff_https_protocol = {
1577 .url_open2 = http_open,
1578 .url_read = http_read,
1579 .url_write = http_write,
1580 .url_seek = http_seek,
1581 .url_close = http_close,
1582 .url_get_file_handle = http_get_file_handle,
1583 .url_get_short_seek = http_get_short_seek,
1584 .url_shutdown = http_shutdown,
1585 .priv_data_size = sizeof(HTTPContext),
1586 .priv_data_class = &https_context_class,
1587 .flags = URL_PROTOCOL_FLAG_NETWORK,
1588 .default_whitelist = "http,https,tls,rtp,tcp,udp,crypto,httpproxy"
1590 #endif /* CONFIG_HTTPS_PROTOCOL */
1592 #if CONFIG_HTTPPROXY_PROTOCOL
1593 static int http_proxy_close(URLContext *h)
1595 HTTPContext *s = h->priv_data;
1597 ffurl_closep(&s->hd);
1601 static int http_proxy_open(URLContext *h, const char *uri, int flags)
1603 HTTPContext *s = h->priv_data;
1604 char hostname[1024], hoststr[1024];
1605 char auth[1024], pathbuf[1024], *path;
1606 char lower_url[100];
1607 int port, ret = 0, attempts = 0;
1608 HTTPAuthType cur_auth_type;
1612 if( s->seekable == 1 )
1617 av_url_split(NULL, 0, auth, sizeof(auth), hostname, sizeof(hostname), &port,
1618 pathbuf, sizeof(pathbuf), uri);
1619 ff_url_join(hoststr, sizeof(hoststr), NULL, NULL, hostname, port, NULL);
1624 ff_url_join(lower_url, sizeof(lower_url), "tcp", NULL, hostname, port,
1627 ret = ffurl_open_whitelist(&s->hd, lower_url, AVIO_FLAG_READ_WRITE,
1628 &h->interrupt_callback, NULL,
1629 h->protocol_whitelist, h->protocol_blacklist, h);
1633 authstr = ff_http_auth_create_response(&s->proxy_auth_state, auth,
1635 snprintf(s->buffer, sizeof(s->buffer),
1636 "CONNECT %s HTTP/1.1\r\n"
1638 "Connection: close\r\n"
1643 authstr ? "Proxy-" : "", authstr ? authstr : "");
1646 if ((ret = ffurl_write(s->hd, s->buffer, strlen(s->buffer))) < 0)
1649 s->buf_ptr = s->buffer;
1650 s->buf_end = s->buffer;
1652 s->filesize = UINT64_MAX;
1653 cur_auth_type = s->proxy_auth_state.auth_type;
1655 /* Note: This uses buffering, potentially reading more than the
1656 * HTTP header. If tunneling a protocol where the server starts
1657 * the conversation, we might buffer part of that here, too.
1658 * Reading that requires using the proper ffurl_read() function
1659 * on this URLContext, not using the fd directly (as the tls
1660 * protocol does). This shouldn't be an issue for tls though,
1661 * since the client starts the conversation there, so there
1662 * is no extra data that we might buffer up here.
1664 ret = http_read_header(h, &new_loc);
1669 if (s->http_code == 407 &&
1670 (cur_auth_type == HTTP_AUTH_NONE || s->proxy_auth_state.stale) &&
1671 s->proxy_auth_state.auth_type != HTTP_AUTH_NONE && attempts < 2) {
1672 ffurl_closep(&s->hd);
1676 if (s->http_code < 400)
1678 ret = ff_http_averror(s->http_code, AVERROR(EIO));
1681 http_proxy_close(h);
1685 static int http_proxy_write(URLContext *h, const uint8_t *buf, int size)
1687 HTTPContext *s = h->priv_data;
1688 return ffurl_write(s->hd, buf, size);
1691 const URLProtocol ff_httpproxy_protocol = {
1692 .name = "httpproxy",
1693 .url_open = http_proxy_open,
1694 .url_read = http_buf_read,
1695 .url_write = http_proxy_write,
1696 .url_close = http_proxy_close,
1697 .url_get_file_handle = http_get_file_handle,
1698 .priv_data_size = sizeof(HTTPContext),
1699 .flags = URL_PROTOCOL_FLAG_NETWORK,
1701 #endif /* CONFIG_HTTPPROXY_PROTOCOL */