2 * HTTP protocol for avconv client
3 * Copyright (c) 2000, 2001 Fabrice Bellard
5 * This file is part of Libav.
7 * Libav 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 * Libav 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 Libav; if not, write to the Free Software
19 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
22 #include "libavutil/avstring.h"
27 #include "os_support.h"
30 #include "libavutil/opt.h"
36 /* XXX: POST protocol is not completely implemented because avconv uses
37 only a subset of it. */
39 /* The IO buffer size is unrelated to the max URL size in itself, but needs
40 * to be large enough to fit the full request headers (including long
43 #define BUFFER_SIZE MAX_URL_SIZE
44 #define MAX_REDIRECTS 8
49 unsigned char buffer[BUFFER_SIZE], *buf_ptr, *buf_end;
52 /* Used if "Transfer-Encoding: chunked" otherwise -1. */
54 int64_t off, filesize;
56 HTTPAuthState auth_state;
57 HTTPAuthState proxy_auth_state;
61 /* Set if the server correctly handles Connection: close and will close
62 * the connection after feeding us the content. */
65 /* A flag which indicates if the end of chunked encoding has been sent. */
67 /* A flag which indicates we have finished to read POST reply. */
69 /* A flag which indicates if we use persistent connections. */
70 int multiple_requests;
74 /* how much data was read since the last ICY metadata packet */
76 /* after how many bytes of read data a new metadata packet will be found */
78 char *icy_metadata_headers;
79 char *icy_metadata_packet;
82 z_stream inflate_stream;
83 uint8_t *inflate_buffer;
85 AVDictionary *chained_options;
89 #define OFFSET(x) offsetof(HTTPContext, x)
90 #define D AV_OPT_FLAG_DECODING_PARAM
91 #define E AV_OPT_FLAG_ENCODING_PARAM
92 #define DEFAULT_USER_AGENT "Lavf/" AV_STRINGIFY(LIBAVFORMAT_VERSION)
93 static const AVOption options[] = {
94 {"chunked_post", "use chunked transfer-encoding for posts", OFFSET(chunked_post), AV_OPT_TYPE_INT, {.i64 = 1}, 0, 1, E },
95 {"headers", "custom HTTP headers, can override built in default headers", OFFSET(headers), AV_OPT_TYPE_STRING, { 0 }, 0, 0, D|E },
96 {"user_agent", "override User-Agent header", OFFSET(user_agent), AV_OPT_TYPE_STRING, {.str = DEFAULT_USER_AGENT}, 0, 0, D },
97 {"user-agent", "override User-Agent header, for compatibility with ffmpeg", OFFSET(user_agent), AV_OPT_TYPE_STRING, {.str = DEFAULT_USER_AGENT}, 0, 0, D },
98 {"multiple_requests", "use persistent connections", OFFSET(multiple_requests), AV_OPT_TYPE_INT, {.i64 = 0}, 0, 1, D|E },
99 {"post_data", "custom HTTP post data", OFFSET(post_data), AV_OPT_TYPE_BINARY, .flags = D|E },
100 {"mime_type", "export the MIME type", OFFSET(mime_type), AV_OPT_TYPE_STRING, {0}, 0, 0, AV_OPT_FLAG_EXPORT | AV_OPT_FLAG_READONLY },
101 {"icy", "request ICY metadata", OFFSET(icy), AV_OPT_TYPE_INT, {.i64 = 0}, 0, 1, D },
102 {"icy_metadata_headers", "return ICY metadata headers", OFFSET(icy_metadata_headers), AV_OPT_TYPE_STRING, {0}, 0, 0, AV_OPT_FLAG_EXPORT },
103 {"icy_metadata_packet", "return current ICY metadata packet", OFFSET(icy_metadata_packet), AV_OPT_TYPE_STRING, {0}, 0, 0, AV_OPT_FLAG_EXPORT },
104 {"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" },
105 {"none", "No auth method set, autodetect", 0, AV_OPT_TYPE_CONST, {.i64 = HTTP_AUTH_NONE}, 0, 0, D|E, "auth_type" },
106 {"basic", "HTTP basic authentication", 0, AV_OPT_TYPE_CONST, {.i64 = HTTP_AUTH_BASIC}, 0, 0, D|E, "auth_type" },
107 {"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 },
108 {"location", "The actual location of the data received", OFFSET(location), AV_OPT_TYPE_STRING, { 0 }, 0, 0, D|E },
111 #define HTTP_CLASS(flavor)\
112 static const AVClass flavor ## _context_class = {\
113 .class_name = #flavor,\
114 .item_name = av_default_item_name,\
116 .version = LIBAVUTIL_VERSION_INT,\
122 static int http_connect(URLContext *h, const char *path, const char *local_path,
123 const char *hoststr, const char *auth,
124 const char *proxyauth, int *new_location);
126 void ff_http_init_auth_state(URLContext *dest, const URLContext *src)
128 memcpy(&((HTTPContext*)dest->priv_data)->auth_state,
129 &((HTTPContext*)src->priv_data)->auth_state, sizeof(HTTPAuthState));
130 memcpy(&((HTTPContext*)dest->priv_data)->proxy_auth_state,
131 &((HTTPContext*)src->priv_data)->proxy_auth_state,
132 sizeof(HTTPAuthState));
135 /* return non zero if error */
136 static int http_open_cnx(URLContext *h, AVDictionary **options)
138 const char *path, *proxy_path, *lower_proto = "tcp", *local_path;
139 char hostname[1024], hoststr[1024], proto[10];
140 char auth[1024], proxyauth[1024] = "";
141 char path1[MAX_URL_SIZE];
142 char buf[1024], urlbuf[MAX_URL_SIZE];
143 int port, use_proxy, err, location_changed = 0, redirects = 0, attempts = 0;
144 HTTPAuthType cur_auth_type, cur_proxy_auth_type;
145 HTTPContext *s = h->priv_data;
147 /* fill the dest addr */
149 /* needed in any case to build the host string */
150 av_url_split(proto, sizeof(proto), auth, sizeof(auth),
151 hostname, sizeof(hostname), &port,
152 path1, sizeof(path1), s->location);
153 ff_url_join(hoststr, sizeof(hoststr), NULL, NULL, hostname, port, NULL);
155 proxy_path = getenv("http_proxy");
156 use_proxy = !ff_http_match_no_proxy(getenv("no_proxy"), hostname) &&
157 proxy_path != NULL && av_strstart(proxy_path, "http://", NULL);
159 if (!strcmp(proto, "https")) {
168 if (path1[0] == '\0')
174 /* Reassemble the request URL without auth string - we don't
175 * want to leak the auth to the proxy. */
176 ff_url_join(urlbuf, sizeof(urlbuf), proto, NULL, hostname, port, "%s",
179 av_url_split(NULL, 0, proxyauth, sizeof(proxyauth),
180 hostname, sizeof(hostname), &port, NULL, 0, proxy_path);
183 ff_url_join(buf, sizeof(buf), lower_proto, NULL, hostname, port, NULL);
186 err = ffurl_open(&s->hd, buf, AVIO_FLAG_READ_WRITE,
187 &h->interrupt_callback, options);
192 cur_auth_type = s->auth_state.auth_type;
193 cur_proxy_auth_type = s->auth_state.auth_type;
194 if (http_connect(h, path, local_path, hoststr, auth, proxyauth, &location_changed) < 0)
197 if (s->http_code == 401) {
198 if ((cur_auth_type == HTTP_AUTH_NONE || s->auth_state.stale) &&
199 s->auth_state.auth_type != HTTP_AUTH_NONE && attempts < 4) {
206 if (s->http_code == 407) {
207 if ((cur_proxy_auth_type == HTTP_AUTH_NONE || s->proxy_auth_state.stale) &&
208 s->proxy_auth_state.auth_type != HTTP_AUTH_NONE && attempts < 4) {
215 if ((s->http_code == 301 || s->http_code == 302 || s->http_code == 303 || s->http_code == 307)
216 && location_changed == 1) {
217 /* url moved, get next */
220 if (redirects++ >= MAX_REDIRECTS)
222 /* Restart the authentication process with the new target, which
223 * might use a different auth mechanism. */
224 memset(&s->auth_state, 0, sizeof(s->auth_state));
226 location_changed = 0;
237 int ff_http_do_new_request(URLContext *h, const char *uri)
239 HTTPContext *s = h->priv_data;
240 AVDictionary *options = NULL;
244 s->icy_data_read = 0;
245 av_free(s->location);
246 s->location = av_strdup(uri);
248 return AVERROR(ENOMEM);
250 av_dict_copy(&options, s->chained_options, 0);
251 ret = http_open_cnx(h, &options);
252 av_dict_free(&options);
256 static int http_open(URLContext *h, const char *uri, int flags,
257 AVDictionary **options)
259 HTTPContext *s = h->priv_data;
265 s->location = av_strdup(uri);
267 return AVERROR(ENOMEM);
269 av_dict_copy(&s->chained_options, *options, 0);
272 int len = strlen(s->headers);
273 if (len < 2 || strcmp("\r\n", s->headers + len - 2))
274 av_log(h, AV_LOG_WARNING, "No trailing CRLF found in HTTP header.\n");
277 ret = http_open_cnx(h, options);
279 av_dict_free(&s->chained_options);
282 static int http_getc(HTTPContext *s)
285 if (s->buf_ptr >= s->buf_end) {
286 len = ffurl_read(s->hd, s->buffer, BUFFER_SIZE);
289 } else if (len == 0) {
292 s->buf_ptr = s->buffer;
293 s->buf_end = s->buffer + len;
296 return *s->buf_ptr++;
299 static int http_get_line(HTTPContext *s, char *line, int line_size)
311 if (q > line && q[-1] == '\r')
317 if ((q - line) < line_size - 1)
323 static int check_http_code(URLContext *h, int http_code, const char *end)
325 HTTPContext *s = h->priv_data;
326 /* error codes are 4xx and 5xx, but regard 401 as a success, so we
327 * don't abort until all headers have been parsed. */
328 if (http_code >= 400 && http_code < 600 &&
329 (http_code != 401 || s->auth_state.auth_type != HTTP_AUTH_NONE) &&
330 (http_code != 407 || s->proxy_auth_state.auth_type != HTTP_AUTH_NONE)) {
331 end += strspn(end, SPACE_CHARS);
332 av_log(h, AV_LOG_WARNING, "HTTP error %d %s\n", http_code, end);
338 static int parse_location(HTTPContext *s, const char *p)
340 char redirected_location[MAX_URL_SIZE], *new_loc;
341 ff_make_absolute_url(redirected_location, sizeof(redirected_location),
343 new_loc = av_strdup(redirected_location);
345 return AVERROR(ENOMEM);
346 av_free(s->location);
347 s->location = new_loc;
351 /* "bytes $from-$to/$document_size" */
352 static void parse_content_range(URLContext *h, char *p)
354 HTTPContext *s = h->priv_data;
357 if (!strncmp(p, "bytes ", 6)) {
359 s->off = strtoll(p, NULL, 10);
360 if ((slash = strchr(p, '/')) && strlen(slash) > 0)
361 s->filesize = strtoll(slash+1, NULL, 10);
363 h->is_streamed = 0; /* we _can_ in fact seek */
366 static int parse_content_encoding(URLContext *h, char *p)
368 HTTPContext *s = h->priv_data;
370 if (!av_strncasecmp(p, "gzip", 4) ||
371 !av_strncasecmp(p, "deflate", 7)) {
374 inflateEnd(&s->inflate_stream);
375 if (inflateInit2(&s->inflate_stream, 32 + 15) != Z_OK) {
376 av_log(h, AV_LOG_WARNING, "Error during zlib initialisation: %s\n",
377 s->inflate_stream.msg);
378 return AVERROR(ENOSYS);
380 if (zlibCompileFlags() & (1 << 17)) {
381 av_log(h, AV_LOG_WARNING,
382 "Your zlib was compiled without gzip support.\n");
383 return AVERROR(ENOSYS);
386 av_log(h, AV_LOG_WARNING,
387 "Compressed (%s) content, need zlib with gzip support\n", p);
388 return AVERROR(ENOSYS);
390 } else if (!av_strncasecmp(p, "identity", 8)) {
391 // The normal, no-encoding case (although servers shouldn't include
392 // the header at all if this is the case).
394 av_log(h, AV_LOG_WARNING, "Unknown content coding: %s\n", p);
395 return AVERROR(ENOSYS);
400 // Concat all Icy- header lines
401 static int parse_icy(HTTPContext *s, const char *tag, const char *p)
403 int len = 4 + strlen(p) + strlen(tag);
406 if (s->icy_metadata_headers)
407 len += strlen(s->icy_metadata_headers);
409 if ((ret = av_reallocp(&s->icy_metadata_headers, len)) < 0)
412 av_strlcatf(s->icy_metadata_headers, len, "%s: %s\n", tag, p);
417 static int process_line(URLContext *h, char *line, int line_count,
420 HTTPContext *s = h->priv_data;
425 if (line[0] == '\0') {
431 if (line_count == 0) {
432 while (!av_isspace(*p) && *p != '\0')
434 while (av_isspace(*p))
436 s->http_code = strtol(p, &end, 10);
438 av_dlog(NULL, "http_code=%d\n", s->http_code);
440 if ((ret = check_http_code(h, s->http_code, end)) < 0)
443 while (*p != '\0' && *p != ':')
451 while (av_isspace(*p))
453 if (!av_strcasecmp(tag, "Location")) {
454 if ((ret = parse_location(s, p)) < 0)
457 } else if (!av_strcasecmp(tag, "Content-Length") && s->filesize == -1) {
458 s->filesize = strtoll(p, NULL, 10);
459 } else if (!av_strcasecmp(tag, "Content-Range")) {
460 parse_content_range(h, p);
461 } else if (!av_strcasecmp(tag, "Accept-Ranges") &&
462 !strncmp(p, "bytes", 5)) {
464 } else if (!av_strcasecmp(tag, "Transfer-Encoding") &&
465 !av_strncasecmp(p, "chunked", 7)) {
468 } else if (!av_strcasecmp(tag, "WWW-Authenticate")) {
469 ff_http_auth_handle_header(&s->auth_state, tag, p);
470 } else if (!av_strcasecmp(tag, "Authentication-Info")) {
471 ff_http_auth_handle_header(&s->auth_state, tag, p);
472 } else if (!av_strcasecmp(tag, "Proxy-Authenticate")) {
473 ff_http_auth_handle_header(&s->proxy_auth_state, tag, p);
474 } else if (!av_strcasecmp(tag, "Connection")) {
475 if (!strcmp(p, "close"))
477 } else if (!av_strcasecmp (tag, "Content-Type")) {
478 av_free(s->mime_type);
479 s->mime_type = av_strdup(p);
480 } else if (!av_strcasecmp (tag, "Icy-MetaInt")) {
481 s->icy_metaint = strtoll(p, NULL, 10);
482 } else if (!av_strncasecmp(tag, "Icy-", 4)) {
483 if ((ret = parse_icy(s, tag, p)) < 0)
485 } else if (!av_strcasecmp(tag, "Content-Encoding")) {
486 if ((ret = parse_content_encoding(h, p)) < 0)
493 static inline int has_header(const char *str, const char *header)
495 /* header + 2 to skip over CRLF prefix. (make sure you have one!) */
498 return av_stristart(str, header + 2, NULL) || av_stristr(str, header);
501 static int http_read_header(URLContext *h, int *new_location)
503 HTTPContext *s = h->priv_data;
504 char line[MAX_URL_SIZE];
510 if ((err = http_get_line(s, line, sizeof(line))) < 0)
513 av_dlog(NULL, "header='%s'\n", line);
515 err = process_line(h, line, s->line_count, new_location);
526 static int http_connect(URLContext *h, const char *path, const char *local_path,
527 const char *hoststr, const char *auth,
528 const char *proxyauth, int *new_location)
530 HTTPContext *s = h->priv_data;
532 char headers[1024] = "";
533 char *authstr = NULL, *proxyauthstr = NULL;
534 int64_t off = s->off;
537 int send_expect_100 = 0;
540 /* send http header */
541 post = h->flags & AVIO_FLAG_WRITE;
544 /* force POST method and disable chunked encoding when
545 * custom HTTP post data is set */
550 method = post ? "POST" : "GET";
551 authstr = ff_http_auth_create_response(&s->auth_state, auth, local_path,
553 proxyauthstr = ff_http_auth_create_response(&s->proxy_auth_state, proxyauth,
555 if (post && !s->post_data) {
556 send_expect_100 = s->send_expect_100;
557 /* The user has supplied authentication but we don't know the auth type,
558 * send Expect: 100-continue to get the 401 response including the
559 * WWW-Authenticate header, or an 100 continue if no auth actually
562 s->auth_state.auth_type == HTTP_AUTH_NONE &&
567 /* set default headers if needed */
568 if (!has_header(s->headers, "\r\nUser-Agent: "))
569 len += av_strlcatf(headers + len, sizeof(headers) - len,
570 "User-Agent: %s\r\n", s->user_agent);
571 if (!has_header(s->headers, "\r\nAccept: "))
572 len += av_strlcpy(headers + len, "Accept: */*\r\n",
573 sizeof(headers) - len);
574 if (!has_header(s->headers, "\r\nRange: ") && !post)
575 len += av_strlcatf(headers + len, sizeof(headers) - len,
576 "Range: bytes=%"PRId64"-\r\n", s->off);
577 if (send_expect_100 && !has_header(s->headers, "\r\nExpect: "))
578 len += av_strlcatf(headers + len, sizeof(headers) - len,
579 "Expect: 100-continue\r\n");
581 if (!has_header(s->headers, "\r\nConnection: ")) {
582 if (s->multiple_requests) {
583 len += av_strlcpy(headers + len, "Connection: keep-alive\r\n",
584 sizeof(headers) - len);
586 len += av_strlcpy(headers + len, "Connection: close\r\n",
587 sizeof(headers) - len);
591 if (!has_header(s->headers, "\r\nHost: "))
592 len += av_strlcatf(headers + len, sizeof(headers) - len,
593 "Host: %s\r\n", hoststr);
594 if (!has_header(s->headers, "\r\nContent-Length: ") && s->post_data)
595 len += av_strlcatf(headers + len, sizeof(headers) - len,
596 "Content-Length: %d\r\n", s->post_datalen);
597 if (!has_header(s->headers, "\r\nIcy-MetaData: ") && s->icy) {
598 len += av_strlcatf(headers + len, sizeof(headers) - len,
599 "Icy-MetaData: %d\r\n", 1);
602 /* now add in custom headers */
604 av_strlcpy(headers + len, s->headers, sizeof(headers) - len);
606 snprintf(s->buffer, sizeof(s->buffer),
615 post && s->chunked_post ? "Transfer-Encoding: chunked\r\n" : "",
617 authstr ? authstr : "",
618 proxyauthstr ? "Proxy-" : "", proxyauthstr ? proxyauthstr : "");
621 av_freep(&proxyauthstr);
622 if ((err = ffurl_write(s->hd, s->buffer, strlen(s->buffer))) < 0)
626 if ((err = ffurl_write(s->hd, s->post_data, s->post_datalen)) < 0)
629 /* init input buffer */
630 s->buf_ptr = s->buffer;
631 s->buf_end = s->buffer;
634 s->icy_data_read = 0;
637 s->end_chunked_post = 0;
639 if (post && !s->post_data && !send_expect_100) {
640 /* Pretend that it did work. We didn't read any header yet, since
641 * we've still to send the POST data, but the code calling this
642 * function will check http_code after we return. */
647 /* wait for header */
648 err = http_read_header(h, new_location);
652 return (off == s->off) ? 0 : -1;
656 static int http_buf_read(URLContext *h, uint8_t *buf, int size)
658 HTTPContext *s = h->priv_data;
660 /* read bytes from input buffer first */
661 len = s->buf_end - s->buf_ptr;
665 memcpy(buf, s->buf_ptr, len);
668 if (!s->willclose && s->filesize >= 0 && s->off >= s->filesize)
670 len = ffurl_read(s->hd, buf, size);
674 if (s->chunksize > 0)
681 #define DECOMPRESS_BUF_SIZE (256 * 1024)
682 static int http_buf_read_compressed(URLContext *h, uint8_t *buf, int size)
684 HTTPContext *s = h->priv_data;
687 if (!s->inflate_buffer) {
688 s->inflate_buffer = av_malloc(DECOMPRESS_BUF_SIZE);
689 if (!s->inflate_buffer)
690 return AVERROR(ENOMEM);
693 if (s->inflate_stream.avail_in == 0) {
694 int read = http_buf_read(h, s->inflate_buffer, DECOMPRESS_BUF_SIZE);
697 s->inflate_stream.next_in = s->inflate_buffer;
698 s->inflate_stream.avail_in = read;
701 s->inflate_stream.avail_out = size;
702 s->inflate_stream.next_out = buf;
704 ret = inflate(&s->inflate_stream, Z_SYNC_FLUSH);
705 if (ret != Z_OK && ret != Z_STREAM_END)
706 av_log(h, AV_LOG_WARNING, "inflate return value: %d, %s\n", ret, s->inflate_stream.msg);
708 return size - s->inflate_stream.avail_out;
712 static int http_read_stream(URLContext *h, uint8_t *buf, int size)
714 HTTPContext *s = h->priv_data;
715 int err, new_location;
720 if (s->end_chunked_post && !s->end_header) {
721 err = http_read_header(h, &new_location);
726 if (s->chunksize >= 0) {
732 if ((err = http_get_line(s, line, sizeof(line))) < 0)
734 } while (!*line); /* skip CR LF from last chunk */
736 s->chunksize = strtoll(line, NULL, 16);
738 av_dlog(NULL, "Chunked encoding data size: %"PRId64"'\n", s->chunksize);
745 size = FFMIN(size, s->chunksize);
749 return http_buf_read_compressed(h, buf, size);
751 return http_buf_read(h, buf, size);
754 static int http_read_stream_all(URLContext *h, uint8_t *buf, int size)
758 int len = http_read_stream(h, buf + pos, size - pos);
766 static int store_icy(URLContext *h, int size)
768 HTTPContext *s = h->priv_data;
769 /* until next metadata packet */
770 int remaining = s->icy_metaint - s->icy_data_read;
773 return AVERROR_INVALIDDATA;
776 // The metadata packet is variable sized. It has a 1 byte header
777 // which sets the length of the packet (divided by 16). If it's 0,
778 // the metadata doesn't change. After the packet, icy_metaint bytes
779 // of normal data follow.
781 int len = http_read_stream_all(h, &ch, 1);
785 char data[255 * 16 + 1];
788 ret = http_read_stream_all(h, data, len);
792 if ((ret = av_opt_set(s, "icy_metadata_packet", data, 0)) < 0)
795 s->icy_data_read = 0;
796 remaining = s->icy_metaint;
799 return FFMIN(size, remaining);
802 static int http_read(URLContext *h, uint8_t *buf, int size)
804 HTTPContext *s = h->priv_data;
806 if (s->icy_metaint > 0) {
807 size = store_icy(h, size);
812 size = http_read_stream(h, buf, size);
814 s->icy_data_read += size;
818 /* used only when posting data */
819 static int http_write(URLContext *h, const uint8_t *buf, int size)
821 char temp[11] = ""; /* 32-bit hex + CRLF + nul */
823 char crlf[] = "\r\n";
824 HTTPContext *s = h->priv_data;
826 if (!s->chunked_post) {
827 /* non-chunked data is sent without any special encoding */
828 return ffurl_write(s->hd, buf, size);
831 /* silently ignore zero-size data since chunk encoding that would
834 /* upload data using chunked encoding */
835 snprintf(temp, sizeof(temp), "%x\r\n", size);
837 if ((ret = ffurl_write(s->hd, temp, strlen(temp))) < 0 ||
838 (ret = ffurl_write(s->hd, buf, size)) < 0 ||
839 (ret = ffurl_write(s->hd, crlf, sizeof(crlf) - 1)) < 0)
845 static int http_shutdown(URLContext *h, int flags)
848 char footer[] = "0\r\n\r\n";
849 HTTPContext *s = h->priv_data;
851 /* signal end of chunked encoding if used */
852 if ((flags & AVIO_FLAG_WRITE) && s->chunked_post) {
853 ret = ffurl_write(s->hd, footer, sizeof(footer) - 1);
854 ret = ret > 0 ? 0 : ret;
855 s->end_chunked_post = 1;
861 static int http_close(URLContext *h)
864 HTTPContext *s = h->priv_data;
867 inflateEnd(&s->inflate_stream);
868 av_freep(&s->inflate_buffer);
871 if (!s->end_chunked_post) {
872 /* Close the write direction by sending the end of chunked encoding. */
873 ret = http_shutdown(h, h->flags);
878 av_dict_free(&s->chained_options);
882 static int64_t http_seek(URLContext *h, int64_t off, int whence)
884 HTTPContext *s = h->priv_data;
885 URLContext *old_hd = s->hd;
886 int64_t old_off = s->off;
887 uint8_t old_buf[BUFFER_SIZE];
888 int old_buf_size, ret;
889 AVDictionary *options = NULL;
891 if (whence == AVSEEK_SIZE)
893 else if ((s->filesize == -1 && whence == SEEK_END) || h->is_streamed)
894 return AVERROR(ENOSYS);
896 /* we save the old context in case the seek fails */
897 old_buf_size = s->buf_end - s->buf_ptr;
898 memcpy(old_buf, s->buf_ptr, old_buf_size);
900 if (whence == SEEK_CUR)
902 else if (whence == SEEK_END)
906 /* if it fails, continue on old connection */
907 av_dict_copy(&options, s->chained_options, 0);
908 if ((ret = http_open_cnx(h, &options)) < 0) {
909 av_dict_free(&options);
910 memcpy(s->buffer, old_buf, old_buf_size);
911 s->buf_ptr = s->buffer;
912 s->buf_end = s->buffer + old_buf_size;
917 av_dict_free(&options);
923 http_get_file_handle(URLContext *h)
925 HTTPContext *s = h->priv_data;
926 return ffurl_get_file_handle(s->hd);
929 #if CONFIG_HTTP_PROTOCOL
930 URLProtocol ff_http_protocol = {
932 .url_open2 = http_open,
933 .url_read = http_read,
934 .url_write = http_write,
935 .url_seek = http_seek,
936 .url_close = http_close,
937 .url_get_file_handle = http_get_file_handle,
938 .url_shutdown = http_shutdown,
939 .priv_data_size = sizeof(HTTPContext),
940 .priv_data_class = &http_context_class,
941 .flags = URL_PROTOCOL_FLAG_NETWORK,
944 #if CONFIG_HTTPS_PROTOCOL
945 URLProtocol ff_https_protocol = {
947 .url_open2 = http_open,
948 .url_read = http_read,
949 .url_write = http_write,
950 .url_seek = http_seek,
951 .url_close = http_close,
952 .url_get_file_handle = http_get_file_handle,
953 .url_shutdown = http_shutdown,
954 .priv_data_size = sizeof(HTTPContext),
955 .priv_data_class = &https_context_class,
956 .flags = URL_PROTOCOL_FLAG_NETWORK,
960 #if CONFIG_HTTPPROXY_PROTOCOL
961 static int http_proxy_close(URLContext *h)
963 HTTPContext *s = h->priv_data;
969 static int http_proxy_open(URLContext *h, const char *uri, int flags)
971 HTTPContext *s = h->priv_data;
972 char hostname[1024], hoststr[1024];
973 char auth[1024], pathbuf[1024], *path;
975 int port, ret = 0, attempts = 0;
976 HTTPAuthType cur_auth_type;
982 av_url_split(NULL, 0, auth, sizeof(auth), hostname, sizeof(hostname), &port,
983 pathbuf, sizeof(pathbuf), uri);
984 ff_url_join(hoststr, sizeof(hoststr), NULL, NULL, hostname, port, NULL);
989 ff_url_join(lower_url, sizeof(lower_url), "tcp", NULL, hostname, port,
992 ret = ffurl_open(&s->hd, lower_url, AVIO_FLAG_READ_WRITE,
993 &h->interrupt_callback, NULL);
997 authstr = ff_http_auth_create_response(&s->proxy_auth_state, auth,
999 snprintf(s->buffer, sizeof(s->buffer),
1000 "CONNECT %s HTTP/1.1\r\n"
1002 "Connection: close\r\n"
1007 authstr ? "Proxy-" : "", authstr ? authstr : "");
1010 if ((ret = ffurl_write(s->hd, s->buffer, strlen(s->buffer))) < 0)
1013 s->buf_ptr = s->buffer;
1014 s->buf_end = s->buffer;
1017 cur_auth_type = s->proxy_auth_state.auth_type;
1019 /* Note: This uses buffering, potentially reading more than the
1020 * HTTP header. If tunneling a protocol where the server starts
1021 * the conversation, we might buffer part of that here, too.
1022 * Reading that requires using the proper ffurl_read() function
1023 * on this URLContext, not using the fd directly (as the tls
1024 * protocol does). This shouldn't be an issue for tls though,
1025 * since the client starts the conversation there, so there
1026 * is no extra data that we might buffer up here.
1028 ret = http_read_header(h, &new_loc);
1033 if (s->http_code == 407 &&
1034 (cur_auth_type == HTTP_AUTH_NONE || s->proxy_auth_state.stale) &&
1035 s->proxy_auth_state.auth_type != HTTP_AUTH_NONE && attempts < 2) {
1041 if (s->http_code < 400)
1046 http_proxy_close(h);
1050 static int http_proxy_write(URLContext *h, const uint8_t *buf, int size)
1052 HTTPContext *s = h->priv_data;
1053 return ffurl_write(s->hd, buf, size);
1056 URLProtocol ff_httpproxy_protocol = {
1057 .name = "httpproxy",
1058 .url_open = http_proxy_open,
1059 .url_read = http_buf_read,
1060 .url_write = http_proxy_write,
1061 .url_close = http_proxy_close,
1062 .url_get_file_handle = http_get_file_handle,
1063 .priv_data_size = sizeof(HTTPContext),
1064 .flags = URL_PROTOCOL_FLAG_NETWORK,