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. */
57 int end_chunked_post; /**< A flag which indicates if the end of chunked encoding has been sent. */
58 int end_header; /**< A flag which indicates we have finished to read POST reply. */
59 int multiple_requests; /**< A flag which indicates if we use persistent connections. */
65 #define OFFSET(x) offsetof(HTTPContext, x)
66 #define D AV_OPT_FLAG_DECODING_PARAM
67 #define E AV_OPT_FLAG_ENCODING_PARAM
68 #define DEC AV_OPT_FLAG_DECODING_PARAM
69 static const AVOption options[] = {
70 {"chunked_post", "use chunked transfer-encoding for posts", OFFSET(chunked_post), AV_OPT_TYPE_INT, {.i64 = 1}, 0, 1, E },
71 {"headers", "custom HTTP headers, can override built in default headers", OFFSET(headers), AV_OPT_TYPE_STRING, { 0 }, 0, 0, D|E },
72 {"user-agent", "override User-Agent header", OFFSET(user_agent), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, DEC},
73 {"multiple_requests", "use persistent connections", OFFSET(multiple_requests), AV_OPT_TYPE_INT, {.i64 = 0}, 0, 1, D|E },
74 {"post_data", "custom HTTP post data", OFFSET(post_data), AV_OPT_TYPE_BINARY, .flags = D|E },
77 #define HTTP_CLASS(flavor)\
78 static const AVClass flavor ## _context_class = {\
79 .class_name = #flavor,\
80 .item_name = av_default_item_name,\
82 .version = LIBAVUTIL_VERSION_INT,\
88 static int http_connect(URLContext *h, const char *path, const char *local_path,
89 const char *hoststr, const char *auth,
90 const char *proxyauth, int *new_location);
92 void ff_http_init_auth_state(URLContext *dest, const URLContext *src)
94 memcpy(&((HTTPContext*)dest->priv_data)->auth_state,
95 &((HTTPContext*)src->priv_data)->auth_state, sizeof(HTTPAuthState));
96 memcpy(&((HTTPContext*)dest->priv_data)->proxy_auth_state,
97 &((HTTPContext*)src->priv_data)->proxy_auth_state,
98 sizeof(HTTPAuthState));
101 /* return non zero if error */
102 static int http_open_cnx(URLContext *h)
104 const char *path, *proxy_path, *lower_proto = "tcp", *local_path;
105 char hostname[1024], hoststr[1024], proto[10];
106 char auth[1024], proxyauth[1024] = "";
107 char path1[MAX_URL_SIZE];
108 char buf[1024], urlbuf[MAX_URL_SIZE];
109 int port, use_proxy, err, location_changed = 0, redirects = 0, attempts = 0;
110 HTTPAuthType cur_auth_type, cur_proxy_auth_type;
111 HTTPContext *s = h->priv_data;
113 proxy_path = getenv("http_proxy");
114 use_proxy = (proxy_path != NULL) && !getenv("no_proxy") &&
115 av_strstart(proxy_path, "http://", NULL);
117 /* fill the dest addr */
119 /* needed in any case to build the host string */
120 av_url_split(proto, sizeof(proto), auth, sizeof(auth),
121 hostname, sizeof(hostname), &port,
122 path1, sizeof(path1), s->location);
123 ff_url_join(hoststr, sizeof(hoststr), NULL, NULL, hostname, port, NULL);
125 if (!strcmp(proto, "https")) {
134 if (path1[0] == '\0')
140 /* Reassemble the request URL without auth string - we don't
141 * want to leak the auth to the proxy. */
142 ff_url_join(urlbuf, sizeof(urlbuf), proto, NULL, hostname, port, "%s",
145 av_url_split(NULL, 0, proxyauth, sizeof(proxyauth),
146 hostname, sizeof(hostname), &port, NULL, 0, proxy_path);
149 ff_url_join(buf, sizeof(buf), lower_proto, NULL, hostname, port, NULL);
152 err = ffurl_open(&s->hd, buf, AVIO_FLAG_READ_WRITE,
153 &h->interrupt_callback, NULL);
158 cur_auth_type = s->auth_state.auth_type;
159 cur_proxy_auth_type = s->auth_state.auth_type;
160 if (http_connect(h, path, local_path, hoststr, auth, proxyauth, &location_changed) < 0)
163 if (s->http_code == 401) {
164 if ((cur_auth_type == HTTP_AUTH_NONE || s->auth_state.stale) &&
165 s->auth_state.auth_type != HTTP_AUTH_NONE && attempts < 4) {
166 ffurl_closep(&s->hd);
171 if (s->http_code == 407) {
172 if ((cur_proxy_auth_type == HTTP_AUTH_NONE || s->proxy_auth_state.stale) &&
173 s->proxy_auth_state.auth_type != HTTP_AUTH_NONE && attempts < 4) {
174 ffurl_closep(&s->hd);
179 if ((s->http_code == 301 || s->http_code == 302 || s->http_code == 303 || s->http_code == 307)
180 && location_changed == 1) {
181 /* url moved, get next */
182 ffurl_closep(&s->hd);
183 if (redirects++ >= MAX_REDIRECTS)
185 /* Restart the authentication process with the new target, which
186 * might use a different auth mechanism. */
187 memset(&s->auth_state, 0, sizeof(s->auth_state));
189 location_changed = 0;
195 ffurl_closep(&s->hd);
199 int ff_http_do_new_request(URLContext *h, const char *uri)
201 HTTPContext *s = h->priv_data;
204 av_strlcpy(s->location, uri, sizeof(s->location));
206 return http_open_cnx(h);
209 static int http_open(URLContext *h, const char *uri, int flags)
211 HTTPContext *s = h->priv_data;
216 av_strlcpy(s->location, uri, sizeof(s->location));
219 int len = strlen(s->headers);
220 if (len < 2 || strcmp("\r\n", s->headers + len - 2))
221 av_log(h, AV_LOG_WARNING, "No trailing CRLF found in HTTP header.\n");
224 return http_open_cnx(h);
226 static int http_getc(HTTPContext *s)
229 if (s->buf_ptr >= s->buf_end) {
230 len = ffurl_read(s->hd, s->buffer, BUFFER_SIZE);
233 } else if (len == 0) {
236 s->buf_ptr = s->buffer;
237 s->buf_end = s->buffer + len;
240 return *s->buf_ptr++;
243 static int http_get_line(HTTPContext *s, char *line, int line_size)
255 if (q > line && q[-1] == '\r')
261 if ((q - line) < line_size - 1)
267 static int process_line(URLContext *h, char *line, int line_count,
270 HTTPContext *s = h->priv_data;
274 if (line[0] == '\0') {
280 if (line_count == 0) {
281 while (!isspace(*p) && *p != '\0')
285 s->http_code = strtol(p, &end, 10);
287 av_dlog(NULL, "http_code=%d\n", s->http_code);
289 /* error codes are 4xx and 5xx, but regard 401 as a success, so we
290 * don't abort until all headers have been parsed. */
291 if (s->http_code >= 400 && s->http_code < 600 && (s->http_code != 401
292 || s->auth_state.auth_type != HTTP_AUTH_NONE) &&
293 (s->http_code != 407 || s->proxy_auth_state.auth_type != HTTP_AUTH_NONE)) {
294 end += strspn(end, SPACE_CHARS);
295 av_log(h, AV_LOG_WARNING, "HTTP error %d %s\n",
300 while (*p != '\0' && *p != ':')
310 if (!av_strcasecmp(tag, "Location")) {
311 strcpy(s->location, p);
313 } else if (!av_strcasecmp (tag, "Content-Length") && s->filesize == -1) {
314 s->filesize = strtoll(p, NULL, 10);
315 } else if (!av_strcasecmp (tag, "Content-Range")) {
316 /* "bytes $from-$to/$document_size" */
318 if (!strncmp (p, "bytes ", 6)) {
320 s->off = strtoll(p, NULL, 10);
321 if ((slash = strchr(p, '/')) && strlen(slash) > 0)
322 s->filesize = strtoll(slash+1, NULL, 10);
324 if (!s->is_akamai || s->filesize != 2147483647)
325 h->is_streamed = 0; /* we _can_ in fact seek */
326 } else if (!av_strcasecmp(tag, "Accept-Ranges") && !strncmp(p, "bytes", 5)) {
328 } else if (!av_strcasecmp (tag, "Transfer-Encoding") && !av_strncasecmp(p, "chunked", 7)) {
331 } else if (!av_strcasecmp (tag, "WWW-Authenticate")) {
332 ff_http_auth_handle_header(&s->auth_state, tag, p);
333 } else if (!av_strcasecmp (tag, "Authentication-Info")) {
334 ff_http_auth_handle_header(&s->auth_state, tag, p);
335 } else if (!av_strcasecmp (tag, "Proxy-Authenticate")) {
336 ff_http_auth_handle_header(&s->proxy_auth_state, tag, p);
337 } else if (!av_strcasecmp (tag, "Connection")) {
338 if (!strcmp(p, "close"))
340 } else if (!av_strcasecmp (tag, "Server") && !av_strcasecmp (p, "AkamaiGHost")) {
347 static inline int has_header(const char *str, const char *header)
349 /* header + 2 to skip over CRLF prefix. (make sure you have one!) */
352 return av_stristart(str, header + 2, NULL) || av_stristr(str, header);
355 static int http_read_header(URLContext *h, int *new_location)
357 HTTPContext *s = h->priv_data;
358 char line[MAX_URL_SIZE];
364 if ((err = http_get_line(s, line, sizeof(line))) < 0)
367 av_dlog(NULL, "header='%s'\n", line);
369 err = process_line(h, line, s->line_count, new_location);
380 static int http_connect(URLContext *h, const char *path, const char *local_path,
381 const char *hoststr, const char *auth,
382 const char *proxyauth, int *new_location)
384 HTTPContext *s = h->priv_data;
386 char headers[4096] = "";
387 char *authstr = NULL, *proxyauthstr = NULL;
388 int64_t off = s->off;
393 /* send http header */
394 post = h->flags & AVIO_FLAG_WRITE;
397 /* force POST method and disable chunked encoding when
398 * custom HTTP post data is set */
403 method = post ? "POST" : "GET";
404 authstr = ff_http_auth_create_response(&s->auth_state, auth, local_path,
406 proxyauthstr = ff_http_auth_create_response(&s->proxy_auth_state, proxyauth,
409 /* set default headers if needed */
410 if (!has_header(s->headers, "\r\nUser-Agent: "))
411 len += av_strlcatf(headers + len, sizeof(headers) - len,
412 "User-Agent: %s\r\n",
413 s->user_agent ? s->user_agent : LIBAVFORMAT_IDENT);
414 if (!has_header(s->headers, "\r\nAccept: "))
415 len += av_strlcpy(headers + len, "Accept: */*\r\n",
416 sizeof(headers) - len);
417 // Note: we send this on purpose even when s->off is 0,
418 // since it allows us to detect more reliably if a (non-conforming)
419 // server supports seeking by analysing the reply headers.
420 if (!has_header(s->headers, "\r\nRange: ") && !post)
421 len += av_strlcatf(headers + len, sizeof(headers) - len,
422 "Range: bytes=%"PRId64"-\r\n", s->off);
424 if (!has_header(s->headers, "\r\nConnection: ")) {
425 if (s->multiple_requests) {
426 len += av_strlcpy(headers + len, "Connection: keep-alive\r\n",
427 sizeof(headers) - len);
429 len += av_strlcpy(headers + len, "Connection: close\r\n",
430 sizeof(headers) - len);
434 if (!has_header(s->headers, "\r\nHost: "))
435 len += av_strlcatf(headers + len, sizeof(headers) - len,
436 "Host: %s\r\n", hoststr);
437 if (!has_header(s->headers, "\r\nContent-Length: ") && s->post_data)
438 len += av_strlcatf(headers + len, sizeof(headers) - len,
439 "Content-Length: %d\r\n", s->post_datalen);
441 /* now add in custom headers */
443 av_strlcpy(headers + len, s->headers, sizeof(headers) - len);
445 snprintf(s->buffer, sizeof(s->buffer),
454 post && s->chunked_post ? "Transfer-Encoding: chunked\r\n" : "",
456 authstr ? authstr : "",
457 proxyauthstr ? "Proxy-" : "", proxyauthstr ? proxyauthstr : "");
460 av_freep(&proxyauthstr);
461 if ((err = ffurl_write(s->hd, s->buffer, strlen(s->buffer))) < 0)
465 if ((err = ffurl_write(s->hd, s->post_data, s->post_datalen)) < 0)
468 /* init input buffer */
469 s->buf_ptr = s->buffer;
470 s->buf_end = s->buffer;
475 s->end_chunked_post = 0;
477 if (post && !s->post_data) {
478 /* Pretend that it did work. We didn't read any header yet, since
479 * we've still to send the POST data, but the code calling this
480 * function will check http_code after we return. */
485 /* wait for header */
486 err = http_read_header(h, new_location);
490 return (off == s->off) ? 0 : -1;
494 static int http_buf_read(URLContext *h, uint8_t *buf, int size)
496 HTTPContext *s = h->priv_data;
498 /* read bytes from input buffer first */
499 len = s->buf_end - s->buf_ptr;
503 memcpy(buf, s->buf_ptr, len);
506 if (!s->willclose && s->filesize >= 0 && s->off >= s->filesize)
508 len = ffurl_read(s->hd, buf, size);
512 if (s->chunksize > 0)
518 static int http_read(URLContext *h, uint8_t *buf, int size)
520 HTTPContext *s = h->priv_data;
521 int err, new_location;
526 if (s->end_chunked_post && !s->end_header) {
527 err = http_read_header(h, &new_location);
532 if (s->chunksize >= 0) {
538 if ((err = http_get_line(s, line, sizeof(line))) < 0)
540 } while (!*line); /* skip CR LF from last chunk */
542 s->chunksize = strtoll(line, NULL, 16);
544 av_dlog(NULL, "Chunked encoding data size: %"PRId64"'\n", s->chunksize);
551 size = FFMIN(size, s->chunksize);
553 return http_buf_read(h, buf, size);
556 /* used only when posting data */
557 static int http_write(URLContext *h, const uint8_t *buf, int size)
559 char temp[11] = ""; /* 32-bit hex + CRLF + nul */
561 char crlf[] = "\r\n";
562 HTTPContext *s = h->priv_data;
564 if (!s->chunked_post) {
565 /* non-chunked data is sent without any special encoding */
566 return ffurl_write(s->hd, buf, size);
569 /* silently ignore zero-size data since chunk encoding that would
572 /* upload data using chunked encoding */
573 snprintf(temp, sizeof(temp), "%x\r\n", size);
575 if ((ret = ffurl_write(s->hd, temp, strlen(temp))) < 0 ||
576 (ret = ffurl_write(s->hd, buf, size)) < 0 ||
577 (ret = ffurl_write(s->hd, crlf, sizeof(crlf) - 1)) < 0)
583 static int http_shutdown(URLContext *h, int flags)
586 char footer[] = "0\r\n\r\n";
587 HTTPContext *s = h->priv_data;
589 /* signal end of chunked encoding if used */
590 if ((flags & AVIO_FLAG_WRITE) && s->chunked_post) {
591 ret = ffurl_write(s->hd, footer, sizeof(footer) - 1);
592 ret = ret > 0 ? 0 : ret;
593 s->end_chunked_post = 1;
599 static int http_close(URLContext *h)
602 HTTPContext *s = h->priv_data;
604 if (!s->end_chunked_post) {
605 /* Close the write direction by sending the end of chunked encoding. */
606 ret = http_shutdown(h, h->flags);
610 ffurl_closep(&s->hd);
614 static int64_t http_seek(URLContext *h, int64_t off, int whence)
616 HTTPContext *s = h->priv_data;
617 URLContext *old_hd = s->hd;
618 int64_t old_off = s->off;
619 uint8_t old_buf[BUFFER_SIZE];
622 if (whence == AVSEEK_SIZE)
624 else if ((s->filesize == -1 && whence == SEEK_END) || h->is_streamed)
627 /* we save the old context in case the seek fails */
628 old_buf_size = s->buf_end - s->buf_ptr;
629 memcpy(old_buf, s->buf_ptr, old_buf_size);
631 if (whence == SEEK_CUR)
633 else if (whence == SEEK_END)
637 /* if it fails, continue on old connection */
638 if (http_open_cnx(h) < 0) {
639 memcpy(s->buffer, old_buf, old_buf_size);
640 s->buf_ptr = s->buffer;
641 s->buf_end = s->buffer + old_buf_size;
651 http_get_file_handle(URLContext *h)
653 HTTPContext *s = h->priv_data;
654 return ffurl_get_file_handle(s->hd);
657 #if CONFIG_HTTP_PROTOCOL
658 URLProtocol ff_http_protocol = {
660 .url_open = http_open,
661 .url_read = http_read,
662 .url_write = http_write,
663 .url_seek = http_seek,
664 .url_close = http_close,
665 .url_get_file_handle = http_get_file_handle,
666 .url_shutdown = http_shutdown,
667 .priv_data_size = sizeof(HTTPContext),
668 .priv_data_class = &http_context_class,
669 .flags = URL_PROTOCOL_FLAG_NETWORK,
672 #if CONFIG_HTTPS_PROTOCOL
673 URLProtocol ff_https_protocol = {
675 .url_open = http_open,
676 .url_read = http_read,
677 .url_write = http_write,
678 .url_seek = http_seek,
679 .url_close = http_close,
680 .url_get_file_handle = http_get_file_handle,
681 .url_shutdown = http_shutdown,
682 .priv_data_size = sizeof(HTTPContext),
683 .priv_data_class = &https_context_class,
684 .flags = URL_PROTOCOL_FLAG_NETWORK,
688 #if CONFIG_HTTPPROXY_PROTOCOL
689 static int http_proxy_close(URLContext *h)
691 HTTPContext *s = h->priv_data;
693 ffurl_closep(&s->hd);
697 static int http_proxy_open(URLContext *h, const char *uri, int flags)
699 HTTPContext *s = h->priv_data;
700 char hostname[1024], hoststr[1024];
701 char auth[1024], pathbuf[1024], *path;
703 int port, ret = 0, attempts = 0;
704 HTTPAuthType cur_auth_type;
710 av_url_split(NULL, 0, auth, sizeof(auth), hostname, sizeof(hostname), &port,
711 pathbuf, sizeof(pathbuf), uri);
712 ff_url_join(hoststr, sizeof(hoststr), NULL, NULL, hostname, port, NULL);
717 ff_url_join(lower_url, sizeof(lower_url), "tcp", NULL, hostname, port,
720 ret = ffurl_open(&s->hd, lower_url, AVIO_FLAG_READ_WRITE,
721 &h->interrupt_callback, NULL);
725 authstr = ff_http_auth_create_response(&s->proxy_auth_state, auth,
727 snprintf(s->buffer, sizeof(s->buffer),
728 "CONNECT %s HTTP/1.1\r\n"
730 "Connection: close\r\n"
735 authstr ? "Proxy-" : "", authstr ? authstr : "");
738 if ((ret = ffurl_write(s->hd, s->buffer, strlen(s->buffer))) < 0)
741 s->buf_ptr = s->buffer;
742 s->buf_end = s->buffer;
745 cur_auth_type = s->proxy_auth_state.auth_type;
747 /* Note: This uses buffering, potentially reading more than the
748 * HTTP header. If tunneling a protocol where the server starts
749 * the conversation, we might buffer part of that here, too.
750 * Reading that requires using the proper ffurl_read() function
751 * on this URLContext, not using the fd directly (as the tls
752 * protocol does). This shouldn't be an issue for tls though,
753 * since the client starts the conversation there, so there
754 * is no extra data that we might buffer up here.
756 ret = http_read_header(h, &new_loc);
761 if (s->http_code == 407 &&
762 (cur_auth_type == HTTP_AUTH_NONE || s->proxy_auth_state.stale) &&
763 s->proxy_auth_state.auth_type != HTTP_AUTH_NONE && attempts < 2) {
764 ffurl_closep(&s->hd);
768 if (s->http_code < 400)
777 static int http_proxy_write(URLContext *h, const uint8_t *buf, int size)
779 HTTPContext *s = h->priv_data;
780 return ffurl_write(s->hd, buf, size);
783 URLProtocol ff_httpproxy_protocol = {
785 .url_open = http_proxy_open,
786 .url_read = http_buf_read,
787 .url_write = http_proxy_write,
788 .url_close = http_proxy_close,
789 .url_get_file_handle = http_get_file_handle,
790 .priv_data_size = sizeof(HTTPContext),
791 .flags = URL_PROTOCOL_FLAG_NETWORK,