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"
28 #include "os_support.h"
31 #include "libavutil/opt.h"
33 /* XXX: POST protocol is not completely implemented because ffmpeg uses
34 only a subset of it. */
36 /* used for protocol handling */
37 #define BUFFER_SIZE 1024
38 #define MAX_REDIRECTS 8
43 unsigned char buffer[BUFFER_SIZE], *buf_ptr, *buf_end;
46 int64_t chunksize; /**< Used if "Transfer-Encoding: chunked" otherwise -1. */
48 int64_t off, filesize;
49 char location[MAX_URL_SIZE];
50 HTTPAuthState auth_state;
51 HTTPAuthState proxy_auth_state;
53 int willclose; /**< Set if the server correctly handles Connection: close and will close the connection after feeding us the content. */
57 #define OFFSET(x) offsetof(HTTPContext, x)
58 #define D AV_OPT_FLAG_DECODING_PARAM
59 #define E AV_OPT_FLAG_ENCODING_PARAM
60 #define DEC AV_OPT_FLAG_DECODING_PARAM
61 static const AVOption options[] = {
62 {"chunked_post", "use chunked transfer-encoding for posts", OFFSET(chunked_post), AV_OPT_TYPE_INT, {.dbl = 1}, 0, 1, E },
63 {"headers", "custom HTTP headers, can override built in default headers", OFFSET(headers), AV_OPT_TYPE_STRING, { 0 }, 0, 0, D|E },
64 {"user-agent", "override User-Agent header", OFFSET(user_agent), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, DEC},
67 #define HTTP_CLASS(flavor)\
68 static const AVClass flavor ## _context_class = {\
69 .class_name = #flavor,\
70 .item_name = av_default_item_name,\
72 .version = LIBAVUTIL_VERSION_INT,\
78 static int http_connect(URLContext *h, const char *path, const char *local_path,
79 const char *hoststr, const char *auth,
80 const char *proxyauth, int *new_location);
82 void ff_http_init_auth_state(URLContext *dest, const URLContext *src)
84 memcpy(&((HTTPContext*)dest->priv_data)->auth_state,
85 &((HTTPContext*)src->priv_data)->auth_state, sizeof(HTTPAuthState));
86 memcpy(&((HTTPContext*)dest->priv_data)->proxy_auth_state,
87 &((HTTPContext*)src->priv_data)->proxy_auth_state,
88 sizeof(HTTPAuthState));
91 /* return non zero if error */
92 static int http_open_cnx(URLContext *h)
94 const char *path, *proxy_path, *lower_proto = "tcp", *local_path;
95 char hostname[1024], hoststr[1024], proto[10];
96 char auth[1024], proxyauth[1024] = "";
98 char buf[1024], urlbuf[1024];
99 int port, use_proxy, err, location_changed = 0, redirects = 0;
100 HTTPAuthType cur_auth_type, cur_proxy_auth_type;
101 HTTPContext *s = h->priv_data;
102 URLContext *hd = NULL;
104 proxy_path = getenv("http_proxy");
105 use_proxy = (proxy_path != NULL) && !getenv("no_proxy") &&
106 av_strstart(proxy_path, "http://", NULL);
108 /* fill the dest addr */
110 /* needed in any case to build the host string */
111 av_url_split(proto, sizeof(proto), auth, sizeof(auth),
112 hostname, sizeof(hostname), &port,
113 path1, sizeof(path1), s->location);
114 ff_url_join(hoststr, sizeof(hoststr), NULL, NULL, hostname, port, NULL);
116 if (!strcmp(proto, "https")) {
125 if (path1[0] == '\0')
131 /* Reassemble the request URL without auth string - we don't
132 * want to leak the auth to the proxy. */
133 ff_url_join(urlbuf, sizeof(urlbuf), proto, NULL, hostname, port, "%s",
136 av_url_split(NULL, 0, proxyauth, sizeof(proxyauth),
137 hostname, sizeof(hostname), &port, NULL, 0, proxy_path);
140 ff_url_join(buf, sizeof(buf), lower_proto, NULL, hostname, port, NULL);
141 err = ffurl_open(&hd, buf, AVIO_FLAG_READ_WRITE,
142 &h->interrupt_callback, NULL);
147 cur_auth_type = s->auth_state.auth_type;
148 cur_proxy_auth_type = s->auth_state.auth_type;
149 if (http_connect(h, path, local_path, hoststr, auth, proxyauth, &location_changed) < 0)
151 if (s->http_code == 401) {
152 if (cur_auth_type == HTTP_AUTH_NONE && s->auth_state.auth_type != HTTP_AUTH_NONE) {
158 if (s->http_code == 407) {
159 if (cur_proxy_auth_type == HTTP_AUTH_NONE &&
160 s->proxy_auth_state.auth_type != HTTP_AUTH_NONE) {
166 if ((s->http_code == 301 || s->http_code == 302 || s->http_code == 303 || s->http_code == 307)
167 && location_changed == 1) {
168 /* url moved, get next */
170 if (redirects++ >= MAX_REDIRECTS)
172 location_changed = 0;
183 static int http_open(URLContext *h, const char *uri, int flags)
185 HTTPContext *s = h->priv_data;
190 av_strlcpy(s->location, uri, sizeof(s->location));
193 int len = strlen(s->headers);
194 if (len < 2 || strcmp("\r\n", s->headers + len - 2))
195 av_log(h, AV_LOG_WARNING, "No trailing CRLF found in HTTP header.\n");
198 return http_open_cnx(h);
200 static int http_getc(HTTPContext *s)
203 if (s->buf_ptr >= s->buf_end) {
204 len = ffurl_read(s->hd, s->buffer, BUFFER_SIZE);
207 } else if (len == 0) {
210 s->buf_ptr = s->buffer;
211 s->buf_end = s->buffer + len;
214 return *s->buf_ptr++;
217 static int http_get_line(HTTPContext *s, char *line, int line_size)
229 if (q > line && q[-1] == '\r')
235 if ((q - line) < line_size - 1)
241 static int process_line(URLContext *h, char *line, int line_count,
244 HTTPContext *s = h->priv_data;
252 if (line_count == 0) {
253 while (!isspace(*p) && *p != '\0')
257 s->http_code = strtol(p, &end, 10);
259 av_dlog(NULL, "http_code=%d\n", s->http_code);
261 /* error codes are 4xx and 5xx, but regard 401 as a success, so we
262 * don't abort until all headers have been parsed. */
263 if (s->http_code >= 400 && s->http_code < 600 && (s->http_code != 401
264 || s->auth_state.auth_type != HTTP_AUTH_NONE) &&
265 (s->http_code != 407 || s->proxy_auth_state.auth_type != HTTP_AUTH_NONE)) {
266 end += strspn(end, SPACE_CHARS);
267 av_log(h, AV_LOG_WARNING, "HTTP error %d %s\n",
272 while (*p != '\0' && *p != ':')
282 if (!av_strcasecmp(tag, "Location")) {
283 strcpy(s->location, p);
285 } else if (!av_strcasecmp (tag, "Content-Length") && s->filesize == -1) {
286 s->filesize = atoll(p);
287 } else if (!av_strcasecmp (tag, "Content-Range")) {
288 /* "bytes $from-$to/$document_size" */
290 if (!strncmp (p, "bytes ", 6)) {
293 if ((slash = strchr(p, '/')) && strlen(slash) > 0)
294 s->filesize = atoll(slash+1);
296 h->is_streamed = 0; /* we _can_ in fact seek */
297 } else if (!av_strcasecmp(tag, "Accept-Ranges") && !strncmp(p, "bytes", 5)) {
299 } else if (!av_strcasecmp (tag, "Transfer-Encoding") && !av_strncasecmp(p, "chunked", 7)) {
302 } else if (!av_strcasecmp (tag, "WWW-Authenticate")) {
303 ff_http_auth_handle_header(&s->auth_state, tag, p);
304 } else if (!av_strcasecmp (tag, "Authentication-Info")) {
305 ff_http_auth_handle_header(&s->auth_state, tag, p);
306 } else if (!av_strcasecmp (tag, "Proxy-Authenticate")) {
307 ff_http_auth_handle_header(&s->proxy_auth_state, tag, p);
308 } else if (!av_strcasecmp (tag, "Connection")) {
309 if (!strcmp(p, "close"))
316 static inline int has_header(const char *str, const char *header)
318 /* header + 2 to skip over CRLF prefix. (make sure you have one!) */
321 return av_stristart(str, header + 2, NULL) || av_stristr(str, header);
324 static int http_connect(URLContext *h, const char *path, const char *local_path,
325 const char *hoststr, const char *auth,
326 const char *proxyauth, int *new_location)
328 HTTPContext *s = h->priv_data;
331 char headers[1024] = "";
332 char *authstr = NULL, *proxyauthstr = NULL;
333 int64_t off = s->off;
338 /* send http header */
339 post = h->flags & AVIO_FLAG_WRITE;
340 method = post ? "POST" : "GET";
341 authstr = ff_http_auth_create_response(&s->auth_state, auth, local_path,
343 proxyauthstr = ff_http_auth_create_response(&s->proxy_auth_state, proxyauth,
346 /* set default headers if needed */
347 if (!has_header(s->headers, "\r\nUser-Agent: "))
348 len += av_strlcatf(headers + len, sizeof(headers) - len,
349 "User-Agent: %s\r\n",
350 s->user_agent ? s->user_agent : LIBAVFORMAT_IDENT);
351 if (!has_header(s->headers, "\r\nAccept: "))
352 len += av_strlcpy(headers + len, "Accept: */*\r\n",
353 sizeof(headers) - len);
354 if (!has_header(s->headers, "\r\nRange: ") && !post)
355 len += av_strlcatf(headers + len, sizeof(headers) - len,
356 "Range: bytes=%"PRId64"-\r\n", s->off);
357 if (!has_header(s->headers, "\r\nConnection: "))
358 len += av_strlcpy(headers + len, "Connection: close\r\n",
359 sizeof(headers)-len);
360 if (!has_header(s->headers, "\r\nHost: "))
361 len += av_strlcatf(headers + len, sizeof(headers) - len,
362 "Host: %s\r\n", hoststr);
364 /* now add in custom headers */
366 av_strlcpy(headers + len, s->headers, sizeof(headers) - len);
368 snprintf(s->buffer, sizeof(s->buffer),
377 post && s->chunked_post ? "Transfer-Encoding: chunked\r\n" : "",
379 authstr ? authstr : "",
380 proxyauthstr ? "Proxy-" : "", proxyauthstr ? proxyauthstr : "");
383 av_freep(&proxyauthstr);
384 if (ffurl_write(s->hd, s->buffer, strlen(s->buffer)) < 0)
387 /* init input buffer */
388 s->buf_ptr = s->buffer;
389 s->buf_end = s->buffer;
395 /* Pretend that it did work. We didn't read any header yet, since
396 * we've still to send the POST data, but the code calling this
397 * function will check http_code after we return. */
403 /* wait for header */
405 if (http_get_line(s, line, sizeof(line)) < 0)
408 av_dlog(NULL, "header='%s'\n", line);
410 err = process_line(h, line, s->line_count, new_location);
418 return (off == s->off) ? 0 : -1;
422 static int http_buf_read(URLContext *h, uint8_t *buf, int size)
424 HTTPContext *s = h->priv_data;
426 /* read bytes from input buffer first */
427 len = s->buf_end - s->buf_ptr;
431 memcpy(buf, s->buf_ptr, len);
434 if (!s->willclose && s->filesize >= 0 && s->off >= s->filesize)
436 len = ffurl_read(s->hd, buf, size);
440 if (s->chunksize > 0)
446 static int http_read(URLContext *h, uint8_t *buf, int size)
448 HTTPContext *s = h->priv_data;
450 if (s->chunksize >= 0) {
456 if (http_get_line(s, line, sizeof(line)) < 0)
458 } while (!*line); /* skip CR LF from last chunk */
460 s->chunksize = strtoll(line, NULL, 16);
462 av_dlog(NULL, "Chunked encoding data size: %"PRId64"'\n", s->chunksize);
469 size = FFMIN(size, s->chunksize);
471 return http_buf_read(h, buf, size);
474 /* used only when posting data */
475 static int http_write(URLContext *h, const uint8_t *buf, int size)
477 char temp[11] = ""; /* 32-bit hex + CRLF + nul */
479 char crlf[] = "\r\n";
480 HTTPContext *s = h->priv_data;
482 if (!s->chunked_post) {
483 /* non-chunked data is sent without any special encoding */
484 return ffurl_write(s->hd, buf, size);
487 /* silently ignore zero-size data since chunk encoding that would
490 /* upload data using chunked encoding */
491 snprintf(temp, sizeof(temp), "%x\r\n", size);
493 if ((ret = ffurl_write(s->hd, temp, strlen(temp))) < 0 ||
494 (ret = ffurl_write(s->hd, buf, size)) < 0 ||
495 (ret = ffurl_write(s->hd, crlf, sizeof(crlf) - 1)) < 0)
501 static int http_close(URLContext *h)
504 char footer[] = "0\r\n\r\n";
505 HTTPContext *s = h->priv_data;
507 /* signal end of chunked encoding if used */
508 if ((h->flags & AVIO_FLAG_WRITE) && s->chunked_post) {
509 ret = ffurl_write(s->hd, footer, sizeof(footer) - 1);
510 ret = ret > 0 ? 0 : ret;
518 static int64_t http_seek(URLContext *h, int64_t off, int whence)
520 HTTPContext *s = h->priv_data;
521 URLContext *old_hd = s->hd;
522 int64_t old_off = s->off;
523 uint8_t old_buf[BUFFER_SIZE];
526 if (whence == AVSEEK_SIZE)
528 else if ((s->filesize == -1 && whence == SEEK_END) || h->is_streamed)
531 /* we save the old context in case the seek fails */
532 old_buf_size = s->buf_end - s->buf_ptr;
533 memcpy(old_buf, s->buf_ptr, old_buf_size);
535 if (whence == SEEK_CUR)
537 else if (whence == SEEK_END)
541 /* if it fails, continue on old connection */
542 if (http_open_cnx(h) < 0) {
543 memcpy(s->buffer, old_buf, old_buf_size);
544 s->buf_ptr = s->buffer;
545 s->buf_end = s->buffer + old_buf_size;
555 http_get_file_handle(URLContext *h)
557 HTTPContext *s = h->priv_data;
558 return ffurl_get_file_handle(s->hd);
561 #if CONFIG_HTTP_PROTOCOL
562 URLProtocol ff_http_protocol = {
564 .url_open = http_open,
565 .url_read = http_read,
566 .url_write = http_write,
567 .url_seek = http_seek,
568 .url_close = http_close,
569 .url_get_file_handle = http_get_file_handle,
570 .priv_data_size = sizeof(HTTPContext),
571 .priv_data_class = &http_context_class,
572 .flags = URL_PROTOCOL_FLAG_NETWORK,
575 #if CONFIG_HTTPS_PROTOCOL
576 URLProtocol ff_https_protocol = {
578 .url_open = http_open,
579 .url_read = http_read,
580 .url_write = http_write,
581 .url_seek = http_seek,
582 .url_close = http_close,
583 .url_get_file_handle = http_get_file_handle,
584 .priv_data_size = sizeof(HTTPContext),
585 .priv_data_class = &https_context_class,
586 .flags = URL_PROTOCOL_FLAG_NETWORK,
590 #if CONFIG_HTTPPROXY_PROTOCOL
591 static int http_proxy_close(URLContext *h)
593 HTTPContext *s = h->priv_data;
599 static int http_proxy_open(URLContext *h, const char *uri, int flags)
601 HTTPContext *s = h->priv_data;
602 char hostname[1024], hoststr[1024];
603 char auth[1024], pathbuf[1024], *path;
604 char line[1024], lower_url[100];
606 HTTPAuthType cur_auth_type;
611 av_url_split(NULL, 0, auth, sizeof(auth), hostname, sizeof(hostname), &port,
612 pathbuf, sizeof(pathbuf), uri);
613 ff_url_join(hoststr, sizeof(hoststr), NULL, NULL, hostname, port, NULL);
618 ff_url_join(lower_url, sizeof(lower_url), "tcp", NULL, hostname, port,
621 ret = ffurl_open(&s->hd, lower_url, AVIO_FLAG_READ_WRITE,
622 &h->interrupt_callback, NULL);
626 authstr = ff_http_auth_create_response(&s->proxy_auth_state, auth,
628 snprintf(s->buffer, sizeof(s->buffer),
629 "CONNECT %s HTTP/1.1\r\n"
631 "Connection: close\r\n"
636 authstr ? "Proxy-" : "", authstr ? authstr : "");
639 if ((ret = ffurl_write(s->hd, s->buffer, strlen(s->buffer))) < 0)
642 s->buf_ptr = s->buffer;
643 s->buf_end = s->buffer;
646 cur_auth_type = s->proxy_auth_state.auth_type;
650 // Note: This uses buffering, potentially reading more than the
651 // HTTP header. If tunneling a protocol where the server starts
652 // the conversation, we might buffer part of that here, too.
653 // Reading that requires using the proper ffurl_read() function
654 // on this URLContext, not using the fd directly (as the tls
655 // protocol does). This shouldn't be an issue for tls though,
656 // since the client starts the conversation there, so there
657 // is no extra data that we might buffer up here.
658 if (http_get_line(s, line, sizeof(line)) < 0) {
663 av_dlog(h, "header='%s'\n", line);
665 ret = process_line(h, line, s->line_count, &new_loc);
672 if (s->http_code == 407 && cur_auth_type == HTTP_AUTH_NONE &&
673 s->proxy_auth_state.auth_type != HTTP_AUTH_NONE) {
679 if (s->http_code < 400)
688 static int http_proxy_write(URLContext *h, const uint8_t *buf, int size)
690 HTTPContext *s = h->priv_data;
691 return ffurl_write(s->hd, buf, size);
694 URLProtocol ff_httpproxy_protocol = {
696 .url_open = http_proxy_open,
697 .url_read = http_buf_read,
698 .url_write = http_proxy_write,
699 .url_close = http_proxy_close,
700 .url_get_file_handle = http_get_file_handle,
701 .priv_data_size = sizeof(HTTPContext),
702 .flags = URL_PROTOCOL_FLAG_NETWORK,