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
22 #include "libavutil/avstring.h"
27 #include "os_support.h"
30 #include "libavutil/opt.h"
32 /* XXX: POST protocol is not completely implemented because ffmpeg uses
33 only a subset of it. */
35 /* The IO buffer size is unrelated to the max URL size in itself, but needs
36 * to be large enough to fit the full request headers (including long
39 #define BUFFER_SIZE MAX_URL_SIZE
40 #define MAX_REDIRECTS 8
45 unsigned char buffer[BUFFER_SIZE], *buf_ptr, *buf_end;
48 int64_t chunksize; /**< Used if "Transfer-Encoding: chunked" otherwise -1. */
50 int64_t off, filesize;
51 char location[MAX_URL_SIZE];
52 HTTPAuthState auth_state;
53 HTTPAuthState proxy_auth_state;
55 int willclose; /**< Set if the server correctly handles Connection: close and will close the connection after feeding us the content. */
56 int seekable; /**< Control seekability, 0 = disable, 1 = enable, -1 = probe. */
58 int end_chunked_post; /**< A flag which indicates if the end of chunked encoding has been sent. */
59 int end_header; /**< A flag which indicates we have finished to read POST reply. */
60 int multiple_requests; /**< A flag which indicates if we use persistent connections. */
67 #define OFFSET(x) offsetof(HTTPContext, x)
68 #define D AV_OPT_FLAG_DECODING_PARAM
69 #define E AV_OPT_FLAG_ENCODING_PARAM
70 #define DEC AV_OPT_FLAG_DECODING_PARAM
71 static const AVOption options[] = {
72 {"seekable", "Control seekability of connection", OFFSET(seekable), AV_OPT_TYPE_INT, {.i64 = -1}, -1, 1, D },
73 {"chunked_post", "use chunked transfer-encoding for posts", OFFSET(chunked_post), AV_OPT_TYPE_INT, {.i64 = 1}, 0, 1, E },
74 {"headers", "custom HTTP headers, can override built in default headers", OFFSET(headers), AV_OPT_TYPE_STRING, { 0 }, 0, 0, D|E },
75 {"user-agent", "override User-Agent header", OFFSET(user_agent), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, DEC},
76 {"multiple_requests", "use persistent connections", OFFSET(multiple_requests), AV_OPT_TYPE_INT, {.i64 = 0}, 0, 1, D|E },
77 {"post_data", "custom HTTP post data", OFFSET(post_data), AV_OPT_TYPE_BINARY, .flags = D|E },
78 {"timeout", "timeout of socket i/o operations", OFFSET(rw_timeout), AV_OPT_TYPE_INT, {.i64 = -1}, -1, INT_MAX, D|E },
81 #define HTTP_CLASS(flavor)\
82 static const AVClass flavor ## _context_class = {\
83 .class_name = #flavor,\
84 .item_name = av_default_item_name,\
86 .version = LIBAVUTIL_VERSION_INT,\
92 static int http_connect(URLContext *h, const char *path, const char *local_path,
93 const char *hoststr, const char *auth,
94 const char *proxyauth, int *new_location);
96 void ff_http_init_auth_state(URLContext *dest, const URLContext *src)
98 memcpy(&((HTTPContext*)dest->priv_data)->auth_state,
99 &((HTTPContext*)src->priv_data)->auth_state, sizeof(HTTPAuthState));
100 memcpy(&((HTTPContext*)dest->priv_data)->proxy_auth_state,
101 &((HTTPContext*)src->priv_data)->proxy_auth_state,
102 sizeof(HTTPAuthState));
105 /* return non zero if error */
106 static int http_open_cnx(URLContext *h)
108 const char *path, *proxy_path, *lower_proto = "tcp", *local_path;
109 char hostname[1024], hoststr[1024], proto[10];
110 char auth[1024], proxyauth[1024] = "";
111 char path1[MAX_URL_SIZE];
112 char buf[1024], urlbuf[MAX_URL_SIZE];
113 int port, use_proxy, err, location_changed = 0, redirects = 0, attempts = 0;
114 HTTPAuthType cur_auth_type, cur_proxy_auth_type;
115 HTTPContext *s = h->priv_data;
117 proxy_path = getenv("http_proxy");
118 use_proxy = (proxy_path != NULL) && !getenv("no_proxy") &&
119 av_strstart(proxy_path, "http://", NULL);
121 /* fill the dest addr */
123 /* needed in any case to build the host string */
124 av_url_split(proto, sizeof(proto), auth, sizeof(auth),
125 hostname, sizeof(hostname), &port,
126 path1, sizeof(path1), s->location);
127 ff_url_join(hoststr, sizeof(hoststr), NULL, NULL, hostname, port, NULL);
129 if (!strcmp(proto, "https")) {
138 if (path1[0] == '\0')
144 /* Reassemble the request URL without auth string - we don't
145 * want to leak the auth to the proxy. */
146 ff_url_join(urlbuf, sizeof(urlbuf), proto, NULL, hostname, port, "%s",
149 av_url_split(NULL, 0, proxyauth, sizeof(proxyauth),
150 hostname, sizeof(hostname), &port, NULL, 0, proxy_path);
153 ff_url_join(buf, sizeof(buf), lower_proto, NULL, hostname, port, NULL);
156 AVDictionary *opts = NULL;
157 char opts_format[20];
158 if (s->rw_timeout != -1) {
159 snprintf(opts_format, sizeof(opts_format), "%d", s->rw_timeout);
160 av_dict_set(&opts, "timeout", opts_format, 0);
161 } /* if option is not given, don't pass it and let tcp use its own default */
162 err = ffurl_open(&s->hd, buf, AVIO_FLAG_READ_WRITE,
163 &h->interrupt_callback, &opts);
169 cur_auth_type = s->auth_state.auth_type;
170 cur_proxy_auth_type = s->auth_state.auth_type;
171 if (http_connect(h, path, local_path, hoststr, auth, proxyauth, &location_changed) < 0)
174 if (s->http_code == 401) {
175 if ((cur_auth_type == HTTP_AUTH_NONE || s->auth_state.stale) &&
176 s->auth_state.auth_type != HTTP_AUTH_NONE && attempts < 4) {
177 ffurl_closep(&s->hd);
182 if (s->http_code == 407) {
183 if ((cur_proxy_auth_type == HTTP_AUTH_NONE || s->proxy_auth_state.stale) &&
184 s->proxy_auth_state.auth_type != HTTP_AUTH_NONE && attempts < 4) {
185 ffurl_closep(&s->hd);
190 if ((s->http_code == 301 || s->http_code == 302 || s->http_code == 303 || s->http_code == 307)
191 && location_changed == 1) {
192 /* url moved, get next */
193 ffurl_closep(&s->hd);
194 if (redirects++ >= MAX_REDIRECTS)
196 /* Restart the authentication process with the new target, which
197 * might use a different auth mechanism. */
198 memset(&s->auth_state, 0, sizeof(s->auth_state));
200 location_changed = 0;
206 ffurl_closep(&s->hd);
210 int ff_http_do_new_request(URLContext *h, const char *uri)
212 HTTPContext *s = h->priv_data;
215 av_strlcpy(s->location, uri, sizeof(s->location));
217 return http_open_cnx(h);
220 static int http_open(URLContext *h, const char *uri, int flags)
222 HTTPContext *s = h->priv_data;
224 if( s->seekable == 1 )
230 av_strlcpy(s->location, uri, sizeof(s->location));
233 int len = strlen(s->headers);
234 if (len < 2 || strcmp("\r\n", s->headers + len - 2))
235 av_log(h, AV_LOG_WARNING, "No trailing CRLF found in HTTP header.\n");
238 return http_open_cnx(h);
240 static int http_getc(HTTPContext *s)
243 if (s->buf_ptr >= s->buf_end) {
244 len = ffurl_read(s->hd, s->buffer, BUFFER_SIZE);
247 } else if (len == 0) {
250 s->buf_ptr = s->buffer;
251 s->buf_end = s->buffer + len;
254 return *s->buf_ptr++;
257 static int http_get_line(HTTPContext *s, char *line, int line_size)
269 if (q > line && q[-1] == '\r')
275 if ((q - line) < line_size - 1)
281 static int process_line(URLContext *h, char *line, int line_count,
284 HTTPContext *s = h->priv_data;
288 if (line[0] == '\0') {
294 if (line_count == 0) {
295 while (!isspace(*p) && *p != '\0')
299 s->http_code = strtol(p, &end, 10);
301 av_dlog(NULL, "http_code=%d\n", s->http_code);
303 /* error codes are 4xx and 5xx, but regard 401 as a success, so we
304 * don't abort until all headers have been parsed. */
305 if (s->http_code >= 400 && s->http_code < 600 && (s->http_code != 401
306 || s->auth_state.auth_type != HTTP_AUTH_NONE) &&
307 (s->http_code != 407 || s->proxy_auth_state.auth_type != HTTP_AUTH_NONE)) {
308 end += strspn(end, SPACE_CHARS);
309 av_log(h, AV_LOG_WARNING, "HTTP error %d %s\n",
314 while (*p != '\0' && *p != ':')
324 if (!av_strcasecmp(tag, "Location")) {
325 av_strlcpy(s->location, p, sizeof(s->location));
327 } else if (!av_strcasecmp (tag, "Content-Length") && s->filesize == -1) {
328 s->filesize = strtoll(p, NULL, 10);
329 } else if (!av_strcasecmp (tag, "Content-Range")) {
330 /* "bytes $from-$to/$document_size" */
332 if (!strncmp (p, "bytes ", 6)) {
334 s->off = strtoll(p, NULL, 10);
335 if ((slash = strchr(p, '/')) && strlen(slash) > 0)
336 s->filesize = strtoll(slash+1, NULL, 10);
338 if (s->seekable == -1 && (!s->is_akamai || s->filesize != 2147483647))
339 h->is_streamed = 0; /* we _can_ in fact seek */
340 } else if (!av_strcasecmp(tag, "Accept-Ranges") && !strncmp(p, "bytes", 5) && s->seekable == -1) {
342 } else if (!av_strcasecmp (tag, "Transfer-Encoding") && !av_strncasecmp(p, "chunked", 7)) {
345 } else if (!av_strcasecmp (tag, "WWW-Authenticate")) {
346 ff_http_auth_handle_header(&s->auth_state, tag, p);
347 } else if (!av_strcasecmp (tag, "Authentication-Info")) {
348 ff_http_auth_handle_header(&s->auth_state, tag, p);
349 } else if (!av_strcasecmp (tag, "Proxy-Authenticate")) {
350 ff_http_auth_handle_header(&s->proxy_auth_state, tag, p);
351 } else if (!av_strcasecmp (tag, "Connection")) {
352 if (!strcmp(p, "close"))
354 } else if (!av_strcasecmp (tag, "Server") && !av_strcasecmp (p, "AkamaiGHost")) {
361 static inline int has_header(const char *str, const char *header)
363 /* header + 2 to skip over CRLF prefix. (make sure you have one!) */
366 return av_stristart(str, header + 2, NULL) || av_stristr(str, header);
369 static int http_read_header(URLContext *h, int *new_location)
371 HTTPContext *s = h->priv_data;
372 char line[MAX_URL_SIZE];
378 if ((err = http_get_line(s, line, sizeof(line))) < 0)
381 av_dlog(NULL, "header='%s'\n", line);
383 err = process_line(h, line, s->line_count, new_location);
394 static int http_connect(URLContext *h, const char *path, const char *local_path,
395 const char *hoststr, const char *auth,
396 const char *proxyauth, int *new_location)
398 HTTPContext *s = h->priv_data;
400 char headers[4096] = "";
401 char *authstr = NULL, *proxyauthstr = NULL;
402 int64_t off = s->off;
407 /* send http header */
408 post = h->flags & AVIO_FLAG_WRITE;
411 /* force POST method and disable chunked encoding when
412 * custom HTTP post data is set */
417 method = post ? "POST" : "GET";
418 authstr = ff_http_auth_create_response(&s->auth_state, auth, local_path,
420 proxyauthstr = ff_http_auth_create_response(&s->proxy_auth_state, proxyauth,
423 /* set default headers if needed */
424 if (!has_header(s->headers, "\r\nUser-Agent: "))
425 len += av_strlcatf(headers + len, sizeof(headers) - len,
426 "User-Agent: %s\r\n",
427 s->user_agent ? s->user_agent : LIBAVFORMAT_IDENT);
428 if (!has_header(s->headers, "\r\nAccept: "))
429 len += av_strlcpy(headers + len, "Accept: */*\r\n",
430 sizeof(headers) - len);
431 // Note: we send this on purpose even when s->off is 0 when we're probing,
432 // since it allows us to detect more reliably if a (non-conforming)
433 // server supports seeking by analysing the reply headers.
434 if (!has_header(s->headers, "\r\nRange: ") && !post && (s->off > 0 || s->seekable == -1))
435 len += av_strlcatf(headers + len, sizeof(headers) - len,
436 "Range: bytes=%"PRId64"-\r\n", s->off);
438 if (!has_header(s->headers, "\r\nConnection: ")) {
439 if (s->multiple_requests) {
440 len += av_strlcpy(headers + len, "Connection: keep-alive\r\n",
441 sizeof(headers) - len);
443 len += av_strlcpy(headers + len, "Connection: close\r\n",
444 sizeof(headers) - len);
448 if (!has_header(s->headers, "\r\nHost: "))
449 len += av_strlcatf(headers + len, sizeof(headers) - len,
450 "Host: %s\r\n", hoststr);
451 if (!has_header(s->headers, "\r\nContent-Length: ") && s->post_data)
452 len += av_strlcatf(headers + len, sizeof(headers) - len,
453 "Content-Length: %d\r\n", s->post_datalen);
455 /* now add in custom headers */
457 av_strlcpy(headers + len, s->headers, sizeof(headers) - len);
459 snprintf(s->buffer, sizeof(s->buffer),
468 post && s->chunked_post ? "Transfer-Encoding: chunked\r\n" : "",
470 authstr ? authstr : "",
471 proxyauthstr ? "Proxy-" : "", proxyauthstr ? proxyauthstr : "");
474 av_freep(&proxyauthstr);
475 if ((err = ffurl_write(s->hd, s->buffer, strlen(s->buffer))) < 0)
479 if ((err = ffurl_write(s->hd, s->post_data, s->post_datalen)) < 0)
482 /* init input buffer */
483 s->buf_ptr = s->buffer;
484 s->buf_end = s->buffer;
489 s->end_chunked_post = 0;
491 if (post && !s->post_data) {
492 /* Pretend that it did work. We didn't read any header yet, since
493 * we've still to send the POST data, but the code calling this
494 * function will check http_code after we return. */
499 /* wait for header */
500 err = http_read_header(h, new_location);
504 return (off == s->off) ? 0 : -1;
508 static int http_buf_read(URLContext *h, uint8_t *buf, int size)
510 HTTPContext *s = h->priv_data;
512 /* read bytes from input buffer first */
513 len = s->buf_end - s->buf_ptr;
517 memcpy(buf, s->buf_ptr, len);
520 if (!s->willclose && s->filesize >= 0 && s->off >= s->filesize)
522 len = ffurl_read(s->hd, buf, size);
526 if (s->chunksize > 0)
532 static int http_read(URLContext *h, uint8_t *buf, int size)
534 HTTPContext *s = h->priv_data;
535 int err, new_location;
540 if (s->end_chunked_post && !s->end_header) {
541 err = http_read_header(h, &new_location);
546 if (s->chunksize >= 0) {
552 if ((err = http_get_line(s, line, sizeof(line))) < 0)
554 } while (!*line); /* skip CR LF from last chunk */
556 s->chunksize = strtoll(line, NULL, 16);
558 av_dlog(NULL, "Chunked encoding data size: %"PRId64"'\n", s->chunksize);
565 size = FFMIN(size, s->chunksize);
567 return http_buf_read(h, buf, size);
570 /* used only when posting data */
571 static int http_write(URLContext *h, const uint8_t *buf, int size)
573 char temp[11] = ""; /* 32-bit hex + CRLF + nul */
575 char crlf[] = "\r\n";
576 HTTPContext *s = h->priv_data;
578 if (!s->chunked_post) {
579 /* non-chunked data is sent without any special encoding */
580 return ffurl_write(s->hd, buf, size);
583 /* silently ignore zero-size data since chunk encoding that would
586 /* upload data using chunked encoding */
587 snprintf(temp, sizeof(temp), "%x\r\n", size);
589 if ((ret = ffurl_write(s->hd, temp, strlen(temp))) < 0 ||
590 (ret = ffurl_write(s->hd, buf, size)) < 0 ||
591 (ret = ffurl_write(s->hd, crlf, sizeof(crlf) - 1)) < 0)
597 static int http_shutdown(URLContext *h, int flags)
600 char footer[] = "0\r\n\r\n";
601 HTTPContext *s = h->priv_data;
603 /* signal end of chunked encoding if used */
604 if ((flags & AVIO_FLAG_WRITE) && s->chunked_post) {
605 ret = ffurl_write(s->hd, footer, sizeof(footer) - 1);
606 ret = ret > 0 ? 0 : ret;
607 s->end_chunked_post = 1;
613 static int http_close(URLContext *h)
616 HTTPContext *s = h->priv_data;
618 if (!s->end_chunked_post) {
619 /* Close the write direction by sending the end of chunked encoding. */
620 ret = http_shutdown(h, h->flags);
624 ffurl_closep(&s->hd);
628 static int64_t http_seek(URLContext *h, int64_t off, int whence)
630 HTTPContext *s = h->priv_data;
631 URLContext *old_hd = s->hd;
632 int64_t old_off = s->off;
633 uint8_t old_buf[BUFFER_SIZE];
636 if (whence == AVSEEK_SIZE)
638 else if ((s->filesize == -1 && whence == SEEK_END) || h->is_streamed)
641 /* we save the old context in case the seek fails */
642 old_buf_size = s->buf_end - s->buf_ptr;
643 memcpy(old_buf, s->buf_ptr, old_buf_size);
645 if (whence == SEEK_CUR)
647 else if (whence == SEEK_END)
651 /* if it fails, continue on old connection */
652 if (http_open_cnx(h) < 0) {
653 memcpy(s->buffer, old_buf, old_buf_size);
654 s->buf_ptr = s->buffer;
655 s->buf_end = s->buffer + old_buf_size;
665 http_get_file_handle(URLContext *h)
667 HTTPContext *s = h->priv_data;
668 return ffurl_get_file_handle(s->hd);
671 #if CONFIG_HTTP_PROTOCOL
672 URLProtocol ff_http_protocol = {
674 .url_open = http_open,
675 .url_read = http_read,
676 .url_write = http_write,
677 .url_seek = http_seek,
678 .url_close = http_close,
679 .url_get_file_handle = http_get_file_handle,
680 .url_shutdown = http_shutdown,
681 .priv_data_size = sizeof(HTTPContext),
682 .priv_data_class = &http_context_class,
683 .flags = URL_PROTOCOL_FLAG_NETWORK,
686 #if CONFIG_HTTPS_PROTOCOL
687 URLProtocol ff_https_protocol = {
689 .url_open = http_open,
690 .url_read = http_read,
691 .url_write = http_write,
692 .url_seek = http_seek,
693 .url_close = http_close,
694 .url_get_file_handle = http_get_file_handle,
695 .url_shutdown = http_shutdown,
696 .priv_data_size = sizeof(HTTPContext),
697 .priv_data_class = &https_context_class,
698 .flags = URL_PROTOCOL_FLAG_NETWORK,
702 #if CONFIG_HTTPPROXY_PROTOCOL
703 static int http_proxy_close(URLContext *h)
705 HTTPContext *s = h->priv_data;
707 ffurl_closep(&s->hd);
711 static int http_proxy_open(URLContext *h, const char *uri, int flags)
713 HTTPContext *s = h->priv_data;
714 char hostname[1024], hoststr[1024];
715 char auth[1024], pathbuf[1024], *path;
717 int port, ret = 0, attempts = 0;
718 HTTPAuthType cur_auth_type;
721 AVDictionary *opts = NULL;
722 char opts_format[20];
724 if( s->seekable == 1 )
729 av_url_split(NULL, 0, auth, sizeof(auth), hostname, sizeof(hostname), &port,
730 pathbuf, sizeof(pathbuf), uri);
731 ff_url_join(hoststr, sizeof(hoststr), NULL, NULL, hostname, port, NULL);
736 ff_url_join(lower_url, sizeof(lower_url), "tcp", NULL, hostname, port,
739 if (s->rw_timeout != -1) {
740 snprintf(opts_format, sizeof(opts_format), "%d", s->rw_timeout);
741 av_dict_set(&opts, "timeout", opts_format, 0);
742 } /* if option is not given, don't pass it and let tcp use its own default */
743 ret = ffurl_open(&s->hd, lower_url, AVIO_FLAG_READ_WRITE,
744 &h->interrupt_callback, &opts);
749 authstr = ff_http_auth_create_response(&s->proxy_auth_state, auth,
751 snprintf(s->buffer, sizeof(s->buffer),
752 "CONNECT %s HTTP/1.1\r\n"
754 "Connection: close\r\n"
759 authstr ? "Proxy-" : "", authstr ? authstr : "");
762 if ((ret = ffurl_write(s->hd, s->buffer, strlen(s->buffer))) < 0)
765 s->buf_ptr = s->buffer;
766 s->buf_end = s->buffer;
769 cur_auth_type = s->proxy_auth_state.auth_type;
771 /* Note: This uses buffering, potentially reading more than the
772 * HTTP header. If tunneling a protocol where the server starts
773 * the conversation, we might buffer part of that here, too.
774 * Reading that requires using the proper ffurl_read() function
775 * on this URLContext, not using the fd directly (as the tls
776 * protocol does). This shouldn't be an issue for tls though,
777 * since the client starts the conversation there, so there
778 * is no extra data that we might buffer up here.
780 ret = http_read_header(h, &new_loc);
785 if (s->http_code == 407 &&
786 (cur_auth_type == HTTP_AUTH_NONE || s->proxy_auth_state.stale) &&
787 s->proxy_auth_state.auth_type != HTTP_AUTH_NONE && attempts < 2) {
788 ffurl_closep(&s->hd);
792 if (s->http_code < 400)
801 static int http_proxy_write(URLContext *h, const uint8_t *buf, int size)
803 HTTPContext *s = h->priv_data;
804 return ffurl_write(s->hd, buf, size);
807 URLProtocol ff_httpproxy_protocol = {
809 .url_open = http_proxy_open,
810 .url_read = http_buf_read,
811 .url_write = http_proxy_write,
812 .url_close = http_proxy_close,
813 .url_get_file_handle = http_get_file_handle,
814 .priv_data_size = sizeof(HTTPContext),
815 .flags = URL_PROTOCOL_FLAG_NETWORK,