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"
29 #include "os_support.h"
32 #include "libavutil/opt.h"
34 /* XXX: POST protocol is not completely implemented because ffmpeg uses
35 only a subset of it. */
37 /* used for protocol handling */
38 #define BUFFER_SIZE 1024
39 #define MAX_REDIRECTS 8
44 unsigned char buffer[BUFFER_SIZE], *buf_ptr, *buf_end;
47 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 unsigned char headers[BUFFER_SIZE];
52 int willclose; /**< Set if the server correctly handles Connection: close and will close the connection after feeding us the content. */
55 #define OFFSET(x) offsetof(HTTPContext, x)
56 static const AVOption options[] = {
57 {"chunksize", "use chunked transfer-encoding for posts, -1 disables it, 0 enables it", OFFSET(chunksize), FF_OPT_TYPE_INT64, {.dbl = 0}, -1, 0 }, /* Default to 0, for chunked POSTs */
60 static const AVClass httpcontext_class = {
62 .item_name = av_default_item_name,
64 .version = LIBAVUTIL_VERSION_INT,
67 static int http_connect(URLContext *h, const char *path, const char *hoststr,
68 const char *auth, int *new_location);
70 void ff_http_set_headers(URLContext *h, const char *headers)
72 HTTPContext *s = h->priv_data;
73 int len = strlen(headers);
75 if (len && strcmp("\r\n", headers + len - 2))
76 av_log(h, AV_LOG_ERROR, "No trailing CRLF found in HTTP header.\n");
78 av_strlcpy(s->headers, headers, sizeof(s->headers));
81 void ff_http_set_chunked_transfer_encoding(URLContext *h, int is_chunked)
83 ((HTTPContext*)h->priv_data)->chunksize = is_chunked ? 0 : -1;
86 void ff_http_init_auth_state(URLContext *dest, const URLContext *src)
88 memcpy(&((HTTPContext*)dest->priv_data)->auth_state,
89 &((HTTPContext*)src->priv_data)->auth_state, sizeof(HTTPAuthState));
92 /* return non zero if error */
93 static int http_open_cnx(URLContext *h)
95 const char *path, *proxy_path;
96 char hostname[1024], hoststr[1024];
100 int port, use_proxy, err, location_changed = 0, redirects = 0;
101 HTTPAuthType cur_auth_type;
102 HTTPContext *s = h->priv_data;
103 URLContext *hd = NULL;
105 proxy_path = getenv("http_proxy");
106 use_proxy = (proxy_path != NULL) && !getenv("no_proxy") &&
107 av_strstart(proxy_path, "http://", NULL);
109 /* fill the dest addr */
111 /* needed in any case to build the host string */
112 av_url_split(NULL, 0, auth, sizeof(auth), hostname, sizeof(hostname), &port,
113 path1, sizeof(path1), s->location);
114 ff_url_join(hoststr, sizeof(hoststr), NULL, NULL, hostname, port, NULL);
117 av_url_split(NULL, 0, auth, sizeof(auth), hostname, sizeof(hostname), &port,
118 NULL, 0, proxy_path);
121 if (path1[0] == '\0')
129 ff_url_join(buf, sizeof(buf), "tcp", NULL, hostname, port, NULL);
130 err = ffurl_open(&hd, buf, AVIO_FLAG_READ_WRITE);
135 cur_auth_type = s->auth_state.auth_type;
136 if (http_connect(h, path, hoststr, auth, &location_changed) < 0)
138 if (s->http_code == 401) {
139 if (cur_auth_type == HTTP_AUTH_NONE && s->auth_state.auth_type != HTTP_AUTH_NONE) {
145 if ((s->http_code == 301 || s->http_code == 302 || s->http_code == 303 || s->http_code == 307)
146 && location_changed == 1) {
147 /* url moved, get next */
149 if (redirects++ >= MAX_REDIRECTS)
151 location_changed = 0;
162 static int http_open(URLContext *h, const char *uri, int flags)
164 HTTPContext *s = h->priv_data;
169 av_strlcpy(s->location, uri, sizeof(s->location));
171 return http_open_cnx(h);
173 static int http_getc(HTTPContext *s)
176 if (s->buf_ptr >= s->buf_end) {
177 len = ffurl_read(s->hd, s->buffer, BUFFER_SIZE);
180 } else if (len == 0) {
183 s->buf_ptr = s->buffer;
184 s->buf_end = s->buffer + len;
187 return *s->buf_ptr++;
190 static int http_get_line(HTTPContext *s, char *line, int line_size)
202 if (q > line && q[-1] == '\r')
208 if ((q - line) < line_size - 1)
214 static int process_line(URLContext *h, char *line, int line_count,
217 HTTPContext *s = h->priv_data;
225 if (line_count == 0) {
226 while (!isspace(*p) && *p != '\0')
230 s->http_code = strtol(p, &end, 10);
232 av_dlog(NULL, "http_code=%d\n", s->http_code);
234 /* error codes are 4xx and 5xx, but regard 401 as a success, so we
235 * don't abort until all headers have been parsed. */
236 if (s->http_code >= 400 && s->http_code < 600 && s->http_code != 401) {
237 end += strspn(end, SPACE_CHARS);
238 av_log(h, AV_LOG_WARNING, "HTTP error %d %s\n",
243 while (*p != '\0' && *p != ':')
253 if (!strcasecmp(tag, "Location")) {
254 strcpy(s->location, p);
256 } else if (!strcasecmp (tag, "Content-Length") && s->filesize == -1) {
257 s->filesize = atoll(p);
258 } else if (!strcasecmp (tag, "Content-Range")) {
259 /* "bytes $from-$to/$document_size" */
261 if (!strncmp (p, "bytes ", 6)) {
264 if ((slash = strchr(p, '/')) && strlen(slash) > 0)
265 s->filesize = atoll(slash+1);
267 h->is_streamed = 0; /* we _can_ in fact seek */
268 } else if (!strcasecmp (tag, "Transfer-Encoding") && !strncasecmp(p, "chunked", 7)) {
271 } else if (!strcasecmp (tag, "WWW-Authenticate")) {
272 ff_http_auth_handle_header(&s->auth_state, tag, p);
273 } else if (!strcasecmp (tag, "Authentication-Info")) {
274 ff_http_auth_handle_header(&s->auth_state, tag, p);
275 } else if (!strcasecmp (tag, "Connection")) {
276 if (!strcmp(p, "close"))
283 static inline int has_header(const char *str, const char *header)
285 /* header + 2 to skip over CRLF prefix. (make sure you have one!) */
286 return av_stristart(str, header + 2, NULL) || av_stristr(str, header);
289 static int http_connect(URLContext *h, const char *path, const char *hoststr,
290 const char *auth, int *new_location)
292 HTTPContext *s = h->priv_data;
295 char headers[1024] = "";
296 char *authstr = NULL;
297 int64_t off = s->off;
301 /* send http header */
302 post = h->flags & AVIO_FLAG_WRITE;
303 authstr = ff_http_auth_create_response(&s->auth_state, auth, path,
304 post ? "POST" : "GET");
306 /* set default headers if needed */
307 if (!has_header(s->headers, "\r\nUser-Agent: "))
308 len += av_strlcatf(headers + len, sizeof(headers) - len,
309 "User-Agent: %s\r\n", LIBAVFORMAT_IDENT);
310 if (!has_header(s->headers, "\r\nAccept: "))
311 len += av_strlcpy(headers + len, "Accept: */*\r\n",
312 sizeof(headers) - len);
313 if (!has_header(s->headers, "\r\nRange: "))
314 len += av_strlcatf(headers + len, sizeof(headers) - len,
315 "Range: bytes=%"PRId64"-\r\n", s->off);
316 if (!has_header(s->headers, "\r\nConnection: "))
317 len += av_strlcpy(headers + len, "Connection: close\r\n",
318 sizeof(headers)-len);
319 if (!has_header(s->headers, "\r\nHost: "))
320 len += av_strlcatf(headers + len, sizeof(headers) - len,
321 "Host: %s\r\n", hoststr);
323 /* now add in custom headers */
324 av_strlcpy(headers+len, s->headers, sizeof(headers)-len);
326 snprintf(s->buffer, sizeof(s->buffer),
332 post ? "POST" : "GET",
334 post && s->chunksize >= 0 ? "Transfer-Encoding: chunked\r\n" : "",
336 authstr ? authstr : "");
339 if (ffurl_write(s->hd, s->buffer, strlen(s->buffer)) < 0)
342 /* init input buffer */
343 s->buf_ptr = s->buffer;
344 s->buf_end = s->buffer;
350 /* Pretend that it did work. We didn't read any header yet, since
351 * we've still to send the POST data, but the code calling this
352 * function will check http_code after we return. */
358 /* wait for header */
360 if (http_get_line(s, line, sizeof(line)) < 0)
363 av_dlog(NULL, "header='%s'\n", line);
365 err = process_line(h, line, s->line_count, new_location);
373 return (off == s->off) ? 0 : -1;
377 static int http_read(URLContext *h, uint8_t *buf, int size)
379 HTTPContext *s = h->priv_data;
382 if (s->chunksize >= 0) {
388 if (http_get_line(s, line, sizeof(line)) < 0)
390 } while (!*line); /* skip CR LF from last chunk */
392 s->chunksize = strtoll(line, NULL, 16);
394 av_dlog(NULL, "Chunked encoding data size: %"PRId64"'\n", s->chunksize);
401 size = FFMIN(size, s->chunksize);
403 /* read bytes from input buffer first */
404 len = s->buf_end - s->buf_ptr;
408 memcpy(buf, s->buf_ptr, len);
411 if (!s->willclose && s->filesize >= 0 && s->off >= s->filesize)
413 len = ffurl_read(s->hd, buf, size);
417 if (s->chunksize > 0)
423 /* used only when posting data */
424 static int http_write(URLContext *h, const uint8_t *buf, int size)
426 char temp[11] = ""; /* 32-bit hex + CRLF + nul */
428 char crlf[] = "\r\n";
429 HTTPContext *s = h->priv_data;
431 if (s->chunksize == -1) {
432 /* non-chunked data is sent without any special encoding */
433 return ffurl_write(s->hd, buf, size);
436 /* silently ignore zero-size data since chunk encoding that would
439 /* upload data using chunked encoding */
440 snprintf(temp, sizeof(temp), "%x\r\n", size);
442 if ((ret = ffurl_write(s->hd, temp, strlen(temp))) < 0 ||
443 (ret = ffurl_write(s->hd, buf, size)) < 0 ||
444 (ret = ffurl_write(s->hd, crlf, sizeof(crlf) - 1)) < 0)
450 static int http_close(URLContext *h)
453 char footer[] = "0\r\n\r\n";
454 HTTPContext *s = h->priv_data;
456 /* signal end of chunked encoding if used */
457 if ((h->flags & AVIO_FLAG_WRITE) && s->chunksize != -1) {
458 ret = ffurl_write(s->hd, footer, sizeof(footer) - 1);
459 ret = ret > 0 ? 0 : ret;
467 static int64_t http_seek(URLContext *h, int64_t off, int whence)
469 HTTPContext *s = h->priv_data;
470 URLContext *old_hd = s->hd;
471 int64_t old_off = s->off;
472 uint8_t old_buf[BUFFER_SIZE];
475 if (whence == AVSEEK_SIZE)
477 else if ((s->filesize == -1 && whence == SEEK_END) || h->is_streamed)
480 /* we save the old context in case the seek fails */
481 old_buf_size = s->buf_end - s->buf_ptr;
482 memcpy(old_buf, s->buf_ptr, old_buf_size);
484 if (whence == SEEK_CUR)
486 else if (whence == SEEK_END)
490 /* if it fails, continue on old connection */
491 if (http_open_cnx(h) < 0) {
492 memcpy(s->buffer, old_buf, old_buf_size);
493 s->buf_ptr = s->buffer;
494 s->buf_end = s->buffer + old_buf_size;
504 http_get_file_handle(URLContext *h)
506 HTTPContext *s = h->priv_data;
507 return ffurl_get_file_handle(s->hd);
510 URLProtocol ff_http_protocol = {
512 .url_open = http_open,
513 .url_read = http_read,
514 .url_write = http_write,
515 .url_seek = http_seek,
516 .url_close = http_close,
517 .url_get_file_handle = http_get_file_handle,
518 .priv_data_size = sizeof(HTTPContext),
519 .priv_data_class = &httpcontext_class,