]> git.sesse.net Git - ffmpeg/blob - libavformat/http.c
Merge commit '9bb11be0e5a75782c3139ad058c2b571499aa37d'
[ffmpeg] / libavformat / http.c
1 /*
2  * HTTP protocol for ffmpeg client
3  * Copyright (c) 2000, 2001 Fabrice Bellard
4  *
5  * This file is part of FFmpeg.
6  *
7  * FFmpeg 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  * FFmpeg 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 FFmpeg; 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 ffmpeg 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 seekable;           /**< Control seekability, 0 = disable, 1 = enable, -1 = probe. */
68     int chunked_post;
69     /* A flag which indicates if the end of chunked encoding has been sent. */
70     int end_chunked_post;
71     /* A flag which indicates we have finished to read POST reply. */
72     int end_header;
73     /* A flag which indicates if we use persistent connections. */
74     int multiple_requests;
75     uint8_t *post_data;
76     int post_datalen;
77     int is_akamai;
78     int is_mediagateway;
79     char *cookies;          ///< holds newline (\n) delimited Set-Cookie header field values (without the "Set-Cookie: " field name)
80     /* A dictionary containing cookies keyed by cookie name */
81     AVDictionary *cookie_dict;
82     int icy;
83     /* how much data was read since the last ICY metadata packet */
84     int icy_data_read;
85     /* after how many bytes of read data a new metadata packet will be found */
86     int icy_metaint;
87     char *icy_metadata_headers;
88     char *icy_metadata_packet;
89     AVDictionary *metadata;
90 #if CONFIG_ZLIB
91     int compressed;
92     z_stream inflate_stream;
93     uint8_t *inflate_buffer;
94 #endif /* CONFIG_ZLIB */
95     AVDictionary *chained_options;
96     int send_expect_100;
97     char *method;
98     int reconnect;
99     int listen;
100 } HTTPContext;
101
102 #define OFFSET(x) offsetof(HTTPContext, x)
103 #define D AV_OPT_FLAG_DECODING_PARAM
104 #define E AV_OPT_FLAG_ENCODING_PARAM
105 #define DEFAULT_USER_AGENT "Lavf/" AV_STRINGIFY(LIBAVFORMAT_VERSION)
106
107 static const AVOption options[] = {
108     { "seekable", "control seekability of connection", OFFSET(seekable), AV_OPT_TYPE_INT, { .i64 = -1 }, -1, 1, D },
109     { "chunked_post", "use chunked transfer-encoding for posts", OFFSET(chunked_post), AV_OPT_TYPE_INT, { .i64 = 1 }, 0, 1, E },
110     { "headers", "set custom HTTP headers, can override built in default headers", OFFSET(headers), AV_OPT_TYPE_STRING, { 0 }, 0, 0, D | E },
111     { "content_type", "set a specific content type for the POST messages", OFFSET(content_type), AV_OPT_TYPE_STRING, { 0 }, 0, 0, D | E },
112     { "user_agent", "override User-Agent header", OFFSET(user_agent), AV_OPT_TYPE_STRING, { .str = DEFAULT_USER_AGENT }, 0, 0, D },
113     { "user-agent", "override User-Agent header", OFFSET(user_agent), AV_OPT_TYPE_STRING, { .str = DEFAULT_USER_AGENT }, 0, 0, D },
114     { "multiple_requests", "use persistent connections", OFFSET(multiple_requests), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 1, D | E },
115     { "post_data", "set custom HTTP post data", OFFSET(post_data), AV_OPT_TYPE_BINARY, .flags = D | E },
116     { "mime_type", "export the MIME type", OFFSET(mime_type), AV_OPT_TYPE_STRING, { 0 }, 0, 0, AV_OPT_FLAG_EXPORT | AV_OPT_FLAG_READONLY },
117     { "cookies", "set cookies to be sent in applicable future requests, use newline delimited Set-Cookie HTTP field value syntax", OFFSET(cookies), AV_OPT_TYPE_STRING, { 0 }, 0, 0, D },
118     { "icy", "request ICY metadata", OFFSET(icy), AV_OPT_TYPE_INT, { .i64 = 1 }, 0, 1, D },
119     { "icy_metadata_headers", "return ICY metadata headers", OFFSET(icy_metadata_headers), AV_OPT_TYPE_STRING, { 0 }, 0, 0, AV_OPT_FLAG_EXPORT },
120     { "icy_metadata_packet", "return current ICY metadata packet", OFFSET(icy_metadata_packet), AV_OPT_TYPE_STRING, { 0 }, 0, 0, AV_OPT_FLAG_EXPORT },
121     { "metadata", "metadata read from the bitstream", OFFSET(metadata), AV_OPT_TYPE_DICT, {0}, 0, 0, AV_OPT_FLAG_EXPORT },
122     { "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"},
123     { "none", "No auth method set, autodetect", 0, AV_OPT_TYPE_CONST, { .i64 = HTTP_AUTH_NONE }, 0, 0, D | E, "auth_type"},
124     { "basic", "HTTP basic authentication", 0, AV_OPT_TYPE_CONST, { .i64 = HTTP_AUTH_BASIC }, 0, 0, D | E, "auth_type"},
125     { "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 },
126     { "location", "The actual location of the data received", OFFSET(location), AV_OPT_TYPE_STRING, { 0 }, 0, 0, D | E },
127     { "offset", "initial byte offset", OFFSET(off), AV_OPT_TYPE_INT64, { .i64 = 0 }, 0, INT64_MAX, D },
128     { "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 },
129     { "method", "Override the HTTP method or set the expected HTTP method from a client", OFFSET(method), AV_OPT_TYPE_STRING, { .str = NULL }, 0, 0, D | E },
130     { "reconnect", "auto reconnect after disconnect before EOF", OFFSET(reconnect), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 1, D },
131     { "listen", "listen on HTTP", OFFSET(listen), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 1, D | E },
132     { NULL }
133 };
134
135 static int http_connect(URLContext *h, const char *path, const char *local_path,
136                         const char *hoststr, const char *auth,
137                         const char *proxyauth, int *new_location);
138 static int http_read_header(URLContext *h, int *new_location);
139
140 void ff_http_init_auth_state(URLContext *dest, const URLContext *src)
141 {
142     memcpy(&((HTTPContext *)dest->priv_data)->auth_state,
143            &((HTTPContext *)src->priv_data)->auth_state,
144            sizeof(HTTPAuthState));
145     memcpy(&((HTTPContext *)dest->priv_data)->proxy_auth_state,
146            &((HTTPContext *)src->priv_data)->proxy_auth_state,
147            sizeof(HTTPAuthState));
148 }
149
150 static int http_open_cnx_internal(URLContext *h, AVDictionary **options)
151 {
152     const char *path, *proxy_path, *lower_proto = "tcp", *local_path;
153     char hostname[1024], hoststr[1024], proto[10];
154     char auth[1024], proxyauth[1024] = "";
155     char path1[MAX_URL_SIZE];
156     char buf[1024], urlbuf[MAX_URL_SIZE];
157     int port, use_proxy, err, location_changed = 0;
158     HTTPContext *s = h->priv_data;
159
160     av_url_split(proto, sizeof(proto), auth, sizeof(auth),
161                  hostname, sizeof(hostname), &port,
162                  path1, sizeof(path1), s->location);
163     ff_url_join(hoststr, sizeof(hoststr), NULL, NULL, hostname, port, NULL);
164
165     proxy_path = getenv("http_proxy");
166     use_proxy  = !ff_http_match_no_proxy(getenv("no_proxy"), hostname) &&
167                  proxy_path && av_strstart(proxy_path, "http://", NULL);
168
169     if (!strcmp(proto, "https")) {
170         lower_proto = "tls";
171         use_proxy   = 0;
172         if (port < 0)
173             port = 443;
174     }
175     if (port < 0)
176         port = 80;
177
178     if (path1[0] == '\0')
179         path = "/";
180     else
181         path = path1;
182     local_path = path;
183     if (use_proxy) {
184         /* Reassemble the request URL without auth string - we don't
185          * want to leak the auth to the proxy. */
186         ff_url_join(urlbuf, sizeof(urlbuf), proto, NULL, hostname, port, "%s",
187                     path1);
188         path = urlbuf;
189         av_url_split(NULL, 0, proxyauth, sizeof(proxyauth),
190                      hostname, sizeof(hostname), &port, NULL, 0, proxy_path);
191     }
192
193     ff_url_join(buf, sizeof(buf), lower_proto, NULL, hostname, port, NULL);
194
195     if (!s->hd) {
196         err = ffurl_open(&s->hd, buf, AVIO_FLAG_READ_WRITE,
197                          &h->interrupt_callback, options);
198         if (err < 0)
199             return err;
200     }
201
202     err = http_connect(h, path, local_path, hoststr,
203                        auth, proxyauth, &location_changed);
204     if (err < 0)
205         return err;
206
207     return location_changed;
208 }
209
210 /* return non zero if error */
211 static int http_open_cnx(URLContext *h, AVDictionary **options)
212 {
213     HTTPAuthType cur_auth_type, cur_proxy_auth_type;
214     HTTPContext *s = h->priv_data;
215     int location_changed, attempts = 0, redirects = 0;
216 redo:
217     av_dict_copy(options, s->chained_options, 0);
218
219     cur_auth_type       = s->auth_state.auth_type;
220     cur_proxy_auth_type = s->auth_state.auth_type;
221
222     location_changed = http_open_cnx_internal(h, options);
223     if (location_changed < 0)
224         goto fail;
225
226     attempts++;
227     if (s->http_code == 401) {
228         if ((cur_auth_type == HTTP_AUTH_NONE || s->auth_state.stale) &&
229             s->auth_state.auth_type != HTTP_AUTH_NONE && attempts < 4) {
230             ffurl_closep(&s->hd);
231             goto redo;
232         } else
233             goto fail;
234     }
235     if (s->http_code == 407) {
236         if ((cur_proxy_auth_type == HTTP_AUTH_NONE || s->proxy_auth_state.stale) &&
237             s->proxy_auth_state.auth_type != HTTP_AUTH_NONE && attempts < 4) {
238             ffurl_closep(&s->hd);
239             goto redo;
240         } else
241             goto fail;
242     }
243     if ((s->http_code == 301 || s->http_code == 302 ||
244          s->http_code == 303 || s->http_code == 307) &&
245         location_changed == 1) {
246         /* url moved, get next */
247         ffurl_closep(&s->hd);
248         if (redirects++ >= MAX_REDIRECTS)
249             return AVERROR(EIO);
250         /* Restart the authentication process with the new target, which
251          * might use a different auth mechanism. */
252         memset(&s->auth_state, 0, sizeof(s->auth_state));
253         attempts         = 0;
254         location_changed = 0;
255         goto redo;
256     }
257     return 0;
258
259 fail:
260     if (s->hd)
261         ffurl_closep(&s->hd);
262     if (location_changed < 0)
263         return location_changed;
264     return ff_http_averror(s->http_code, AVERROR(EIO));
265 }
266
267 int ff_http_do_new_request(URLContext *h, const char *uri)
268 {
269     HTTPContext *s = h->priv_data;
270     AVDictionary *options = NULL;
271     int ret;
272
273     s->off           = 0;
274     s->icy_data_read = 0;
275     av_free(s->location);
276     s->location = av_strdup(uri);
277     if (!s->location)
278         return AVERROR(ENOMEM);
279
280     ret = http_open_cnx(h, &options);
281     av_dict_free(&options);
282     return ret;
283 }
284
285 int ff_http_averror(int status_code, int default_averror)
286 {
287     switch (status_code) {
288         case 400: return AVERROR_HTTP_BAD_REQUEST;
289         case 401: return AVERROR_HTTP_UNAUTHORIZED;
290         case 403: return AVERROR_HTTP_FORBIDDEN;
291         case 404: return AVERROR_HTTP_NOT_FOUND;
292         default: break;
293     }
294     if (status_code >= 400 && status_code <= 499)
295         return AVERROR_HTTP_OTHER_4XX;
296     else if (status_code >= 500)
297         return AVERROR_HTTP_SERVER_ERROR;
298     else
299         return default_averror;
300 }
301
302 static void handle_http_errors(URLContext *h, int error)
303 {
304     static const char bad_request[] = "HTTP/1.1 400 Bad Request\r\nContent-Type: text/plain\r\n\r\n400 Bad Request\r\n";
305     static const char internal_server_error[] = "HTTP/1.1 500 Internal server error\r\nContent-Type: text/plain\r\n\r\n500 Internal server error\r\n";
306     HTTPContext *s = h->priv_data;
307     if (h->is_connected) {
308         switch(error) {
309             case AVERROR_HTTP_BAD_REQUEST:
310                 ffurl_write(s->hd, bad_request, strlen(bad_request));
311                 break;
312             default:
313                 av_log(h, AV_LOG_ERROR, "Unhandled HTTP error.\n");
314                 ffurl_write(s->hd, internal_server_error, strlen(internal_server_error));
315         }
316     }
317 }
318
319 static int http_listen(URLContext *h, const char *uri, int flags,
320                        AVDictionary **options) {
321     HTTPContext *s = h->priv_data;
322     int ret;
323     static const char header[] = "HTTP/1.1 200 OK\r\nContent-Type: application/octet-stream\r\nTransfer-Encoding: chunked\r\n\r\n";
324     char hostname[1024], proto[10];
325     char lower_url[100];
326     const char *lower_proto = "tcp";
327     int port, new_location;
328     av_url_split(proto, sizeof(proto), NULL, 0, hostname, sizeof(hostname), &port,
329                  NULL, 0, uri);
330     if (!strcmp(proto, "https"))
331         lower_proto = "tls";
332     ff_url_join(lower_url, sizeof(lower_url), lower_proto, NULL, hostname, port,
333                 NULL);
334     av_dict_set(options, "listen", "1", 0);
335     if ((ret = ffurl_open(&s->hd, lower_url, AVIO_FLAG_READ_WRITE,
336                           &h->interrupt_callback, options)) < 0)
337         goto fail;
338     if ((ret = http_read_header(h, &new_location)) < 0)
339          goto fail;
340     if ((ret = ffurl_write(s->hd, header, strlen(header))) < 0)
341          goto fail;
342     return 0;
343
344 fail:
345     handle_http_errors(h, ret);
346     av_dict_free(&s->chained_options);
347     return ret;
348 }
349
350 static int http_open(URLContext *h, const char *uri, int flags,
351                      AVDictionary **options)
352 {
353     HTTPContext *s = h->priv_data;
354     int ret;
355
356     if( s->seekable == 1 )
357         h->is_streamed = 0;
358     else
359         h->is_streamed = 1;
360
361     s->filesize = -1;
362     s->location = av_strdup(uri);
363     if (!s->location)
364         return AVERROR(ENOMEM);
365     if (options)
366         av_dict_copy(&s->chained_options, *options, 0);
367
368     if (s->headers) {
369         int len = strlen(s->headers);
370         if (len < 2 || strcmp("\r\n", s->headers + len - 2))
371             av_log(h, AV_LOG_WARNING,
372                    "No trailing CRLF found in HTTP header.\n");
373     }
374
375     if (s->listen) {
376         return http_listen(h, uri, flags, options);
377     }
378     ret = http_open_cnx(h, options);
379     if (ret < 0)
380         av_dict_free(&s->chained_options);
381     return ret;
382 }
383
384 static int http_getc(HTTPContext *s)
385 {
386     int len;
387     if (s->buf_ptr >= s->buf_end) {
388         len = ffurl_read(s->hd, s->buffer, BUFFER_SIZE);
389         if (len < 0) {
390             return len;
391         } else if (len == 0) {
392             return AVERROR_EOF;
393         } else {
394             s->buf_ptr = s->buffer;
395             s->buf_end = s->buffer + len;
396         }
397     }
398     return *s->buf_ptr++;
399 }
400
401 static int http_get_line(HTTPContext *s, char *line, int line_size)
402 {
403     int ch;
404     char *q;
405
406     q = line;
407     for (;;) {
408         ch = http_getc(s);
409         if (ch < 0)
410             return ch;
411         if (ch == '\n') {
412             /* process line */
413             if (q > line && q[-1] == '\r')
414                 q--;
415             *q = '\0';
416
417             return 0;
418         } else {
419             if ((q - line) < line_size - 1)
420                 *q++ = ch;
421         }
422     }
423 }
424
425 static int check_http_code(URLContext *h, int http_code, const char *end)
426 {
427     HTTPContext *s = h->priv_data;
428     /* error codes are 4xx and 5xx, but regard 401 as a success, so we
429      * don't abort until all headers have been parsed. */
430     if (http_code >= 400 && http_code < 600 &&
431         (http_code != 401 || s->auth_state.auth_type != HTTP_AUTH_NONE) &&
432         (http_code != 407 || s->proxy_auth_state.auth_type != HTTP_AUTH_NONE)) {
433         end += strspn(end, SPACE_CHARS);
434         av_log(h, AV_LOG_WARNING, "HTTP error %d %s\n", http_code, end);
435         return ff_http_averror(http_code, AVERROR(EIO));
436     }
437     return 0;
438 }
439
440 static int parse_location(HTTPContext *s, const char *p)
441 {
442     char redirected_location[MAX_URL_SIZE], *new_loc;
443     ff_make_absolute_url(redirected_location, sizeof(redirected_location),
444                          s->location, p);
445     new_loc = av_strdup(redirected_location);
446     if (!new_loc)
447         return AVERROR(ENOMEM);
448     av_free(s->location);
449     s->location = new_loc;
450     return 0;
451 }
452
453 /* "bytes $from-$to/$document_size" */
454 static void parse_content_range(URLContext *h, const char *p)
455 {
456     HTTPContext *s = h->priv_data;
457     const char *slash;
458
459     if (!strncmp(p, "bytes ", 6)) {
460         p     += 6;
461         s->off = strtoll(p, NULL, 10);
462         if ((slash = strchr(p, '/')) && strlen(slash) > 0)
463             s->filesize = strtoll(slash + 1, NULL, 10);
464     }
465     if (s->seekable == -1 && (!s->is_akamai || s->filesize != 2147483647))
466         h->is_streamed = 0; /* we _can_ in fact seek */
467 }
468
469 static int parse_content_encoding(URLContext *h, const char *p)
470 {
471     if (!av_strncasecmp(p, "gzip", 4) ||
472         !av_strncasecmp(p, "deflate", 7)) {
473 #if CONFIG_ZLIB
474         HTTPContext *s = h->priv_data;
475
476         s->compressed = 1;
477         inflateEnd(&s->inflate_stream);
478         if (inflateInit2(&s->inflate_stream, 32 + 15) != Z_OK) {
479             av_log(h, AV_LOG_WARNING, "Error during zlib initialisation: %s\n",
480                    s->inflate_stream.msg);
481             return AVERROR(ENOSYS);
482         }
483         if (zlibCompileFlags() & (1 << 17)) {
484             av_log(h, AV_LOG_WARNING,
485                    "Your zlib was compiled without gzip support.\n");
486             return AVERROR(ENOSYS);
487         }
488 #else
489         av_log(h, AV_LOG_WARNING,
490                "Compressed (%s) content, need zlib with gzip support\n", p);
491         return AVERROR(ENOSYS);
492 #endif /* CONFIG_ZLIB */
493     } else if (!av_strncasecmp(p, "identity", 8)) {
494         // The normal, no-encoding case (although servers shouldn't include
495         // the header at all if this is the case).
496     } else {
497         av_log(h, AV_LOG_WARNING, "Unknown content coding: %s\n", p);
498     }
499     return 0;
500 }
501
502 // Concat all Icy- header lines
503 static int parse_icy(HTTPContext *s, const char *tag, const char *p)
504 {
505     int len = 4 + strlen(p) + strlen(tag);
506     int is_first = !s->icy_metadata_headers;
507     int ret;
508
509     av_dict_set(&s->metadata, tag, p, 0);
510
511     if (s->icy_metadata_headers)
512         len += strlen(s->icy_metadata_headers);
513
514     if ((ret = av_reallocp(&s->icy_metadata_headers, len)) < 0)
515         return ret;
516
517     if (is_first)
518         *s->icy_metadata_headers = '\0';
519
520     av_strlcatf(s->icy_metadata_headers, len, "%s: %s\n", tag, p);
521
522     return 0;
523 }
524
525 static int parse_cookie(HTTPContext *s, const char *p, AVDictionary **cookies)
526 {
527     char *eql, *name;
528
529     // duplicate the cookie name (dict will dupe the value)
530     if (!(eql = strchr(p, '='))) return AVERROR(EINVAL);
531     if (!(name = av_strndup(p, eql - p))) return AVERROR(ENOMEM);
532
533     // add the cookie to the dictionary
534     av_dict_set(cookies, name, eql, AV_DICT_DONT_STRDUP_KEY);
535
536     return 0;
537 }
538
539 static int cookie_string(AVDictionary *dict, char **cookies)
540 {
541     AVDictionaryEntry *e = NULL;
542     int len = 1;
543
544     // determine how much memory is needed for the cookies string
545     while (e = av_dict_get(dict, "", e, AV_DICT_IGNORE_SUFFIX))
546         len += strlen(e->key) + strlen(e->value) + 1;
547
548     // reallocate the cookies
549     e = NULL;
550     if (*cookies) av_free(*cookies);
551     *cookies = av_malloc(len);
552     if (!*cookies) return AVERROR(ENOMEM);
553     *cookies[0] = '\0';
554
555     // write out the cookies
556     while (e = av_dict_get(dict, "", e, AV_DICT_IGNORE_SUFFIX))
557         av_strlcatf(*cookies, len, "%s%s\n", e->key, e->value);
558
559     return 0;
560 }
561
562 static int process_line(URLContext *h, char *line, int line_count,
563                         int *new_location)
564 {
565     HTTPContext *s = h->priv_data;
566     const char *auto_method =  h->flags & AVIO_FLAG_READ ? "POST" : "GET";
567     char *tag, *p, *end, *method, *resource, *version;
568     int ret;
569
570     /* end of header */
571     if (line[0] == '\0') {
572         s->end_header = 1;
573         return 0;
574     }
575
576     p = line;
577     if (line_count == 0) {
578         if (s->listen) {
579             // HTTP method
580             method = p;
581             while (!av_isspace(*p))
582                 p++;
583             *(p++) = '\0';
584             av_log(h, AV_LOG_TRACE, "Received method: %s\n", method);
585             if (s->method) {
586                 if (av_strcasecmp(s->method, method)) {
587                     av_log(h, AV_LOG_ERROR, "Received and expected HTTP method do not match. (%s expected, %s received)\n",
588                            s->method, method);
589                     return ff_http_averror(400, AVERROR(EIO));
590                 }
591             } else {
592                 // use autodetected HTTP method to expect
593                 av_log(h, AV_LOG_TRACE, "Autodetected %s HTTP method\n", auto_method);
594                 if (av_strcasecmp(auto_method, method)) {
595                     av_log(h, AV_LOG_ERROR, "Received and autodetected HTTP method did not match "
596                            "(%s autodetected %s received)\n", auto_method, method);
597                     return ff_http_averror(400, AVERROR(EIO));
598                 }
599             }
600
601             // HTTP resource
602             while (av_isspace(*p))
603                 p++;
604             resource = p;
605             while (!av_isspace(*p))
606                 p++;
607             *(p++) = '\0';
608             av_log(h, AV_LOG_TRACE, "Requested resource: %s\n", resource);
609
610             // HTTP version
611             while (av_isspace(*p))
612                 p++;
613             version = p;
614             while (!av_isspace(*p))
615                 p++;
616             *p = '\0';
617             if (av_strncasecmp(version, "HTTP/", 5)) {
618                 av_log(h, AV_LOG_ERROR, "Malformed HTTP version string.\n");
619                 return ff_http_averror(400, AVERROR(EIO));
620             }
621             av_log(h, AV_LOG_TRACE, "HTTP version string: %s\n", version);
622         } else {
623             while (!av_isspace(*p) && *p != '\0')
624                 p++;
625             while (av_isspace(*p))
626                 p++;
627             s->http_code = strtol(p, &end, 10);
628
629             av_log(h, AV_LOG_TRACE, "http_code=%d\n", s->http_code);
630
631             if ((ret = check_http_code(h, s->http_code, end)) < 0)
632                 return ret;
633         }
634     } else {
635         while (*p != '\0' && *p != ':')
636             p++;
637         if (*p != ':')
638             return 1;
639
640         *p  = '\0';
641         tag = line;
642         p++;
643         while (av_isspace(*p))
644             p++;
645         if (!av_strcasecmp(tag, "Location")) {
646             if ((ret = parse_location(s, p)) < 0)
647                 return ret;
648             *new_location = 1;
649         } else if (!av_strcasecmp(tag, "Content-Length") && s->filesize == -1) {
650             s->filesize = strtoll(p, NULL, 10);
651         } else if (!av_strcasecmp(tag, "Content-Range")) {
652             parse_content_range(h, p);
653         } else if (!av_strcasecmp(tag, "Accept-Ranges") &&
654                    !strncmp(p, "bytes", 5) &&
655                    s->seekable == -1) {
656             h->is_streamed = 0;
657         } else if (!av_strcasecmp(tag, "Transfer-Encoding") &&
658                    !av_strncasecmp(p, "chunked", 7)) {
659             s->filesize  = -1;
660             s->chunksize = 0;
661         } else if (!av_strcasecmp(tag, "WWW-Authenticate")) {
662             ff_http_auth_handle_header(&s->auth_state, tag, p);
663         } else if (!av_strcasecmp(tag, "Authentication-Info")) {
664             ff_http_auth_handle_header(&s->auth_state, tag, p);
665         } else if (!av_strcasecmp(tag, "Proxy-Authenticate")) {
666             ff_http_auth_handle_header(&s->proxy_auth_state, tag, p);
667         } else if (!av_strcasecmp(tag, "Connection")) {
668             if (!strcmp(p, "close"))
669                 s->willclose = 1;
670         } else if (!av_strcasecmp(tag, "Server")) {
671             if (!av_strcasecmp(p, "AkamaiGHost")) {
672                 s->is_akamai = 1;
673             } else if (!av_strncasecmp(p, "MediaGateway", 12)) {
674                 s->is_mediagateway = 1;
675             }
676         } else if (!av_strcasecmp(tag, "Content-Type")) {
677             av_free(s->mime_type);
678             s->mime_type = av_strdup(p);
679         } else if (!av_strcasecmp(tag, "Set-Cookie")) {
680             if (parse_cookie(s, p, &s->cookie_dict))
681                 av_log(h, AV_LOG_WARNING, "Unable to parse '%s'\n", p);
682         } else if (!av_strcasecmp(tag, "Icy-MetaInt")) {
683             s->icy_metaint = strtoll(p, NULL, 10);
684         } else if (!av_strncasecmp(tag, "Icy-", 4)) {
685             if ((ret = parse_icy(s, tag, p)) < 0)
686                 return ret;
687         } else if (!av_strcasecmp(tag, "Content-Encoding")) {
688             if ((ret = parse_content_encoding(h, p)) < 0)
689                 return ret;
690         }
691     }
692     return 1;
693 }
694
695 /**
696  * Create a string containing cookie values for use as a HTTP cookie header
697  * field value for a particular path and domain from the cookie values stored in
698  * the HTTP protocol context. The cookie string is stored in *cookies.
699  *
700  * @return a negative value if an error condition occurred, 0 otherwise
701  */
702 static int get_cookies(HTTPContext *s, char **cookies, const char *path,
703                        const char *domain)
704 {
705     // cookie strings will look like Set-Cookie header field values.  Multiple
706     // Set-Cookie fields will result in multiple values delimited by a newline
707     int ret = 0;
708     char *next, *cookie, *set_cookies = av_strdup(s->cookies), *cset_cookies = set_cookies;
709
710     if (!set_cookies) return AVERROR(EINVAL);
711
712     // destroy any cookies in the dictionary.
713     av_dict_free(&s->cookie_dict);
714
715     *cookies = NULL;
716     while ((cookie = av_strtok(set_cookies, "\n", &next))) {
717         int domain_offset = 0;
718         char *param, *next_param, *cdomain = NULL, *cpath = NULL, *cvalue = NULL;
719         set_cookies = NULL;
720
721         // store the cookie in a dict in case it is updated in the response
722         if (parse_cookie(s, cookie, &s->cookie_dict))
723             av_log(s, AV_LOG_WARNING, "Unable to parse '%s'\n", cookie);
724
725         while ((param = av_strtok(cookie, "; ", &next_param))) {
726             if (cookie) {
727                 // first key-value pair is the actual cookie value
728                 cvalue = av_strdup(param);
729                 cookie = NULL;
730             } else if (!av_strncasecmp("path=",   param, 5)) {
731                 av_free(cpath);
732                 cpath = av_strdup(&param[5]);
733             } else if (!av_strncasecmp("domain=", param, 7)) {
734                 // if the cookie specifies a sub-domain, skip the leading dot thereby
735                 // supporting URLs that point to sub-domains and the master domain
736                 int leading_dot = (param[7] == '.');
737                 av_free(cdomain);
738                 cdomain = av_strdup(&param[7+leading_dot]);
739             } else {
740                 // ignore unknown attributes
741             }
742         }
743         if (!cdomain)
744             cdomain = av_strdup(domain);
745
746         // ensure all of the necessary values are valid
747         if (!cdomain || !cpath || !cvalue) {
748             av_log(s, AV_LOG_WARNING,
749                    "Invalid cookie found, no value, path or domain specified\n");
750             goto done_cookie;
751         }
752
753         // check if the request path matches the cookie path
754         if (av_strncasecmp(path, cpath, strlen(cpath)))
755             goto done_cookie;
756
757         // the domain should be at least the size of our cookie domain
758         domain_offset = strlen(domain) - strlen(cdomain);
759         if (domain_offset < 0)
760             goto done_cookie;
761
762         // match the cookie domain
763         if (av_strcasecmp(&domain[domain_offset], cdomain))
764             goto done_cookie;
765
766         // cookie parameters match, so copy the value
767         if (!*cookies) {
768             if (!(*cookies = av_strdup(cvalue))) {
769                 ret = AVERROR(ENOMEM);
770                 goto done_cookie;
771             }
772         } else {
773             char *tmp = *cookies;
774             size_t str_size = strlen(cvalue) + strlen(*cookies) + 3;
775             if (!(*cookies = av_malloc(str_size))) {
776                 ret = AVERROR(ENOMEM);
777                 goto done_cookie;
778             }
779             snprintf(*cookies, str_size, "%s; %s", tmp, cvalue);
780             av_free(tmp);
781         }
782
783         done_cookie:
784         av_freep(&cdomain);
785         av_freep(&cpath);
786         av_freep(&cvalue);
787         if (ret < 0) {
788             if (*cookies) av_freep(cookies);
789             av_free(cset_cookies);
790             return ret;
791         }
792     }
793
794     av_free(cset_cookies);
795
796     return 0;
797 }
798
799 static inline int has_header(const char *str, const char *header)
800 {
801     /* header + 2 to skip over CRLF prefix. (make sure you have one!) */
802     if (!str)
803         return 0;
804     return av_stristart(str, header + 2, NULL) || av_stristr(str, header);
805 }
806
807 static int http_read_header(URLContext *h, int *new_location)
808 {
809     HTTPContext *s = h->priv_data;
810     char line[MAX_URL_SIZE];
811     int err = 0;
812
813     s->chunksize = -1;
814
815     for (;;) {
816         if ((err = http_get_line(s, line, sizeof(line))) < 0)
817             return err;
818
819         av_log(h, AV_LOG_TRACE, "header='%s'\n", line);
820
821         err = process_line(h, line, s->line_count, new_location);
822         if (err < 0)
823             return err;
824         if (err == 0)
825             break;
826         s->line_count++;
827     }
828
829     if (s->seekable == -1 && s->is_mediagateway && s->filesize == 2000000000)
830         h->is_streamed = 1; /* we can in fact _not_ seek */
831
832     // add any new cookies into the existing cookie string
833     cookie_string(s->cookie_dict, &s->cookies);
834     av_dict_free(&s->cookie_dict);
835
836     return err;
837 }
838
839 static int http_connect(URLContext *h, const char *path, const char *local_path,
840                         const char *hoststr, const char *auth,
841                         const char *proxyauth, int *new_location)
842 {
843     HTTPContext *s = h->priv_data;
844     int post, err;
845     char headers[HTTP_HEADERS_SIZE] = "";
846     char *authstr = NULL, *proxyauthstr = NULL;
847     int64_t off = s->off;
848     int len = 0;
849     const char *method;
850     int send_expect_100 = 0;
851
852     /* send http header */
853     post = h->flags & AVIO_FLAG_WRITE;
854
855     if (s->post_data) {
856         /* force POST method and disable chunked encoding when
857          * custom HTTP post data is set */
858         post            = 1;
859         s->chunked_post = 0;
860     }
861
862     if (s->method)
863         method = s->method;
864     else
865         method = post ? "POST" : "GET";
866
867     authstr      = ff_http_auth_create_response(&s->auth_state, auth,
868                                                 local_path, method);
869     proxyauthstr = ff_http_auth_create_response(&s->proxy_auth_state, proxyauth,
870                                                 local_path, method);
871     if (post && !s->post_data) {
872         send_expect_100 = s->send_expect_100;
873         /* The user has supplied authentication but we don't know the auth type,
874          * send Expect: 100-continue to get the 401 response including the
875          * WWW-Authenticate header, or an 100 continue if no auth actually
876          * is needed. */
877         if (auth && *auth &&
878             s->auth_state.auth_type == HTTP_AUTH_NONE &&
879             s->http_code != 401)
880             send_expect_100 = 1;
881     }
882
883     /* set default headers if needed */
884     if (!has_header(s->headers, "\r\nUser-Agent: "))
885         len += av_strlcatf(headers + len, sizeof(headers) - len,
886                            "User-Agent: %s\r\n", s->user_agent);
887     if (!has_header(s->headers, "\r\nAccept: "))
888         len += av_strlcpy(headers + len, "Accept: */*\r\n",
889                           sizeof(headers) - len);
890     // Note: we send this on purpose even when s->off is 0 when we're probing,
891     // since it allows us to detect more reliably if a (non-conforming)
892     // server supports seeking by analysing the reply headers.
893     if (!has_header(s->headers, "\r\nRange: ") && !post && (s->off > 0 || s->end_off || s->seekable == -1)) {
894         len += av_strlcatf(headers + len, sizeof(headers) - len,
895                            "Range: bytes=%"PRId64"-", s->off);
896         if (s->end_off)
897             len += av_strlcatf(headers + len, sizeof(headers) - len,
898                                "%"PRId64, s->end_off - 1);
899         len += av_strlcpy(headers + len, "\r\n",
900                           sizeof(headers) - len);
901     }
902     if (send_expect_100 && !has_header(s->headers, "\r\nExpect: "))
903         len += av_strlcatf(headers + len, sizeof(headers) - len,
904                            "Expect: 100-continue\r\n");
905
906     if (!has_header(s->headers, "\r\nConnection: ")) {
907         if (s->multiple_requests)
908             len += av_strlcpy(headers + len, "Connection: keep-alive\r\n",
909                               sizeof(headers) - len);
910         else
911             len += av_strlcpy(headers + len, "Connection: close\r\n",
912                               sizeof(headers) - len);
913     }
914
915     if (!has_header(s->headers, "\r\nHost: "))
916         len += av_strlcatf(headers + len, sizeof(headers) - len,
917                            "Host: %s\r\n", hoststr);
918     if (!has_header(s->headers, "\r\nContent-Length: ") && s->post_data)
919         len += av_strlcatf(headers + len, sizeof(headers) - len,
920                            "Content-Length: %d\r\n", s->post_datalen);
921
922     if (!has_header(s->headers, "\r\nContent-Type: ") && s->content_type)
923         len += av_strlcatf(headers + len, sizeof(headers) - len,
924                            "Content-Type: %s\r\n", s->content_type);
925     if (!has_header(s->headers, "\r\nCookie: ") && s->cookies) {
926         char *cookies = NULL;
927         if (!get_cookies(s, &cookies, path, hoststr) && cookies) {
928             len += av_strlcatf(headers + len, sizeof(headers) - len,
929                                "Cookie: %s\r\n", cookies);
930             av_free(cookies);
931         }
932     }
933     if (!has_header(s->headers, "\r\nIcy-MetaData: ") && s->icy)
934         len += av_strlcatf(headers + len, sizeof(headers) - len,
935                            "Icy-MetaData: %d\r\n", 1);
936
937     /* now add in custom headers */
938     if (s->headers)
939         av_strlcpy(headers + len, s->headers, sizeof(headers) - len);
940
941     snprintf(s->buffer, sizeof(s->buffer),
942              "%s %s HTTP/1.1\r\n"
943              "%s"
944              "%s"
945              "%s"
946              "%s%s"
947              "\r\n",
948              method,
949              path,
950              post && s->chunked_post ? "Transfer-Encoding: chunked\r\n" : "",
951              headers,
952              authstr ? authstr : "",
953              proxyauthstr ? "Proxy-" : "", proxyauthstr ? proxyauthstr : "");
954
955     av_log(h, AV_LOG_DEBUG, "request: %s\n", s->buffer);
956
957     if ((err = ffurl_write(s->hd, s->buffer, strlen(s->buffer))) < 0)
958         goto done;
959
960     if (s->post_data)
961         if ((err = ffurl_write(s->hd, s->post_data, s->post_datalen)) < 0)
962             goto done;
963
964     /* init input buffer */
965     s->buf_ptr          = s->buffer;
966     s->buf_end          = s->buffer;
967     s->line_count       = 0;
968     s->off              = 0;
969     s->icy_data_read    = 0;
970     s->filesize         = -1;
971     s->willclose        = 0;
972     s->end_chunked_post = 0;
973     s->end_header       = 0;
974     if (post && !s->post_data && !send_expect_100) {
975         /* Pretend that it did work. We didn't read any header yet, since
976          * we've still to send the POST data, but the code calling this
977          * function will check http_code after we return. */
978         s->http_code = 200;
979         err = 0;
980         goto done;
981     }
982
983     /* wait for header */
984     err = http_read_header(h, new_location);
985     if (err < 0)
986         goto done;
987
988     if (*new_location)
989         s->off = off;
990
991     err = (off == s->off) ? 0 : -1;
992 done:
993     av_freep(&authstr);
994     av_freep(&proxyauthstr);
995     return err;
996 }
997
998 static int http_buf_read(URLContext *h, uint8_t *buf, int size)
999 {
1000     HTTPContext *s = h->priv_data;
1001     int len;
1002     /* read bytes from input buffer first */
1003     len = s->buf_end - s->buf_ptr;
1004     if (len > 0) {
1005         if (len > size)
1006             len = size;
1007         memcpy(buf, s->buf_ptr, len);
1008         s->buf_ptr += len;
1009     } else {
1010         if ((!s->willclose || s->chunksize < 0) &&
1011             s->filesize >= 0 && s->off >= s->filesize)
1012             return AVERROR_EOF;
1013         len = ffurl_read(s->hd, buf, size);
1014         if (!len && (!s->willclose || s->chunksize < 0) &&
1015             s->filesize >= 0 && s->off < s->filesize) {
1016             av_log(h, AV_LOG_ERROR,
1017                    "Stream ends prematurely at %"PRId64", should be %"PRId64"\n",
1018                    s->off, s->filesize
1019                   );
1020             return AVERROR(EIO);
1021         }
1022     }
1023     if (len > 0) {
1024         s->off += len;
1025         if (s->chunksize > 0)
1026             s->chunksize -= len;
1027     }
1028     return len;
1029 }
1030
1031 #if CONFIG_ZLIB
1032 #define DECOMPRESS_BUF_SIZE (256 * 1024)
1033 static int http_buf_read_compressed(URLContext *h, uint8_t *buf, int size)
1034 {
1035     HTTPContext *s = h->priv_data;
1036     int ret;
1037
1038     if (!s->inflate_buffer) {
1039         s->inflate_buffer = av_malloc(DECOMPRESS_BUF_SIZE);
1040         if (!s->inflate_buffer)
1041             return AVERROR(ENOMEM);
1042     }
1043
1044     if (s->inflate_stream.avail_in == 0) {
1045         int read = http_buf_read(h, s->inflate_buffer, DECOMPRESS_BUF_SIZE);
1046         if (read <= 0)
1047             return read;
1048         s->inflate_stream.next_in  = s->inflate_buffer;
1049         s->inflate_stream.avail_in = read;
1050     }
1051
1052     s->inflate_stream.avail_out = size;
1053     s->inflate_stream.next_out  = buf;
1054
1055     ret = inflate(&s->inflate_stream, Z_SYNC_FLUSH);
1056     if (ret != Z_OK && ret != Z_STREAM_END)
1057         av_log(h, AV_LOG_WARNING, "inflate return value: %d, %s\n",
1058                ret, s->inflate_stream.msg);
1059
1060     return size - s->inflate_stream.avail_out;
1061 }
1062 #endif /* CONFIG_ZLIB */
1063
1064 static int64_t http_seek_internal(URLContext *h, int64_t off, int whence, int force_reconnect);
1065
1066 static int http_read_stream(URLContext *h, uint8_t *buf, int size)
1067 {
1068     HTTPContext *s = h->priv_data;
1069     int err, new_location, read_ret, seek_ret;
1070
1071     if (!s->hd)
1072         return AVERROR_EOF;
1073
1074     if (s->end_chunked_post && !s->end_header) {
1075         err = http_read_header(h, &new_location);
1076         if (err < 0)
1077             return err;
1078     }
1079
1080     if (s->chunksize >= 0) {
1081         if (!s->chunksize) {
1082             char line[32];
1083
1084                 do {
1085                     if ((err = http_get_line(s, line, sizeof(line))) < 0)
1086                         return err;
1087                 } while (!*line);    /* skip CR LF from last chunk */
1088
1089                 s->chunksize = strtoll(line, NULL, 16);
1090
1091                 av_log(NULL, AV_LOG_TRACE, "Chunked encoding data size: %"PRId64"'\n",
1092                         s->chunksize);
1093
1094                 if (!s->chunksize)
1095                     return 0;
1096         }
1097         size = FFMIN(size, s->chunksize);
1098     }
1099 #if CONFIG_ZLIB
1100     if (s->compressed)
1101         return http_buf_read_compressed(h, buf, size);
1102 #endif /* CONFIG_ZLIB */
1103     read_ret = http_buf_read(h, buf, size);
1104     if (read_ret < 0 && s->reconnect && !h->is_streamed && s->filesize > 0 && s->off < s->filesize) {
1105         av_log(h, AV_LOG_INFO, "Will reconnect at %"PRId64".\n", s->off);
1106         seek_ret = http_seek_internal(h, s->off, SEEK_SET, 1);
1107         if (seek_ret != s->off) {
1108             av_log(h, AV_LOG_ERROR, "Failed to reconnect at %"PRId64".\n", s->off);
1109             return read_ret;
1110         }
1111
1112         read_ret = http_buf_read(h, buf, size);
1113     }
1114
1115     return read_ret;
1116 }
1117
1118 // Like http_read_stream(), but no short reads.
1119 // Assumes partial reads are an error.
1120 static int http_read_stream_all(URLContext *h, uint8_t *buf, int size)
1121 {
1122     int pos = 0;
1123     while (pos < size) {
1124         int len = http_read_stream(h, buf + pos, size - pos);
1125         if (len < 0)
1126             return len;
1127         pos += len;
1128     }
1129     return pos;
1130 }
1131
1132 static void update_metadata(HTTPContext *s, char *data)
1133 {
1134     char *key;
1135     char *val;
1136     char *end;
1137     char *next = data;
1138
1139     while (*next) {
1140         key = next;
1141         val = strstr(key, "='");
1142         if (!val)
1143             break;
1144         end = strstr(val, "';");
1145         if (!end)
1146             break;
1147
1148         *val = '\0';
1149         *end = '\0';
1150         val += 2;
1151
1152         av_dict_set(&s->metadata, key, val, 0);
1153
1154         next = end + 2;
1155     }
1156 }
1157
1158 static int store_icy(URLContext *h, int size)
1159 {
1160     HTTPContext *s = h->priv_data;
1161     /* until next metadata packet */
1162     int remaining = s->icy_metaint - s->icy_data_read;
1163
1164     if (remaining < 0)
1165         return AVERROR_INVALIDDATA;
1166
1167     if (!remaining) {
1168         /* The metadata packet is variable sized. It has a 1 byte header
1169          * which sets the length of the packet (divided by 16). If it's 0,
1170          * the metadata doesn't change. After the packet, icy_metaint bytes
1171          * of normal data follows. */
1172         uint8_t ch;
1173         int len = http_read_stream_all(h, &ch, 1);
1174         if (len < 0)
1175             return len;
1176         if (ch > 0) {
1177             char data[255 * 16 + 1];
1178             int ret;
1179             len = ch * 16;
1180             ret = http_read_stream_all(h, data, len);
1181             if (ret < 0)
1182                 return ret;
1183             data[len + 1] = 0;
1184             if ((ret = av_opt_set(s, "icy_metadata_packet", data, 0)) < 0)
1185                 return ret;
1186             update_metadata(s, data);
1187         }
1188         s->icy_data_read = 0;
1189         remaining        = s->icy_metaint;
1190     }
1191
1192     return FFMIN(size, remaining);
1193 }
1194
1195 static int http_read(URLContext *h, uint8_t *buf, int size)
1196 {
1197     HTTPContext *s = h->priv_data;
1198
1199     if (s->icy_metaint > 0) {
1200         size = store_icy(h, size);
1201         if (size < 0)
1202             return size;
1203     }
1204
1205     size = http_read_stream(h, buf, size);
1206     if (size > 0)
1207         s->icy_data_read += size;
1208     return size;
1209 }
1210
1211 /* used only when posting data */
1212 static int http_write(URLContext *h, const uint8_t *buf, int size)
1213 {
1214     char temp[11] = "";  /* 32-bit hex + CRLF + nul */
1215     int ret;
1216     char crlf[] = "\r\n";
1217     HTTPContext *s = h->priv_data;
1218
1219     if (!s->chunked_post) {
1220         /* non-chunked data is sent without any special encoding */
1221         return ffurl_write(s->hd, buf, size);
1222     }
1223
1224     /* silently ignore zero-size data since chunk encoding that would
1225      * signal EOF */
1226     if (size > 0) {
1227         /* upload data using chunked encoding */
1228         snprintf(temp, sizeof(temp), "%x\r\n", size);
1229
1230         if ((ret = ffurl_write(s->hd, temp, strlen(temp))) < 0 ||
1231             (ret = ffurl_write(s->hd, buf, size)) < 0          ||
1232             (ret = ffurl_write(s->hd, crlf, sizeof(crlf) - 1)) < 0)
1233             return ret;
1234     }
1235     return size;
1236 }
1237
1238 static int http_shutdown(URLContext *h, int flags)
1239 {
1240     int ret = 0;
1241     char footer[] = "0\r\n\r\n";
1242     HTTPContext *s = h->priv_data;
1243
1244     /* signal end of chunked encoding if used */
1245     if ((flags & AVIO_FLAG_WRITE) && s->chunked_post) {
1246         ret = ffurl_write(s->hd, footer, sizeof(footer) - 1);
1247         ret = ret > 0 ? 0 : ret;
1248         s->end_chunked_post = 1;
1249     }
1250
1251     return ret;
1252 }
1253
1254 static int http_close(URLContext *h)
1255 {
1256     int ret = 0;
1257     HTTPContext *s = h->priv_data;
1258
1259 #if CONFIG_ZLIB
1260     inflateEnd(&s->inflate_stream);
1261     av_freep(&s->inflate_buffer);
1262 #endif /* CONFIG_ZLIB */
1263
1264     if (!s->end_chunked_post)
1265         /* Close the write direction by sending the end of chunked encoding. */
1266         ret = http_shutdown(h, h->flags);
1267
1268     if (s->hd)
1269         ffurl_closep(&s->hd);
1270     av_dict_free(&s->chained_options);
1271     return ret;
1272 }
1273
1274 static int64_t http_seek_internal(URLContext *h, int64_t off, int whence, int force_reconnect)
1275 {
1276     HTTPContext *s = h->priv_data;
1277     URLContext *old_hd = s->hd;
1278     int64_t old_off = s->off;
1279     uint8_t old_buf[BUFFER_SIZE];
1280     int old_buf_size, ret;
1281     AVDictionary *options = NULL;
1282
1283     if (whence == AVSEEK_SIZE)
1284         return s->filesize;
1285     else if (!force_reconnect &&
1286              ((whence == SEEK_CUR && off == 0) ||
1287               (whence == SEEK_SET && off == s->off)))
1288         return s->off;
1289     else if ((s->filesize == -1 && whence == SEEK_END) || h->is_streamed)
1290         return AVERROR(ENOSYS);
1291
1292     if (whence == SEEK_CUR)
1293         off += s->off;
1294     else if (whence == SEEK_END)
1295         off += s->filesize;
1296     else if (whence != SEEK_SET)
1297         return AVERROR(EINVAL);
1298     if (off < 0)
1299         return AVERROR(EINVAL);
1300     s->off = off;
1301
1302     /* we save the old context in case the seek fails */
1303     old_buf_size = s->buf_end - s->buf_ptr;
1304     memcpy(old_buf, s->buf_ptr, old_buf_size);
1305     s->hd = NULL;
1306
1307     /* if it fails, continue on old connection */
1308     if ((ret = http_open_cnx(h, &options)) < 0) {
1309         av_dict_free(&options);
1310         memcpy(s->buffer, old_buf, old_buf_size);
1311         s->buf_ptr = s->buffer;
1312         s->buf_end = s->buffer + old_buf_size;
1313         s->hd      = old_hd;
1314         s->off     = old_off;
1315         return ret;
1316     }
1317     av_dict_free(&options);
1318     ffurl_close(old_hd);
1319     return off;
1320 }
1321
1322 static int64_t http_seek(URLContext *h, int64_t off, int whence)
1323 {
1324     return http_seek_internal(h, off, whence, 0);
1325 }
1326
1327 static int http_get_file_handle(URLContext *h)
1328 {
1329     HTTPContext *s = h->priv_data;
1330     return ffurl_get_file_handle(s->hd);
1331 }
1332
1333 #define HTTP_CLASS(flavor)                          \
1334 static const AVClass flavor ## _context_class = {   \
1335     .class_name = # flavor,                         \
1336     .item_name  = av_default_item_name,             \
1337     .option     = options,                          \
1338     .version    = LIBAVUTIL_VERSION_INT,            \
1339 }
1340
1341 #if CONFIG_HTTP_PROTOCOL
1342 HTTP_CLASS(http);
1343
1344 URLProtocol ff_http_protocol = {
1345     .name                = "http",
1346     .url_open2           = http_open,
1347     .url_read            = http_read,
1348     .url_write           = http_write,
1349     .url_seek            = http_seek,
1350     .url_close           = http_close,
1351     .url_get_file_handle = http_get_file_handle,
1352     .url_shutdown        = http_shutdown,
1353     .priv_data_size      = sizeof(HTTPContext),
1354     .priv_data_class     = &http_context_class,
1355     .flags               = URL_PROTOCOL_FLAG_NETWORK,
1356 };
1357 #endif /* CONFIG_HTTP_PROTOCOL */
1358
1359 #if CONFIG_HTTPS_PROTOCOL
1360 HTTP_CLASS(https);
1361
1362 URLProtocol ff_https_protocol = {
1363     .name                = "https",
1364     .url_open2           = http_open,
1365     .url_read            = http_read,
1366     .url_write           = http_write,
1367     .url_seek            = http_seek,
1368     .url_close           = http_close,
1369     .url_get_file_handle = http_get_file_handle,
1370     .url_shutdown        = http_shutdown,
1371     .priv_data_size      = sizeof(HTTPContext),
1372     .priv_data_class     = &https_context_class,
1373     .flags               = URL_PROTOCOL_FLAG_NETWORK,
1374 };
1375 #endif /* CONFIG_HTTPS_PROTOCOL */
1376
1377 #if CONFIG_HTTPPROXY_PROTOCOL
1378 static int http_proxy_close(URLContext *h)
1379 {
1380     HTTPContext *s = h->priv_data;
1381     if (s->hd)
1382         ffurl_closep(&s->hd);
1383     return 0;
1384 }
1385
1386 static int http_proxy_open(URLContext *h, const char *uri, int flags)
1387 {
1388     HTTPContext *s = h->priv_data;
1389     char hostname[1024], hoststr[1024];
1390     char auth[1024], pathbuf[1024], *path;
1391     char lower_url[100];
1392     int port, ret = 0, attempts = 0;
1393     HTTPAuthType cur_auth_type;
1394     char *authstr;
1395     int new_loc;
1396
1397     if( s->seekable == 1 )
1398         h->is_streamed = 0;
1399     else
1400         h->is_streamed = 1;
1401
1402     av_url_split(NULL, 0, auth, sizeof(auth), hostname, sizeof(hostname), &port,
1403                  pathbuf, sizeof(pathbuf), uri);
1404     ff_url_join(hoststr, sizeof(hoststr), NULL, NULL, hostname, port, NULL);
1405     path = pathbuf;
1406     if (*path == '/')
1407         path++;
1408
1409     ff_url_join(lower_url, sizeof(lower_url), "tcp", NULL, hostname, port,
1410                 NULL);
1411 redo:
1412     ret = ffurl_open(&s->hd, lower_url, AVIO_FLAG_READ_WRITE,
1413                      &h->interrupt_callback, NULL);
1414     if (ret < 0)
1415         return ret;
1416
1417     authstr = ff_http_auth_create_response(&s->proxy_auth_state, auth,
1418                                            path, "CONNECT");
1419     snprintf(s->buffer, sizeof(s->buffer),
1420              "CONNECT %s HTTP/1.1\r\n"
1421              "Host: %s\r\n"
1422              "Connection: close\r\n"
1423              "%s%s"
1424              "\r\n",
1425              path,
1426              hoststr,
1427              authstr ? "Proxy-" : "", authstr ? authstr : "");
1428     av_freep(&authstr);
1429
1430     if ((ret = ffurl_write(s->hd, s->buffer, strlen(s->buffer))) < 0)
1431         goto fail;
1432
1433     s->buf_ptr    = s->buffer;
1434     s->buf_end    = s->buffer;
1435     s->line_count = 0;
1436     s->filesize   = -1;
1437     cur_auth_type = s->proxy_auth_state.auth_type;
1438
1439     /* Note: This uses buffering, potentially reading more than the
1440      * HTTP header. If tunneling a protocol where the server starts
1441      * the conversation, we might buffer part of that here, too.
1442      * Reading that requires using the proper ffurl_read() function
1443      * on this URLContext, not using the fd directly (as the tls
1444      * protocol does). This shouldn't be an issue for tls though,
1445      * since the client starts the conversation there, so there
1446      * is no extra data that we might buffer up here.
1447      */
1448     ret = http_read_header(h, &new_loc);
1449     if (ret < 0)
1450         goto fail;
1451
1452     attempts++;
1453     if (s->http_code == 407 &&
1454         (cur_auth_type == HTTP_AUTH_NONE || s->proxy_auth_state.stale) &&
1455         s->proxy_auth_state.auth_type != HTTP_AUTH_NONE && attempts < 2) {
1456         ffurl_closep(&s->hd);
1457         goto redo;
1458     }
1459
1460     if (s->http_code < 400)
1461         return 0;
1462     ret = ff_http_averror(s->http_code, AVERROR(EIO));
1463
1464 fail:
1465     http_proxy_close(h);
1466     return ret;
1467 }
1468
1469 static int http_proxy_write(URLContext *h, const uint8_t *buf, int size)
1470 {
1471     HTTPContext *s = h->priv_data;
1472     return ffurl_write(s->hd, buf, size);
1473 }
1474
1475 URLProtocol ff_httpproxy_protocol = {
1476     .name                = "httpproxy",
1477     .url_open            = http_proxy_open,
1478     .url_read            = http_buf_read,
1479     .url_write           = http_proxy_write,
1480     .url_close           = http_proxy_close,
1481     .url_get_file_handle = http_get_file_handle,
1482     .priv_data_size      = sizeof(HTTPContext),
1483     .flags               = URL_PROTOCOL_FLAG_NETWORK,
1484 };
1485 #endif /* CONFIG_HTTPPROXY_PROTOCOL */