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. */
68 #define OFFSET(x) offsetof(HTTPContext, x)
69 #define D AV_OPT_FLAG_DECODING_PARAM
70 #define E AV_OPT_FLAG_ENCODING_PARAM
71 #define DEC AV_OPT_FLAG_DECODING_PARAM
72 static const AVOption options[] = {
73 {"seekable", "Control seekability of connection", OFFSET(seekable), AV_OPT_TYPE_INT, {.i64 = -1}, -1, 1, D },
74 {"chunked_post", "use chunked transfer-encoding for posts", OFFSET(chunked_post), AV_OPT_TYPE_INT, {.i64 = 1}, 0, 1, E },
75 {"headers", "custom HTTP headers, can override built in default headers", OFFSET(headers), AV_OPT_TYPE_STRING, { 0 }, 0, 0, D|E },
76 {"content_type", "force a content type", OFFSET(content_type), AV_OPT_TYPE_STRING, { 0 }, 0, 0, D|E },
77 {"user-agent", "override User-Agent header", OFFSET(user_agent), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, DEC},
78 {"multiple_requests", "use persistent connections", OFFSET(multiple_requests), AV_OPT_TYPE_INT, {.i64 = 0}, 0, 1, D|E },
79 {"post_data", "custom HTTP post data", OFFSET(post_data), AV_OPT_TYPE_BINARY, .flags = D|E },
80 {"timeout", "timeout of socket i/o operations", OFFSET(rw_timeout), AV_OPT_TYPE_INT, {.i64 = -1}, -1, INT_MAX, D|E },
83 #define HTTP_CLASS(flavor)\
84 static const AVClass flavor ## _context_class = {\
85 .class_name = #flavor,\
86 .item_name = av_default_item_name,\
88 .version = LIBAVUTIL_VERSION_INT,\
94 static int http_connect(URLContext *h, const char *path, const char *local_path,
95 const char *hoststr, const char *auth,
96 const char *proxyauth, int *new_location);
98 void ff_http_init_auth_state(URLContext *dest, const URLContext *src)
100 memcpy(&((HTTPContext*)dest->priv_data)->auth_state,
101 &((HTTPContext*)src->priv_data)->auth_state, sizeof(HTTPAuthState));
102 memcpy(&((HTTPContext*)dest->priv_data)->proxy_auth_state,
103 &((HTTPContext*)src->priv_data)->proxy_auth_state,
104 sizeof(HTTPAuthState));
107 /* return non zero if error */
108 static int http_open_cnx(URLContext *h)
110 const char *path, *proxy_path, *lower_proto = "tcp", *local_path;
111 char hostname[1024], hoststr[1024], proto[10];
112 char auth[1024], proxyauth[1024] = "";
113 char path1[MAX_URL_SIZE];
114 char buf[1024], urlbuf[MAX_URL_SIZE];
115 int port, use_proxy, err, location_changed = 0, redirects = 0, attempts = 0;
116 HTTPAuthType cur_auth_type, cur_proxy_auth_type;
117 HTTPContext *s = h->priv_data;
119 proxy_path = getenv("http_proxy");
120 use_proxy = (proxy_path != NULL) && !getenv("no_proxy") &&
121 av_strstart(proxy_path, "http://", NULL);
123 /* fill the dest addr */
125 /* needed in any case to build the host string */
126 av_url_split(proto, sizeof(proto), auth, sizeof(auth),
127 hostname, sizeof(hostname), &port,
128 path1, sizeof(path1), s->location);
129 ff_url_join(hoststr, sizeof(hoststr), NULL, NULL, hostname, port, NULL);
131 if (!strcmp(proto, "https")) {
140 if (path1[0] == '\0')
146 /* Reassemble the request URL without auth string - we don't
147 * want to leak the auth to the proxy. */
148 ff_url_join(urlbuf, sizeof(urlbuf), proto, NULL, hostname, port, "%s",
151 av_url_split(NULL, 0, proxyauth, sizeof(proxyauth),
152 hostname, sizeof(hostname), &port, NULL, 0, proxy_path);
155 ff_url_join(buf, sizeof(buf), lower_proto, NULL, hostname, port, NULL);
158 AVDictionary *opts = NULL;
159 char opts_format[20];
160 if (s->rw_timeout != -1) {
161 snprintf(opts_format, sizeof(opts_format), "%d", s->rw_timeout);
162 av_dict_set(&opts, "timeout", opts_format, 0);
163 } /* if option is not given, don't pass it and let tcp use its own default */
164 err = ffurl_open(&s->hd, buf, AVIO_FLAG_READ_WRITE,
165 &h->interrupt_callback, &opts);
171 cur_auth_type = s->auth_state.auth_type;
172 cur_proxy_auth_type = s->auth_state.auth_type;
173 if (http_connect(h, path, local_path, hoststr, auth, proxyauth, &location_changed) < 0)
176 if (s->http_code == 401) {
177 if ((cur_auth_type == HTTP_AUTH_NONE || s->auth_state.stale) &&
178 s->auth_state.auth_type != HTTP_AUTH_NONE && attempts < 4) {
179 ffurl_closep(&s->hd);
184 if (s->http_code == 407) {
185 if ((cur_proxy_auth_type == HTTP_AUTH_NONE || s->proxy_auth_state.stale) &&
186 s->proxy_auth_state.auth_type != HTTP_AUTH_NONE && attempts < 4) {
187 ffurl_closep(&s->hd);
192 if ((s->http_code == 301 || s->http_code == 302 || s->http_code == 303 || s->http_code == 307)
193 && location_changed == 1) {
194 /* url moved, get next */
195 ffurl_closep(&s->hd);
196 if (redirects++ >= MAX_REDIRECTS)
198 /* Restart the authentication process with the new target, which
199 * might use a different auth mechanism. */
200 memset(&s->auth_state, 0, sizeof(s->auth_state));
202 location_changed = 0;
208 ffurl_closep(&s->hd);
212 int ff_http_do_new_request(URLContext *h, const char *uri)
214 HTTPContext *s = h->priv_data;
217 av_strlcpy(s->location, uri, sizeof(s->location));
219 return http_open_cnx(h);
222 static int http_open(URLContext *h, const char *uri, int flags)
224 HTTPContext *s = h->priv_data;
226 if( s->seekable == 1 )
232 av_strlcpy(s->location, uri, sizeof(s->location));
235 int len = strlen(s->headers);
236 if (len < 2 || strcmp("\r\n", s->headers + len - 2))
237 av_log(h, AV_LOG_WARNING, "No trailing CRLF found in HTTP header.\n");
240 return http_open_cnx(h);
242 static int http_getc(HTTPContext *s)
245 if (s->buf_ptr >= s->buf_end) {
246 len = ffurl_read(s->hd, s->buffer, BUFFER_SIZE);
249 } else if (len == 0) {
252 s->buf_ptr = s->buffer;
253 s->buf_end = s->buffer + len;
256 return *s->buf_ptr++;
259 static int http_get_line(HTTPContext *s, char *line, int line_size)
271 if (q > line && q[-1] == '\r')
277 if ((q - line) < line_size - 1)
283 static int process_line(URLContext *h, char *line, int line_count,
286 HTTPContext *s = h->priv_data;
290 if (line[0] == '\0') {
296 if (line_count == 0) {
297 while (!isspace(*p) && *p != '\0')
301 s->http_code = strtol(p, &end, 10);
303 av_dlog(NULL, "http_code=%d\n", s->http_code);
305 /* error codes are 4xx and 5xx, but regard 401 as a success, so we
306 * don't abort until all headers have been parsed. */
307 if (s->http_code >= 400 && s->http_code < 600 && (s->http_code != 401
308 || s->auth_state.auth_type != HTTP_AUTH_NONE) &&
309 (s->http_code != 407 || s->proxy_auth_state.auth_type != HTTP_AUTH_NONE)) {
310 end += strspn(end, SPACE_CHARS);
311 av_log(h, AV_LOG_WARNING, "HTTP error %d %s\n",
316 while (*p != '\0' && *p != ':')
326 if (!av_strcasecmp(tag, "Location")) {
327 av_strlcpy(s->location, p, sizeof(s->location));
329 } else if (!av_strcasecmp (tag, "Content-Length") && s->filesize == -1) {
330 s->filesize = strtoll(p, NULL, 10);
331 } else if (!av_strcasecmp (tag, "Content-Range")) {
332 /* "bytes $from-$to/$document_size" */
334 if (!strncmp (p, "bytes ", 6)) {
336 s->off = strtoll(p, NULL, 10);
337 if ((slash = strchr(p, '/')) && strlen(slash) > 0)
338 s->filesize = strtoll(slash+1, NULL, 10);
340 if (s->seekable == -1 && (!s->is_akamai || s->filesize != 2147483647))
341 h->is_streamed = 0; /* we _can_ in fact seek */
342 } else if (!av_strcasecmp(tag, "Accept-Ranges") && !strncmp(p, "bytes", 5) && s->seekable == -1) {
344 } else if (!av_strcasecmp (tag, "Transfer-Encoding") && !av_strncasecmp(p, "chunked", 7)) {
347 } else if (!av_strcasecmp (tag, "WWW-Authenticate")) {
348 ff_http_auth_handle_header(&s->auth_state, tag, p);
349 } else if (!av_strcasecmp (tag, "Authentication-Info")) {
350 ff_http_auth_handle_header(&s->auth_state, tag, p);
351 } else if (!av_strcasecmp (tag, "Proxy-Authenticate")) {
352 ff_http_auth_handle_header(&s->proxy_auth_state, tag, p);
353 } else if (!av_strcasecmp (tag, "Connection")) {
354 if (!strcmp(p, "close"))
356 } else if (!av_strcasecmp (tag, "Server") && !av_strcasecmp (p, "AkamaiGHost")) {
363 static inline int has_header(const char *str, const char *header)
365 /* header + 2 to skip over CRLF prefix. (make sure you have one!) */
368 return av_stristart(str, header + 2, NULL) || av_stristr(str, header);
371 static int http_read_header(URLContext *h, int *new_location)
373 HTTPContext *s = h->priv_data;
374 char line[MAX_URL_SIZE];
380 if ((err = http_get_line(s, line, sizeof(line))) < 0)
383 av_dlog(NULL, "header='%s'\n", line);
385 err = process_line(h, line, s->line_count, new_location);
396 static int http_connect(URLContext *h, const char *path, const char *local_path,
397 const char *hoststr, const char *auth,
398 const char *proxyauth, int *new_location)
400 HTTPContext *s = h->priv_data;
402 char headers[4096] = "";
403 char *authstr = NULL, *proxyauthstr = NULL;
404 int64_t off = s->off;
409 /* send http header */
410 post = h->flags & AVIO_FLAG_WRITE;
413 /* force POST method and disable chunked encoding when
414 * custom HTTP post data is set */
419 method = post ? "POST" : "GET";
420 authstr = ff_http_auth_create_response(&s->auth_state, auth, local_path,
422 proxyauthstr = ff_http_auth_create_response(&s->proxy_auth_state, proxyauth,
425 /* set default headers if needed */
426 if (!has_header(s->headers, "\r\nUser-Agent: "))
427 len += av_strlcatf(headers + len, sizeof(headers) - len,
428 "User-Agent: %s\r\n",
429 s->user_agent ? s->user_agent : LIBAVFORMAT_IDENT);
430 if (!has_header(s->headers, "\r\nAccept: "))
431 len += av_strlcpy(headers + len, "Accept: */*\r\n",
432 sizeof(headers) - len);
433 // Note: we send this on purpose even when s->off is 0 when we're probing,
434 // since it allows us to detect more reliably if a (non-conforming)
435 // server supports seeking by analysing the reply headers.
436 if (!has_header(s->headers, "\r\nRange: ") && !post && (s->off > 0 || s->seekable == -1))
437 len += av_strlcatf(headers + len, sizeof(headers) - len,
438 "Range: bytes=%"PRId64"-\r\n", s->off);
440 if (!has_header(s->headers, "\r\nConnection: ")) {
441 if (s->multiple_requests) {
442 len += av_strlcpy(headers + len, "Connection: keep-alive\r\n",
443 sizeof(headers) - len);
445 len += av_strlcpy(headers + len, "Connection: close\r\n",
446 sizeof(headers) - len);
450 if (!has_header(s->headers, "\r\nHost: "))
451 len += av_strlcatf(headers + len, sizeof(headers) - len,
452 "Host: %s\r\n", hoststr);
453 if (!has_header(s->headers, "\r\nContent-Length: ") && s->post_data)
454 len += av_strlcatf(headers + len, sizeof(headers) - len,
455 "Content-Length: %d\r\n", s->post_datalen);
456 if (!has_header(s->headers, "\r\nContent-Type: ") && s->content_type)
457 len += av_strlcatf(headers + len, sizeof(headers) - len,
458 "Content-Type: %s\r\n", s->content_type);
460 /* now add in custom headers */
462 av_strlcpy(headers + len, s->headers, sizeof(headers) - len);
464 snprintf(s->buffer, sizeof(s->buffer),
473 post && s->chunked_post ? "Transfer-Encoding: chunked\r\n" : "",
475 authstr ? authstr : "",
476 proxyauthstr ? "Proxy-" : "", proxyauthstr ? proxyauthstr : "");
479 av_freep(&proxyauthstr);
480 if ((err = ffurl_write(s->hd, s->buffer, strlen(s->buffer))) < 0)
484 if ((err = ffurl_write(s->hd, s->post_data, s->post_datalen)) < 0)
487 /* init input buffer */
488 s->buf_ptr = s->buffer;
489 s->buf_end = s->buffer;
494 s->end_chunked_post = 0;
496 if (post && !s->post_data) {
497 /* Pretend that it did work. We didn't read any header yet, since
498 * we've still to send the POST data, but the code calling this
499 * function will check http_code after we return. */
504 /* wait for header */
505 err = http_read_header(h, new_location);
509 return (off == s->off) ? 0 : -1;
513 static int http_buf_read(URLContext *h, uint8_t *buf, int size)
515 HTTPContext *s = h->priv_data;
517 /* read bytes from input buffer first */
518 len = s->buf_end - s->buf_ptr;
522 memcpy(buf, s->buf_ptr, len);
525 if (!s->willclose && s->filesize >= 0 && s->off >= s->filesize)
527 len = ffurl_read(s->hd, buf, size);
531 if (s->chunksize > 0)
537 static int http_read(URLContext *h, uint8_t *buf, int size)
539 HTTPContext *s = h->priv_data;
540 int err, new_location;
545 if (s->end_chunked_post && !s->end_header) {
546 err = http_read_header(h, &new_location);
551 if (s->chunksize >= 0) {
557 if ((err = http_get_line(s, line, sizeof(line))) < 0)
559 } while (!*line); /* skip CR LF from last chunk */
561 s->chunksize = strtoll(line, NULL, 16);
563 av_dlog(NULL, "Chunked encoding data size: %"PRId64"'\n", s->chunksize);
570 size = FFMIN(size, s->chunksize);
572 return http_buf_read(h, buf, size);
575 /* used only when posting data */
576 static int http_write(URLContext *h, const uint8_t *buf, int size)
578 char temp[11] = ""; /* 32-bit hex + CRLF + nul */
580 char crlf[] = "\r\n";
581 HTTPContext *s = h->priv_data;
583 if (!s->chunked_post) {
584 /* non-chunked data is sent without any special encoding */
585 return ffurl_write(s->hd, buf, size);
588 /* silently ignore zero-size data since chunk encoding that would
591 /* upload data using chunked encoding */
592 snprintf(temp, sizeof(temp), "%x\r\n", size);
594 if ((ret = ffurl_write(s->hd, temp, strlen(temp))) < 0 ||
595 (ret = ffurl_write(s->hd, buf, size)) < 0 ||
596 (ret = ffurl_write(s->hd, crlf, sizeof(crlf) - 1)) < 0)
602 static int http_shutdown(URLContext *h, int flags)
605 char footer[] = "0\r\n\r\n";
606 HTTPContext *s = h->priv_data;
608 /* signal end of chunked encoding if used */
609 if ((flags & AVIO_FLAG_WRITE) && s->chunked_post) {
610 ret = ffurl_write(s->hd, footer, sizeof(footer) - 1);
611 ret = ret > 0 ? 0 : ret;
612 s->end_chunked_post = 1;
618 static int http_close(URLContext *h)
621 HTTPContext *s = h->priv_data;
623 if (!s->end_chunked_post) {
624 /* Close the write direction by sending the end of chunked encoding. */
625 ret = http_shutdown(h, h->flags);
629 ffurl_closep(&s->hd);
633 static int64_t http_seek(URLContext *h, int64_t off, int whence)
635 HTTPContext *s = h->priv_data;
636 URLContext *old_hd = s->hd;
637 int64_t old_off = s->off;
638 uint8_t old_buf[BUFFER_SIZE];
641 if (whence == AVSEEK_SIZE)
643 else if ((s->filesize == -1 && whence == SEEK_END) || h->is_streamed)
646 /* we save the old context in case the seek fails */
647 old_buf_size = s->buf_end - s->buf_ptr;
648 memcpy(old_buf, s->buf_ptr, old_buf_size);
650 if (whence == SEEK_CUR)
652 else if (whence == SEEK_END)
656 /* if it fails, continue on old connection */
657 if (http_open_cnx(h) < 0) {
658 memcpy(s->buffer, old_buf, old_buf_size);
659 s->buf_ptr = s->buffer;
660 s->buf_end = s->buffer + old_buf_size;
670 http_get_file_handle(URLContext *h)
672 HTTPContext *s = h->priv_data;
673 return ffurl_get_file_handle(s->hd);
676 #if CONFIG_HTTP_PROTOCOL
677 URLProtocol ff_http_protocol = {
679 .url_open = http_open,
680 .url_read = http_read,
681 .url_write = http_write,
682 .url_seek = http_seek,
683 .url_close = http_close,
684 .url_get_file_handle = http_get_file_handle,
685 .url_shutdown = http_shutdown,
686 .priv_data_size = sizeof(HTTPContext),
687 .priv_data_class = &http_context_class,
688 .flags = URL_PROTOCOL_FLAG_NETWORK,
691 #if CONFIG_HTTPS_PROTOCOL
692 URLProtocol ff_https_protocol = {
694 .url_open = http_open,
695 .url_read = http_read,
696 .url_write = http_write,
697 .url_seek = http_seek,
698 .url_close = http_close,
699 .url_get_file_handle = http_get_file_handle,
700 .url_shutdown = http_shutdown,
701 .priv_data_size = sizeof(HTTPContext),
702 .priv_data_class = &https_context_class,
703 .flags = URL_PROTOCOL_FLAG_NETWORK,
707 #if CONFIG_HTTPPROXY_PROTOCOL
708 static int http_proxy_close(URLContext *h)
710 HTTPContext *s = h->priv_data;
712 ffurl_closep(&s->hd);
716 static int http_proxy_open(URLContext *h, const char *uri, int flags)
718 HTTPContext *s = h->priv_data;
719 char hostname[1024], hoststr[1024];
720 char auth[1024], pathbuf[1024], *path;
722 int port, ret = 0, attempts = 0;
723 HTTPAuthType cur_auth_type;
726 AVDictionary *opts = NULL;
727 char opts_format[20];
729 if( s->seekable == 1 )
734 av_url_split(NULL, 0, auth, sizeof(auth), hostname, sizeof(hostname), &port,
735 pathbuf, sizeof(pathbuf), uri);
736 ff_url_join(hoststr, sizeof(hoststr), NULL, NULL, hostname, port, NULL);
741 ff_url_join(lower_url, sizeof(lower_url), "tcp", NULL, hostname, port,
744 if (s->rw_timeout != -1) {
745 snprintf(opts_format, sizeof(opts_format), "%d", s->rw_timeout);
746 av_dict_set(&opts, "timeout", opts_format, 0);
747 } /* if option is not given, don't pass it and let tcp use its own default */
748 ret = ffurl_open(&s->hd, lower_url, AVIO_FLAG_READ_WRITE,
749 &h->interrupt_callback, &opts);
754 authstr = ff_http_auth_create_response(&s->proxy_auth_state, auth,
756 snprintf(s->buffer, sizeof(s->buffer),
757 "CONNECT %s HTTP/1.1\r\n"
759 "Connection: close\r\n"
764 authstr ? "Proxy-" : "", authstr ? authstr : "");
767 if ((ret = ffurl_write(s->hd, s->buffer, strlen(s->buffer))) < 0)
770 s->buf_ptr = s->buffer;
771 s->buf_end = s->buffer;
774 cur_auth_type = s->proxy_auth_state.auth_type;
776 /* Note: This uses buffering, potentially reading more than the
777 * HTTP header. If tunneling a protocol where the server starts
778 * the conversation, we might buffer part of that here, too.
779 * Reading that requires using the proper ffurl_read() function
780 * on this URLContext, not using the fd directly (as the tls
781 * protocol does). This shouldn't be an issue for tls though,
782 * since the client starts the conversation there, so there
783 * is no extra data that we might buffer up here.
785 ret = http_read_header(h, &new_loc);
790 if (s->http_code == 407 &&
791 (cur_auth_type == HTTP_AUTH_NONE || s->proxy_auth_state.stale) &&
792 s->proxy_auth_state.auth_type != HTTP_AUTH_NONE && attempts < 2) {
793 ffurl_closep(&s->hd);
797 if (s->http_code < 400)
806 static int http_proxy_write(URLContext *h, const uint8_t *buf, int size)
808 HTTPContext *s = h->priv_data;
809 return ffurl_write(s->hd, buf, size);
812 URLProtocol ff_httpproxy_protocol = {
814 .url_open = http_proxy_open,
815 .url_read = http_buf_read,
816 .url_write = http_proxy_write,
817 .url_close = http_proxy_close,
818 .url_get_file_handle = http_get_file_handle,
819 .priv_data_size = sizeof(HTTPContext),
820 .flags = URL_PROTOCOL_FLAG_NETWORK,