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. */
51 int64_t off, filesize;
52 char location[MAX_URL_SIZE];
53 HTTPAuthState auth_state;
54 HTTPAuthState proxy_auth_state;
56 int willclose; /**< Set if the server correctly handles Connection: close and will close the connection after feeding us the content. */
57 int seekable; /**< Control seekability, 0 = disable, 1 = enable, -1 = probe. */
59 int end_chunked_post; /**< A flag which indicates if the end of chunked encoding has been sent. */
60 int end_header; /**< A flag which indicates we have finished to read POST reply. */
61 int multiple_requests; /**< A flag which indicates if we use persistent connections. */
69 #define OFFSET(x) offsetof(HTTPContext, x)
70 #define D AV_OPT_FLAG_DECODING_PARAM
71 #define E AV_OPT_FLAG_ENCODING_PARAM
72 #define DEC AV_OPT_FLAG_DECODING_PARAM
73 static const AVOption options[] = {
74 {"seekable", "Control seekability of connection", OFFSET(seekable), AV_OPT_TYPE_INT, {.i64 = -1}, -1, 1, D },
75 {"chunked_post", "use chunked transfer-encoding for posts", OFFSET(chunked_post), AV_OPT_TYPE_INT, {.i64 = 1}, 0, 1, E },
76 {"headers", "custom HTTP headers, can override built in default headers", OFFSET(headers), AV_OPT_TYPE_STRING, { 0 }, 0, 0, D|E },
77 {"content_type", "force a content type", OFFSET(content_type), AV_OPT_TYPE_STRING, { 0 }, 0, 0, D|E },
78 {"user-agent", "override User-Agent header", OFFSET(user_agent), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, DEC},
79 {"multiple_requests", "use persistent connections", OFFSET(multiple_requests), AV_OPT_TYPE_INT, {.i64 = 0}, 0, 1, D|E },
80 {"post_data", "custom HTTP post data", OFFSET(post_data), AV_OPT_TYPE_BINARY, .flags = D|E },
81 {"timeout", "timeout of socket i/o operations", OFFSET(rw_timeout), AV_OPT_TYPE_INT, {.i64 = -1}, -1, INT_MAX, D|E },
82 {"mime_type", "", OFFSET(mime_type), AV_OPT_TYPE_STRING, {0}, 0, 0, 0 },
85 #define HTTP_CLASS(flavor)\
86 static const AVClass flavor ## _context_class = {\
87 .class_name = #flavor,\
88 .item_name = av_default_item_name,\
90 .version = LIBAVUTIL_VERSION_INT,\
96 static int http_connect(URLContext *h, const char *path, const char *local_path,
97 const char *hoststr, const char *auth,
98 const char *proxyauth, int *new_location);
100 void ff_http_init_auth_state(URLContext *dest, const URLContext *src)
102 memcpy(&((HTTPContext*)dest->priv_data)->auth_state,
103 &((HTTPContext*)src->priv_data)->auth_state, sizeof(HTTPAuthState));
104 memcpy(&((HTTPContext*)dest->priv_data)->proxy_auth_state,
105 &((HTTPContext*)src->priv_data)->proxy_auth_state,
106 sizeof(HTTPAuthState));
109 /* return non zero if error */
110 static int http_open_cnx(URLContext *h)
112 const char *path, *proxy_path, *lower_proto = "tcp", *local_path;
113 char hostname[1024], hoststr[1024], proto[10];
114 char auth[1024], proxyauth[1024] = "";
115 char path1[MAX_URL_SIZE];
116 char buf[1024], urlbuf[MAX_URL_SIZE];
117 int port, use_proxy, err, location_changed = 0, redirects = 0, attempts = 0;
118 HTTPAuthType cur_auth_type, cur_proxy_auth_type;
119 HTTPContext *s = h->priv_data;
121 proxy_path = getenv("http_proxy");
122 use_proxy = (proxy_path != NULL) && !getenv("no_proxy") &&
123 av_strstart(proxy_path, "http://", NULL);
125 /* fill the dest addr */
127 /* needed in any case to build the host string */
128 av_url_split(proto, sizeof(proto), auth, sizeof(auth),
129 hostname, sizeof(hostname), &port,
130 path1, sizeof(path1), s->location);
131 ff_url_join(hoststr, sizeof(hoststr), NULL, NULL, hostname, port, NULL);
133 if (!strcmp(proto, "https")) {
142 if (path1[0] == '\0')
148 /* Reassemble the request URL without auth string - we don't
149 * want to leak the auth to the proxy. */
150 ff_url_join(urlbuf, sizeof(urlbuf), proto, NULL, hostname, port, "%s",
153 av_url_split(NULL, 0, proxyauth, sizeof(proxyauth),
154 hostname, sizeof(hostname), &port, NULL, 0, proxy_path);
157 ff_url_join(buf, sizeof(buf), lower_proto, NULL, hostname, port, NULL);
160 AVDictionary *opts = NULL;
161 char opts_format[20];
162 if (s->rw_timeout != -1) {
163 snprintf(opts_format, sizeof(opts_format), "%d", s->rw_timeout);
164 av_dict_set(&opts, "timeout", opts_format, 0);
165 } /* if option is not given, don't pass it and let tcp use its own default */
166 err = ffurl_open(&s->hd, buf, AVIO_FLAG_READ_WRITE,
167 &h->interrupt_callback, &opts);
173 cur_auth_type = s->auth_state.auth_type;
174 cur_proxy_auth_type = s->auth_state.auth_type;
175 if (http_connect(h, path, local_path, hoststr, auth, proxyauth, &location_changed) < 0)
178 if (s->http_code == 401) {
179 if ((cur_auth_type == HTTP_AUTH_NONE || s->auth_state.stale) &&
180 s->auth_state.auth_type != HTTP_AUTH_NONE && attempts < 4) {
181 ffurl_closep(&s->hd);
186 if (s->http_code == 407) {
187 if ((cur_proxy_auth_type == HTTP_AUTH_NONE || s->proxy_auth_state.stale) &&
188 s->proxy_auth_state.auth_type != HTTP_AUTH_NONE && attempts < 4) {
189 ffurl_closep(&s->hd);
194 if ((s->http_code == 301 || s->http_code == 302 || s->http_code == 303 || s->http_code == 307)
195 && location_changed == 1) {
196 /* url moved, get next */
197 ffurl_closep(&s->hd);
198 if (redirects++ >= MAX_REDIRECTS)
200 /* Restart the authentication process with the new target, which
201 * might use a different auth mechanism. */
202 memset(&s->auth_state, 0, sizeof(s->auth_state));
204 location_changed = 0;
210 ffurl_closep(&s->hd);
214 int ff_http_do_new_request(URLContext *h, const char *uri)
216 HTTPContext *s = h->priv_data;
219 av_strlcpy(s->location, uri, sizeof(s->location));
221 return http_open_cnx(h);
224 static int http_open(URLContext *h, const char *uri, int flags)
226 HTTPContext *s = h->priv_data;
228 if( s->seekable == 1 )
234 av_strlcpy(s->location, uri, sizeof(s->location));
237 int len = strlen(s->headers);
238 if (len < 2 || strcmp("\r\n", s->headers + len - 2))
239 av_log(h, AV_LOG_WARNING, "No trailing CRLF found in HTTP header.\n");
242 return http_open_cnx(h);
244 static int http_getc(HTTPContext *s)
247 if (s->buf_ptr >= s->buf_end) {
248 len = ffurl_read(s->hd, s->buffer, BUFFER_SIZE);
251 } else if (len == 0) {
254 s->buf_ptr = s->buffer;
255 s->buf_end = s->buffer + len;
258 return *s->buf_ptr++;
261 static int http_get_line(HTTPContext *s, char *line, int line_size)
273 if (q > line && q[-1] == '\r')
279 if ((q - line) < line_size - 1)
285 static int process_line(URLContext *h, char *line, int line_count,
288 HTTPContext *s = h->priv_data;
292 if (line[0] == '\0') {
298 if (line_count == 0) {
299 while (!isspace(*p) && *p != '\0')
303 s->http_code = strtol(p, &end, 10);
305 av_dlog(NULL, "http_code=%d\n", s->http_code);
307 /* error codes are 4xx and 5xx, but regard 401 as a success, so we
308 * don't abort until all headers have been parsed. */
309 if (s->http_code >= 400 && s->http_code < 600 && (s->http_code != 401
310 || s->auth_state.auth_type != HTTP_AUTH_NONE) &&
311 (s->http_code != 407 || s->proxy_auth_state.auth_type != HTTP_AUTH_NONE)) {
312 end += strspn(end, SPACE_CHARS);
313 av_log(h, AV_LOG_WARNING, "HTTP error %d %s\n",
318 while (*p != '\0' && *p != ':')
328 if (!av_strcasecmp(tag, "Location")) {
329 av_strlcpy(s->location, p, sizeof(s->location));
331 } else if (!av_strcasecmp (tag, "Content-Length") && s->filesize == -1) {
332 s->filesize = strtoll(p, NULL, 10);
333 } else if (!av_strcasecmp (tag, "Content-Range")) {
334 /* "bytes $from-$to/$document_size" */
336 if (!strncmp (p, "bytes ", 6)) {
338 s->off = strtoll(p, NULL, 10);
339 if ((slash = strchr(p, '/')) && strlen(slash) > 0)
340 s->filesize = strtoll(slash+1, NULL, 10);
342 if (s->seekable == -1 && (!s->is_akamai || s->filesize != 2147483647))
343 h->is_streamed = 0; /* we _can_ in fact seek */
344 } else if (!av_strcasecmp(tag, "Accept-Ranges") && !strncmp(p, "bytes", 5) && s->seekable == -1) {
346 } else if (!av_strcasecmp (tag, "Transfer-Encoding") && !av_strncasecmp(p, "chunked", 7)) {
349 } else if (!av_strcasecmp (tag, "WWW-Authenticate")) {
350 ff_http_auth_handle_header(&s->auth_state, tag, p);
351 } else if (!av_strcasecmp (tag, "Authentication-Info")) {
352 ff_http_auth_handle_header(&s->auth_state, tag, p);
353 } else if (!av_strcasecmp (tag, "Proxy-Authenticate")) {
354 ff_http_auth_handle_header(&s->proxy_auth_state, tag, p);
355 } else if (!av_strcasecmp (tag, "Connection")) {
356 if (!strcmp(p, "close"))
358 } else if (!av_strcasecmp (tag, "Server") && !av_strcasecmp (p, "AkamaiGHost")) {
360 } else if (!av_strcasecmp (tag, "Content-Type")) {
361 av_free(s->mime_type); s->mime_type = av_strdup(p);
367 static inline int has_header(const char *str, const char *header)
369 /* header + 2 to skip over CRLF prefix. (make sure you have one!) */
372 return av_stristart(str, header + 2, NULL) || av_stristr(str, header);
375 static int http_read_header(URLContext *h, int *new_location)
377 HTTPContext *s = h->priv_data;
378 char line[MAX_URL_SIZE];
384 if ((err = http_get_line(s, line, sizeof(line))) < 0)
387 av_dlog(NULL, "header='%s'\n", line);
389 err = process_line(h, line, s->line_count, new_location);
400 static int http_connect(URLContext *h, const char *path, const char *local_path,
401 const char *hoststr, const char *auth,
402 const char *proxyauth, int *new_location)
404 HTTPContext *s = h->priv_data;
406 char headers[4096] = "";
407 char *authstr = NULL, *proxyauthstr = NULL;
408 int64_t off = s->off;
413 /* send http header */
414 post = h->flags & AVIO_FLAG_WRITE;
417 /* force POST method and disable chunked encoding when
418 * custom HTTP post data is set */
423 method = post ? "POST" : "GET";
424 authstr = ff_http_auth_create_response(&s->auth_state, auth, local_path,
426 proxyauthstr = ff_http_auth_create_response(&s->proxy_auth_state, proxyauth,
429 /* set default headers if needed */
430 if (!has_header(s->headers, "\r\nUser-Agent: "))
431 len += av_strlcatf(headers + len, sizeof(headers) - len,
432 "User-Agent: %s\r\n",
433 s->user_agent ? s->user_agent : LIBAVFORMAT_IDENT);
434 if (!has_header(s->headers, "\r\nAccept: "))
435 len += av_strlcpy(headers + len, "Accept: */*\r\n",
436 sizeof(headers) - len);
437 // Note: we send this on purpose even when s->off is 0 when we're probing,
438 // since it allows us to detect more reliably if a (non-conforming)
439 // server supports seeking by analysing the reply headers.
440 if (!has_header(s->headers, "\r\nRange: ") && !post && (s->off > 0 || s->seekable == -1))
441 len += av_strlcatf(headers + len, sizeof(headers) - len,
442 "Range: bytes=%"PRId64"-\r\n", s->off);
444 if (!has_header(s->headers, "\r\nConnection: ")) {
445 if (s->multiple_requests) {
446 len += av_strlcpy(headers + len, "Connection: keep-alive\r\n",
447 sizeof(headers) - len);
449 len += av_strlcpy(headers + len, "Connection: close\r\n",
450 sizeof(headers) - len);
454 if (!has_header(s->headers, "\r\nHost: "))
455 len += av_strlcatf(headers + len, sizeof(headers) - len,
456 "Host: %s\r\n", hoststr);
457 if (!has_header(s->headers, "\r\nContent-Length: ") && s->post_data)
458 len += av_strlcatf(headers + len, sizeof(headers) - len,
459 "Content-Length: %d\r\n", s->post_datalen);
460 if (!has_header(s->headers, "\r\nContent-Type: ") && s->content_type)
461 len += av_strlcatf(headers + len, sizeof(headers) - len,
462 "Content-Type: %s\r\n", s->content_type);
464 /* now add in custom headers */
466 av_strlcpy(headers + len, s->headers, sizeof(headers) - len);
468 snprintf(s->buffer, sizeof(s->buffer),
477 post && s->chunked_post ? "Transfer-Encoding: chunked\r\n" : "",
479 authstr ? authstr : "",
480 proxyauthstr ? "Proxy-" : "", proxyauthstr ? proxyauthstr : "");
483 av_freep(&proxyauthstr);
484 if ((err = ffurl_write(s->hd, s->buffer, strlen(s->buffer))) < 0)
488 if ((err = ffurl_write(s->hd, s->post_data, s->post_datalen)) < 0)
491 /* init input buffer */
492 s->buf_ptr = s->buffer;
493 s->buf_end = s->buffer;
498 s->end_chunked_post = 0;
500 if (post && !s->post_data) {
501 /* Pretend that it did work. We didn't read any header yet, since
502 * we've still to send the POST data, but the code calling this
503 * function will check http_code after we return. */
508 /* wait for header */
509 err = http_read_header(h, new_location);
513 return (off == s->off) ? 0 : -1;
517 static int http_buf_read(URLContext *h, uint8_t *buf, int size)
519 HTTPContext *s = h->priv_data;
521 /* read bytes from input buffer first */
522 len = s->buf_end - s->buf_ptr;
526 memcpy(buf, s->buf_ptr, len);
529 if (!s->willclose && s->filesize >= 0 && s->off >= s->filesize)
531 len = ffurl_read(s->hd, buf, size);
535 if (s->chunksize > 0)
541 static int http_read(URLContext *h, uint8_t *buf, int size)
543 HTTPContext *s = h->priv_data;
544 int err, new_location;
549 if (s->end_chunked_post && !s->end_header) {
550 err = http_read_header(h, &new_location);
555 if (s->chunksize >= 0) {
561 if ((err = http_get_line(s, line, sizeof(line))) < 0)
563 } while (!*line); /* skip CR LF from last chunk */
565 s->chunksize = strtoll(line, NULL, 16);
567 av_dlog(NULL, "Chunked encoding data size: %"PRId64"'\n", s->chunksize);
574 size = FFMIN(size, s->chunksize);
576 return http_buf_read(h, buf, size);
579 /* used only when posting data */
580 static int http_write(URLContext *h, const uint8_t *buf, int size)
582 char temp[11] = ""; /* 32-bit hex + CRLF + nul */
584 char crlf[] = "\r\n";
585 HTTPContext *s = h->priv_data;
587 if (!s->chunked_post) {
588 /* non-chunked data is sent without any special encoding */
589 return ffurl_write(s->hd, buf, size);
592 /* silently ignore zero-size data since chunk encoding that would
595 /* upload data using chunked encoding */
596 snprintf(temp, sizeof(temp), "%x\r\n", size);
598 if ((ret = ffurl_write(s->hd, temp, strlen(temp))) < 0 ||
599 (ret = ffurl_write(s->hd, buf, size)) < 0 ||
600 (ret = ffurl_write(s->hd, crlf, sizeof(crlf) - 1)) < 0)
606 static int http_shutdown(URLContext *h, int flags)
609 char footer[] = "0\r\n\r\n";
610 HTTPContext *s = h->priv_data;
612 /* signal end of chunked encoding if used */
613 if ((flags & AVIO_FLAG_WRITE) && s->chunked_post) {
614 ret = ffurl_write(s->hd, footer, sizeof(footer) - 1);
615 ret = ret > 0 ? 0 : ret;
616 s->end_chunked_post = 1;
622 static int http_close(URLContext *h)
625 HTTPContext *s = h->priv_data;
627 if (!s->end_chunked_post) {
628 /* Close the write direction by sending the end of chunked encoding. */
629 ret = http_shutdown(h, h->flags);
633 ffurl_closep(&s->hd);
637 static int64_t http_seek(URLContext *h, int64_t off, int whence)
639 HTTPContext *s = h->priv_data;
640 URLContext *old_hd = s->hd;
641 int64_t old_off = s->off;
642 uint8_t old_buf[BUFFER_SIZE];
645 if (whence == AVSEEK_SIZE)
647 else if ((s->filesize == -1 && whence == SEEK_END) || h->is_streamed)
650 /* we save the old context in case the seek fails */
651 old_buf_size = s->buf_end - s->buf_ptr;
652 memcpy(old_buf, s->buf_ptr, old_buf_size);
654 if (whence == SEEK_CUR)
656 else if (whence == SEEK_END)
660 /* if it fails, continue on old connection */
661 if (http_open_cnx(h) < 0) {
662 memcpy(s->buffer, old_buf, old_buf_size);
663 s->buf_ptr = s->buffer;
664 s->buf_end = s->buffer + old_buf_size;
674 http_get_file_handle(URLContext *h)
676 HTTPContext *s = h->priv_data;
677 return ffurl_get_file_handle(s->hd);
680 #if CONFIG_HTTP_PROTOCOL
681 URLProtocol ff_http_protocol = {
683 .url_open = http_open,
684 .url_read = http_read,
685 .url_write = http_write,
686 .url_seek = http_seek,
687 .url_close = http_close,
688 .url_get_file_handle = http_get_file_handle,
689 .url_shutdown = http_shutdown,
690 .priv_data_size = sizeof(HTTPContext),
691 .priv_data_class = &http_context_class,
692 .flags = URL_PROTOCOL_FLAG_NETWORK,
695 #if CONFIG_HTTPS_PROTOCOL
696 URLProtocol ff_https_protocol = {
698 .url_open = http_open,
699 .url_read = http_read,
700 .url_write = http_write,
701 .url_seek = http_seek,
702 .url_close = http_close,
703 .url_get_file_handle = http_get_file_handle,
704 .url_shutdown = http_shutdown,
705 .priv_data_size = sizeof(HTTPContext),
706 .priv_data_class = &https_context_class,
707 .flags = URL_PROTOCOL_FLAG_NETWORK,
711 #if CONFIG_HTTPPROXY_PROTOCOL
712 static int http_proxy_close(URLContext *h)
714 HTTPContext *s = h->priv_data;
716 ffurl_closep(&s->hd);
720 static int http_proxy_open(URLContext *h, const char *uri, int flags)
722 HTTPContext *s = h->priv_data;
723 char hostname[1024], hoststr[1024];
724 char auth[1024], pathbuf[1024], *path;
726 int port, ret = 0, attempts = 0;
727 HTTPAuthType cur_auth_type;
730 AVDictionary *opts = NULL;
731 char opts_format[20];
733 if( s->seekable == 1 )
738 av_url_split(NULL, 0, auth, sizeof(auth), hostname, sizeof(hostname), &port,
739 pathbuf, sizeof(pathbuf), uri);
740 ff_url_join(hoststr, sizeof(hoststr), NULL, NULL, hostname, port, NULL);
745 ff_url_join(lower_url, sizeof(lower_url), "tcp", NULL, hostname, port,
748 if (s->rw_timeout != -1) {
749 snprintf(opts_format, sizeof(opts_format), "%d", s->rw_timeout);
750 av_dict_set(&opts, "timeout", opts_format, 0);
751 } /* if option is not given, don't pass it and let tcp use its own default */
752 ret = ffurl_open(&s->hd, lower_url, AVIO_FLAG_READ_WRITE,
753 &h->interrupt_callback, &opts);
758 authstr = ff_http_auth_create_response(&s->proxy_auth_state, auth,
760 snprintf(s->buffer, sizeof(s->buffer),
761 "CONNECT %s HTTP/1.1\r\n"
763 "Connection: close\r\n"
768 authstr ? "Proxy-" : "", authstr ? authstr : "");
771 if ((ret = ffurl_write(s->hd, s->buffer, strlen(s->buffer))) < 0)
774 s->buf_ptr = s->buffer;
775 s->buf_end = s->buffer;
778 cur_auth_type = s->proxy_auth_state.auth_type;
780 /* Note: This uses buffering, potentially reading more than the
781 * HTTP header. If tunneling a protocol where the server starts
782 * the conversation, we might buffer part of that here, too.
783 * Reading that requires using the proper ffurl_read() function
784 * on this URLContext, not using the fd directly (as the tls
785 * protocol does). This shouldn't be an issue for tls though,
786 * since the client starts the conversation there, so there
787 * is no extra data that we might buffer up here.
789 ret = http_read_header(h, &new_loc);
794 if (s->http_code == 407 &&
795 (cur_auth_type == HTTP_AUTH_NONE || s->proxy_auth_state.stale) &&
796 s->proxy_auth_state.auth_type != HTTP_AUTH_NONE && attempts < 2) {
797 ffurl_closep(&s->hd);
801 if (s->http_code < 400)
810 static int http_proxy_write(URLContext *h, const uint8_t *buf, int size)
812 HTTPContext *s = h->priv_data;
813 return ffurl_write(s->hd, buf, size);
816 URLProtocol ff_httpproxy_protocol = {
818 .url_open = http_proxy_open,
819 .url_read = http_buf_read,
820 .url_write = http_proxy_write,
821 .url_close = http_proxy_close,
822 .url_get_file_handle = http_get_file_handle,
823 .priv_data_size = sizeof(HTTPContext),
824 .flags = URL_PROTOCOL_FLAG_NETWORK,