2 * HTTP protocol for avconv client
3 * Copyright (c) 2000, 2001 Fabrice Bellard
5 * This file is part of Libav.
7 * Libav 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 * Libav 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 Libav; 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 avconv 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
;
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
), AV_OPT_TYPE_INT64
, {.dbl
= 0}, -1, 0 }, /* Default to 0, for chunked POSTs */
57 {"headers", "custom HTTP headers, can override built in default headers", OFFSET(headers
), AV_OPT_TYPE_STRING
},
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_init_auth_state(URLContext
*dest
, const URLContext
*src
)
72 memcpy(&((HTTPContext
*)dest
->priv_data
)->auth_state
,
73 &((HTTPContext
*)src
->priv_data
)->auth_state
, sizeof(HTTPAuthState
));
76 /* return non zero if error */
77 static int http_open_cnx(URLContext
*h
)
79 const char *path
, *proxy_path
, *lower_proto
= "tcp";
80 char hostname
[1024], hoststr
[1024], proto
[10];
84 int port
, use_proxy
, err
, location_changed
= 0, redirects
= 0;
85 HTTPAuthType cur_auth_type
;
86 HTTPContext
*s
= h
->priv_data
;
87 URLContext
*hd
= NULL
;
89 proxy_path
= getenv("http_proxy");
90 use_proxy
= (proxy_path
!= NULL
) && !getenv("no_proxy") &&
91 av_strstart(proxy_path
, "http://", NULL
);
93 /* fill the dest addr */
95 /* needed in any case to build the host string */
96 av_url_split(proto
, sizeof(proto
), auth
, sizeof(auth
),
97 hostname
, sizeof(hostname
), &port
,
98 path1
, sizeof(path1
), s
->location
);
99 ff_url_join(hoststr
, sizeof(hoststr
), NULL
, NULL
, hostname
, port
, NULL
);
102 av_url_split(NULL
, 0, auth
, sizeof(auth
), hostname
, sizeof(hostname
), &port
,
103 NULL
, 0, proxy_path
);
106 if (path1
[0] == '\0')
111 if (!strcmp(proto
, "https")) {
119 ff_url_join(buf
, sizeof(buf
), lower_proto
, NULL
, hostname
, port
, NULL
);
120 err
= ffurl_open(&hd
, buf
, AVIO_FLAG_READ_WRITE
);
125 cur_auth_type
= s
->auth_state
.auth_type
;
126 if (http_connect(h
, path
, hoststr
, auth
, &location_changed
) < 0)
128 if (s
->http_code
== 401) {
129 if (cur_auth_type
== HTTP_AUTH_NONE
&& s
->auth_state
.auth_type
!= HTTP_AUTH_NONE
) {
135 if ((s
->http_code
== 301 || s
->http_code
== 302 || s
->http_code
== 303 || s
->http_code
== 307)
136 && location_changed
== 1) {
137 /* url moved, get next */
139 if (redirects
++ >= MAX_REDIRECTS
)
141 location_changed
= 0;
152 static int http_open(URLContext
*h
, const char *uri
, int flags
)
154 HTTPContext
*s
= h
->priv_data
;
159 av_strlcpy(s
->location
, uri
, sizeof(s
->location
));
162 int len
= strlen(s
->headers
);
163 if (len
< 2 || strcmp("\r\n", s
->headers
+ len
- 2))
164 av_log(h
, AV_LOG_ERROR
, "No trailing CRLF found in HTTP header.\n");
167 return http_open_cnx(h
);
169 static int http_getc(HTTPContext
*s
)
172 if (s
->buf_ptr
>= s
->buf_end
) {
173 len
= ffurl_read(s
->hd
, s
->buffer
, BUFFER_SIZE
);
176 } else if (len
== 0) {
179 s
->buf_ptr
= s
->buffer
;
180 s
->buf_end
= s
->buffer
+ len
;
183 return *s
->buf_ptr
++;
186 static int http_get_line(HTTPContext
*s
, char *line
, int line_size
)
198 if (q
> line
&& q
[-1] == '\r')
204 if ((q
- line
) < line_size
- 1)
210 static int process_line(URLContext
*h
, char *line
, int line_count
,
213 HTTPContext
*s
= h
->priv_data
;
221 if (line_count
== 0) {
222 while (!isspace(*p
) && *p
!= '\0')
226 s
->http_code
= strtol(p
, &end
, 10);
228 av_dlog(NULL
, "http_code=%d\n", s
->http_code
);
230 /* error codes are 4xx and 5xx, but regard 401 as a success, so we
231 * don't abort until all headers have been parsed. */
232 if (s
->http_code
>= 400 && s
->http_code
< 600 && s
->http_code
!= 401) {
233 end
+= strspn(end
, SPACE_CHARS
);
234 av_log(h
, AV_LOG_WARNING
, "HTTP error %d %s\n",
239 while (*p
!= '\0' && *p
!= ':')
249 if (!av_strcasecmp(tag
, "Location")) {
250 strcpy(s
->location
, p
);
252 } else if (!av_strcasecmp (tag
, "Content-Length") && s
->filesize
== -1) {
253 s
->filesize
= atoll(p
);
254 } else if (!av_strcasecmp (tag
, "Content-Range")) {
255 /* "bytes $from-$to/$document_size" */
257 if (!strncmp (p
, "bytes ", 6)) {
260 if ((slash
= strchr(p
, '/')) && strlen(slash
) > 0)
261 s
->filesize
= atoll(slash
+1);
263 h
->is_streamed
= 0; /* we _can_ in fact seek */
264 } else if (!av_strcasecmp(tag
, "Accept-Ranges") && !strncmp(p
, "bytes", 5)) {
266 } else if (!av_strcasecmp (tag
, "Transfer-Encoding") && !av_strncasecmp(p
, "chunked", 7)) {
269 } else if (!av_strcasecmp (tag
, "WWW-Authenticate")) {
270 ff_http_auth_handle_header(&s
->auth_state
, tag
, p
);
271 } else if (!av_strcasecmp (tag
, "Authentication-Info")) {
272 ff_http_auth_handle_header(&s
->auth_state
, tag
, p
);
273 } else if (!av_strcasecmp (tag
, "Connection")) {
274 if (!strcmp(p
, "close"))
281 static inline int has_header(const char *str
, const char *header
)
283 /* 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 */
325 av_strlcpy(headers
+ len
, s
->headers
, sizeof(headers
) - len
);
327 snprintf(s
->buffer
, sizeof(s
->buffer
),
333 post ?
"POST" : "GET",
335 post
&& s
->chunksize
>= 0 ?
"Transfer-Encoding: chunked\r\n" : "",
337 authstr ? authstr
: "");
340 if (ffurl_write(s
->hd
, s
->buffer
, strlen(s
->buffer
)) < 0)
343 /* init input buffer */
344 s
->buf_ptr
= s
->buffer
;
345 s
->buf_end
= s
->buffer
;
351 /* Pretend that it did work. We didn't read any header yet, since
352 * we've still to send the POST data, but the code calling this
353 * function will check http_code after we return. */
359 /* wait for header */
361 if (http_get_line(s
, line
, sizeof(line
)) < 0)
364 av_dlog(NULL
, "header='%s'\n", line
);
366 err
= process_line(h
, line
, s
->line_count
, new_location
);
374 return (off
== s
->off
) ?
0 : -1;
378 static int http_read(URLContext
*h
, uint8_t *buf
, int size
)
380 HTTPContext
*s
= h
->priv_data
;
383 if (s
->chunksize
>= 0) {
389 if (http_get_line(s
, line
, sizeof(line
)) < 0)
391 } while (!*line
); /* skip CR LF from last chunk */
393 s
->chunksize
= strtoll(line
, NULL
, 16);
395 av_dlog(NULL
, "Chunked encoding data size: %"PRId64
"'\n", s
->chunksize
);
402 size
= FFMIN(size
, s
->chunksize
);
404 /* read bytes from input buffer first */
405 len
= s
->buf_end
- s
->buf_ptr
;
409 memcpy(buf
, s
->buf_ptr
, len
);
412 if (!s
->willclose
&& s
->filesize
>= 0 && s
->off
>= s
->filesize
)
414 len
= ffurl_read(s
->hd
, buf
, size
);
418 if (s
->chunksize
> 0)
424 /* used only when posting data */
425 static int http_write(URLContext
*h
, const uint8_t *buf
, int size
)
427 char temp
[11] = ""; /* 32-bit hex + CRLF + nul */
429 char crlf
[] = "\r\n";
430 HTTPContext
*s
= h
->priv_data
;
432 if (s
->chunksize
== -1) {
433 /* non-chunked data is sent without any special encoding */
434 return ffurl_write(s
->hd
, buf
, size
);
437 /* silently ignore zero-size data since chunk encoding that would
440 /* upload data using chunked encoding */
441 snprintf(temp
, sizeof(temp
), "%x\r\n", size
);
443 if ((ret
= ffurl_write(s
->hd
, temp
, strlen(temp
))) < 0 ||
444 (ret
= ffurl_write(s
->hd
, buf
, size
)) < 0 ||
445 (ret
= ffurl_write(s
->hd
, crlf
, sizeof(crlf
) - 1)) < 0)
451 static int http_close(URLContext
*h
)
454 char footer
[] = "0\r\n\r\n";
455 HTTPContext
*s
= h
->priv_data
;
457 /* signal end of chunked encoding if used */
458 if ((h
->flags
& AVIO_FLAG_WRITE
) && s
->chunksize
!= -1) {
459 ret
= ffurl_write(s
->hd
, footer
, sizeof(footer
) - 1);
460 ret
= ret
> 0 ?
0 : ret
;
468 static int64_t http_seek(URLContext
*h
, int64_t off
, int whence
)
470 HTTPContext
*s
= h
->priv_data
;
471 URLContext
*old_hd
= s
->hd
;
472 int64_t old_off
= s
->off
;
473 uint8_t old_buf
[BUFFER_SIZE
];
476 if (whence
== AVSEEK_SIZE
)
478 else if ((s
->filesize
== -1 && whence
== SEEK_END
) || h
->is_streamed
)
481 /* we save the old context in case the seek fails */
482 old_buf_size
= s
->buf_end
- s
->buf_ptr
;
483 memcpy(old_buf
, s
->buf_ptr
, old_buf_size
);
485 if (whence
== SEEK_CUR
)
487 else if (whence
== SEEK_END
)
491 /* if it fails, continue on old connection */
492 if (http_open_cnx(h
) < 0) {
493 memcpy(s
->buffer
, old_buf
, old_buf_size
);
494 s
->buf_ptr
= s
->buffer
;
495 s
->buf_end
= s
->buffer
+ old_buf_size
;
505 http_get_file_handle(URLContext
*h
)
507 HTTPContext
*s
= h
->priv_data
;
508 return ffurl_get_file_handle(s
->hd
);
511 #if CONFIG_HTTP_PROTOCOL
512 URLProtocol ff_http_protocol
= {
514 .url_open
= http_open
,
515 .url_read
= http_read
,
516 .url_write
= http_write
,
517 .url_seek
= http_seek
,
518 .url_close
= http_close
,
519 .url_get_file_handle
= http_get_file_handle
,
520 .priv_data_size
= sizeof(HTTPContext
),
521 .priv_data_class
= &httpcontext_class
,
524 #if CONFIG_HTTPS_PROTOCOL
525 URLProtocol ff_https_protocol
= {
527 .url_open
= http_open
,
528 .url_read
= http_read
,
529 .url_write
= http_write
,
530 .url_seek
= http_seek
,
531 .url_close
= http_close
,
532 .url_get_file_handle
= http_get_file_handle
,
533 .priv_data_size
= sizeof(HTTPContext
),
534 .priv_data_class
= &httpcontext_class
,