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"
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. */
47 int64_t off, filesize;
48 char location[MAX_URL_SIZE];
49 HTTPAuthState auth_state;
50 unsigned char headers[BUFFER_SIZE];
51 int willclose; /**< Set if the server correctly handles Connection: close and will close the connection after feeding us the content. */
54 #define OFFSET(x) offsetof(HTTPContext, x)
55 static const AVOption options[] = {
56 {"chunksize", "use chunked transfer-encoding for posts, -1 disables it, 0 enables it", OFFSET(chunksize), FF_OPT_TYPE_INT64, 0, -1, 0 }, /* Default to 0, for chunked POSTs */
59 static const AVClass httpcontext_class = {
60 "HTTP", av_default_item_name, options, LIBAVUTIL_VERSION_INT
63 static int http_connect(URLContext *h, const char *path, const char *hoststr,
64 const char *auth, int *new_location);
66 void ff_http_set_headers(URLContext *h, const char *headers)
68 HTTPContext *s = h->priv_data;
69 int len = strlen(headers);
71 if (len && strcmp("\r\n", headers + len - 2))
72 av_log(NULL, AV_LOG_ERROR, "No trailing CRLF found in HTTP header.\n");
74 av_strlcpy(s->headers, headers, sizeof(s->headers));
77 void ff_http_set_chunked_transfer_encoding(URLContext *h, int is_chunked)
79 ((HTTPContext*)h->priv_data)->chunksize = is_chunked ? 0 : -1;
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));
88 /* return non zero if error */
89 static int http_open_cnx(URLContext *h)
91 const char *path, *proxy_path;
92 char hostname[1024], hoststr[1024];
96 int port, use_proxy, err, location_changed = 0, redirects = 0;
97 HTTPAuthType cur_auth_type;
98 HTTPContext *s = h->priv_data;
99 URLContext *hd = NULL;
101 proxy_path = getenv("http_proxy");
102 use_proxy = (proxy_path != NULL) && !getenv("no_proxy") &&
103 av_strstart(proxy_path, "http://", NULL);
105 /* fill the dest addr */
107 /* needed in any case to build the host string */
108 av_url_split(NULL, 0, auth, sizeof(auth), hostname, sizeof(hostname), &port,
109 path1, sizeof(path1), s->location);
110 ff_url_join(hoststr, sizeof(hoststr), NULL, NULL, hostname, port, NULL);
113 av_url_split(NULL, 0, auth, sizeof(auth), hostname, sizeof(hostname), &port,
114 NULL, 0, proxy_path);
117 if (path1[0] == '\0')
125 ff_url_join(buf, sizeof(buf), "tcp", NULL, hostname, port, NULL);
126 err = url_open(&hd, buf, URL_RDWR);
131 cur_auth_type = s->auth_state.auth_type;
132 if (http_connect(h, path, hoststr, auth, &location_changed) < 0)
134 if (s->http_code == 401) {
135 if (cur_auth_type == HTTP_AUTH_NONE && s->auth_state.auth_type != HTTP_AUTH_NONE) {
141 if ((s->http_code == 302 || s->http_code == 303) && location_changed == 1) {
142 /* url moved, get next */
144 if (redirects++ >= MAX_REDIRECTS)
146 location_changed = 0;
157 static int http_open(URLContext *h, const char *uri, int flags)
159 HTTPContext *s = h->priv_data;
164 av_strlcpy(s->location, uri, sizeof(s->location));
166 return http_open_cnx(h);
168 static int http_getc(HTTPContext *s)
171 if (s->buf_ptr >= s->buf_end) {
172 len = url_read(s->hd, s->buffer, BUFFER_SIZE);
175 } else if (len == 0) {
178 s->buf_ptr = s->buffer;
179 s->buf_end = s->buffer + len;
182 return *s->buf_ptr++;
185 static int http_get_line(HTTPContext *s, char *line, int line_size)
197 if (q > line && q[-1] == '\r')
203 if ((q - line) < line_size - 1)
209 static int process_line(URLContext *h, char *line, int line_count,
212 HTTPContext *s = h->priv_data;
220 if (line_count == 0) {
221 while (!isspace(*p) && *p != '\0')
225 s->http_code = strtol(p, &end, 10);
227 dprintf(NULL, "http_code=%d\n", s->http_code);
229 /* error codes are 4xx and 5xx, but regard 401 as a success, so we
230 * don't abort until all headers have been parsed. */
231 if (s->http_code >= 400 && s->http_code < 600 && s->http_code != 401) {
232 end += strspn(end, SPACE_CHARS);
233 av_log(NULL, AV_LOG_WARNING, "HTTP error %d %s\n",
238 while (*p != '\0' && *p != ':')
248 if (!strcmp(tag, "Location")) {
249 strcpy(s->location, p);
251 } else if (!strcmp (tag, "Content-Length") && s->filesize == -1) {
252 s->filesize = atoll(p);
253 } else if (!strcmp (tag, "Content-Range")) {
254 /* "bytes $from-$to/$document_size" */
256 if (!strncmp (p, "bytes ", 6)) {
259 if ((slash = strchr(p, '/')) && strlen(slash) > 0)
260 s->filesize = atoll(slash+1);
262 h->is_streamed = 0; /* we _can_ in fact seek */
263 } else if (!strcmp (tag, "Transfer-Encoding") && !strncasecmp(p, "chunked", 7)) {
266 } else if (!strcmp (tag, "WWW-Authenticate")) {
267 ff_http_auth_handle_header(&s->auth_state, tag, p);
268 } else if (!strcmp (tag, "Authentication-Info")) {
269 ff_http_auth_handle_header(&s->auth_state, tag, p);
270 } else if (!strcmp (tag, "Connection")) {
271 if (!strcmp(p, "close"))
278 static inline int has_header(const char *str, const char *header)
280 /* header + 2 to skip over CRLF prefix. (make sure you have one!) */
281 return av_stristart(str, header + 2, NULL) || av_stristr(str, header);
284 static int http_connect(URLContext *h, const char *path, const char *hoststr,
285 const char *auth, int *new_location)
287 HTTPContext *s = h->priv_data;
290 char headers[1024] = "";
291 char *authstr = NULL;
292 int64_t off = s->off;
296 /* send http header */
297 post = h->flags & URL_WRONLY;
298 authstr = ff_http_auth_create_response(&s->auth_state, auth, path,
299 post ? "POST" : "GET");
301 /* set default headers if needed */
302 if (!has_header(s->headers, "\r\nUser-Agent: "))
303 len += av_strlcatf(headers + len, sizeof(headers) - len,
304 "User-Agent: %s\r\n", LIBAVFORMAT_IDENT);
305 if (!has_header(s->headers, "\r\nAccept: "))
306 len += av_strlcpy(headers + len, "Accept: */*\r\n",
307 sizeof(headers) - len);
308 if (!has_header(s->headers, "\r\nRange: "))
309 len += av_strlcatf(headers + len, sizeof(headers) - len,
310 "Range: bytes=%"PRId64"-\r\n", s->off);
311 if (!has_header(s->headers, "\r\nConnection: "))
312 len += av_strlcpy(headers + len, "Connection: close\r\n",
313 sizeof(headers)-len);
314 if (!has_header(s->headers, "\r\nHost: "))
315 len += av_strlcatf(headers + len, sizeof(headers) - len,
316 "Host: %s\r\n", hoststr);
318 /* now add in custom headers */
319 av_strlcpy(headers+len, s->headers, sizeof(headers)-len);
321 snprintf(s->buffer, sizeof(s->buffer),
327 post ? "POST" : "GET",
329 post && s->chunksize >= 0 ? "Transfer-Encoding: chunked\r\n" : "",
331 authstr ? authstr : "");
334 if (url_write(s->hd, s->buffer, strlen(s->buffer)) < 0)
337 /* init input buffer */
338 s->buf_ptr = s->buffer;
339 s->buf_end = s->buffer;
345 /* Pretend that it did work. We didn't read any header yet, since
346 * we've still to send the POST data, but the code calling this
347 * function will check http_code after we return. */
353 /* wait for header */
355 if (http_get_line(s, line, sizeof(line)) < 0)
358 dprintf(NULL, "header='%s'\n", line);
360 err = process_line(h, line, s->line_count, new_location);
368 return (off == s->off) ? 0 : -1;
372 static int http_read(URLContext *h, uint8_t *buf, int size)
374 HTTPContext *s = h->priv_data;
377 if (s->chunksize >= 0) {
383 if (http_get_line(s, line, sizeof(line)) < 0)
385 } while (!*line); /* skip CR LF from last chunk */
387 s->chunksize = strtoll(line, NULL, 16);
389 dprintf(NULL, "Chunked encoding data size: %"PRId64"'\n", s->chunksize);
396 size = FFMIN(size, s->chunksize);
398 /* read bytes from input buffer first */
399 len = s->buf_end - s->buf_ptr;
403 memcpy(buf, s->buf_ptr, len);
406 if (!s->willclose && s->filesize >= 0 && s->off >= s->filesize)
408 len = url_read(s->hd, buf, size);
412 if (s->chunksize > 0)
418 /* used only when posting data */
419 static int http_write(URLContext *h, const uint8_t *buf, int size)
421 char temp[11] = ""; /* 32-bit hex + CRLF + nul */
423 char crlf[] = "\r\n";
424 HTTPContext *s = h->priv_data;
426 if (s->chunksize == -1) {
427 /* non-chunked data is sent without any special encoding */
428 return url_write(s->hd, buf, size);
431 /* silently ignore zero-size data since chunk encoding that would
434 /* upload data using chunked encoding */
435 snprintf(temp, sizeof(temp), "%x\r\n", size);
437 if ((ret = url_write(s->hd, temp, strlen(temp))) < 0 ||
438 (ret = url_write(s->hd, buf, size)) < 0 ||
439 (ret = url_write(s->hd, crlf, sizeof(crlf) - 1)) < 0)
445 static int http_close(URLContext *h)
448 char footer[] = "0\r\n\r\n";
449 HTTPContext *s = h->priv_data;
451 /* signal end of chunked encoding if used */
452 if ((h->flags & URL_WRONLY) && s->chunksize != -1) {
453 ret = url_write(s->hd, footer, sizeof(footer) - 1);
454 ret = ret > 0 ? 0 : ret;
462 static int64_t http_seek(URLContext *h, int64_t off, int whence)
464 HTTPContext *s = h->priv_data;
465 URLContext *old_hd = s->hd;
466 int64_t old_off = s->off;
467 uint8_t old_buf[BUFFER_SIZE];
470 if (whence == AVSEEK_SIZE)
472 else if ((s->filesize == -1 && whence == SEEK_END) || h->is_streamed)
475 /* we save the old context in case the seek fails */
476 old_buf_size = s->buf_end - s->buf_ptr;
477 memcpy(old_buf, s->buf_ptr, old_buf_size);
479 if (whence == SEEK_CUR)
481 else if (whence == SEEK_END)
485 /* if it fails, continue on old connection */
486 if (http_open_cnx(h) < 0) {
487 memcpy(s->buffer, old_buf, old_buf_size);
488 s->buf_ptr = s->buffer;
489 s->buf_end = s->buffer + old_buf_size;
499 http_get_file_handle(URLContext *h)
501 HTTPContext *s = h->priv_data;
502 return url_get_file_handle(s->hd);
505 URLProtocol http_protocol = {
512 .url_get_file_handle = http_get_file_handle,
513 .priv_data_size = sizeof(HTTPContext),
514 .priv_data_class = &httpcontext_class,