http: Improve options descriptions
[libav.git] / libavformat / http.c
CommitLineData
558b86a5 1/*
20566eb0 2 * HTTP protocol for avconv client
406792e7 3 * Copyright (c) 2000, 2001 Fabrice Bellard
558b86a5 4 *
2912e87a 5 * This file is part of Libav.
558b86a5 6 *
2912e87a 7 * Libav is free software; you can redistribute it and/or
558b86a5
LB
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.
11 *
2912e87a 12 * Libav is distributed in the hope that it will be useful,
558b86a5
LB
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.
16 *
17 * You should have received a copy of the GNU Lesser General Public
2912e87a 18 * License along with Libav; if not, write to the Free Software
558b86a5
LB
19 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20 */
245976da 21
245976da 22#include "libavutil/avstring.h"
558b86a5 23#include "avformat.h"
e4a9e3cc 24#include "internal.h"
558b86a5 25#include "network.h"
6964d510 26#include "http.h"
a5e979f4 27#include "os_support.h"
9405f733 28#include "httpauth.h"
0589da0a 29#include "url.h"
6ed04040 30#include "libavutil/opt.h"
558b86a5 31
0f51c398
ZR
32#if CONFIG_ZLIB
33#include <zlib.h>
34#endif
35
20566eb0 36/* XXX: POST protocol is not completely implemented because avconv uses
e42dba48 37 only a subset of it. */
558b86a5 38
8bd324e9
DS
39/* The IO buffer size is unrelated to the max URL size in itself, but needs
40 * to be large enough to fit the full request headers (including long
41 * path names).
42 */
43#define BUFFER_SIZE MAX_URL_SIZE
558b86a5
LB
44#define MAX_REDIRECTS 8
45
46typedef struct {
4167ba0b 47 const AVClass *class;
558b86a5
LB
48 URLContext *hd;
49 unsigned char buffer[BUFFER_SIZE], *buf_ptr, *buf_end;
50 int line_count;
51 int http_code;
78b21c1d
LB
52 /* Used if "Transfer-Encoding: chunked" otherwise -1. */
53 int64_t chunksize;
2ec33d27 54 int64_t off, end_off, filesize;
be4edda6 55 char *location;
9405f733 56 HTTPAuthState auth_state;
b911518d 57 HTTPAuthState proxy_auth_state;
10da1e91 58 char *headers;
e58c85b0 59 char *mime_type;
ddfc9890 60 char *user_agent;
78b21c1d
LB
61 /* Set if the server correctly handles Connection: close and will close
62 * the connection after feeding us the content. */
63 int willclose;
6149485f 64 int chunked_post;
78b21c1d
LB
65 /* A flag which indicates if the end of chunked encoding has been sent. */
66 int end_chunked_post;
67 /* A flag which indicates we have finished to read POST reply. */
68 int end_header;
69 /* A flag which indicates if we use persistent connections. */
70 int multiple_requests;
1876e7c0
SP
71 uint8_t *post_data;
72 int post_datalen;
8075c3d8
LB
73 int icy;
74 /* how much data was read since the last ICY metadata packet */
75 int icy_data_read;
76 /* after how many bytes of read data a new metadata packet will be found */
77 int icy_metaint;
78 char *icy_metadata_headers;
79 char *icy_metadata_packet;
0f51c398
ZR
80#if CONFIG_ZLIB
81 int compressed;
82 z_stream inflate_stream;
83 uint8_t *inflate_buffer;
84#endif
5c53bf7a 85 AVDictionary *chained_options;
71549a85 86 int send_expect_100;
558b86a5
LB
87} HTTPContext;
88
4167ba0b 89#define OFFSET(x) offsetof(HTTPContext, x)
a2519280
AK
90#define D AV_OPT_FLAG_DECODING_PARAM
91#define E AV_OPT_FLAG_ENCODING_PARAM
ddfc9890 92#define DEFAULT_USER_AGENT "Lavf/" AV_STRINGIFY(LIBAVFORMAT_VERSION)
4167ba0b 93static const AVOption options[] = {
e6153f17 94{"chunked_post", "use chunked transfer-encoding for posts", OFFSET(chunked_post), AV_OPT_TYPE_INT, {.i64 = 1}, 0, 1, E },
fe568b3d 95{"headers", "set custom HTTP headers, can override built in default headers", OFFSET(headers), AV_OPT_TYPE_STRING, { 0 }, 0, 0, D|E },
ddfc9890
CB
96{"user_agent", "override User-Agent header", OFFSET(user_agent), AV_OPT_TYPE_STRING, {.str = DEFAULT_USER_AGENT}, 0, 0, D },
97{"user-agent", "override User-Agent header, for compatibility with ffmpeg", OFFSET(user_agent), AV_OPT_TYPE_STRING, {.str = DEFAULT_USER_AGENT}, 0, 0, D },
e6153f17 98{"multiple_requests", "use persistent connections", OFFSET(multiple_requests), AV_OPT_TYPE_INT, {.i64 = 0}, 0, 1, D|E },
fe568b3d 99{"post_data", "set custom HTTP post data", OFFSET(post_data), AV_OPT_TYPE_BINARY, .flags = D|E },
e58c85b0 100{"mime_type", "export the MIME type", OFFSET(mime_type), AV_OPT_TYPE_STRING, {0}, 0, 0, AV_OPT_FLAG_EXPORT | AV_OPT_FLAG_READONLY },
8075c3d8
LB
101{"icy", "request ICY metadata", OFFSET(icy), AV_OPT_TYPE_INT, {.i64 = 0}, 0, 1, D },
102{"icy_metadata_headers", "return ICY metadata headers", OFFSET(icy_metadata_headers), AV_OPT_TYPE_STRING, {0}, 0, 0, AV_OPT_FLAG_EXPORT },
103{"icy_metadata_packet", "return current ICY metadata packet", OFFSET(icy_metadata_packet), AV_OPT_TYPE_STRING, {0}, 0, 0, AV_OPT_FLAG_EXPORT },
eb8b05a3
MS
104{"auth_type", "HTTP authentication type", OFFSET(auth_state.auth_type), AV_OPT_TYPE_INT, {.i64 = HTTP_AUTH_NONE}, HTTP_AUTH_NONE, HTTP_AUTH_BASIC, D|E, "auth_type" },
105{"none", "No auth method set, autodetect", 0, AV_OPT_TYPE_CONST, {.i64 = HTTP_AUTH_NONE}, 0, 0, D|E, "auth_type" },
106{"basic", "HTTP basic authentication", 0, AV_OPT_TYPE_CONST, {.i64 = HTTP_AUTH_BASIC}, 0, 0, D|E, "auth_type" },
76267ecc 107{"send_expect_100", "Force sending an Expect: 100-continue header for POST", OFFSET(send_expect_100), AV_OPT_TYPE_INT, {.i64 = 0}, 0, 1, E },
be4edda6 108{"location", "The actual location of the data received", OFFSET(location), AV_OPT_TYPE_STRING, { 0 }, 0, 0, D|E },
2ec33d27
AH
109{"offset", "initial byte offset", OFFSET(off), AV_OPT_TYPE_INT64, {.i64 = 0}, 0, INT64_MAX, D },
110{"end_offset", "try to limit the request to bytes preceding this offset", OFFSET(end_off), AV_OPT_TYPE_INT64, {.i64 = 0}, 0, INT64_MAX, D },
4167ba0b
MS
111{NULL}
112};
3b384502
AK
113#define HTTP_CLASS(flavor)\
114static const AVClass flavor ## _context_class = {\
115 .class_name = #flavor,\
116 .item_name = av_default_item_name,\
117 .option = options,\
118 .version = LIBAVUTIL_VERSION_INT,\
373211d8 119}
4167ba0b 120
3b384502
AK
121HTTP_CLASS(http);
122HTTP_CLASS(https);
123
b911518d
MS
124static int http_connect(URLContext *h, const char *path, const char *local_path,
125 const char *hoststr, const char *auth,
126 const char *proxyauth, int *new_location);
558b86a5 127
db302347
MS
128void ff_http_init_auth_state(URLContext *dest, const URLContext *src)
129{
130 memcpy(&((HTTPContext*)dest->priv_data)->auth_state,
131 &((HTTPContext*)src->priv_data)->auth_state, sizeof(HTTPAuthState));
b911518d
MS
132 memcpy(&((HTTPContext*)dest->priv_data)->proxy_auth_state,
133 &((HTTPContext*)src->priv_data)->proxy_auth_state,
134 sizeof(HTTPAuthState));
db302347
MS
135}
136
558b86a5 137/* return non zero if error */
5c53bf7a 138static int http_open_cnx(URLContext *h, AVDictionary **options)
558b86a5 139{
b911518d 140 const char *path, *proxy_path, *lower_proto = "tcp", *local_path;
183baead 141 char hostname[1024], hoststr[1024], proto[10];
abe20c59 142 char auth[1024], proxyauth[1024] = "";
8bd324e9
DS
143 char path1[MAX_URL_SIZE];
144 char buf[1024], urlbuf[MAX_URL_SIZE];
e75bbcf4 145 int port, use_proxy, err, location_changed = 0, redirects = 0, attempts = 0;
b911518d 146 HTTPAuthType cur_auth_type, cur_proxy_auth_type;
558b86a5 147 HTTPContext *s = h->priv_data;
558b86a5 148
558b86a5
LB
149 /* fill the dest addr */
150 redo:
151 /* needed in any case to build the host string */
183baead
MS
152 av_url_split(proto, sizeof(proto), auth, sizeof(auth),
153 hostname, sizeof(hostname), &port,
f984dcf6 154 path1, sizeof(path1), s->location);
57b5555c 155 ff_url_join(hoststr, sizeof(hoststr), NULL, NULL, hostname, port, NULL);
558b86a5 156
de9cd1b1
MS
157 proxy_path = getenv("http_proxy");
158 use_proxy = !ff_http_match_no_proxy(getenv("no_proxy"), hostname) &&
159 proxy_path != NULL && av_strstart(proxy_path, "http://", NULL);
160
f5c5d57b
MS
161 if (!strcmp(proto, "https")) {
162 lower_proto = "tls";
dbc2424b 163 use_proxy = 0;
f5c5d57b
MS
164 if (port < 0)
165 port = 443;
166 }
167 if (port < 0)
168 port = 80;
169
b911518d
MS
170 if (path1[0] == '\0')
171 path = "/";
172 else
173 path = path1;
174 local_path = path;
558b86a5 175 if (use_proxy) {
b911518d
MS
176 /* Reassemble the request URL without auth string - we don't
177 * want to leak the auth to the proxy. */
178 ff_url_join(urlbuf, sizeof(urlbuf), proto, NULL, hostname, port, "%s",
179 path1);
180 path = urlbuf;
181 av_url_split(NULL, 0, proxyauth, sizeof(proxyauth),
182 hostname, sizeof(hostname), &port, NULL, 0, proxy_path);
558b86a5 183 }
558b86a5 184
183baead 185 ff_url_join(buf, sizeof(buf), lower_proto, NULL, hostname, port, NULL);
558b86a5 186
e999b641 187 if (!s->hd) {
59525641 188 err = ffurl_open(&s->hd, buf, AVIO_FLAG_READ_WRITE,
5c53bf7a 189 &h->interrupt_callback, options);
e999b641
SP
190 if (err < 0)
191 goto fail;
e999b641
SP
192 }
193
9405f733 194 cur_auth_type = s->auth_state.auth_type;
b911518d
MS
195 cur_proxy_auth_type = s->auth_state.auth_type;
196 if (http_connect(h, path, local_path, hoststr, auth, proxyauth, &location_changed) < 0)
558b86a5 197 goto fail;
e75bbcf4 198 attempts++;
9405f733 199 if (s->http_code == 401) {
e75bbcf4
MS
200 if ((cur_auth_type == HTTP_AUTH_NONE || s->auth_state.stale) &&
201 s->auth_state.auth_type != HTTP_AUTH_NONE && attempts < 4) {
59525641
MS
202 ffurl_close(s->hd);
203 s->hd = NULL;
9405f733
MS
204 goto redo;
205 } else
206 goto fail;
207 }
b911518d 208 if (s->http_code == 407) {
e75bbcf4
MS
209 if ((cur_proxy_auth_type == HTTP_AUTH_NONE || s->proxy_auth_state.stale) &&
210 s->proxy_auth_state.auth_type != HTTP_AUTH_NONE && attempts < 4) {
59525641
MS
211 ffurl_close(s->hd);
212 s->hd = NULL;
b911518d
MS
213 goto redo;
214 } else
215 goto fail;
216 }
7e35d859
ME
217 if ((s->http_code == 301 || s->http_code == 302 || s->http_code == 303 || s->http_code == 307)
218 && location_changed == 1) {
558b86a5 219 /* url moved, get next */
59525641
MS
220 ffurl_close(s->hd);
221 s->hd = NULL;
558b86a5 222 if (redirects++ >= MAX_REDIRECTS)
6f3e0b21 223 return AVERROR(EIO);
499ad54d
MS
224 /* Restart the authentication process with the new target, which
225 * might use a different auth mechanism. */
226 memset(&s->auth_state, 0, sizeof(s->auth_state));
e75bbcf4 227 attempts = 0;
558b86a5
LB
228 location_changed = 0;
229 goto redo;
230 }
231 return 0;
232 fail:
59525641
MS
233 if (s->hd)
234 ffurl_close(s->hd);
701ea516 235 s->hd = NULL;
6f3e0b21 236 return AVERROR(EIO);
558b86a5
LB
237}
238
e999b641
SP
239int ff_http_do_new_request(URLContext *h, const char *uri)
240{
241 HTTPContext *s = h->priv_data;
5c53bf7a
MS
242 AVDictionary *options = NULL;
243 int ret;
e999b641
SP
244
245 s->off = 0;
8075c3d8 246 s->icy_data_read = 0;
be4edda6
MS
247 av_free(s->location);
248 s->location = av_strdup(uri);
249 if (!s->location)
250 return AVERROR(ENOMEM);
e999b641 251
5c53bf7a
MS
252 av_dict_copy(&options, s->chained_options, 0);
253 ret = http_open_cnx(h, &options);
254 av_dict_free(&options);
255 return ret;
e999b641
SP
256}
257
5c53bf7a
MS
258static int http_open(URLContext *h, const char *uri, int flags,
259 AVDictionary **options)
558b86a5 260{
a9a3364c 261 HTTPContext *s = h->priv_data;
5c53bf7a 262 int ret;
558b86a5
LB
263
264 h->is_streamed = 1;
265
558b86a5 266 s->filesize = -1;
be4edda6
MS
267 s->location = av_strdup(uri);
268 if (!s->location)
269 return AVERROR(ENOMEM);
5c53bf7a
MS
270 if (options)
271 av_dict_copy(&s->chained_options, *options, 0);
558b86a5 272
10da1e91
MS
273 if (s->headers) {
274 int len = strlen(s->headers);
275 if (len < 2 || strcmp("\r\n", s->headers + len - 2))
8ef79f42 276 av_log(h, AV_LOG_WARNING, "No trailing CRLF found in HTTP header.\n");
10da1e91
MS
277 }
278
5c53bf7a
MS
279 ret = http_open_cnx(h, options);
280 if (ret < 0)
281 av_dict_free(&s->chained_options);
282 return ret;
558b86a5
LB
283}
284static int http_getc(HTTPContext *s)
285{
286 int len;
287 if (s->buf_ptr >= s->buf_end) {
bc371aca 288 len = ffurl_read(s->hd, s->buffer, BUFFER_SIZE);
558b86a5 289 if (len < 0) {
9613240f 290 return len;
558b86a5 291 } else if (len == 0) {
55a215ba 292 return AVERROR_EOF;
558b86a5
LB
293 } else {
294 s->buf_ptr = s->buffer;
295 s->buf_end = s->buffer + len;
296 }
297 }
298 return *s->buf_ptr++;
299}
300
682d49f4
PH
301static int http_get_line(HTTPContext *s, char *line, int line_size)
302{
303 int ch;
304 char *q;
305
306 q = line;
307 for(;;) {
308 ch = http_getc(s);
309 if (ch < 0)
9613240f 310 return ch;
682d49f4
PH
311 if (ch == '\n') {
312 /* process line */
313 if (q > line && q[-1] == '\r')
314 q--;
315 *q = '\0';
316
317 return 0;
318 } else {
319 if ((q - line) < line_size - 1)
320 *q++ = ch;
321 }
322 }
323}
324
4ff99ab3
LB
325static int check_http_code(URLContext *h, int http_code, const char *end)
326{
327 HTTPContext *s = h->priv_data;
328 /* error codes are 4xx and 5xx, but regard 401 as a success, so we
329 * don't abort until all headers have been parsed. */
330 if (http_code >= 400 && http_code < 600 &&
331 (http_code != 401 || s->auth_state.auth_type != HTTP_AUTH_NONE) &&
332 (http_code != 407 || s->proxy_auth_state.auth_type != HTTP_AUTH_NONE)) {
333 end += strspn(end, SPACE_CHARS);
334 av_log(h, AV_LOG_WARNING, "HTTP error %d %s\n", http_code, end);
335 return AVERROR(EIO);
336 }
337 return 0;
338}
339
340static int parse_location(HTTPContext *s, const char *p)
341{
342 char redirected_location[MAX_URL_SIZE], *new_loc;
343 ff_make_absolute_url(redirected_location, sizeof(redirected_location),
344 s->location, p);
345 new_loc = av_strdup(redirected_location);
346 if (!new_loc)
347 return AVERROR(ENOMEM);
348 av_free(s->location);
349 s->location = new_loc;
350 return 0;
351}
352
353/* "bytes $from-$to/$document_size" */
354static void parse_content_range(URLContext *h, char *p)
355{
356 HTTPContext *s = h->priv_data;
357 const char *slash;
358
359 if (!strncmp(p, "bytes ", 6)) {
360 p += 6;
361 s->off = strtoll(p, NULL, 10);
362 if ((slash = strchr(p, '/')) && strlen(slash) > 0)
363 s->filesize = strtoll(slash+1, NULL, 10);
364 }
365 h->is_streamed = 0; /* we _can_ in fact seek */
366}
367
368static int parse_content_encoding(URLContext *h, char *p)
369{
370 HTTPContext *s = h->priv_data;
371
372 if (!av_strncasecmp(p, "gzip", 4) ||
373 !av_strncasecmp(p, "deflate", 7)) {
374#if CONFIG_ZLIB
375 s->compressed = 1;
376 inflateEnd(&s->inflate_stream);
377 if (inflateInit2(&s->inflate_stream, 32 + 15) != Z_OK) {
378 av_log(h, AV_LOG_WARNING, "Error during zlib initialisation: %s\n",
379 s->inflate_stream.msg);
380 return AVERROR(ENOSYS);
381 }
382 if (zlibCompileFlags() & (1 << 17)) {
383 av_log(h, AV_LOG_WARNING,
384 "Your zlib was compiled without gzip support.\n");
385 return AVERROR(ENOSYS);
386 }
387#else
388 av_log(h, AV_LOG_WARNING,
389 "Compressed (%s) content, need zlib with gzip support\n", p);
390 return AVERROR(ENOSYS);
391#endif
392 } else if (!av_strncasecmp(p, "identity", 8)) {
393 // The normal, no-encoding case (although servers shouldn't include
394 // the header at all if this is the case).
395 } else {
396 av_log(h, AV_LOG_WARNING, "Unknown content coding: %s\n", p);
397 return AVERROR(ENOSYS);
398 }
399 return 0;
400}
401
8075c3d8
LB
402// Concat all Icy- header lines
403static int parse_icy(HTTPContext *s, const char *tag, const char *p)
404{
405 int len = 4 + strlen(p) + strlen(tag);
406 int ret;
407
408 if (s->icy_metadata_headers)
409 len += strlen(s->icy_metadata_headers);
410
411 if ((ret = av_reallocp(&s->icy_metadata_headers, len)) < 0)
412 return ret;
413
414 av_strlcatf(s->icy_metadata_headers, len, "%s: %s\n", tag, p);
415
416 return 0;
417}
418
558b86a5
LB
419static int process_line(URLContext *h, char *line, int line_count,
420 int *new_location)
421{
422 HTTPContext *s = h->priv_data;
db979afe 423 char *tag, *p, *end;
4ff99ab3 424 int ret;
558b86a5
LB
425
426 /* end of header */
e5773d8b
SP
427 if (line[0] == '\0') {
428 s->end_header = 1;
558b86a5 429 return 0;
e5773d8b 430 }
558b86a5
LB
431
432 p = line;
433 if (line_count == 0) {
efa7f420 434 while (!av_isspace(*p) && *p != '\0')
558b86a5 435 p++;
efa7f420 436 while (av_isspace(*p))
558b86a5 437 p++;
db979afe 438 s->http_code = strtol(p, &end, 10);
a52dc730 439
dfd2a005 440 av_dlog(NULL, "http_code=%d\n", s->http_code);
a52dc730 441
4ff99ab3
LB
442 if ((ret = check_http_code(h, s->http_code, end)) < 0)
443 return ret;
558b86a5
LB
444 } else {
445 while (*p != '\0' && *p != ':')
446 p++;
447 if (*p != ':')
448 return 1;
449
450 *p = '\0';
451 tag = line;
452 p++;
efa7f420 453 while (av_isspace(*p))
558b86a5 454 p++;
bb3244de 455 if (!av_strcasecmp(tag, "Location")) {
4ff99ab3
LB
456 if ((ret = parse_location(s, p)) < 0)
457 return ret;
558b86a5 458 *new_location = 1;
7a2fddb4 459 } else if (!av_strcasecmp(tag, "Content-Length") && s->filesize == -1) {
51a2b554 460 s->filesize = strtoll(p, NULL, 10);
7a2fddb4 461 } else if (!av_strcasecmp(tag, "Content-Range")) {
4ff99ab3 462 parse_content_range(h, p);
7a2fddb4
LB
463 } else if (!av_strcasecmp(tag, "Accept-Ranges") &&
464 !strncmp(p, "bytes", 5)) {
346ea9e2 465 h->is_streamed = 0;
7a2fddb4
LB
466 } else if (!av_strcasecmp(tag, "Transfer-Encoding") &&
467 !av_strncasecmp(p, "chunked", 7)) {
7995ed8e
PH
468 s->filesize = -1;
469 s->chunksize = 0;
7a2fddb4 470 } else if (!av_strcasecmp(tag, "WWW-Authenticate")) {
9405f733 471 ff_http_auth_handle_header(&s->auth_state, tag, p);
7a2fddb4 472 } else if (!av_strcasecmp(tag, "Authentication-Info")) {
9405f733 473 ff_http_auth_handle_header(&s->auth_state, tag, p);
7a2fddb4 474 } else if (!av_strcasecmp(tag, "Proxy-Authenticate")) {
b911518d 475 ff_http_auth_handle_header(&s->proxy_auth_state, tag, p);
7a2fddb4 476 } else if (!av_strcasecmp(tag, "Connection")) {
f240ed18
MS
477 if (!strcmp(p, "close"))
478 s->willclose = 1;
e58c85b0
MN
479 } else if (!av_strcasecmp (tag, "Content-Type")) {
480 av_free(s->mime_type);
481 s->mime_type = av_strdup(p);
8075c3d8
LB
482 } else if (!av_strcasecmp (tag, "Icy-MetaInt")) {
483 s->icy_metaint = strtoll(p, NULL, 10);
484 } else if (!av_strncasecmp(tag, "Icy-", 4)) {
485 if ((ret = parse_icy(s, tag, p)) < 0)
486 return ret;
7a2fddb4 487 } else if (!av_strcasecmp(tag, "Content-Encoding")) {
4ff99ab3
LB
488 if ((ret = parse_content_encoding(h, p)) < 0)
489 return ret;
558b86a5
LB
490 }
491 }
492 return 1;
493}
494
6964d510
JA
495static inline int has_header(const char *str, const char *header)
496{
497 /* header + 2 to skip over CRLF prefix. (make sure you have one!) */
10da1e91
MS
498 if (!str)
499 return 0;
6964d510
JA
500 return av_stristart(str, header + 2, NULL) || av_stristr(str, header);
501}
502
5d603f1b
SP
503static int http_read_header(URLContext *h, int *new_location)
504{
505 HTTPContext *s = h->priv_data;
8bd324e9 506 char line[MAX_URL_SIZE];
5d603f1b
SP
507 int err = 0;
508
35127bf1
MS
509 s->chunksize = -1;
510
5d603f1b 511 for (;;) {
9613240f
SP
512 if ((err = http_get_line(s, line, sizeof(line))) < 0)
513 return err;
5d603f1b
SP
514
515 av_dlog(NULL, "header='%s'\n", line);
516
517 err = process_line(h, line, s->line_count, new_location);
518 if (err < 0)
519 return err;
520 if (err == 0)
521 break;
522 s->line_count++;
523 }
524
525 return err;
526}
527
b911518d
MS
528static int http_connect(URLContext *h, const char *path, const char *local_path,
529 const char *hoststr, const char *auth,
530 const char *proxyauth, int *new_location)
558b86a5
LB
531{
532 HTTPContext *s = h->priv_data;
682d49f4 533 int post, err;
4ceb8b34 534 char headers[1024] = "";
b911518d 535 char *authstr = NULL, *proxyauthstr = NULL;
bc5c918e 536 int64_t off = s->off;
6964d510 537 int len = 0;
b911518d 538 const char *method;
71549a85 539 int send_expect_100 = 0;
558b86a5
LB
540
541
542 /* send http header */
59d96941 543 post = h->flags & AVIO_FLAG_WRITE;
1876e7c0
SP
544
545 if (s->post_data) {
546 /* force POST method and disable chunked encoding when
547 * custom HTTP post data is set */
548 post = 1;
549 s->chunked_post = 0;
550 }
551
b911518d
MS
552 method = post ? "POST" : "GET";
553 authstr = ff_http_auth_create_response(&s->auth_state, auth, local_path,
554 method);
555 proxyauthstr = ff_http_auth_create_response(&s->proxy_auth_state, proxyauth,
556 local_path, method);
71549a85
MS
557 if (post && !s->post_data) {
558 send_expect_100 = s->send_expect_100;
559 /* The user has supplied authentication but we don't know the auth type,
560 * send Expect: 100-continue to get the 401 response including the
561 * WWW-Authenticate header, or an 100 continue if no auth actually
562 * is needed. */
708b32b6
MN
563 if (auth && *auth &&
564 s->auth_state.auth_type == HTTP_AUTH_NONE &&
71549a85
MS
565 s->http_code != 401)
566 send_expect_100 = 1;
567 }
6964d510
JA
568
569 /* set default headers if needed */
570 if (!has_header(s->headers, "\r\nUser-Agent: "))
ddfc9890
CB
571 len += av_strlcatf(headers + len, sizeof(headers) - len,
572 "User-Agent: %s\r\n", s->user_agent);
6964d510
JA
573 if (!has_header(s->headers, "\r\nAccept: "))
574 len += av_strlcpy(headers + len, "Accept: */*\r\n",
575 sizeof(headers) - len);
2ec33d27
AH
576 // Note: we send this on purpose even when s->off is 0 when we're probing,
577 // since it allows us to detect more reliably if a (non-conforming)
578 // server supports seeking by analysing the reply headers.
579 if (!has_header(s->headers, "\r\nRange: ") && !post) {
6964d510 580 len += av_strlcatf(headers + len, sizeof(headers) - len,
2ec33d27
AH
581 "Range: bytes=%"PRId64"-", s->off);
582 if (s->end_off)
583 len += av_strlcatf(headers + len, sizeof(headers) - len,
584 "%"PRId64, s->end_off - 1);
585 len += av_strlcpy(headers + len, "\r\n",
586 sizeof(headers) - len);
587 }
71549a85
MS
588 if (send_expect_100 && !has_header(s->headers, "\r\nExpect: "))
589 len += av_strlcatf(headers + len, sizeof(headers) - len,
590 "Expect: 100-continue\r\n");
3bdb438e
SP
591
592 if (!has_header(s->headers, "\r\nConnection: ")) {
593 if (s->multiple_requests) {
594 len += av_strlcpy(headers + len, "Connection: keep-alive\r\n",
595 sizeof(headers) - len);
596 } else {
597 len += av_strlcpy(headers + len, "Connection: close\r\n",
598 sizeof(headers) - len);
599 }
600 }
601
6964d510
JA
602 if (!has_header(s->headers, "\r\nHost: "))
603 len += av_strlcatf(headers + len, sizeof(headers) - len,
604 "Host: %s\r\n", hoststr);
1876e7c0
SP
605 if (!has_header(s->headers, "\r\nContent-Length: ") && s->post_data)
606 len += av_strlcatf(headers + len, sizeof(headers) - len,
607 "Content-Length: %d\r\n", s->post_datalen);
8075c3d8
LB
608 if (!has_header(s->headers, "\r\nIcy-MetaData: ") && s->icy) {
609 len += av_strlcatf(headers + len, sizeof(headers) - len,
610 "Icy-MetaData: %d\r\n", 1);
611 }
6964d510
JA
612
613 /* now add in custom headers */
10da1e91
MS
614 if (s->headers)
615 av_strlcpy(headers + len, s->headers, sizeof(headers) - len);
6964d510 616
558b86a5
LB
617 snprintf(s->buffer, sizeof(s->buffer),
618 "%s %s HTTP/1.1\r\n"
9405f733 619 "%s"
6964d510 620 "%s"
08f7a8ac 621 "%s"
b911518d 622 "%s%s"
558b86a5 623 "\r\n",
b911518d 624 method,
558b86a5 625 path,
6149485f 626 post && s->chunked_post ? "Transfer-Encoding: chunked\r\n" : "",
6964d510 627 headers,
b911518d
MS
628 authstr ? authstr : "",
629 proxyauthstr ? "Proxy-" : "", proxyauthstr ? proxyauthstr : "");
558b86a5 630
9405f733 631 av_freep(&authstr);
b911518d 632 av_freep(&proxyauthstr);
9613240f
SP
633 if ((err = ffurl_write(s->hd, s->buffer, strlen(s->buffer))) < 0)
634 return err;
558b86a5 635
1876e7c0
SP
636 if (s->post_data)
637 if ((err = ffurl_write(s->hd, s->post_data, s->post_datalen)) < 0)
638 return err;
639
558b86a5
LB
640 /* init input buffer */
641 s->buf_ptr = s->buffer;
642 s->buf_end = s->buffer;
643 s->line_count = 0;
644 s->off = 0;
8075c3d8 645 s->icy_data_read = 0;
ecb4a895 646 s->filesize = -1;
f240ed18 647 s->willclose = 0;
ba354a8c 648 s->end_chunked_post = 0;
e999b641 649 s->end_header = 0;
71549a85 650 if (post && !s->post_data && !send_expect_100) {
dd798dcd
MS
651 /* Pretend that it did work. We didn't read any header yet, since
652 * we've still to send the POST data, but the code calling this
653 * function will check http_code after we return. */
654 s->http_code = 200;
558b86a5
LB
655 return 0;
656 }
657
658 /* wait for header */
5d603f1b
SP
659 err = http_read_header(h, new_location);
660 if (err < 0)
661 return err;
558b86a5
LB
662
663 return (off == s->off) ? 0 : -1;
664}
665
666
bf7723a6 667static int http_buf_read(URLContext *h, uint8_t *buf, int size)
558b86a5
LB
668{
669 HTTPContext *s = h->priv_data;
670 int len;
bf7723a6
MS
671 /* read bytes from input buffer first */
672 len = s->buf_end - s->buf_ptr;
673 if (len > 0) {
674 if (len > size)
675 len = size;
676 memcpy(buf, s->buf_ptr, len);
677 s->buf_ptr += len;
678 } else {
679 if (!s->willclose && s->filesize >= 0 && s->off >= s->filesize)
680 return AVERROR_EOF;
681 len = ffurl_read(s->hd, buf, size);
682 }
683 if (len > 0) {
684 s->off += len;
685 if (s->chunksize > 0)
686 s->chunksize -= len;
687 }
688 return len;
689}
690
0f51c398
ZR
691#if CONFIG_ZLIB
692#define DECOMPRESS_BUF_SIZE (256 * 1024)
693static int http_buf_read_compressed(URLContext *h, uint8_t *buf, int size)
694{
695 HTTPContext *s = h->priv_data;
696 int ret;
697
698 if (!s->inflate_buffer) {
699 s->inflate_buffer = av_malloc(DECOMPRESS_BUF_SIZE);
700 if (!s->inflate_buffer)
701 return AVERROR(ENOMEM);
702 }
703
704 if (s->inflate_stream.avail_in == 0) {
705 int read = http_buf_read(h, s->inflate_buffer, DECOMPRESS_BUF_SIZE);
706 if (read <= 0)
707 return read;
708 s->inflate_stream.next_in = s->inflate_buffer;
709 s->inflate_stream.avail_in = read;
710 }
711
712 s->inflate_stream.avail_out = size;
713 s->inflate_stream.next_out = buf;
714
715 ret = inflate(&s->inflate_stream, Z_SYNC_FLUSH);
716 if (ret != Z_OK && ret != Z_STREAM_END)
717 av_log(h, AV_LOG_WARNING, "inflate return value: %d, %s\n", ret, s->inflate_stream.msg);
718
719 return size - s->inflate_stream.avail_out;
720}
721#endif
722
8075c3d8 723static int http_read_stream(URLContext *h, uint8_t *buf, int size)
bf7723a6
MS
724{
725 HTTPContext *s = h->priv_data;
e5773d8b
SP
726 int err, new_location;
727
eb564b23
MS
728 if (!s->hd)
729 return AVERROR_EOF;
730
35127bf1
MS
731 if (s->end_chunked_post && !s->end_header) {
732 err = http_read_header(h, &new_location);
733 if (err < 0)
734 return err;
e5773d8b 735 }
558b86a5 736
7995ed8e
PH
737 if (s->chunksize >= 0) {
738 if (!s->chunksize) {
739 char line[32];
740
741 for(;;) {
742 do {
9613240f
SP
743 if ((err = http_get_line(s, line, sizeof(line))) < 0)
744 return err;
7995ed8e
PH
745 } while (!*line); /* skip CR LF from last chunk */
746
747 s->chunksize = strtoll(line, NULL, 16);
748
dfd2a005 749 av_dlog(NULL, "Chunked encoding data size: %"PRId64"'\n", s->chunksize);
7995ed8e
PH
750
751 if (!s->chunksize)
752 return 0;
753 break;
754 }
755 }
756 size = FFMIN(size, s->chunksize);
757 }
0f51c398
ZR
758#if CONFIG_ZLIB
759 if (s->compressed)
760 return http_buf_read_compressed(h, buf, size);
761#endif
bf7723a6 762 return http_buf_read(h, buf, size);
558b86a5
LB
763}
764
8075c3d8
LB
765static int http_read_stream_all(URLContext *h, uint8_t *buf, int size)
766{
767 int pos = 0;
768 while (pos < size) {
769 int len = http_read_stream(h, buf + pos, size - pos);
770 if (len < 0)
771 return len;
772 pos += len;
773 }
774 return pos;
775}
776
777static int store_icy(URLContext *h, int size)
778{
779 HTTPContext *s = h->priv_data;
780 /* until next metadata packet */
781 int remaining = s->icy_metaint - s->icy_data_read;
782
783 if (remaining < 0)
784 return AVERROR_INVALIDDATA;
785
786 if (!remaining) {
787 // The metadata packet is variable sized. It has a 1 byte header
788 // which sets the length of the packet (divided by 16). If it's 0,
789 // the metadata doesn't change. After the packet, icy_metaint bytes
790 // of normal data follow.
791 uint8_t ch;
792 int len = http_read_stream_all(h, &ch, 1);
793 if (len < 0)
794 return len;
795 if (ch > 0) {
796 char data[255 * 16 + 1];
797 int ret;
798 len = ch * 16;
799 ret = http_read_stream_all(h, data, len);
800 if (ret < 0)
801 return ret;
802 data[len + 1] = 0;
803 if ((ret = av_opt_set(s, "icy_metadata_packet", data, 0)) < 0)
804 return ret;
805 }
806 s->icy_data_read = 0;
807 remaining = s->icy_metaint;
808 }
809
810 return FFMIN(size, remaining);
811}
812
813static int http_read(URLContext *h, uint8_t *buf, int size)
814{
815 HTTPContext *s = h->priv_data;
816
817 if (s->icy_metaint > 0) {
818 size = store_icy(h, size);
819 if (size < 0)
820 return size;
821 }
822
823 size = http_read_stream(h, buf, size);
824 if (size > 0)
825 s->icy_data_read += size;
826 return size;
827}
828
558b86a5 829/* used only when posting data */
27241cbf 830static int http_write(URLContext *h, const uint8_t *buf, int size)
558b86a5 831{
f2b9b19f 832 char temp[11] = ""; /* 32-bit hex + CRLF + nul */
08f7a8ac
TH
833 int ret;
834 char crlf[] = "\r\n";
558b86a5 835 HTTPContext *s = h->priv_data;
08f7a8ac 836
6149485f 837 if (!s->chunked_post) {
a6a91589 838 /* non-chunked data is sent without any special encoding */
925e908b 839 return ffurl_write(s->hd, buf, size);
08f7a8ac
TH
840 }
841
842 /* silently ignore zero-size data since chunk encoding that would
843 * signal EOF */
844 if (size > 0) {
845 /* upload data using chunked encoding */
17b1493f 846 snprintf(temp, sizeof(temp), "%x\r\n", size);
f2b9b19f 847
925e908b
AK
848 if ((ret = ffurl_write(s->hd, temp, strlen(temp))) < 0 ||
849 (ret = ffurl_write(s->hd, buf, size)) < 0 ||
850 (ret = ffurl_write(s->hd, crlf, sizeof(crlf) - 1)) < 0)
08f7a8ac
TH
851 return ret;
852 }
853 return size;
558b86a5
LB
854}
855
ba354a8c 856static int http_shutdown(URLContext *h, int flags)
558b86a5 857{
08f7a8ac
TH
858 int ret = 0;
859 char footer[] = "0\r\n\r\n";
558b86a5 860 HTTPContext *s = h->priv_data;
08f7a8ac
TH
861
862 /* signal end of chunked encoding if used */
ba354a8c 863 if ((flags & AVIO_FLAG_WRITE) && s->chunked_post) {
925e908b 864 ret = ffurl_write(s->hd, footer, sizeof(footer) - 1);
08f7a8ac 865 ret = ret > 0 ? 0 : ret;
ba354a8c
SP
866 s->end_chunked_post = 1;
867 }
868
869 return ret;
870}
871
872static int http_close(URLContext *h)
873{
874 int ret = 0;
875 HTTPContext *s = h->priv_data;
876
0f51c398
ZR
877#if CONFIG_ZLIB
878 inflateEnd(&s->inflate_stream);
879 av_freep(&s->inflate_buffer);
880#endif
881
ba354a8c
SP
882 if (!s->end_chunked_post) {
883 /* Close the write direction by sending the end of chunked encoding. */
884 ret = http_shutdown(h, h->flags);
08f7a8ac
TH
885 }
886
701ea516 887 if (s->hd)
e52a9145 888 ffurl_close(s->hd);
5c53bf7a 889 av_dict_free(&s->chained_options);
08f7a8ac 890 return ret;
558b86a5
LB
891}
892
bc5c918e 893static int64_t http_seek(URLContext *h, int64_t off, int whence)
558b86a5
LB
894{
895 HTTPContext *s = h->priv_data;
896 URLContext *old_hd = s->hd;
bc5c918e 897 int64_t old_off = s->off;
08c8e66a 898 uint8_t old_buf[BUFFER_SIZE];
55a215ba 899 int old_buf_size, ret;
5c53bf7a 900 AVDictionary *options = NULL;
558b86a5
LB
901
902 if (whence == AVSEEK_SIZE)
903 return s->filesize;
ab76d9f6
AH
904 else if ((whence == SEEK_CUR && off == 0) ||
905 (whence == SEEK_SET && off == s->off))
906 return s->off;
558b86a5 907 else if ((s->filesize == -1 && whence == SEEK_END) || h->is_streamed)
55a215ba 908 return AVERROR(ENOSYS);
558b86a5
LB
909
910 /* we save the old context in case the seek fails */
08c8e66a
BC
911 old_buf_size = s->buf_end - s->buf_ptr;
912 memcpy(old_buf, s->buf_ptr, old_buf_size);
558b86a5
LB
913 s->hd = NULL;
914 if (whence == SEEK_CUR)
915 off += s->off;
916 else if (whence == SEEK_END)
917 off += s->filesize;
918 s->off = off;
919
920 /* if it fails, continue on old connection */
5c53bf7a 921 av_dict_copy(&options, s->chained_options, 0);
55a215ba 922 if ((ret = http_open_cnx(h, &options)) < 0) {
5c53bf7a 923 av_dict_free(&options);
08c8e66a
BC
924 memcpy(s->buffer, old_buf, old_buf_size);
925 s->buf_ptr = s->buffer;
926 s->buf_end = s->buffer + old_buf_size;
558b86a5
LB
927 s->hd = old_hd;
928 s->off = old_off;
55a215ba 929 return ret;
558b86a5 930 }
5c53bf7a 931 av_dict_free(&options);
e52a9145 932 ffurl_close(old_hd);
558b86a5
LB
933 return off;
934}
935
f0a80394
RB
936static int
937http_get_file_handle(URLContext *h)
938{
939 HTTPContext *s = h->priv_data;
1869ea03 940 return ffurl_get_file_handle(s->hd);
f0a80394
RB
941}
942
183baead 943#if CONFIG_HTTP_PROTOCOL
c6610a21 944URLProtocol ff_http_protocol = {
f35ff97f 945 .name = "http",
5c53bf7a 946 .url_open2 = http_open,
f35ff97f
AK
947 .url_read = http_read,
948 .url_write = http_write,
949 .url_seek = http_seek,
950 .url_close = http_close,
f0a80394 951 .url_get_file_handle = http_get_file_handle,
ba354a8c 952 .url_shutdown = http_shutdown,
f35ff97f 953 .priv_data_size = sizeof(HTTPContext),
3b384502 954 .priv_data_class = &http_context_class,
32b83aee 955 .flags = URL_PROTOCOL_FLAG_NETWORK,
558b86a5 956};
183baead
MS
957#endif
958#if CONFIG_HTTPS_PROTOCOL
959URLProtocol ff_https_protocol = {
960 .name = "https",
5c53bf7a 961 .url_open2 = http_open,
183baead
MS
962 .url_read = http_read,
963 .url_write = http_write,
964 .url_seek = http_seek,
965 .url_close = http_close,
966 .url_get_file_handle = http_get_file_handle,
dbaf79c9 967 .url_shutdown = http_shutdown,
183baead 968 .priv_data_size = sizeof(HTTPContext),
3b384502 969 .priv_data_class = &https_context_class,
32b83aee 970 .flags = URL_PROTOCOL_FLAG_NETWORK,
183baead
MS
971};
972#endif
9f1dae94
MS
973
974#if CONFIG_HTTPPROXY_PROTOCOL
975static int http_proxy_close(URLContext *h)
976{
977 HTTPContext *s = h->priv_data;
978 if (s->hd)
979 ffurl_close(s->hd);
980 return 0;
981}
982
983static int http_proxy_open(URLContext *h, const char *uri, int flags)
984{
985 HTTPContext *s = h->priv_data;
986 char hostname[1024], hoststr[1024];
987 char auth[1024], pathbuf[1024], *path;
5d603f1b 988 char lower_url[100];
e75bbcf4 989 int port, ret = 0, attempts = 0;
9f1dae94
MS
990 HTTPAuthType cur_auth_type;
991 char *authstr;
5d603f1b 992 int new_loc;
9f1dae94
MS
993
994 h->is_streamed = 1;
995
996 av_url_split(NULL, 0, auth, sizeof(auth), hostname, sizeof(hostname), &port,
997 pathbuf, sizeof(pathbuf), uri);
998 ff_url_join(hoststr, sizeof(hoststr), NULL, NULL, hostname, port, NULL);
999 path = pathbuf;
1000 if (*path == '/')
1001 path++;
1002
1003 ff_url_join(lower_url, sizeof(lower_url), "tcp", NULL, hostname, port,
1004 NULL);
1005redo:
1006 ret = ffurl_open(&s->hd, lower_url, AVIO_FLAG_READ_WRITE,
1007 &h->interrupt_callback, NULL);
1008 if (ret < 0)
1009 return ret;
1010
1011 authstr = ff_http_auth_create_response(&s->proxy_auth_state, auth,
1012 path, "CONNECT");
1013 snprintf(s->buffer, sizeof(s->buffer),
1014 "CONNECT %s HTTP/1.1\r\n"
1015 "Host: %s\r\n"
1016 "Connection: close\r\n"
1017 "%s%s"
1018 "\r\n",
1019 path,
1020 hoststr,
1021 authstr ? "Proxy-" : "", authstr ? authstr : "");
1022 av_freep(&authstr);
1023
1024 if ((ret = ffurl_write(s->hd, s->buffer, strlen(s->buffer))) < 0)
1025 goto fail;
1026
1027 s->buf_ptr = s->buffer;
1028 s->buf_end = s->buffer;
1029 s->line_count = 0;
1030 s->filesize = -1;
1031 cur_auth_type = s->proxy_auth_state.auth_type;
1032
5d603f1b
SP
1033 /* Note: This uses buffering, potentially reading more than the
1034 * HTTP header. If tunneling a protocol where the server starts
1035 * the conversation, we might buffer part of that here, too.
1036 * Reading that requires using the proper ffurl_read() function
1037 * on this URLContext, not using the fd directly (as the tls
1038 * protocol does). This shouldn't be an issue for tls though,
1039 * since the client starts the conversation there, so there
1040 * is no extra data that we might buffer up here.
1041 */
1042 ret = http_read_header(h, &new_loc);
1043 if (ret < 0)
1044 goto fail;
9f1dae94 1045
e75bbcf4
MS
1046 attempts++;
1047 if (s->http_code == 407 &&
1048 (cur_auth_type == HTTP_AUTH_NONE || s->proxy_auth_state.stale) &&
1049 s->proxy_auth_state.auth_type != HTTP_AUTH_NONE && attempts < 2) {
9f1dae94
MS
1050 ffurl_close(s->hd);
1051 s->hd = NULL;
1052 goto redo;
1053 }
1054
1055 if (s->http_code < 400)
1056 return 0;
1057 ret = AVERROR(EIO);
1058
1059fail:
1060 http_proxy_close(h);
1061 return ret;
1062}
1063
1064static int http_proxy_write(URLContext *h, const uint8_t *buf, int size)
1065{
1066 HTTPContext *s = h->priv_data;
1067 return ffurl_write(s->hd, buf, size);
1068}
1069
1070URLProtocol ff_httpproxy_protocol = {
1071 .name = "httpproxy",
1072 .url_open = http_proxy_open,
1073 .url_read = http_buf_read,
1074 .url_write = http_proxy_write,
1075 .url_close = http_proxy_close,
1076 .url_get_file_handle = http_get_file_handle,
1077 .priv_data_size = sizeof(HTTPContext),
32b83aee 1078 .flags = URL_PROTOCOL_FLAG_NETWORK,
9f1dae94
MS
1079};
1080#endif