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 int64_t off, end_off, filesize;
68 HTTPAuthState auth_state;
69 HTTPAuthState proxy_auth_state;
74 /* Set if the server correctly handles Connection: close and will close
75 * the connection after feeding us the content. */
77 int seekable; /**< Control seekability, 0 = disable, 1 = enable, -1 = probe. */
79 /* A flag which indicates if the end of chunked encoding has been sent. */
81 /* A flag which indicates we have finished to read POST reply. */
83 /* A flag which indicates if we use persistent connections. */
84 int multiple_requests;
89 char *cookies; ///< holds newline (\n) delimited Set-Cookie header field values (without the "Set-Cookie: " field name)
90 /* A dictionary containing cookies keyed by cookie name */
91 AVDictionary *cookie_dict;
93 /* how much data was read since the last ICY metadata packet */
95 /* after how many bytes of read data a new metadata packet will be found */
97 char *icy_metadata_headers;
98 char *icy_metadata_packet;
99 AVDictionary *metadata;
102 z_stream inflate_stream;
103 uint8_t *inflate_buffer;
104 #endif /* CONFIG_ZLIB */
105 AVDictionary *chained_options;
109 int reconnect_at_eof;
110 int reconnect_streamed;
112 int reconnect_delay_max;
117 HandshakeState handshake_step;
118 int is_connected_server;
121 #define OFFSET(x) offsetof(HTTPContext, x)
122 #define D AV_OPT_FLAG_DECODING_PARAM
123 #define E AV_OPT_FLAG_ENCODING_PARAM
124 #define DEFAULT_USER_AGENT "Lavf/" AV_STRINGIFY(LIBAVFORMAT_VERSION)
126 static const AVOption options[] = {
127 { "seekable", "control seekability of connection", OFFSET(seekable), AV_OPT_TYPE_INT, { .i64 = -1 }, -1, 1, D },
128 { "chunked_post", "use chunked transfer-encoding for posts", OFFSET(chunked_post), AV_OPT_TYPE_INT, { .i64 = 1 }, 0, 1, E },
129 { "headers", "set custom HTTP headers, can override built in default headers", OFFSET(headers), AV_OPT_TYPE_STRING, { .str = NULL }, 0, 0, D | E },
130 { "content_type", "set a specific content type for the POST messages", OFFSET(content_type), AV_OPT_TYPE_STRING, { .str = NULL }, 0, 0, D | E },
131 { "user_agent", "override User-Agent header", OFFSET(user_agent), AV_OPT_TYPE_STRING, { .str = DEFAULT_USER_AGENT }, 0, 0, D },
132 { "user-agent", "override User-Agent header", OFFSET(user_agent), AV_OPT_TYPE_STRING, { .str = DEFAULT_USER_AGENT }, 0, 0, D },
133 { "multiple_requests", "use persistent connections", OFFSET(multiple_requests), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 1, D | E },
134 { "post_data", "set custom HTTP post data", OFFSET(post_data), AV_OPT_TYPE_BINARY, .flags = D | E },
135 { "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 },
136 { "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 },
137 { "icy", "request ICY metadata", OFFSET(icy), AV_OPT_TYPE_INT, { .i64 = 1 }, 0, 1, D },
138 { "icy_metadata_headers", "return ICY metadata headers", OFFSET(icy_metadata_headers), AV_OPT_TYPE_STRING, { .str = NULL }, 0, 0, AV_OPT_FLAG_EXPORT },
139 { "icy_metadata_packet", "return current ICY metadata packet", OFFSET(icy_metadata_packet), AV_OPT_TYPE_STRING, { .str = NULL }, 0, 0, AV_OPT_FLAG_EXPORT },
140 { "metadata", "metadata read from the bitstream", OFFSET(metadata), AV_OPT_TYPE_DICT, {0}, 0, 0, AV_OPT_FLAG_EXPORT },
141 { "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"},
142 { "none", "No auth method set, autodetect", 0, AV_OPT_TYPE_CONST, { .i64 = HTTP_AUTH_NONE }, 0, 0, D | E, "auth_type"},
143 { "basic", "HTTP basic authentication", 0, AV_OPT_TYPE_CONST, { .i64 = HTTP_AUTH_BASIC }, 0, 0, D | E, "auth_type"},
144 { "send_expect_100", "Force sending an Expect: 100-continue header for POST", OFFSET(send_expect_100), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 1, E },
145 { "location", "The actual location of the data received", OFFSET(location), AV_OPT_TYPE_STRING, { .str = NULL }, 0, 0, D | E },
146 { "offset", "initial byte offset", OFFSET(off), AV_OPT_TYPE_INT64, { .i64 = 0 }, 0, INT64_MAX, D },
147 { "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 },
148 { "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 },
149 { "reconnect", "auto reconnect after disconnect before EOF", OFFSET(reconnect), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 1, D },
150 { "reconnect_at_eof", "auto reconnect at EOF", OFFSET(reconnect_at_eof), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 1, D },
151 { "reconnect_streamed", "auto reconnect streamed / non seekable streams", OFFSET(reconnect_streamed), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 1, D },
152 { "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 },
153 { "listen", "listen on HTTP", OFFSET(listen), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 2, D | E },
154 { "resource", "The resource requested by a client", OFFSET(resource), AV_OPT_TYPE_STRING, { .str = NULL }, 0, 0, E },
155 { "reply_code", "The http status code to return to a client", OFFSET(reply_code), AV_OPT_TYPE_INT, { .i64 = 200}, INT_MIN, 599, E},
159 static int http_connect(URLContext *h, const char *path, const char *local_path,
160 const char *hoststr, const char *auth,
161 const char *proxyauth, int *new_location);
162 static int http_read_header(URLContext *h, int *new_location);
164 void ff_http_init_auth_state(URLContext *dest, const URLContext *src)
166 memcpy(&((HTTPContext *)dest->priv_data)->auth_state,
167 &((HTTPContext *)src->priv_data)->auth_state,
168 sizeof(HTTPAuthState));
169 memcpy(&((HTTPContext *)dest->priv_data)->proxy_auth_state,
170 &((HTTPContext *)src->priv_data)->proxy_auth_state,
171 sizeof(HTTPAuthState));
174 static int http_open_cnx_internal(URLContext *h, AVDictionary **options)
176 const char *path, *proxy_path, *lower_proto = "tcp", *local_path;
177 char hostname[1024], hoststr[1024], proto[10];
178 char auth[1024], proxyauth[1024] = "";
179 char path1[MAX_URL_SIZE];
180 char buf[1024], urlbuf[MAX_URL_SIZE];
181 int port, use_proxy, err, location_changed = 0;
182 HTTPContext *s = h->priv_data;
184 av_url_split(proto, sizeof(proto), auth, sizeof(auth),
185 hostname, sizeof(hostname), &port,
186 path1, sizeof(path1), s->location);
187 ff_url_join(hoststr, sizeof(hoststr), NULL, NULL, hostname, port, NULL);
189 proxy_path = getenv("http_proxy");
190 use_proxy = !ff_http_match_no_proxy(getenv("no_proxy"), hostname) &&
191 proxy_path && av_strstart(proxy_path, "http://", NULL);
193 if (!strcmp(proto, "https")) {
202 if (path1[0] == '\0')
208 /* Reassemble the request URL without auth string - we don't
209 * want to leak the auth to the proxy. */
210 ff_url_join(urlbuf, sizeof(urlbuf), proto, NULL, hostname, port, "%s",
213 av_url_split(NULL, 0, proxyauth, sizeof(proxyauth),
214 hostname, sizeof(hostname), &port, NULL, 0, proxy_path);
217 ff_url_join(buf, sizeof(buf), lower_proto, NULL, hostname, port, NULL);
220 err = ffurl_open(&s->hd, buf, AVIO_FLAG_READ_WRITE,
221 &h->interrupt_callback, options);
226 err = http_connect(h, path, local_path, hoststr,
227 auth, proxyauth, &location_changed);
231 return location_changed;
234 /* return non zero if error */
235 static int http_open_cnx(URLContext *h, AVDictionary **options)
237 HTTPAuthType cur_auth_type, cur_proxy_auth_type;
238 HTTPContext *s = h->priv_data;
239 int location_changed, attempts = 0, redirects = 0;
241 av_dict_copy(options, s->chained_options, 0);
243 cur_auth_type = s->auth_state.auth_type;
244 cur_proxy_auth_type = s->auth_state.auth_type;
246 location_changed = http_open_cnx_internal(h, options);
247 if (location_changed < 0)
251 if (s->http_code == 401) {
252 if ((cur_auth_type == HTTP_AUTH_NONE || s->auth_state.stale) &&
253 s->auth_state.auth_type != HTTP_AUTH_NONE && attempts < 4) {
254 ffurl_closep(&s->hd);
259 if (s->http_code == 407) {
260 if ((cur_proxy_auth_type == HTTP_AUTH_NONE || s->proxy_auth_state.stale) &&
261 s->proxy_auth_state.auth_type != HTTP_AUTH_NONE && attempts < 4) {
262 ffurl_closep(&s->hd);
267 if ((s->http_code == 301 || s->http_code == 302 ||
268 s->http_code == 303 || s->http_code == 307) &&
269 location_changed == 1) {
270 /* url moved, get next */
271 ffurl_closep(&s->hd);
272 if (redirects++ >= MAX_REDIRECTS)
274 /* Restart the authentication process with the new target, which
275 * might use a different auth mechanism. */
276 memset(&s->auth_state, 0, sizeof(s->auth_state));
278 location_changed = 0;
285 ffurl_closep(&s->hd);
286 if (location_changed < 0)
287 return location_changed;
288 return ff_http_averror(s->http_code, AVERROR(EIO));
291 int ff_http_do_new_request(URLContext *h, const char *uri)
293 HTTPContext *s = h->priv_data;
294 AVDictionary *options = NULL;
298 s->icy_data_read = 0;
299 av_free(s->location);
300 s->location = av_strdup(uri);
302 return AVERROR(ENOMEM);
304 ret = http_open_cnx(h, &options);
305 av_dict_free(&options);
309 int ff_http_averror(int status_code, int default_averror)
311 switch (status_code) {
312 case 400: return AVERROR_HTTP_BAD_REQUEST;
313 case 401: return AVERROR_HTTP_UNAUTHORIZED;
314 case 403: return AVERROR_HTTP_FORBIDDEN;
315 case 404: return AVERROR_HTTP_NOT_FOUND;
318 if (status_code >= 400 && status_code <= 499)
319 return AVERROR_HTTP_OTHER_4XX;
320 else if (status_code >= 500)
321 return AVERROR_HTTP_SERVER_ERROR;
323 return default_averror;
326 static int http_write_reply(URLContext* h, int status_code)
328 int ret, body = 0, reply_code, message_len;
329 const char *reply_text, *content_type;
330 HTTPContext *s = h->priv_data;
331 char message[BUFFER_SIZE];
332 content_type = "text/plain";
336 switch (status_code) {
337 case AVERROR_HTTP_BAD_REQUEST:
340 reply_text = "Bad Request";
342 case AVERROR_HTTP_FORBIDDEN:
345 reply_text = "Forbidden";
347 case AVERROR_HTTP_NOT_FOUND:
350 reply_text = "Not Found";
355 content_type = "application/octet-stream";
357 case AVERROR_HTTP_SERVER_ERROR:
360 reply_text = "Internal server error";
363 return AVERROR(EINVAL);
367 message_len = snprintf(message, sizeof(message),
368 "HTTP/1.1 %03d %s\r\n"
369 "Content-Type: %s\r\n"
370 "Content-Length: %zu\r\n"
376 strlen(reply_text) + 6, // 3 digit status code + space + \r\n
381 message_len = snprintf(message, sizeof(message),
382 "HTTP/1.1 %03d %s\r\n"
383 "Content-Type: %s\r\n"
384 "Transfer-Encoding: chunked\r\n"
390 av_log(h, AV_LOG_TRACE, "HTTP reply header: \n%s----\n", message);
391 if ((ret = ffurl_write(s->hd, message, message_len)) < 0)
396 static void handle_http_errors(URLContext *h, int error)
398 av_assert0(error < 0);
399 http_write_reply(h, error);
402 static int http_handshake(URLContext *c)
404 int ret, err, new_location;
405 HTTPContext *ch = c->priv_data;
406 URLContext *cl = ch->hd;
407 switch (ch->handshake_step) {
409 av_log(c, AV_LOG_TRACE, "Lower protocol\n");
410 if ((ret = ffurl_handshake(cl)) > 0)
414 ch->handshake_step = READ_HEADERS;
415 ch->is_connected_server = 1;
418 av_log(c, AV_LOG_TRACE, "Read headers\n");
419 if ((err = http_read_header(c, &new_location)) < 0) {
420 handle_http_errors(c, err);
423 ch->handshake_step = WRITE_REPLY_HEADERS;
425 case WRITE_REPLY_HEADERS:
426 av_log(c, AV_LOG_TRACE, "Reply code: %d\n", ch->reply_code);
427 if ((err = http_write_reply(c, ch->reply_code)) < 0)
429 ch->handshake_step = FINISH;
434 // this should never be reached.
435 return AVERROR(EINVAL);
438 static int http_listen(URLContext *h, const char *uri, int flags,
439 AVDictionary **options) {
440 HTTPContext *s = h->priv_data;
442 char hostname[1024], proto[10];
444 const char *lower_proto = "tcp";
446 av_url_split(proto, sizeof(proto), NULL, 0, hostname, sizeof(hostname), &port,
448 if (!strcmp(proto, "https"))
450 ff_url_join(lower_url, sizeof(lower_url), lower_proto, NULL, hostname, port,
452 if ((ret = av_dict_set_int(options, "listen", s->listen, 0)) < 0)
454 if ((ret = ffurl_open(&s->hd, lower_url, AVIO_FLAG_READ_WRITE,
455 &h->interrupt_callback, options)) < 0)
457 s->handshake_step = LOWER_PROTO;
458 if (s->listen == HTTP_SINGLE) { /* single client */
460 while ((ret = http_handshake(h)) > 0);
463 av_dict_free(&s->chained_options);
467 static int http_open(URLContext *h, const char *uri, int flags,
468 AVDictionary **options)
470 HTTPContext *s = h->priv_data;
473 if( s->seekable == 1 )
479 s->location = av_strdup(uri);
481 return AVERROR(ENOMEM);
483 av_dict_copy(&s->chained_options, *options, 0);
486 int len = strlen(s->headers);
487 if (len < 2 || strcmp("\r\n", s->headers + len - 2)) {
488 av_log(h, AV_LOG_WARNING,
489 "No trailing CRLF found in HTTP header.\n");
490 ret = av_reallocp(&s->headers, len + 3);
493 s->headers[len] = '\r';
494 s->headers[len + 1] = '\n';
495 s->headers[len + 2] = '\0';
500 return http_listen(h, uri, flags, options);
502 ret = http_open_cnx(h, options);
504 av_dict_free(&s->chained_options);
508 static int http_accept(URLContext *s, URLContext **c)
511 HTTPContext *sc = s->priv_data;
513 URLContext *sl = sc->hd;
514 URLContext *cl = NULL;
516 av_assert0(sc->listen);
517 if ((ret = ffurl_alloc(c, s->filename, s->flags, &sl->interrupt_callback)) < 0)
519 cc = (*c)->priv_data;
520 if ((ret = ffurl_accept(sl, &cl)) < 0)
523 cc->is_multi_client = 1;
528 static int http_getc(HTTPContext *s)
531 if (s->buf_ptr >= s->buf_end) {
532 len = ffurl_read(s->hd, s->buffer, BUFFER_SIZE);
535 } else if (len == 0) {
538 s->buf_ptr = s->buffer;
539 s->buf_end = s->buffer + len;
542 return *s->buf_ptr++;
545 static int http_get_line(HTTPContext *s, char *line, int line_size)
557 if (q > line && q[-1] == '\r')
563 if ((q - line) < line_size - 1)
569 static int check_http_code(URLContext *h, int http_code, const char *end)
571 HTTPContext *s = h->priv_data;
572 /* error codes are 4xx and 5xx, but regard 401 as a success, so we
573 * don't abort until all headers have been parsed. */
574 if (http_code >= 400 && http_code < 600 &&
575 (http_code != 401 || s->auth_state.auth_type != HTTP_AUTH_NONE) &&
576 (http_code != 407 || s->proxy_auth_state.auth_type != HTTP_AUTH_NONE)) {
577 end += strspn(end, SPACE_CHARS);
578 av_log(h, AV_LOG_WARNING, "HTTP error %d %s\n", http_code, end);
579 return ff_http_averror(http_code, AVERROR(EIO));
584 static int parse_location(HTTPContext *s, const char *p)
586 char redirected_location[MAX_URL_SIZE], *new_loc;
587 ff_make_absolute_url(redirected_location, sizeof(redirected_location),
589 new_loc = av_strdup(redirected_location);
591 return AVERROR(ENOMEM);
592 av_free(s->location);
593 s->location = new_loc;
597 /* "bytes $from-$to/$document_size" */
598 static void parse_content_range(URLContext *h, const char *p)
600 HTTPContext *s = h->priv_data;
603 if (!strncmp(p, "bytes ", 6)) {
605 s->off = strtoll(p, NULL, 10);
606 if ((slash = strchr(p, '/')) && strlen(slash) > 0)
607 s->filesize = strtoll(slash + 1, NULL, 10);
609 if (s->seekable == -1 && (!s->is_akamai || s->filesize != 2147483647))
610 h->is_streamed = 0; /* we _can_ in fact seek */
613 static int parse_content_encoding(URLContext *h, const char *p)
615 if (!av_strncasecmp(p, "gzip", 4) ||
616 !av_strncasecmp(p, "deflate", 7)) {
618 HTTPContext *s = h->priv_data;
621 inflateEnd(&s->inflate_stream);
622 if (inflateInit2(&s->inflate_stream, 32 + 15) != Z_OK) {
623 av_log(h, AV_LOG_WARNING, "Error during zlib initialisation: %s\n",
624 s->inflate_stream.msg);
625 return AVERROR(ENOSYS);
627 if (zlibCompileFlags() & (1 << 17)) {
628 av_log(h, AV_LOG_WARNING,
629 "Your zlib was compiled without gzip support.\n");
630 return AVERROR(ENOSYS);
633 av_log(h, AV_LOG_WARNING,
634 "Compressed (%s) content, need zlib with gzip support\n", p);
635 return AVERROR(ENOSYS);
636 #endif /* CONFIG_ZLIB */
637 } else if (!av_strncasecmp(p, "identity", 8)) {
638 // The normal, no-encoding case (although servers shouldn't include
639 // the header at all if this is the case).
641 av_log(h, AV_LOG_WARNING, "Unknown content coding: %s\n", p);
646 // Concat all Icy- header lines
647 static int parse_icy(HTTPContext *s, const char *tag, const char *p)
649 int len = 4 + strlen(p) + strlen(tag);
650 int is_first = !s->icy_metadata_headers;
653 av_dict_set(&s->metadata, tag, p, 0);
655 if (s->icy_metadata_headers)
656 len += strlen(s->icy_metadata_headers);
658 if ((ret = av_reallocp(&s->icy_metadata_headers, len)) < 0)
662 *s->icy_metadata_headers = '\0';
664 av_strlcatf(s->icy_metadata_headers, len, "%s: %s\n", tag, p);
669 static int parse_cookie(HTTPContext *s, const char *p, AVDictionary **cookies)
673 // duplicate the cookie name (dict will dupe the value)
674 if (!(eql = strchr(p, '='))) return AVERROR(EINVAL);
675 if (!(name = av_strndup(p, eql - p))) return AVERROR(ENOMEM);
677 // add the cookie to the dictionary
678 av_dict_set(cookies, name, eql, AV_DICT_DONT_STRDUP_KEY);
683 static int cookie_string(AVDictionary *dict, char **cookies)
685 AVDictionaryEntry *e = NULL;
688 // determine how much memory is needed for the cookies string
689 while (e = av_dict_get(dict, "", e, AV_DICT_IGNORE_SUFFIX))
690 len += strlen(e->key) + strlen(e->value) + 1;
692 // reallocate the cookies
694 if (*cookies) av_free(*cookies);
695 *cookies = av_malloc(len);
696 if (!*cookies) return AVERROR(ENOMEM);
699 // write out the cookies
700 while (e = av_dict_get(dict, "", e, AV_DICT_IGNORE_SUFFIX))
701 av_strlcatf(*cookies, len, "%s%s\n", e->key, e->value);
706 static int process_line(URLContext *h, char *line, int line_count,
709 HTTPContext *s = h->priv_data;
710 const char *auto_method = h->flags & AVIO_FLAG_READ ? "POST" : "GET";
711 char *tag, *p, *end, *method, *resource, *version;
715 if (line[0] == '\0') {
721 if (line_count == 0) {
722 if (s->is_connected_server) {
725 while (*p && !av_isspace(*p))
728 av_log(h, AV_LOG_TRACE, "Received method: %s\n", method);
730 if (av_strcasecmp(s->method, method)) {
731 av_log(h, AV_LOG_ERROR, "Received and expected HTTP method do not match. (%s expected, %s received)\n",
733 return ff_http_averror(400, AVERROR(EIO));
736 // use autodetected HTTP method to expect
737 av_log(h, AV_LOG_TRACE, "Autodetected %s HTTP method\n", auto_method);
738 if (av_strcasecmp(auto_method, method)) {
739 av_log(h, AV_LOG_ERROR, "Received and autodetected HTTP method did not match "
740 "(%s autodetected %s received)\n", auto_method, method);
741 return ff_http_averror(400, AVERROR(EIO));
743 if (!(s->method = av_strdup(method)))
744 return AVERROR(ENOMEM);
748 while (av_isspace(*p))
751 while (!av_isspace(*p))
754 av_log(h, AV_LOG_TRACE, "Requested resource: %s\n", resource);
755 if (!(s->resource = av_strdup(resource)))
756 return AVERROR(ENOMEM);
759 while (av_isspace(*p))
762 while (*p && !av_isspace(*p))
765 if (av_strncasecmp(version, "HTTP/", 5)) {
766 av_log(h, AV_LOG_ERROR, "Malformed HTTP version string.\n");
767 return ff_http_averror(400, AVERROR(EIO));
769 av_log(h, AV_LOG_TRACE, "HTTP version string: %s\n", version);
771 while (!av_isspace(*p) && *p != '\0')
773 while (av_isspace(*p))
775 s->http_code = strtol(p, &end, 10);
777 av_log(h, AV_LOG_TRACE, "http_code=%d\n", s->http_code);
779 if ((ret = check_http_code(h, s->http_code, end)) < 0)
783 while (*p != '\0' && *p != ':')
791 while (av_isspace(*p))
793 if (!av_strcasecmp(tag, "Location")) {
794 if ((ret = parse_location(s, p)) < 0)
797 } else if (!av_strcasecmp(tag, "Content-Length") && s->filesize == -1) {
798 s->filesize = strtoll(p, NULL, 10);
799 } else if (!av_strcasecmp(tag, "Content-Range")) {
800 parse_content_range(h, p);
801 } else if (!av_strcasecmp(tag, "Accept-Ranges") &&
802 !strncmp(p, "bytes", 5) &&
805 } else if (!av_strcasecmp(tag, "Transfer-Encoding") &&
806 !av_strncasecmp(p, "chunked", 7)) {
809 } else if (!av_strcasecmp(tag, "WWW-Authenticate")) {
810 ff_http_auth_handle_header(&s->auth_state, tag, p);
811 } else if (!av_strcasecmp(tag, "Authentication-Info")) {
812 ff_http_auth_handle_header(&s->auth_state, tag, p);
813 } else if (!av_strcasecmp(tag, "Proxy-Authenticate")) {
814 ff_http_auth_handle_header(&s->proxy_auth_state, tag, p);
815 } else if (!av_strcasecmp(tag, "Connection")) {
816 if (!strcmp(p, "close"))
818 } else if (!av_strcasecmp(tag, "Server")) {
819 if (!av_strcasecmp(p, "AkamaiGHost")) {
821 } else if (!av_strncasecmp(p, "MediaGateway", 12)) {
822 s->is_mediagateway = 1;
824 } else if (!av_strcasecmp(tag, "Content-Type")) {
825 av_free(s->mime_type);
826 s->mime_type = av_strdup(p);
827 } else if (!av_strcasecmp(tag, "Set-Cookie")) {
828 if (parse_cookie(s, p, &s->cookie_dict))
829 av_log(h, AV_LOG_WARNING, "Unable to parse '%s'\n", p);
830 } else if (!av_strcasecmp(tag, "Icy-MetaInt")) {
831 s->icy_metaint = strtoll(p, NULL, 10);
832 } else if (!av_strncasecmp(tag, "Icy-", 4)) {
833 if ((ret = parse_icy(s, tag, p)) < 0)
835 } else if (!av_strcasecmp(tag, "Content-Encoding")) {
836 if ((ret = parse_content_encoding(h, p)) < 0)
844 * Create a string containing cookie values for use as a HTTP cookie header
845 * field value for a particular path and domain from the cookie values stored in
846 * the HTTP protocol context. The cookie string is stored in *cookies.
848 * @return a negative value if an error condition occurred, 0 otherwise
850 static int get_cookies(HTTPContext *s, char **cookies, const char *path,
853 // cookie strings will look like Set-Cookie header field values. Multiple
854 // Set-Cookie fields will result in multiple values delimited by a newline
856 char *next, *cookie, *set_cookies = av_strdup(s->cookies), *cset_cookies = set_cookies;
858 if (!set_cookies) return AVERROR(EINVAL);
860 // destroy any cookies in the dictionary.
861 av_dict_free(&s->cookie_dict);
864 while ((cookie = av_strtok(set_cookies, "\n", &next))) {
865 int domain_offset = 0;
866 char *param, *next_param, *cdomain = NULL, *cpath = NULL, *cvalue = NULL;
869 // store the cookie in a dict in case it is updated in the response
870 if (parse_cookie(s, cookie, &s->cookie_dict))
871 av_log(s, AV_LOG_WARNING, "Unable to parse '%s'\n", cookie);
873 while ((param = av_strtok(cookie, "; ", &next_param))) {
875 // first key-value pair is the actual cookie value
876 cvalue = av_strdup(param);
878 } else if (!av_strncasecmp("path=", param, 5)) {
880 cpath = av_strdup(¶m[5]);
881 } else if (!av_strncasecmp("domain=", param, 7)) {
882 // if the cookie specifies a sub-domain, skip the leading dot thereby
883 // supporting URLs that point to sub-domains and the master domain
884 int leading_dot = (param[7] == '.');
886 cdomain = av_strdup(¶m[7+leading_dot]);
888 // ignore unknown attributes
892 cdomain = av_strdup(domain);
894 // ensure all of the necessary values are valid
895 if (!cdomain || !cpath || !cvalue) {
896 av_log(s, AV_LOG_WARNING,
897 "Invalid cookie found, no value, path or domain specified\n");
901 // check if the request path matches the cookie path
902 if (av_strncasecmp(path, cpath, strlen(cpath)))
905 // the domain should be at least the size of our cookie domain
906 domain_offset = strlen(domain) - strlen(cdomain);
907 if (domain_offset < 0)
910 // match the cookie domain
911 if (av_strcasecmp(&domain[domain_offset], cdomain))
914 // cookie parameters match, so copy the value
916 if (!(*cookies = av_strdup(cvalue))) {
917 ret = AVERROR(ENOMEM);
921 char *tmp = *cookies;
922 size_t str_size = strlen(cvalue) + strlen(*cookies) + 3;
923 if (!(*cookies = av_malloc(str_size))) {
924 ret = AVERROR(ENOMEM);
927 snprintf(*cookies, str_size, "%s; %s", tmp, cvalue);
936 if (*cookies) av_freep(cookies);
937 av_free(cset_cookies);
942 av_free(cset_cookies);
947 static inline int has_header(const char *str, const char *header)
949 /* header + 2 to skip over CRLF prefix. (make sure you have one!) */
952 return av_stristart(str, header + 2, NULL) || av_stristr(str, header);
955 static int http_read_header(URLContext *h, int *new_location)
957 HTTPContext *s = h->priv_data;
958 char line[MAX_URL_SIZE];
964 if ((err = http_get_line(s, line, sizeof(line))) < 0)
967 av_log(h, AV_LOG_TRACE, "header='%s'\n", line);
969 err = process_line(h, line, s->line_count, new_location);
977 if (s->seekable == -1 && s->is_mediagateway && s->filesize == 2000000000)
978 h->is_streamed = 1; /* we can in fact _not_ seek */
980 // add any new cookies into the existing cookie string
981 cookie_string(s->cookie_dict, &s->cookies);
982 av_dict_free(&s->cookie_dict);
987 static int http_connect(URLContext *h, const char *path, const char *local_path,
988 const char *hoststr, const char *auth,
989 const char *proxyauth, int *new_location)
991 HTTPContext *s = h->priv_data;
993 char headers[HTTP_HEADERS_SIZE] = "";
994 char *authstr = NULL, *proxyauthstr = NULL;
995 int64_t off = s->off;
998 int send_expect_100 = 0;
1000 /* send http header */
1001 post = h->flags & AVIO_FLAG_WRITE;
1004 /* force POST method and disable chunked encoding when
1005 * custom HTTP post data is set */
1007 s->chunked_post = 0;
1013 method = post ? "POST" : "GET";
1015 authstr = ff_http_auth_create_response(&s->auth_state, auth,
1016 local_path, method);
1017 proxyauthstr = ff_http_auth_create_response(&s->proxy_auth_state, proxyauth,
1018 local_path, method);
1019 if (post && !s->post_data) {
1020 send_expect_100 = s->send_expect_100;
1021 /* The user has supplied authentication but we don't know the auth type,
1022 * send Expect: 100-continue to get the 401 response including the
1023 * WWW-Authenticate header, or an 100 continue if no auth actually
1025 if (auth && *auth &&
1026 s->auth_state.auth_type == HTTP_AUTH_NONE &&
1027 s->http_code != 401)
1028 send_expect_100 = 1;
1031 /* set default headers if needed */
1032 if (!has_header(s->headers, "\r\nUser-Agent: "))
1033 len += av_strlcatf(headers + len, sizeof(headers) - len,
1034 "User-Agent: %s\r\n", s->user_agent);
1035 if (!has_header(s->headers, "\r\nAccept: "))
1036 len += av_strlcpy(headers + len, "Accept: */*\r\n",
1037 sizeof(headers) - len);
1038 // Note: we send this on purpose even when s->off is 0 when we're probing,
1039 // since it allows us to detect more reliably if a (non-conforming)
1040 // server supports seeking by analysing the reply headers.
1041 if (!has_header(s->headers, "\r\nRange: ") && !post && (s->off > 0 || s->end_off || s->seekable == -1)) {
1042 len += av_strlcatf(headers + len, sizeof(headers) - len,
1043 "Range: bytes=%"PRId64"-", s->off);
1045 len += av_strlcatf(headers + len, sizeof(headers) - len,
1046 "%"PRId64, s->end_off - 1);
1047 len += av_strlcpy(headers + len, "\r\n",
1048 sizeof(headers) - len);
1050 if (send_expect_100 && !has_header(s->headers, "\r\nExpect: "))
1051 len += av_strlcatf(headers + len, sizeof(headers) - len,
1052 "Expect: 100-continue\r\n");
1054 if (!has_header(s->headers, "\r\nConnection: ")) {
1055 if (s->multiple_requests)
1056 len += av_strlcpy(headers + len, "Connection: keep-alive\r\n",
1057 sizeof(headers) - len);
1059 len += av_strlcpy(headers + len, "Connection: close\r\n",
1060 sizeof(headers) - len);
1063 if (!has_header(s->headers, "\r\nHost: "))
1064 len += av_strlcatf(headers + len, sizeof(headers) - len,
1065 "Host: %s\r\n", hoststr);
1066 if (!has_header(s->headers, "\r\nContent-Length: ") && s->post_data)
1067 len += av_strlcatf(headers + len, sizeof(headers) - len,
1068 "Content-Length: %d\r\n", s->post_datalen);
1070 if (!has_header(s->headers, "\r\nContent-Type: ") && s->content_type)
1071 len += av_strlcatf(headers + len, sizeof(headers) - len,
1072 "Content-Type: %s\r\n", s->content_type);
1073 if (!has_header(s->headers, "\r\nCookie: ") && s->cookies) {
1074 char *cookies = NULL;
1075 if (!get_cookies(s, &cookies, path, hoststr) && cookies) {
1076 len += av_strlcatf(headers + len, sizeof(headers) - len,
1077 "Cookie: %s\r\n", cookies);
1081 if (!has_header(s->headers, "\r\nIcy-MetaData: ") && s->icy)
1082 len += av_strlcatf(headers + len, sizeof(headers) - len,
1083 "Icy-MetaData: %d\r\n", 1);
1085 /* now add in custom headers */
1087 av_strlcpy(headers + len, s->headers, sizeof(headers) - len);
1089 snprintf(s->buffer, sizeof(s->buffer),
1090 "%s %s HTTP/1.1\r\n"
1098 post && s->chunked_post ? "Transfer-Encoding: chunked\r\n" : "",
1100 authstr ? authstr : "",
1101 proxyauthstr ? "Proxy-" : "", proxyauthstr ? proxyauthstr : "");
1103 av_log(h, AV_LOG_DEBUG, "request: %s\n", s->buffer);
1105 if ((err = ffurl_write(s->hd, s->buffer, strlen(s->buffer))) < 0)
1109 if ((err = ffurl_write(s->hd, s->post_data, s->post_datalen)) < 0)
1112 /* init input buffer */
1113 s->buf_ptr = s->buffer;
1114 s->buf_end = s->buffer;
1117 s->icy_data_read = 0;
1120 s->end_chunked_post = 0;
1122 if (post && !s->post_data && !send_expect_100) {
1123 /* Pretend that it did work. We didn't read any header yet, since
1124 * we've still to send the POST data, but the code calling this
1125 * function will check http_code after we return. */
1131 /* wait for header */
1132 err = http_read_header(h, new_location);
1139 err = (off == s->off) ? 0 : -1;
1142 av_freep(&proxyauthstr);
1146 static int http_buf_read(URLContext *h, uint8_t *buf, int size)
1148 HTTPContext *s = h->priv_data;
1150 /* read bytes from input buffer first */
1151 len = s->buf_end - s->buf_ptr;
1155 memcpy(buf, s->buf_ptr, len);
1158 if ((!s->willclose || s->chunksize < 0) &&
1159 s->filesize >= 0 && s->off >= s->filesize)
1161 len = ffurl_read(s->hd, buf, size);
1162 if (!len && (!s->willclose || s->chunksize < 0) &&
1163 s->filesize >= 0 && s->off < s->filesize) {
1164 av_log(h, AV_LOG_ERROR,
1165 "Stream ends prematurely at %"PRId64", should be %"PRId64"\n",
1168 return AVERROR(EIO);
1173 if (s->chunksize > 0)
1174 s->chunksize -= len;
1180 #define DECOMPRESS_BUF_SIZE (256 * 1024)
1181 static int http_buf_read_compressed(URLContext *h, uint8_t *buf, int size)
1183 HTTPContext *s = h->priv_data;
1186 if (!s->inflate_buffer) {
1187 s->inflate_buffer = av_malloc(DECOMPRESS_BUF_SIZE);
1188 if (!s->inflate_buffer)
1189 return AVERROR(ENOMEM);
1192 if (s->inflate_stream.avail_in == 0) {
1193 int read = http_buf_read(h, s->inflate_buffer, DECOMPRESS_BUF_SIZE);
1196 s->inflate_stream.next_in = s->inflate_buffer;
1197 s->inflate_stream.avail_in = read;
1200 s->inflate_stream.avail_out = size;
1201 s->inflate_stream.next_out = buf;
1203 ret = inflate(&s->inflate_stream, Z_SYNC_FLUSH);
1204 if (ret != Z_OK && ret != Z_STREAM_END)
1205 av_log(h, AV_LOG_WARNING, "inflate return value: %d, %s\n",
1206 ret, s->inflate_stream.msg);
1208 return size - s->inflate_stream.avail_out;
1210 #endif /* CONFIG_ZLIB */
1212 static int64_t http_seek_internal(URLContext *h, int64_t off, int whence, int force_reconnect);
1214 static int http_read_stream(URLContext *h, uint8_t *buf, int size)
1216 HTTPContext *s = h->priv_data;
1217 int err, new_location, read_ret, seek_ret;
1222 if (s->end_chunked_post && !s->end_header) {
1223 err = http_read_header(h, &new_location);
1228 if (s->chunksize >= 0) {
1229 if (!s->chunksize) {
1233 if ((err = http_get_line(s, line, sizeof(line))) < 0)
1235 } while (!*line); /* skip CR LF from last chunk */
1237 s->chunksize = strtoll(line, NULL, 16);
1239 av_log(NULL, AV_LOG_TRACE, "Chunked encoding data size: %"PRId64"'\n",
1245 size = FFMIN(size, s->chunksize);
1249 return http_buf_read_compressed(h, buf, size);
1250 #endif /* CONFIG_ZLIB */
1251 read_ret = http_buf_read(h, buf, size);
1252 if ( (read_ret < 0 && s->reconnect && (!h->is_streamed || s->reconnect_streamed) && s->filesize > 0 && s->off < s->filesize)
1253 || (read_ret == 0 && s->reconnect_at_eof && (!h->is_streamed || s->reconnect_streamed))) {
1254 int64_t target = h->is_streamed ? 0 : s->off;
1256 if (s->reconnect_delay > s->reconnect_delay_max)
1257 return AVERROR(EIO);
1259 av_log(h, AV_LOG_INFO, "Will reconnect at %"PRId64" error=%s.\n", s->off, av_err2str(read_ret));
1260 av_usleep(1000U*1000*s->reconnect_delay);
1261 s->reconnect_delay = 1 + 2*s->reconnect_delay;
1262 seek_ret = http_seek_internal(h, target, SEEK_SET, 1);
1263 if (seek_ret != target) {
1264 av_log(h, AV_LOG_ERROR, "Failed to reconnect at %"PRId64".\n", target);
1268 read_ret = http_buf_read(h, buf, size);
1270 s->reconnect_delay = 0;
1275 // Like http_read_stream(), but no short reads.
1276 // Assumes partial reads are an error.
1277 static int http_read_stream_all(URLContext *h, uint8_t *buf, int size)
1280 while (pos < size) {
1281 int len = http_read_stream(h, buf + pos, size - pos);
1289 static void update_metadata(HTTPContext *s, char *data)
1298 val = strstr(key, "='");
1301 end = strstr(val, "';");
1309 av_dict_set(&s->metadata, key, val, 0);
1315 static int store_icy(URLContext *h, int size)
1317 HTTPContext *s = h->priv_data;
1318 /* until next metadata packet */
1319 int remaining = s->icy_metaint - s->icy_data_read;
1322 return AVERROR_INVALIDDATA;
1325 /* The metadata packet is variable sized. It has a 1 byte header
1326 * which sets the length of the packet (divided by 16). If it's 0,
1327 * the metadata doesn't change. After the packet, icy_metaint bytes
1328 * of normal data follows. */
1330 int len = http_read_stream_all(h, &ch, 1);
1334 char data[255 * 16 + 1];
1337 ret = http_read_stream_all(h, data, len);
1341 if ((ret = av_opt_set(s, "icy_metadata_packet", data, 0)) < 0)
1343 update_metadata(s, data);
1345 s->icy_data_read = 0;
1346 remaining = s->icy_metaint;
1349 return FFMIN(size, remaining);
1352 static int http_read(URLContext *h, uint8_t *buf, int size)
1354 HTTPContext *s = h->priv_data;
1356 if (s->icy_metaint > 0) {
1357 size = store_icy(h, size);
1362 size = http_read_stream(h, buf, size);
1364 s->icy_data_read += size;
1368 /* used only when posting data */
1369 static int http_write(URLContext *h, const uint8_t *buf, int size)
1371 char temp[11] = ""; /* 32-bit hex + CRLF + nul */
1373 char crlf[] = "\r\n";
1374 HTTPContext *s = h->priv_data;
1376 if (!s->chunked_post) {
1377 /* non-chunked data is sent without any special encoding */
1378 return ffurl_write(s->hd, buf, size);
1381 /* silently ignore zero-size data since chunk encoding that would
1384 /* upload data using chunked encoding */
1385 snprintf(temp, sizeof(temp), "%x\r\n", size);
1387 if ((ret = ffurl_write(s->hd, temp, strlen(temp))) < 0 ||
1388 (ret = ffurl_write(s->hd, buf, size)) < 0 ||
1389 (ret = ffurl_write(s->hd, crlf, sizeof(crlf) - 1)) < 0)
1395 static int http_shutdown(URLContext *h, int flags)
1398 char footer[] = "0\r\n\r\n";
1399 HTTPContext *s = h->priv_data;
1401 /* signal end of chunked encoding if used */
1402 if (((flags & AVIO_FLAG_WRITE) && s->chunked_post) ||
1403 ((flags & AVIO_FLAG_READ) && s->chunked_post && s->listen)) {
1404 ret = ffurl_write(s->hd, footer, sizeof(footer) - 1);
1405 ret = ret > 0 ? 0 : ret;
1406 s->end_chunked_post = 1;
1412 static int http_close(URLContext *h)
1415 HTTPContext *s = h->priv_data;
1418 inflateEnd(&s->inflate_stream);
1419 av_freep(&s->inflate_buffer);
1420 #endif /* CONFIG_ZLIB */
1422 if (!s->end_chunked_post)
1423 /* Close the write direction by sending the end of chunked encoding. */
1424 ret = http_shutdown(h, h->flags);
1427 ffurl_closep(&s->hd);
1428 av_dict_free(&s->chained_options);
1432 static int64_t http_seek_internal(URLContext *h, int64_t off, int whence, int force_reconnect)
1434 HTTPContext *s = h->priv_data;
1435 URLContext *old_hd = s->hd;
1436 int64_t old_off = s->off;
1437 uint8_t old_buf[BUFFER_SIZE];
1438 int old_buf_size, ret;
1439 AVDictionary *options = NULL;
1441 if (whence == AVSEEK_SIZE)
1443 else if (!force_reconnect &&
1444 ((whence == SEEK_CUR && off == 0) ||
1445 (whence == SEEK_SET && off == s->off)))
1447 else if ((s->filesize == -1 && whence == SEEK_END))
1448 return AVERROR(ENOSYS);
1450 if (whence == SEEK_CUR)
1452 else if (whence == SEEK_END)
1454 else if (whence != SEEK_SET)
1455 return AVERROR(EINVAL);
1457 return AVERROR(EINVAL);
1460 if (s->off && h->is_streamed)
1461 return AVERROR(ENOSYS);
1463 /* we save the old context in case the seek fails */
1464 old_buf_size = s->buf_end - s->buf_ptr;
1465 memcpy(old_buf, s->buf_ptr, old_buf_size);
1468 /* if it fails, continue on old connection */
1469 if ((ret = http_open_cnx(h, &options)) < 0) {
1470 av_dict_free(&options);
1471 memcpy(s->buffer, old_buf, old_buf_size);
1472 s->buf_ptr = s->buffer;
1473 s->buf_end = s->buffer + old_buf_size;
1478 av_dict_free(&options);
1479 ffurl_close(old_hd);
1483 static int64_t http_seek(URLContext *h, int64_t off, int whence)
1485 return http_seek_internal(h, off, whence, 0);
1488 static int http_get_file_handle(URLContext *h)
1490 HTTPContext *s = h->priv_data;
1491 return ffurl_get_file_handle(s->hd);
1494 #define HTTP_CLASS(flavor) \
1495 static const AVClass flavor ## _context_class = { \
1496 .class_name = # flavor, \
1497 .item_name = av_default_item_name, \
1498 .option = options, \
1499 .version = LIBAVUTIL_VERSION_INT, \
1502 #if CONFIG_HTTP_PROTOCOL
1505 URLProtocol ff_http_protocol = {
1507 .url_open2 = http_open,
1508 .url_accept = http_accept,
1509 .url_handshake = http_handshake,
1510 .url_read = http_read,
1511 .url_write = http_write,
1512 .url_seek = http_seek,
1513 .url_close = http_close,
1514 .url_get_file_handle = http_get_file_handle,
1515 .url_shutdown = http_shutdown,
1516 .priv_data_size = sizeof(HTTPContext),
1517 .priv_data_class = &http_context_class,
1518 .flags = URL_PROTOCOL_FLAG_NETWORK,
1520 #endif /* CONFIG_HTTP_PROTOCOL */
1522 #if CONFIG_HTTPS_PROTOCOL
1525 URLProtocol ff_https_protocol = {
1527 .url_open2 = http_open,
1528 .url_read = http_read,
1529 .url_write = http_write,
1530 .url_seek = http_seek,
1531 .url_close = http_close,
1532 .url_get_file_handle = http_get_file_handle,
1533 .url_shutdown = http_shutdown,
1534 .priv_data_size = sizeof(HTTPContext),
1535 .priv_data_class = &https_context_class,
1536 .flags = URL_PROTOCOL_FLAG_NETWORK,
1538 #endif /* CONFIG_HTTPS_PROTOCOL */
1540 #if CONFIG_HTTPPROXY_PROTOCOL
1541 static int http_proxy_close(URLContext *h)
1543 HTTPContext *s = h->priv_data;
1545 ffurl_closep(&s->hd);
1549 static int http_proxy_open(URLContext *h, const char *uri, int flags)
1551 HTTPContext *s = h->priv_data;
1552 char hostname[1024], hoststr[1024];
1553 char auth[1024], pathbuf[1024], *path;
1554 char lower_url[100];
1555 int port, ret = 0, attempts = 0;
1556 HTTPAuthType cur_auth_type;
1560 if( s->seekable == 1 )
1565 av_url_split(NULL, 0, auth, sizeof(auth), hostname, sizeof(hostname), &port,
1566 pathbuf, sizeof(pathbuf), uri);
1567 ff_url_join(hoststr, sizeof(hoststr), NULL, NULL, hostname, port, NULL);
1572 ff_url_join(lower_url, sizeof(lower_url), "tcp", NULL, hostname, port,
1575 ret = ffurl_open(&s->hd, lower_url, AVIO_FLAG_READ_WRITE,
1576 &h->interrupt_callback, NULL);
1580 authstr = ff_http_auth_create_response(&s->proxy_auth_state, auth,
1582 snprintf(s->buffer, sizeof(s->buffer),
1583 "CONNECT %s HTTP/1.1\r\n"
1585 "Connection: close\r\n"
1590 authstr ? "Proxy-" : "", authstr ? authstr : "");
1593 if ((ret = ffurl_write(s->hd, s->buffer, strlen(s->buffer))) < 0)
1596 s->buf_ptr = s->buffer;
1597 s->buf_end = s->buffer;
1600 cur_auth_type = s->proxy_auth_state.auth_type;
1602 /* Note: This uses buffering, potentially reading more than the
1603 * HTTP header. If tunneling a protocol where the server starts
1604 * the conversation, we might buffer part of that here, too.
1605 * Reading that requires using the proper ffurl_read() function
1606 * on this URLContext, not using the fd directly (as the tls
1607 * protocol does). This shouldn't be an issue for tls though,
1608 * since the client starts the conversation there, so there
1609 * is no extra data that we might buffer up here.
1611 ret = http_read_header(h, &new_loc);
1616 if (s->http_code == 407 &&
1617 (cur_auth_type == HTTP_AUTH_NONE || s->proxy_auth_state.stale) &&
1618 s->proxy_auth_state.auth_type != HTTP_AUTH_NONE && attempts < 2) {
1619 ffurl_closep(&s->hd);
1623 if (s->http_code < 400)
1625 ret = ff_http_averror(s->http_code, AVERROR(EIO));
1628 http_proxy_close(h);
1632 static int http_proxy_write(URLContext *h, const uint8_t *buf, int size)
1634 HTTPContext *s = h->priv_data;
1635 return ffurl_write(s->hd, buf, size);
1638 URLProtocol ff_httpproxy_protocol = {
1639 .name = "httpproxy",
1640 .url_open = http_proxy_open,
1641 .url_read = http_buf_read,
1642 .url_write = http_proxy_write,
1643 .url_close = http_proxy_close,
1644 .url_get_file_handle = http_get_file_handle,
1645 .priv_data_size = sizeof(HTTPContext),
1646 .flags = URL_PROTOCOL_FLAG_NETWORK,
1648 #endif /* CONFIG_HTTPPROXY_PROTOCOL */