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 /* XXX: POST protocol is not completely implemented because ffmpeg uses
33 only a subset of it. */
35 /* used for protocol handling */
36 #define BUFFER_SIZE 1024
38 #define MAX_REDIRECTS 8
42 unsigned char buffer[BUFFER_SIZE], *buf_ptr, *buf_end;
45 int64_t chunksize; /**< Used if "Transfer-Encoding: chunked" otherwise -1. */
46 int64_t off, filesize;
47 char location[URL_SIZE];
48 HTTPAuthState auth_state;
50 unsigned char headers[BUFFER_SIZE];
54 static int http_connect(URLContext *h, const char *path, const char *hoststr,
55 const char *auth, int *new_location);
57 void ff_http_set_headers(URLContext *h, const char *headers)
59 HTTPContext *s = h->priv_data;
60 int len = strlen(headers);
62 if (len && strcmp("\r\n", headers + len - 2))
63 av_log(NULL, AV_LOG_ERROR, "No trailing CRLF found in HTTP header.\n");
65 av_strlcpy(s->headers, headers, sizeof(s->headers));
68 void ff_http_set_chunked_transfer_encoding(URLContext *h, int is_chunked)
70 ((HTTPContext*)h->priv_data)->is_chunked = is_chunked;
73 /* return non zero if error */
74 static int http_open_cnx(URLContext *h)
76 const char *path, *proxy_path;
77 char hostname[1024], hoststr[1024];
81 int port, use_proxy, err, location_changed = 0, redirects = 0;
82 HTTPAuthType cur_auth_type;
83 HTTPContext *s = h->priv_data;
84 URLContext *hd = NULL;
87 proxy_path = getenv("http_proxy");
88 use_proxy = (proxy_path != NULL) && !getenv("no_proxy") &&
89 av_strstart(proxy_path, "http://", NULL);
91 /* fill the dest addr */
93 /* needed in any case to build the host string */
94 ff_url_split(NULL, 0, auth, sizeof(auth), hostname, sizeof(hostname), &port,
95 path1, sizeof(path1), s->location);
96 ff_url_join(hoststr, sizeof(hoststr), NULL, NULL, hostname, port, NULL);
99 ff_url_split(NULL, 0, auth, sizeof(auth), hostname, sizeof(hostname), &port,
100 NULL, 0, proxy_path);
103 if (path1[0] == '\0')
111 ff_url_join(buf, sizeof(buf), "tcp", NULL, hostname, port, NULL);
112 err = url_open(&hd, buf, URL_RDWR);
117 cur_auth_type = s->auth_state.auth_type;
118 if (http_connect(h, path, hoststr, auth, &location_changed) < 0)
120 if (s->http_code == 401) {
121 if (cur_auth_type == HTTP_AUTH_NONE && s->auth_state.auth_type != HTTP_AUTH_NONE) {
127 if ((s->http_code == 302 || s->http_code == 303) && location_changed == 1) {
128 /* url moved, get next */
130 if (redirects++ >= MAX_REDIRECTS)
132 location_changed = 0;
143 static int http_open(URLContext *h, const char *uri, int flags)
149 s = av_malloc(sizeof(HTTPContext));
151 return AVERROR(ENOMEM);
160 memset(&s->auth_state, 0, sizeof(s->auth_state));
161 av_strlcpy(s->location, uri, URL_SIZE);
165 static int http_getc(HTTPContext *s)
168 if (s->buf_ptr >= s->buf_end) {
169 len = url_read(s->hd, s->buffer, BUFFER_SIZE);
172 } else if (len == 0) {
175 s->buf_ptr = s->buffer;
176 s->buf_end = s->buffer + len;
179 return *s->buf_ptr++;
182 static int http_get_line(HTTPContext *s, char *line, int line_size)
194 if (q > line && q[-1] == '\r')
200 if ((q - line) < line_size - 1)
206 static int process_line(URLContext *h, char *line, int line_count,
209 HTTPContext *s = h->priv_data;
217 if (line_count == 0) {
218 while (!isspace(*p) && *p != '\0')
222 s->http_code = strtol(p, NULL, 10);
224 dprintf(NULL, "http_code=%d\n", s->http_code);
226 /* error codes are 4xx and 5xx, but regard 401 as a success, so we
227 * don't abort until all headers have been parsed. */
228 if (s->http_code >= 400 && s->http_code < 600 && s->http_code != 401)
231 while (*p != '\0' && *p != ':')
241 if (!strcmp(tag, "Location")) {
242 strcpy(s->location, p);
244 } else if (!strcmp (tag, "Content-Length") && s->filesize == -1) {
245 s->filesize = atoll(p);
246 } else if (!strcmp (tag, "Content-Range")) {
247 /* "bytes $from-$to/$document_size" */
249 if (!strncmp (p, "bytes ", 6)) {
252 if ((slash = strchr(p, '/')) && strlen(slash) > 0)
253 s->filesize = atoll(slash+1);
255 h->is_streamed = 0; /* we _can_ in fact seek */
256 } else if (!strcmp (tag, "Transfer-Encoding") && !strncasecmp(p, "chunked", 7)) {
259 } else if (!strcmp (tag, "WWW-Authenticate")) {
260 ff_http_auth_handle_header(&s->auth_state, tag, p);
261 } else if (!strcmp (tag, "Authentication-Info")) {
262 ff_http_auth_handle_header(&s->auth_state, tag, p);
268 static inline int has_header(const char *str, const char *header)
270 /* header + 2 to skip over CRLF prefix. (make sure you have one!) */
271 return av_stristart(str, header + 2, NULL) || av_stristr(str, header);
274 static int http_connect(URLContext *h, const char *path, const char *hoststr,
275 const char *auth, int *new_location)
277 HTTPContext *s = h->priv_data;
280 char headers[1024] = "";
281 char *authstr = NULL;
282 int64_t off = s->off;
286 /* send http header */
287 post = h->flags & URL_WRONLY;
288 authstr = ff_http_auth_create_response(&s->auth_state, auth, path,
289 post ? "POST" : "GET");
291 /* set default headers if needed */
292 if (!has_header(s->headers, "\r\nUser-Agent: "))
293 len += av_strlcatf(headers + len, sizeof(headers) - len,
294 "User-Agent: %s\r\n", LIBAVFORMAT_IDENT);
295 if (!has_header(s->headers, "\r\nAccept: "))
296 len += av_strlcpy(headers + len, "Accept: */*\r\n",
297 sizeof(headers) - len);
298 if (!has_header(s->headers, "\r\nRange: "))
299 len += av_strlcatf(headers + len, sizeof(headers) - len,
300 "Range: bytes=%"PRId64"-\r\n", s->off);
301 if (!has_header(s->headers, "\r\nConnection: "))
302 len += av_strlcpy(headers + len, "Connection: close\r\n",
303 sizeof(headers)-len);
304 if (!has_header(s->headers, "\r\nHost: "))
305 len += av_strlcatf(headers + len, sizeof(headers) - len,
306 "Host: %s\r\n", hoststr);
308 /* now add in custom headers */
309 av_strlcpy(headers+len, s->headers, sizeof(headers)-len);
311 snprintf(s->buffer, sizeof(s->buffer),
317 post ? "POST" : "GET",
319 post && s->is_chunked ? "Transfer-Encoding: chunked\r\n" : "",
321 authstr ? authstr : "");
324 if (url_write(s->hd, s->buffer, strlen(s->buffer)) < 0)
327 /* init input buffer */
328 s->buf_ptr = s->buffer;
329 s->buf_end = s->buffer;
335 /* always use chunked encoding for upload data */
337 /* Pretend that it did work. We didn't read any header yet, since
338 * we've still to send the POST data, but the code calling this
339 * function will check http_code after we return. */
344 /* wait for header */
346 if (http_get_line(s, line, sizeof(line)) < 0)
349 dprintf(NULL, "header='%s'\n", line);
351 err = process_line(h, line, s->line_count, new_location);
359 return (off == s->off) ? 0 : -1;
363 static int http_read(URLContext *h, uint8_t *buf, int size)
365 HTTPContext *s = h->priv_data;
369 int ret = http_open_cnx(h);
376 /* A size of zero can be used to force
377 * initializaton of the connection. */
381 if (s->chunksize >= 0) {
387 if (http_get_line(s, line, sizeof(line)) < 0)
389 } while (!*line); /* skip CR LF from last chunk */
391 s->chunksize = strtoll(line, NULL, 16);
393 dprintf(NULL, "Chunked encoding data size: %"PRId64"'\n", s->chunksize);
400 size = FFMIN(size, s->chunksize);
402 /* read bytes from input buffer first */
403 len = s->buf_end - s->buf_ptr;
407 memcpy(buf, s->buf_ptr, len);
410 len = url_read(s->hd, buf, size);
414 if (s->chunksize > 0)
420 /* used only when posting data */
421 static int http_write(URLContext *h, const uint8_t *buf, int size)
423 char temp[11] = ""; /* 32-bit hex + CRLF + nul */
425 char crlf[] = "\r\n";
426 HTTPContext *s = h->priv_data;
429 int ret = http_open_cnx(h);
436 if (s->chunksize == -1) {
437 /* headers are sent without any special encoding */
438 return url_write(s->hd, buf, size);
441 /* silently ignore zero-size data since chunk encoding that would
444 /* upload data using chunked encoding */
446 snprintf(temp, sizeof(temp), "%x\r\n", size);
447 if ((ret = url_write(s->hd, temp, strlen(temp))) < 0)
451 if ((ret = url_write(s->hd, buf, size)) < 0)
454 if (s->is_chunked && (ret = url_write(s->hd, crlf, sizeof(crlf) - 1)) < 0)
460 static int http_close(URLContext *h)
463 char footer[] = "0\r\n\r\n";
464 HTTPContext *s = h->priv_data;
466 /* signal end of chunked encoding if used */
467 if ((h->flags & URL_WRONLY) && s->chunksize != -1) {
468 ret = url_write(s->hd, footer, sizeof(footer) - 1);
469 ret = ret > 0 ? 0 : ret;
478 static int64_t http_seek(URLContext *h, int64_t off, int whence)
480 HTTPContext *s = h->priv_data;
481 URLContext *old_hd = s->hd;
482 int64_t old_off = s->off;
483 uint8_t old_buf[BUFFER_SIZE];
487 int ret = http_open_cnx(h);
494 if (whence == AVSEEK_SIZE)
496 else if ((s->filesize == -1 && whence == SEEK_END) || h->is_streamed)
499 /* we save the old context in case the seek fails */
500 old_buf_size = s->buf_end - s->buf_ptr;
501 memcpy(old_buf, s->buf_ptr, old_buf_size);
503 if (whence == SEEK_CUR)
505 else if (whence == SEEK_END)
509 /* if it fails, continue on old connection */
510 if (http_open_cnx(h) < 0) {
511 memcpy(s->buffer, old_buf, old_buf_size);
512 s->buf_ptr = s->buffer;
513 s->buf_end = s->buffer + old_buf_size;
523 http_get_file_handle(URLContext *h)
525 HTTPContext *s = h->priv_data;
526 return url_get_file_handle(s->hd);
529 URLProtocol http_protocol = {
536 .url_get_file_handle = http_get_file_handle,