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];
53 static int http_connect(URLContext *h, const char *path, const char *hoststr,
54 const char *auth, int *new_location);
56 void ff_http_set_headers(URLContext *h, const char *headers)
58 HTTPContext *s = h->priv_data;
59 int len = strlen(headers);
61 if (len && strcmp("\r\n", headers + len - 2))
62 av_log(NULL, AV_LOG_ERROR, "No trailing CRLF found in HTTP header.\n");
64 av_strlcpy(s->headers, headers, sizeof(s->headers));
67 void ff_http_set_chunked_transfer_encoding(URLContext *h, int is_chunked)
69 ((HTTPContext*)h->priv_data)->chunksize = is_chunked ? 0 : -1;
72 /* return non zero if error */
73 static int http_open_cnx(URLContext *h)
75 const char *path, *proxy_path;
76 char hostname[1024], hoststr[1024];
80 int port, use_proxy, err, location_changed = 0, redirects = 0;
81 HTTPAuthType cur_auth_type;
82 HTTPContext *s = h->priv_data;
83 URLContext *hd = NULL;
86 proxy_path = getenv("http_proxy");
87 use_proxy = (proxy_path != NULL) && !getenv("no_proxy") &&
88 av_strstart(proxy_path, "http://", NULL);
90 /* fill the dest addr */
92 /* needed in any case to build the host string */
93 ff_url_split(NULL, 0, auth, sizeof(auth), hostname, sizeof(hostname), &port,
94 path1, sizeof(path1), s->location);
95 ff_url_join(hoststr, sizeof(hoststr), NULL, NULL, hostname, port, NULL);
98 ff_url_split(NULL, 0, auth, sizeof(auth), hostname, sizeof(hostname), &port,
102 if (path1[0] == '\0')
110 ff_url_join(buf, sizeof(buf), "tcp", NULL, hostname, port, NULL);
111 err = url_open(&hd, buf, URL_RDWR);
116 cur_auth_type = s->auth_state.auth_type;
117 if (http_connect(h, path, hoststr, auth, &location_changed) < 0)
119 if (s->http_code == 401) {
120 if (cur_auth_type == HTTP_AUTH_NONE && s->auth_state.auth_type != HTTP_AUTH_NONE) {
126 if ((s->http_code == 302 || s->http_code == 303) && location_changed == 1) {
127 /* url moved, get next */
129 if (redirects++ >= MAX_REDIRECTS)
131 location_changed = 0;
142 static int http_open(URLContext *h, const char *uri, int flags)
148 s = av_malloc(sizeof(HTTPContext));
150 return AVERROR(ENOMEM);
154 s->chunksize = 0; /* Default to chunked POSTs */
159 memset(&s->auth_state, 0, sizeof(s->auth_state));
160 av_strlcpy(s->location, uri, URL_SIZE);
164 static int http_getc(HTTPContext *s)
167 if (s->buf_ptr >= s->buf_end) {
168 len = url_read(s->hd, s->buffer, BUFFER_SIZE);
171 } else if (len == 0) {
174 s->buf_ptr = s->buffer;
175 s->buf_end = s->buffer + len;
178 return *s->buf_ptr++;
181 static int http_get_line(HTTPContext *s, char *line, int line_size)
193 if (q > line && q[-1] == '\r')
199 if ((q - line) < line_size - 1)
205 static int process_line(URLContext *h, char *line, int line_count,
208 HTTPContext *s = h->priv_data;
216 if (line_count == 0) {
217 while (!isspace(*p) && *p != '\0')
221 s->http_code = strtol(p, NULL, 10);
223 dprintf(NULL, "http_code=%d\n", s->http_code);
225 /* error codes are 4xx and 5xx, but regard 401 as a success, so we
226 * don't abort until all headers have been parsed. */
227 if (s->http_code >= 400 && s->http_code < 600 && s->http_code != 401)
230 while (*p != '\0' && *p != ':')
240 if (!strcmp(tag, "Location")) {
241 strcpy(s->location, p);
243 } else if (!strcmp (tag, "Content-Length") && s->filesize == -1) {
244 s->filesize = atoll(p);
245 } else if (!strcmp (tag, "Content-Range")) {
246 /* "bytes $from-$to/$document_size" */
248 if (!strncmp (p, "bytes ", 6)) {
251 if ((slash = strchr(p, '/')) && strlen(slash) > 0)
252 s->filesize = atoll(slash+1);
254 h->is_streamed = 0; /* we _can_ in fact seek */
255 } else if (!strcmp (tag, "Transfer-Encoding") && !strncasecmp(p, "chunked", 7)) {
258 } else if (!strcmp (tag, "WWW-Authenticate")) {
259 ff_http_auth_handle_header(&s->auth_state, tag, p);
260 } else if (!strcmp (tag, "Authentication-Info")) {
261 ff_http_auth_handle_header(&s->auth_state, tag, p);
267 static inline int has_header(const char *str, const char *header)
269 /* header + 2 to skip over CRLF prefix. (make sure you have one!) */
270 return av_stristart(str, header + 2, NULL) || av_stristr(str, header);
273 static int http_connect(URLContext *h, const char *path, const char *hoststr,
274 const char *auth, int *new_location)
276 HTTPContext *s = h->priv_data;
279 char headers[1024] = "";
280 char *authstr = NULL;
281 int64_t off = s->off;
285 /* send http header */
286 post = h->flags & URL_WRONLY;
287 authstr = ff_http_auth_create_response(&s->auth_state, auth, path,
288 post ? "POST" : "GET");
290 /* set default headers if needed */
291 if (!has_header(s->headers, "\r\nUser-Agent: "))
292 len += av_strlcatf(headers + len, sizeof(headers) - len,
293 "User-Agent: %s\r\n", LIBAVFORMAT_IDENT);
294 if (!has_header(s->headers, "\r\nAccept: "))
295 len += av_strlcpy(headers + len, "Accept: */*\r\n",
296 sizeof(headers) - len);
297 if (!has_header(s->headers, "\r\nRange: "))
298 len += av_strlcatf(headers + len, sizeof(headers) - len,
299 "Range: bytes=%"PRId64"-\r\n", s->off);
300 if (!has_header(s->headers, "\r\nConnection: "))
301 len += av_strlcpy(headers + len, "Connection: close\r\n",
302 sizeof(headers)-len);
303 if (!has_header(s->headers, "\r\nHost: "))
304 len += av_strlcatf(headers + len, sizeof(headers) - len,
305 "Host: %s\r\n", hoststr);
307 /* now add in custom headers */
308 av_strlcpy(headers+len, s->headers, sizeof(headers)-len);
310 snprintf(s->buffer, sizeof(s->buffer),
316 post ? "POST" : "GET",
318 post && s->chunksize >= 0 ? "Transfer-Encoding: chunked\r\n" : "",
320 authstr ? authstr : "");
323 if (url_write(s->hd, s->buffer, strlen(s->buffer)) < 0)
326 /* init input buffer */
327 s->buf_ptr = s->buffer;
328 s->buf_end = s->buffer;
333 /* Pretend that it did work. We didn't read any header yet, since
334 * we've still to send the POST data, but the code calling this
335 * function will check http_code after we return. */
341 /* wait for header */
343 if (http_get_line(s, line, sizeof(line)) < 0)
346 dprintf(NULL, "header='%s'\n", line);
348 err = process_line(h, line, s->line_count, new_location);
356 return (off == s->off) ? 0 : -1;
360 static int http_read(URLContext *h, uint8_t *buf, int size)
362 HTTPContext *s = h->priv_data;
366 int ret = http_open_cnx(h);
373 /* A size of zero can be used to force
374 * initializaton of the connection. */
378 if (s->chunksize >= 0) {
384 if (http_get_line(s, line, sizeof(line)) < 0)
386 } while (!*line); /* skip CR LF from last chunk */
388 s->chunksize = strtoll(line, NULL, 16);
390 dprintf(NULL, "Chunked encoding data size: %"PRId64"'\n", s->chunksize);
397 size = FFMIN(size, s->chunksize);
399 /* read bytes from input buffer first */
400 len = s->buf_end - s->buf_ptr;
404 memcpy(buf, s->buf_ptr, len);
407 len = url_read(s->hd, buf, size);
411 if (s->chunksize > 0)
417 /* used only when posting data */
418 static int http_write(URLContext *h, const uint8_t *buf, int size)
420 char temp[11] = ""; /* 32-bit hex + CRLF + nul */
422 char crlf[] = "\r\n";
423 HTTPContext *s = h->priv_data;
426 int ret = http_open_cnx(h);
433 if (s->chunksize == -1) {
434 /* non-chunked data is sent without any special encoding */
435 return url_write(s->hd, buf, size);
438 /* silently ignore zero-size data since chunk encoding that would
441 /* upload data using chunked encoding */
442 snprintf(temp, sizeof(temp), "%x\r\n", size);
444 if ((ret = url_write(s->hd, temp, strlen(temp))) < 0 ||
445 (ret = url_write(s->hd, buf, size)) < 0 ||
446 (ret = url_write(s->hd, crlf, sizeof(crlf) - 1)) < 0)
452 static int http_close(URLContext *h)
455 char footer[] = "0\r\n\r\n";
456 HTTPContext *s = h->priv_data;
458 /* signal end of chunked encoding if used */
459 if ((h->flags & URL_WRONLY) && s->chunksize != -1) {
460 ret = url_write(s->hd, footer, sizeof(footer) - 1);
461 ret = ret > 0 ? 0 : ret;
470 static int64_t http_seek(URLContext *h, int64_t off, int whence)
472 HTTPContext *s = h->priv_data;
473 URLContext *old_hd = s->hd;
474 int64_t old_off = s->off;
475 uint8_t old_buf[BUFFER_SIZE];
479 int ret = http_open_cnx(h);
486 if (whence == AVSEEK_SIZE)
488 else if ((s->filesize == -1 && whence == SEEK_END) || h->is_streamed)
491 /* we save the old context in case the seek fails */
492 old_buf_size = s->buf_end - s->buf_ptr;
493 memcpy(old_buf, s->buf_ptr, old_buf_size);
495 if (whence == SEEK_CUR)
497 else if (whence == SEEK_END)
501 /* if it fails, continue on old connection */
502 if (http_open_cnx(h) < 0) {
503 memcpy(s->buffer, old_buf, old_buf_size);
504 s->buf_ptr = s->buffer;
505 s->buf_end = s->buffer + old_buf_size;
515 http_get_file_handle(URLContext *h)
517 HTTPContext *s = h->priv_data;
518 return url_get_file_handle(s->hd);
521 URLProtocol http_protocol = {
528 .url_get_file_handle = http_get_file_handle,