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