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