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