]> git.sesse.net Git - ffmpeg/blob - libavformat/http.c
avformat/avio: Add Metacube support
[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/avassert.h"
29 #include "libavutil/avstring.h"
30 #include "libavutil/bprint.h"
31 #include "libavutil/opt.h"
32 #include "libavutil/time.h"
33 #include "libavutil/parseutils.h"
34
35 #include "avformat.h"
36 #include "http.h"
37 #include "httpauth.h"
38 #include "internal.h"
39 #include "network.h"
40 #include "os_support.h"
41 #include "url.h"
42
43 /* XXX: POST protocol is not completely implemented because ffmpeg uses
44  * only a subset of it. */
45
46 /* The IO buffer size is unrelated to the max URL size in itself, but needs
47  * to be large enough to fit the full request headers (including long
48  * path names). */
49 #define BUFFER_SIZE   (MAX_URL_SIZE + HTTP_HEADERS_SIZE)
50 #define MAX_REDIRECTS 8
51 #define HTTP_SINGLE   1
52 #define HTTP_MUTLI    2
53 #define MAX_EXPIRY    19
54 #define WHITESPACES " \n\t\r"
55 typedef enum {
56     LOWER_PROTO,
57     READ_HEADERS,
58     WRITE_REPLY_HEADERS,
59     FINISH
60 }HandshakeState;
61
62 typedef struct HTTPContext {
63     const AVClass *class;
64     URLContext *hd;
65     unsigned char buffer[BUFFER_SIZE], *buf_ptr, *buf_end;
66     int line_count;
67     int http_code;
68     /* Used if "Transfer-Encoding: chunked" otherwise -1. */
69     uint64_t chunksize;
70     int chunkend;
71     uint64_t off, end_off, filesize;
72     char *location;
73     HTTPAuthState auth_state;
74     HTTPAuthState proxy_auth_state;
75     char *http_proxy;
76     char *headers;
77     char *mime_type;
78     char *http_version;
79     char *user_agent;
80     char *referer;
81     char *content_type;
82     /* Set if the server correctly handles Connection: close and will close
83      * the connection after feeding us the content. */
84     int willclose;
85     int seekable;           /**< Control seekability, 0 = disable, 1 = enable, -1 = probe. */
86     int chunked_post;
87     /* A flag which indicates if the end of chunked encoding has been sent. */
88     int end_chunked_post;
89     /* A flag which indicates we have finished to read POST reply. */
90     int end_header;
91     /* A flag which indicates if we use persistent connections. */
92     int multiple_requests;
93     uint8_t *post_data;
94     int post_datalen;
95     int is_akamai;
96     int is_mediagateway;
97     char *cookies;          ///< holds newline (\n) delimited Set-Cookie header field values (without the "Set-Cookie: " field name)
98     /* A dictionary containing cookies keyed by cookie name */
99     AVDictionary *cookie_dict;
100     int icy;
101     /* how much data was read since the last ICY metadata packet */
102     uint64_t icy_data_read;
103     /* after how many bytes of read data a new metadata packet will be found */
104     uint64_t icy_metaint;
105     char *icy_metadata_headers;
106     char *icy_metadata_packet;
107     AVDictionary *metadata;
108 #if CONFIG_ZLIB
109     int compressed;
110     z_stream inflate_stream;
111     uint8_t *inflate_buffer;
112 #endif /* CONFIG_ZLIB */
113     AVDictionary *chained_options;
114     /* -1 = try to send if applicable, 0 = always disabled, 1 = always enabled */
115     int send_expect_100;
116     char *method;
117     int reconnect;
118     int reconnect_at_eof;
119     int reconnect_on_network_error;
120     int reconnect_streamed;
121     int reconnect_delay_max;
122     char *reconnect_on_http_error;
123     int listen;
124     char *resource;
125     int reply_code;
126     int is_multi_client;
127     HandshakeState handshake_step;
128     int is_connected_server;
129 } HTTPContext;
130
131 #define OFFSET(x) offsetof(HTTPContext, x)
132 #define D AV_OPT_FLAG_DECODING_PARAM
133 #define E AV_OPT_FLAG_ENCODING_PARAM
134 #define DEFAULT_USER_AGENT "Lavf/" AV_STRINGIFY(LIBAVFORMAT_VERSION)
135
136 static const AVOption options[] = {
137     { "seekable", "control seekability of connection", OFFSET(seekable), AV_OPT_TYPE_BOOL, { .i64 = -1 }, -1, 1, D },
138     { "chunked_post", "use chunked transfer-encoding for posts", OFFSET(chunked_post), AV_OPT_TYPE_BOOL, { .i64 = 1 }, 0, 1, E },
139     { "http_proxy", "set HTTP proxy to tunnel through", OFFSET(http_proxy), AV_OPT_TYPE_STRING, { .str = NULL }, 0, 0, D | E },
140     { "headers", "set custom HTTP headers, can override built in default headers", OFFSET(headers), AV_OPT_TYPE_STRING, { .str = NULL }, 0, 0, D | E },
141     { "content_type", "set a specific content type for the POST messages", OFFSET(content_type), AV_OPT_TYPE_STRING, { .str = NULL }, 0, 0, D | E },
142     { "user_agent", "override User-Agent header", OFFSET(user_agent), AV_OPT_TYPE_STRING, { .str = DEFAULT_USER_AGENT }, 0, 0, D },
143     { "referer", "override referer header", OFFSET(referer), AV_OPT_TYPE_STRING, { .str = NULL }, 0, 0, D },
144     { "multiple_requests", "use persistent connections", OFFSET(multiple_requests), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, D | E },
145     { "post_data", "set custom HTTP post data", OFFSET(post_data), AV_OPT_TYPE_BINARY, .flags = D | E },
146     { "mime_type", "export the MIME type", OFFSET(mime_type), AV_OPT_TYPE_STRING, { .str = NULL }, 0, 0, AV_OPT_FLAG_EXPORT | AV_OPT_FLAG_READONLY },
147     { "http_version", "export the http response version", OFFSET(http_version), AV_OPT_TYPE_STRING, { .str = NULL }, 0, 0, AV_OPT_FLAG_EXPORT | AV_OPT_FLAG_READONLY },
148     { "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, { .str = NULL }, 0, 0, D },
149     { "icy", "request ICY metadata", OFFSET(icy), AV_OPT_TYPE_BOOL, { .i64 = 1 }, 0, 1, D },
150     { "icy_metadata_headers", "return ICY metadata headers", OFFSET(icy_metadata_headers), AV_OPT_TYPE_STRING, { .str = NULL }, 0, 0, AV_OPT_FLAG_EXPORT },
151     { "icy_metadata_packet", "return current ICY metadata packet", OFFSET(icy_metadata_packet), AV_OPT_TYPE_STRING, { .str = NULL }, 0, 0, AV_OPT_FLAG_EXPORT },
152     { "metadata", "metadata read from the bitstream", OFFSET(metadata), AV_OPT_TYPE_DICT, {0}, 0, 0, AV_OPT_FLAG_EXPORT },
153     { "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"},
154     { "none", "No auth method set, autodetect", 0, AV_OPT_TYPE_CONST, { .i64 = HTTP_AUTH_NONE }, 0, 0, D | E, "auth_type"},
155     { "basic", "HTTP basic authentication", 0, AV_OPT_TYPE_CONST, { .i64 = HTTP_AUTH_BASIC }, 0, 0, D | E, "auth_type"},
156     { "send_expect_100", "Force sending an Expect: 100-continue header for POST", OFFSET(send_expect_100), AV_OPT_TYPE_BOOL, { .i64 = -1 }, -1, 1, E },
157     { "location", "The actual location of the data received", OFFSET(location), AV_OPT_TYPE_STRING, { .str = NULL }, 0, 0, D | E },
158     { "offset", "initial byte offset", OFFSET(off), AV_OPT_TYPE_INT64, { .i64 = 0 }, 0, INT64_MAX, D },
159     { "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 },
160     { "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 },
161     { "reconnect", "auto reconnect after disconnect before EOF", OFFSET(reconnect), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, D },
162     { "reconnect_at_eof", "auto reconnect at EOF", OFFSET(reconnect_at_eof), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, D },
163     { "reconnect_on_network_error", "auto reconnect in case of tcp/tls error during connect", OFFSET(reconnect_on_network_error), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, D },
164     { "reconnect_on_http_error", "list of http status codes to reconnect on", OFFSET(reconnect_on_http_error), AV_OPT_TYPE_STRING, { .str = NULL }, 0, 0, D },
165     { "reconnect_streamed", "auto reconnect streamed / non seekable streams", OFFSET(reconnect_streamed), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, D },
166     { "reconnect_delay_max", "max reconnect delay in seconds after which to give up", OFFSET(reconnect_delay_max), AV_OPT_TYPE_INT, { .i64 = 120 }, 0, UINT_MAX/1000/1000, D },
167     { "listen", "listen on HTTP", OFFSET(listen), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 2, D | E },
168     { "resource", "The resource requested by a client", OFFSET(resource), AV_OPT_TYPE_STRING, { .str = NULL }, 0, 0, E },
169     { "reply_code", "The http status code to return to a client", OFFSET(reply_code), AV_OPT_TYPE_INT, { .i64 = 200}, INT_MIN, 599, E},
170     { NULL }
171 };
172
173 static int http_connect(URLContext *h, const char *path, const char *local_path,
174                         const char *hoststr, const char *auth,
175                         const char *proxyauth, int *new_location);
176 static int http_read_header(URLContext *h, int *new_location);
177 static int http_shutdown(URLContext *h, int flags);
178
179 void ff_http_init_auth_state(URLContext *dest, const URLContext *src)
180 {
181     memcpy(&((HTTPContext *)dest->priv_data)->auth_state,
182            &((HTTPContext *)src->priv_data)->auth_state,
183            sizeof(HTTPAuthState));
184     memcpy(&((HTTPContext *)dest->priv_data)->proxy_auth_state,
185            &((HTTPContext *)src->priv_data)->proxy_auth_state,
186            sizeof(HTTPAuthState));
187 }
188
189 static int http_open_cnx_internal(URLContext *h, AVDictionary **options)
190 {
191     const char *path, *proxy_path, *lower_proto = "tcp", *local_path;
192     char *hashmark;
193     char hostname[1024], hoststr[1024], proto[10];
194     char auth[1024], proxyauth[1024] = "";
195     char path1[MAX_URL_SIZE], sanitized_path[MAX_URL_SIZE];
196     char buf[1024], urlbuf[MAX_URL_SIZE];
197     int port, use_proxy, err, location_changed = 0;
198     HTTPContext *s = h->priv_data;
199
200     av_url_split(proto, sizeof(proto), auth, sizeof(auth),
201                  hostname, sizeof(hostname), &port,
202                  path1, sizeof(path1), s->location);
203     ff_url_join(hoststr, sizeof(hoststr), NULL, NULL, hostname, port, NULL);
204
205     proxy_path = s->http_proxy ? s->http_proxy : getenv("http_proxy");
206     use_proxy  = !ff_http_match_no_proxy(getenv("no_proxy"), hostname) &&
207                  proxy_path && av_strstart(proxy_path, "http://", NULL);
208
209     if (!strcmp(proto, "https")) {
210         lower_proto = "tls";
211         use_proxy   = 0;
212         if (port < 0)
213             port = 443;
214         /* pass http_proxy to underlying protocol */
215         if (s->http_proxy) {
216             err = av_dict_set(options, "http_proxy", s->http_proxy, 0);
217             if (err < 0)
218                 return err;
219         }
220     }
221     if (port < 0)
222         port = 80;
223
224     hashmark = strchr(path1, '#');
225     if (hashmark)
226         *hashmark = '\0';
227
228     if (path1[0] == '\0') {
229         path = "/";
230     } else if (path1[0] == '?') {
231         snprintf(sanitized_path, sizeof(sanitized_path), "/%s", path1);
232         path = sanitized_path;
233     } else {
234         path = path1;
235     }
236     local_path = path;
237     if (use_proxy) {
238         /* Reassemble the request URL without auth string - we don't
239          * want to leak the auth to the proxy. */
240         ff_url_join(urlbuf, sizeof(urlbuf), proto, NULL, hostname, port, "%s",
241                     path1);
242         path = urlbuf;
243         av_url_split(NULL, 0, proxyauth, sizeof(proxyauth),
244                      hostname, sizeof(hostname), &port, NULL, 0, proxy_path);
245     }
246
247     ff_url_join(buf, sizeof(buf), lower_proto, NULL, hostname, port, NULL);
248
249     if (!s->hd) {
250         err = ffurl_open_whitelist(&s->hd, buf, AVIO_FLAG_READ_WRITE,
251                                    &h->interrupt_callback, options,
252                                    h->protocol_whitelist, h->protocol_blacklist, h);
253         if (err < 0)
254             return err;
255     }
256
257     err = http_connect(h, path, local_path, hoststr,
258                        auth, proxyauth, &location_changed);
259     if (err < 0)
260         return err;
261
262     return location_changed;
263 }
264
265 static int http_should_reconnect(HTTPContext *s, int err)
266 {
267     const char *status_group;
268     char http_code[4];
269
270     switch (err) {
271     case AVERROR_HTTP_BAD_REQUEST:
272     case AVERROR_HTTP_UNAUTHORIZED:
273     case AVERROR_HTTP_FORBIDDEN:
274     case AVERROR_HTTP_NOT_FOUND:
275     case AVERROR_HTTP_OTHER_4XX:
276         status_group = "4xx";
277         break;
278
279     case AVERROR_HTTP_SERVER_ERROR:
280         status_group = "5xx";
281         break;
282
283     default:
284         return s->reconnect_on_network_error;
285     }
286
287     if (!s->reconnect_on_http_error)
288         return 0;
289
290     if (av_match_list(status_group, s->reconnect_on_http_error, ',') > 0)
291         return 1;
292
293     snprintf(http_code, sizeof(http_code), "%d", s->http_code);
294
295     return av_match_list(http_code, s->reconnect_on_http_error, ',') > 0;
296 }
297
298 /* return non zero if error */
299 static int http_open_cnx(URLContext *h, AVDictionary **options)
300 {
301     HTTPAuthType cur_auth_type, cur_proxy_auth_type;
302     HTTPContext *s = h->priv_data;
303     int location_changed, attempts = 0, redirects = 0;
304     int reconnect_delay = 0;
305     uint64_t off;
306
307 redo:
308     av_dict_copy(options, s->chained_options, 0);
309
310     cur_auth_type       = s->auth_state.auth_type;
311     cur_proxy_auth_type = s->auth_state.auth_type;
312
313     off = s->off;
314     location_changed = http_open_cnx_internal(h, options);
315     if (location_changed < 0) {
316         if (!http_should_reconnect(s, location_changed) ||
317             reconnect_delay > s->reconnect_delay_max)
318             goto fail;
319
320         av_log(h, AV_LOG_WARNING, "Will reconnect at %"PRIu64" in %d second(s).\n", off, reconnect_delay);
321         location_changed = ff_network_sleep_interruptible(1000U * 1000 * reconnect_delay, &h->interrupt_callback);
322         if (location_changed != AVERROR(ETIMEDOUT))
323             goto fail;
324         reconnect_delay = 1 + 2 * reconnect_delay;
325
326         /* restore the offset (http_connect resets it) */
327         s->off = off;
328
329         ffurl_closep(&s->hd);
330         goto redo;
331     }
332
333     attempts++;
334     if (s->http_code == 401) {
335         if ((cur_auth_type == HTTP_AUTH_NONE || s->auth_state.stale) &&
336             s->auth_state.auth_type != HTTP_AUTH_NONE && attempts < 4) {
337             ffurl_closep(&s->hd);
338             goto redo;
339         } else
340             goto fail;
341     }
342     if (s->http_code == 407) {
343         if ((cur_proxy_auth_type == HTTP_AUTH_NONE || s->proxy_auth_state.stale) &&
344             s->proxy_auth_state.auth_type != HTTP_AUTH_NONE && attempts < 4) {
345             ffurl_closep(&s->hd);
346             goto redo;
347         } else
348             goto fail;
349     }
350     if ((s->http_code == 301 || s->http_code == 302 ||
351          s->http_code == 303 || s->http_code == 307 || s->http_code == 308) &&
352         location_changed == 1) {
353         /* url moved, get next */
354         ffurl_closep(&s->hd);
355         if (redirects++ >= MAX_REDIRECTS)
356             return AVERROR(EIO);
357         /* Restart the authentication process with the new target, which
358          * might use a different auth mechanism. */
359         memset(&s->auth_state, 0, sizeof(s->auth_state));
360         attempts         = 0;
361         location_changed = 0;
362         goto redo;
363     }
364     return 0;
365
366 fail:
367     if (s->hd)
368         ffurl_closep(&s->hd);
369     if (location_changed < 0)
370         return location_changed;
371     return ff_http_averror(s->http_code, AVERROR(EIO));
372 }
373 int ff_http_get_shutdown_status(URLContext *h)
374 {
375     int ret = 0;
376     HTTPContext *s = h->priv_data;
377
378     /* flush the receive buffer when it is write only mode */
379     char buf[1024];
380     int read_ret;
381     read_ret = ffurl_read(s->hd, buf, sizeof(buf));
382     if (read_ret < 0) {
383         ret = read_ret;
384     }
385
386     return ret;
387 }
388
389 int ff_http_do_new_request(URLContext *h, const char *uri) {
390     return ff_http_do_new_request2(h, uri, NULL);
391 }
392
393 int ff_http_do_new_request2(URLContext *h, const char *uri, AVDictionary **opts)
394 {
395     HTTPContext *s = h->priv_data;
396     AVDictionary *options = NULL;
397     int ret;
398     char hostname1[1024], hostname2[1024], proto1[10], proto2[10];
399     int port1, port2;
400
401     if (!h->prot ||
402         !(!strcmp(h->prot->name, "http") ||
403           !strcmp(h->prot->name, "https")))
404         return AVERROR(EINVAL);
405
406     av_url_split(proto1, sizeof(proto1), NULL, 0,
407                  hostname1, sizeof(hostname1), &port1,
408                  NULL, 0, s->location);
409     av_url_split(proto2, sizeof(proto2), NULL, 0,
410                  hostname2, sizeof(hostname2), &port2,
411                  NULL, 0, uri);
412     if (port1 != port2 || strncmp(hostname1, hostname2, sizeof(hostname2)) != 0) {
413         av_log(h, AV_LOG_ERROR, "Cannot reuse HTTP connection for different host: %s:%d != %s:%d\n",
414             hostname1, port1,
415             hostname2, port2
416         );
417         return AVERROR(EINVAL);
418     }
419
420     if (!s->end_chunked_post) {
421         ret = http_shutdown(h, h->flags);
422         if (ret < 0)
423             return ret;
424     }
425
426     if (s->willclose)
427         return AVERROR_EOF;
428
429     s->end_chunked_post = 0;
430     s->chunkend      = 0;
431     s->off           = 0;
432     s->icy_data_read = 0;
433     av_free(s->location);
434     s->location = av_strdup(uri);
435     if (!s->location)
436         return AVERROR(ENOMEM);
437
438     if ((ret = av_opt_set_dict(s, opts)) < 0)
439         return ret;
440
441     av_log(s, AV_LOG_INFO, "Opening \'%s\' for %s\n", uri, h->flags & AVIO_FLAG_WRITE ? "writing" : "reading");
442     ret = http_open_cnx(h, &options);
443     av_dict_free(&options);
444     return ret;
445 }
446
447 int ff_http_averror(int status_code, int default_averror)
448 {
449     switch (status_code) {
450         case 400: return AVERROR_HTTP_BAD_REQUEST;
451         case 401: return AVERROR_HTTP_UNAUTHORIZED;
452         case 403: return AVERROR_HTTP_FORBIDDEN;
453         case 404: return AVERROR_HTTP_NOT_FOUND;
454         default: break;
455     }
456     if (status_code >= 400 && status_code <= 499)
457         return AVERROR_HTTP_OTHER_4XX;
458     else if (status_code >= 500)
459         return AVERROR_HTTP_SERVER_ERROR;
460     else
461         return default_averror;
462 }
463
464 static int http_write_reply(URLContext* h, int status_code)
465 {
466     int ret, body = 0, reply_code, message_len;
467     const char *reply_text, *content_type;
468     HTTPContext *s = h->priv_data;
469     char message[BUFFER_SIZE];
470     content_type = "text/plain";
471
472     if (status_code < 0)
473         body = 1;
474     switch (status_code) {
475     case AVERROR_HTTP_BAD_REQUEST:
476     case 400:
477         reply_code = 400;
478         reply_text = "Bad Request";
479         break;
480     case AVERROR_HTTP_FORBIDDEN:
481     case 403:
482         reply_code = 403;
483         reply_text = "Forbidden";
484         break;
485     case AVERROR_HTTP_NOT_FOUND:
486     case 404:
487         reply_code = 404;
488         reply_text = "Not Found";
489         break;
490     case 200:
491         reply_code = 200;
492         reply_text = "OK";
493         content_type = s->content_type ? s->content_type : "application/octet-stream";
494         break;
495     case AVERROR_HTTP_SERVER_ERROR:
496     case 500:
497         reply_code = 500;
498         reply_text = "Internal server error";
499         break;
500     default:
501         return AVERROR(EINVAL);
502     }
503     if (h->flags & AVIO_FLAG_METACUBE) {
504         s->chunked_post = 0;
505         message_len = snprintf(message, sizeof(message),
506                  "HTTP/1.1 %03d %s\r\n"
507                  "Content-Type: %s\r\n"
508                  "Content-Encoding: metacube\r\n"
509                  "%s"
510                  "\r\n",
511                  reply_code,
512                  reply_text,
513                  content_type,
514                  s->headers ? s->headers : "");
515     } else if (body) {
516         s->chunked_post = 0;
517         message_len = snprintf(message, sizeof(message),
518                  "HTTP/1.1 %03d %s\r\n"
519                  "Content-Type: %s\r\n"
520                  "Content-Length: %"SIZE_SPECIFIER"\r\n"
521                  "%s"
522                  "\r\n"
523                  "%03d %s\r\n",
524                  reply_code,
525                  reply_text,
526                  content_type,
527                  strlen(reply_text) + 6, // 3 digit status code + space + \r\n
528                  s->headers ? s->headers : "",
529                  reply_code,
530                  reply_text);
531     } else {
532         s->chunked_post = 1;
533         message_len = snprintf(message, sizeof(message),
534                  "HTTP/1.1 %03d %s\r\n"
535                  "Content-Type: %s\r\n"
536                  "Transfer-Encoding: chunked\r\n"
537                  "%s"
538                  "\r\n",
539                  reply_code,
540                  reply_text,
541                  content_type,
542                  s->headers ? s->headers : "");
543     }
544     av_log(h, AV_LOG_TRACE, "HTTP reply header: \n%s----\n", message);
545     if ((ret = ffurl_write(s->hd, message, message_len)) < 0)
546         return ret;
547     return 0;
548 }
549
550 static void handle_http_errors(URLContext *h, int error)
551 {
552     av_assert0(error < 0);
553     http_write_reply(h, error);
554 }
555
556 static int http_handshake(URLContext *c)
557 {
558     int ret, err, new_location;
559     HTTPContext *ch = c->priv_data;
560     URLContext *cl = ch->hd;
561     switch (ch->handshake_step) {
562     case LOWER_PROTO:
563         av_log(c, AV_LOG_TRACE, "Lower protocol\n");
564         if ((ret = ffurl_handshake(cl)) > 0)
565             return 2 + ret;
566         if (ret < 0)
567             return ret;
568         ch->handshake_step = READ_HEADERS;
569         ch->is_connected_server = 1;
570         return 2;
571     case READ_HEADERS:
572         av_log(c, AV_LOG_TRACE, "Read headers\n");
573         if ((err = http_read_header(c, &new_location)) < 0) {
574             handle_http_errors(c, err);
575             return err;
576         }
577         ch->handshake_step = WRITE_REPLY_HEADERS;
578         return 1;
579     case WRITE_REPLY_HEADERS:
580         av_log(c, AV_LOG_TRACE, "Reply code: %d\n", ch->reply_code);
581         if ((err = http_write_reply(c, ch->reply_code)) < 0)
582             return err;
583         ch->handshake_step = FINISH;
584         return 1;
585     case FINISH:
586         return 0;
587     }
588     // this should never be reached.
589     return AVERROR(EINVAL);
590 }
591
592 static int http_listen(URLContext *h, const char *uri, int flags,
593                        AVDictionary **options) {
594     HTTPContext *s = h->priv_data;
595     int ret;
596     char hostname[1024], proto[10];
597     char lower_url[100];
598     const char *lower_proto = "tcp";
599     int port;
600     av_url_split(proto, sizeof(proto), NULL, 0, hostname, sizeof(hostname), &port,
601                  NULL, 0, uri);
602     if (!strcmp(proto, "https"))
603         lower_proto = "tls";
604     ff_url_join(lower_url, sizeof(lower_url), lower_proto, NULL, hostname, port,
605                 NULL);
606     if ((ret = av_dict_set_int(options, "listen", s->listen, 0)) < 0)
607         goto fail;
608     if ((ret = ffurl_open_whitelist(&s->hd, lower_url, AVIO_FLAG_READ_WRITE,
609                                     &h->interrupt_callback, options,
610                                     h->protocol_whitelist, h->protocol_blacklist, h
611                                    )) < 0)
612         goto fail;
613     s->handshake_step = LOWER_PROTO;
614     if (s->listen == HTTP_SINGLE) { /* single client */
615         s->reply_code = 200;
616         while ((ret = http_handshake(h)) > 0);
617     }
618 fail:
619     av_dict_free(&s->chained_options);
620     return ret;
621 }
622
623 static int http_open(URLContext *h, const char *uri, int flags,
624                      AVDictionary **options)
625 {
626     HTTPContext *s = h->priv_data;
627     int ret;
628
629     if( s->seekable == 1 )
630         h->is_streamed = 0;
631     else
632         h->is_streamed = 1;
633
634     s->filesize = UINT64_MAX;
635     s->location = av_strdup(uri);
636     if (!s->location)
637         return AVERROR(ENOMEM);
638     if (options)
639         av_dict_copy(&s->chained_options, *options, 0);
640
641     if (s->headers) {
642         int len = strlen(s->headers);
643         if (len < 2 || strcmp("\r\n", s->headers + len - 2)) {
644             av_log(h, AV_LOG_WARNING,
645                    "No trailing CRLF found in HTTP header. Adding it.\n");
646             ret = av_reallocp(&s->headers, len + 3);
647             if (ret < 0)
648                 goto bail_out;
649             s->headers[len]     = '\r';
650             s->headers[len + 1] = '\n';
651             s->headers[len + 2] = '\0';
652         }
653     }
654
655     if (s->listen) {
656         return http_listen(h, uri, flags, options);
657     }
658     ret = http_open_cnx(h, options);
659 bail_out:
660     if (ret < 0)
661         av_dict_free(&s->chained_options);
662     return ret;
663 }
664
665 static int http_accept(URLContext *s, URLContext **c)
666 {
667     int ret;
668     HTTPContext *sc = s->priv_data;
669     HTTPContext *cc;
670     URLContext *sl = sc->hd;
671     URLContext *cl = NULL;
672
673     av_assert0(sc->listen);
674     if ((ret = ffurl_alloc(c, s->filename, s->flags, &sl->interrupt_callback)) < 0)
675         goto fail;
676     cc = (*c)->priv_data;
677     if ((ret = ffurl_accept(sl, &cl)) < 0)
678         goto fail;
679     cc->hd = cl;
680     cc->is_multi_client = 1;
681     return 0;
682 fail:
683     if (c) {
684         ffurl_closep(c);
685     }
686     return ret;
687 }
688
689 static int http_getc(HTTPContext *s)
690 {
691     int len;
692     if (s->buf_ptr >= s->buf_end) {
693         len = ffurl_read(s->hd, s->buffer, BUFFER_SIZE);
694         if (len < 0) {
695             return len;
696         } else if (len == 0) {
697             return AVERROR_EOF;
698         } else {
699             s->buf_ptr = s->buffer;
700             s->buf_end = s->buffer + len;
701         }
702     }
703     return *s->buf_ptr++;
704 }
705
706 static int http_get_line(HTTPContext *s, char *line, int line_size)
707 {
708     int ch;
709     char *q;
710
711     q = line;
712     for (;;) {
713         ch = http_getc(s);
714         if (ch < 0)
715             return ch;
716         if (ch == '\n') {
717             /* process line */
718             if (q > line && q[-1] == '\r')
719                 q--;
720             *q = '\0';
721
722             return 0;
723         } else {
724             if ((q - line) < line_size - 1)
725                 *q++ = ch;
726         }
727     }
728 }
729
730 static int check_http_code(URLContext *h, int http_code, const char *end)
731 {
732     HTTPContext *s = h->priv_data;
733     /* error codes are 4xx and 5xx, but regard 401 as a success, so we
734      * don't abort until all headers have been parsed. */
735     if (http_code >= 400 && http_code < 600 &&
736         (http_code != 401 || s->auth_state.auth_type != HTTP_AUTH_NONE) &&
737         (http_code != 407 || s->proxy_auth_state.auth_type != HTTP_AUTH_NONE)) {
738         end += strspn(end, SPACE_CHARS);
739         av_log(h, AV_LOG_WARNING, "HTTP error %d %s\n", http_code, end);
740         return ff_http_averror(http_code, AVERROR(EIO));
741     }
742     return 0;
743 }
744
745 static int parse_location(HTTPContext *s, const char *p)
746 {
747     char redirected_location[MAX_URL_SIZE], *new_loc;
748     ff_make_absolute_url(redirected_location, sizeof(redirected_location),
749                          s->location, p);
750     new_loc = av_strdup(redirected_location);
751     if (!new_loc)
752         return AVERROR(ENOMEM);
753     av_free(s->location);
754     s->location = new_loc;
755     return 0;
756 }
757
758 /* "bytes $from-$to/$document_size" */
759 static void parse_content_range(URLContext *h, const char *p)
760 {
761     HTTPContext *s = h->priv_data;
762     const char *slash;
763
764     if (!strncmp(p, "bytes ", 6)) {
765         p     += 6;
766         s->off = strtoull(p, NULL, 10);
767         if ((slash = strchr(p, '/')) && strlen(slash) > 0)
768             s->filesize = strtoull(slash + 1, NULL, 10);
769     }
770     if (s->seekable == -1 && (!s->is_akamai || s->filesize != 2147483647))
771         h->is_streamed = 0; /* we _can_ in fact seek */
772 }
773
774 static int parse_content_encoding(URLContext *h, const char *p)
775 {
776     if (!av_strncasecmp(p, "gzip", 4) ||
777         !av_strncasecmp(p, "deflate", 7)) {
778 #if CONFIG_ZLIB
779         HTTPContext *s = h->priv_data;
780
781         s->compressed = 1;
782         inflateEnd(&s->inflate_stream);
783         if (inflateInit2(&s->inflate_stream, 32 + 15) != Z_OK) {
784             av_log(h, AV_LOG_WARNING, "Error during zlib initialisation: %s\n",
785                    s->inflate_stream.msg);
786             return AVERROR(ENOSYS);
787         }
788         if (zlibCompileFlags() & (1 << 17)) {
789             av_log(h, AV_LOG_WARNING,
790                    "Your zlib was compiled without gzip support.\n");
791             return AVERROR(ENOSYS);
792         }
793 #else
794         av_log(h, AV_LOG_WARNING,
795                "Compressed (%s) content, need zlib with gzip support\n", p);
796         return AVERROR(ENOSYS);
797 #endif /* CONFIG_ZLIB */
798     } else if (!av_strncasecmp(p, "identity", 8)) {
799         // The normal, no-encoding case (although servers shouldn't include
800         // the header at all if this is the case).
801     } else {
802         av_log(h, AV_LOG_WARNING, "Unknown content coding: %s\n", p);
803     }
804     return 0;
805 }
806
807 // Concat all Icy- header lines
808 static int parse_icy(HTTPContext *s, const char *tag, const char *p)
809 {
810     int len = 4 + strlen(p) + strlen(tag);
811     int is_first = !s->icy_metadata_headers;
812     int ret;
813
814     av_dict_set(&s->metadata, tag, p, 0);
815
816     if (s->icy_metadata_headers)
817         len += strlen(s->icy_metadata_headers);
818
819     if ((ret = av_reallocp(&s->icy_metadata_headers, len)) < 0)
820         return ret;
821
822     if (is_first)
823         *s->icy_metadata_headers = '\0';
824
825     av_strlcatf(s->icy_metadata_headers, len, "%s: %s\n", tag, p);
826
827     return 0;
828 }
829
830 static int parse_set_cookie_expiry_time(const char *exp_str, struct tm *buf)
831 {
832     char exp_buf[MAX_EXPIRY];
833     int i, j, exp_buf_len = MAX_EXPIRY-1;
834     char *expiry;
835
836     // strip off any punctuation or whitespace
837     for (i = 0, j = 0; exp_str[i] != '\0' && j < exp_buf_len; i++) {
838         if ((exp_str[i] >= '0' && exp_str[i] <= '9') ||
839             (exp_str[i] >= 'A' && exp_str[i] <= 'Z') ||
840             (exp_str[i] >= 'a' && exp_str[i] <= 'z')) {
841             exp_buf[j] = exp_str[i];
842             j++;
843         }
844     }
845     exp_buf[j] = '\0';
846     expiry = exp_buf;
847
848     // move the string beyond the day of week
849     while ((*expiry < '0' || *expiry > '9') && *expiry != '\0')
850         expiry++;
851
852     return av_small_strptime(expiry, "%d%b%Y%H%M%S", buf) ? 0 : AVERROR(EINVAL);
853 }
854
855 static int parse_set_cookie(const char *set_cookie, AVDictionary **dict)
856 {
857     char *param, *next_param, *cstr, *back;
858     char *saveptr = NULL;
859
860     if (!set_cookie[0])
861         return 0;
862
863     if (!(cstr = av_strdup(set_cookie)))
864         return AVERROR(EINVAL);
865
866     // strip any trailing whitespace
867     back = &cstr[strlen(cstr)-1];
868     while (strchr(WHITESPACES, *back)) {
869         *back='\0';
870         if (back == cstr)
871             break;
872         back--;
873     }
874
875     next_param = cstr;
876     while ((param = av_strtok(next_param, ";", &saveptr))) {
877         char *name, *value;
878         next_param = NULL;
879         param += strspn(param, WHITESPACES);
880         if ((name = av_strtok(param, "=", &value))) {
881             if (av_dict_set(dict, name, value, 0) < 0) {
882                 av_free(cstr);
883                 return -1;
884             }
885         }
886     }
887
888     av_free(cstr);
889     return 0;
890 }
891
892 static int parse_cookie(HTTPContext *s, const char *p, AVDictionary **cookies)
893 {
894     AVDictionary *new_params = NULL;
895     AVDictionaryEntry *e, *cookie_entry;
896     char *eql, *name;
897
898     // ensure the cookie is parsable
899     if (parse_set_cookie(p, &new_params))
900         return -1;
901
902     // if there is no cookie value there is nothing to parse
903     cookie_entry = av_dict_get(new_params, "", NULL, AV_DICT_IGNORE_SUFFIX);
904     if (!cookie_entry || !cookie_entry->value) {
905         av_dict_free(&new_params);
906         return -1;
907     }
908
909     // ensure the cookie is not expired or older than an existing value
910     if ((e = av_dict_get(new_params, "expires", NULL, 0)) && e->value) {
911         struct tm new_tm = {0};
912         if (!parse_set_cookie_expiry_time(e->value, &new_tm)) {
913             AVDictionaryEntry *e2;
914
915             // if the cookie has already expired ignore it
916             if (av_timegm(&new_tm) < av_gettime() / 1000000) {
917                 av_dict_free(&new_params);
918                 return 0;
919             }
920
921             // only replace an older cookie with the same name
922             e2 = av_dict_get(*cookies, cookie_entry->key, NULL, 0);
923             if (e2 && e2->value) {
924                 AVDictionary *old_params = NULL;
925                 if (!parse_set_cookie(p, &old_params)) {
926                     e2 = av_dict_get(old_params, "expires", NULL, 0);
927                     if (e2 && e2->value) {
928                         struct tm old_tm = {0};
929                         if (!parse_set_cookie_expiry_time(e->value, &old_tm)) {
930                             if (av_timegm(&new_tm) < av_timegm(&old_tm)) {
931                                 av_dict_free(&new_params);
932                                 av_dict_free(&old_params);
933                                 return -1;
934                             }
935                         }
936                     }
937                 }
938                 av_dict_free(&old_params);
939             }
940         }
941     }
942     av_dict_free(&new_params);
943
944     // duplicate the cookie name (dict will dupe the value)
945     if (!(eql = strchr(p, '='))) return AVERROR(EINVAL);
946     if (!(name = av_strndup(p, eql - p))) return AVERROR(ENOMEM);
947
948     // add the cookie to the dictionary
949     av_dict_set(cookies, name, eql, AV_DICT_DONT_STRDUP_KEY);
950
951     return 0;
952 }
953
954 static int cookie_string(AVDictionary *dict, char **cookies)
955 {
956     AVDictionaryEntry *e = NULL;
957     int len = 1;
958
959     // determine how much memory is needed for the cookies string
960     while (e = av_dict_get(dict, "", e, AV_DICT_IGNORE_SUFFIX))
961         len += strlen(e->key) + strlen(e->value) + 1;
962
963     // reallocate the cookies
964     e = NULL;
965     if (*cookies) av_free(*cookies);
966     *cookies = av_malloc(len);
967     if (!*cookies) return AVERROR(ENOMEM);
968     *cookies[0] = '\0';
969
970     // write out the cookies
971     while (e = av_dict_get(dict, "", e, AV_DICT_IGNORE_SUFFIX))
972         av_strlcatf(*cookies, len, "%s%s\n", e->key, e->value);
973
974     return 0;
975 }
976
977 static int process_line(URLContext *h, char *line, int line_count,
978                         int *new_location)
979 {
980     HTTPContext *s = h->priv_data;
981     const char *auto_method =  h->flags & AVIO_FLAG_READ ? "POST" : "GET";
982     char *tag, *p, *end, *method, *resource, *version;
983     int ret;
984
985     /* end of header */
986     if (line[0] == '\0') {
987         s->end_header = 1;
988         return 0;
989     }
990
991     p = line;
992     if (line_count == 0) {
993         if (s->is_connected_server) {
994             // HTTP method
995             method = p;
996             while (*p && !av_isspace(*p))
997                 p++;
998             *(p++) = '\0';
999             av_log(h, AV_LOG_TRACE, "Received method: %s\n", method);
1000             if (s->method) {
1001                 if (av_strcasecmp(s->method, method)) {
1002                     av_log(h, AV_LOG_ERROR, "Received and expected HTTP method do not match. (%s expected, %s received)\n",
1003                            s->method, method);
1004                     return ff_http_averror(400, AVERROR(EIO));
1005                 }
1006             } else {
1007                 // use autodetected HTTP method to expect
1008                 av_log(h, AV_LOG_TRACE, "Autodetected %s HTTP method\n", auto_method);
1009                 if (av_strcasecmp(auto_method, method)) {
1010                     av_log(h, AV_LOG_ERROR, "Received and autodetected HTTP method did not match "
1011                            "(%s autodetected %s received)\n", auto_method, method);
1012                     return ff_http_averror(400, AVERROR(EIO));
1013                 }
1014                 if (!(s->method = av_strdup(method)))
1015                     return AVERROR(ENOMEM);
1016             }
1017
1018             // HTTP resource
1019             while (av_isspace(*p))
1020                 p++;
1021             resource = p;
1022             while (*p && !av_isspace(*p))
1023                 p++;
1024             *(p++) = '\0';
1025             av_log(h, AV_LOG_TRACE, "Requested resource: %s\n", resource);
1026             if (!(s->resource = av_strdup(resource)))
1027                 return AVERROR(ENOMEM);
1028
1029             // HTTP version
1030             while (av_isspace(*p))
1031                 p++;
1032             version = p;
1033             while (*p && !av_isspace(*p))
1034                 p++;
1035             *p = '\0';
1036             if (av_strncasecmp(version, "HTTP/", 5)) {
1037                 av_log(h, AV_LOG_ERROR, "Malformed HTTP version string.\n");
1038                 return ff_http_averror(400, AVERROR(EIO));
1039             }
1040             av_log(h, AV_LOG_TRACE, "HTTP version string: %s\n", version);
1041         } else {
1042             if (av_strncasecmp(p, "HTTP/1.0", 8) == 0)
1043                 s->willclose = 1;
1044             while (*p != '/' && *p != '\0')
1045                 p++;
1046             while (*p == '/')
1047                 p++;
1048             av_freep(&s->http_version);
1049             s->http_version = av_strndup(p, 3);
1050             while (!av_isspace(*p) && *p != '\0')
1051                 p++;
1052             while (av_isspace(*p))
1053                 p++;
1054             s->http_code = strtol(p, &end, 10);
1055
1056             av_log(h, AV_LOG_TRACE, "http_code=%d\n", s->http_code);
1057
1058             if ((ret = check_http_code(h, s->http_code, end)) < 0)
1059                 return ret;
1060         }
1061     } else {
1062         while (*p != '\0' && *p != ':')
1063             p++;
1064         if (*p != ':')
1065             return 1;
1066
1067         *p  = '\0';
1068         tag = line;
1069         p++;
1070         while (av_isspace(*p))
1071             p++;
1072         if (!av_strcasecmp(tag, "Location")) {
1073             if ((ret = parse_location(s, p)) < 0)
1074                 return ret;
1075             *new_location = 1;
1076         } else if (!av_strcasecmp(tag, "Content-Length") &&
1077                    s->filesize == UINT64_MAX) {
1078             s->filesize = strtoull(p, NULL, 10);
1079         } else if (!av_strcasecmp(tag, "Content-Range")) {
1080             parse_content_range(h, p);
1081         } else if (!av_strcasecmp(tag, "Accept-Ranges") &&
1082                    !strncmp(p, "bytes", 5) &&
1083                    s->seekable == -1) {
1084             h->is_streamed = 0;
1085         } else if (!av_strcasecmp(tag, "Transfer-Encoding") &&
1086                    !av_strncasecmp(p, "chunked", 7)) {
1087             s->filesize  = UINT64_MAX;
1088             s->chunksize = 0;
1089         } else if (!av_strcasecmp(tag, "WWW-Authenticate")) {
1090             ff_http_auth_handle_header(&s->auth_state, tag, p);
1091         } else if (!av_strcasecmp(tag, "Authentication-Info")) {
1092             ff_http_auth_handle_header(&s->auth_state, tag, p);
1093         } else if (!av_strcasecmp(tag, "Proxy-Authenticate")) {
1094             ff_http_auth_handle_header(&s->proxy_auth_state, tag, p);
1095         } else if (!av_strcasecmp(tag, "Connection")) {
1096             if (!strcmp(p, "close"))
1097                 s->willclose = 1;
1098         } else if (!av_strcasecmp(tag, "Server")) {
1099             if (!av_strcasecmp(p, "AkamaiGHost")) {
1100                 s->is_akamai = 1;
1101             } else if (!av_strncasecmp(p, "MediaGateway", 12)) {
1102                 s->is_mediagateway = 1;
1103             }
1104         } else if (!av_strcasecmp(tag, "Content-Type")) {
1105             av_free(s->mime_type);
1106             s->mime_type = av_strdup(p);
1107         } else if (!av_strcasecmp(tag, "Set-Cookie")) {
1108             if (parse_cookie(s, p, &s->cookie_dict))
1109                 av_log(h, AV_LOG_WARNING, "Unable to parse '%s'\n", p);
1110         } else if (!av_strcasecmp(tag, "Icy-MetaInt")) {
1111             s->icy_metaint = strtoull(p, NULL, 10);
1112         } else if (!av_strncasecmp(tag, "Icy-", 4)) {
1113             if ((ret = parse_icy(s, tag, p)) < 0)
1114                 return ret;
1115         } else if (!av_strcasecmp(tag, "Content-Encoding")) {
1116             if ((ret = parse_content_encoding(h, p)) < 0)
1117                 return ret;
1118         }
1119     }
1120     return 1;
1121 }
1122
1123 /**
1124  * Create a string containing cookie values for use as a HTTP cookie header
1125  * field value for a particular path and domain from the cookie values stored in
1126  * the HTTP protocol context. The cookie string is stored in *cookies, and may
1127  * be NULL if there are no valid cookies.
1128  *
1129  * @return a negative value if an error condition occurred, 0 otherwise
1130  */
1131 static int get_cookies(HTTPContext *s, char **cookies, const char *path,
1132                        const char *domain)
1133 {
1134     // cookie strings will look like Set-Cookie header field values.  Multiple
1135     // Set-Cookie fields will result in multiple values delimited by a newline
1136     int ret = 0;
1137     char *cookie, *set_cookies, *next;
1138     char *saveptr = NULL;
1139
1140     // destroy any cookies in the dictionary.
1141     av_dict_free(&s->cookie_dict);
1142
1143     if (!s->cookies)
1144         return 0;
1145
1146     next = set_cookies = av_strdup(s->cookies);
1147     if (!next)
1148         return AVERROR(ENOMEM);
1149
1150     *cookies = NULL;
1151     while ((cookie = av_strtok(next, "\n", &saveptr)) && !ret) {
1152         AVDictionary *cookie_params = NULL;
1153         AVDictionaryEntry *cookie_entry, *e;
1154
1155         next = NULL;
1156         // store the cookie in a dict in case it is updated in the response
1157         if (parse_cookie(s, cookie, &s->cookie_dict))
1158             av_log(s, AV_LOG_WARNING, "Unable to parse '%s'\n", cookie);
1159
1160         // continue on to the next cookie if this one cannot be parsed
1161         if (parse_set_cookie(cookie, &cookie_params))
1162             goto skip_cookie;
1163
1164         // if the cookie has no value, skip it
1165         cookie_entry = av_dict_get(cookie_params, "", NULL, AV_DICT_IGNORE_SUFFIX);
1166         if (!cookie_entry || !cookie_entry->value)
1167             goto skip_cookie;
1168
1169         // if the cookie has expired, don't add it
1170         if ((e = av_dict_get(cookie_params, "expires", NULL, 0)) && e->value) {
1171             struct tm tm_buf = {0};
1172             if (!parse_set_cookie_expiry_time(e->value, &tm_buf)) {
1173                 if (av_timegm(&tm_buf) < av_gettime() / 1000000)
1174                     goto skip_cookie;
1175             }
1176         }
1177
1178         // if no domain in the cookie assume it appied to this request
1179         if ((e = av_dict_get(cookie_params, "domain", NULL, 0)) && e->value) {
1180             // find the offset comparison is on the min domain (b.com, not a.b.com)
1181             int domain_offset = strlen(domain) - strlen(e->value);
1182             if (domain_offset < 0)
1183                 goto skip_cookie;
1184
1185             // match the cookie domain
1186             if (av_strcasecmp(&domain[domain_offset], e->value))
1187                 goto skip_cookie;
1188         }
1189
1190         // ensure this cookie matches the path
1191         e = av_dict_get(cookie_params, "path", NULL, 0);
1192         if (!e || av_strncasecmp(path, e->value, strlen(e->value)))
1193             goto skip_cookie;
1194
1195         // cookie parameters match, so copy the value
1196         if (!*cookies) {
1197             *cookies = av_asprintf("%s=%s", cookie_entry->key, cookie_entry->value);
1198         } else {
1199             char *tmp = *cookies;
1200             *cookies = av_asprintf("%s; %s=%s", tmp, cookie_entry->key, cookie_entry->value);
1201             av_free(tmp);
1202         }
1203         if (!*cookies)
1204             ret = AVERROR(ENOMEM);
1205
1206     skip_cookie:
1207         av_dict_free(&cookie_params);
1208     }
1209
1210     av_free(set_cookies);
1211
1212     return ret;
1213 }
1214
1215 static inline int has_header(const char *str, const char *header)
1216 {
1217     /* header + 2 to skip over CRLF prefix. (make sure you have one!) */
1218     if (!str)
1219         return 0;
1220     return av_stristart(str, header + 2, NULL) || av_stristr(str, header);
1221 }
1222
1223 static int http_read_header(URLContext *h, int *new_location)
1224 {
1225     HTTPContext *s = h->priv_data;
1226     char line[MAX_URL_SIZE];
1227     int err = 0;
1228
1229     s->chunksize = UINT64_MAX;
1230
1231     for (;;) {
1232         if ((err = http_get_line(s, line, sizeof(line))) < 0)
1233             return err;
1234
1235         av_log(h, AV_LOG_TRACE, "header='%s'\n", line);
1236
1237         err = process_line(h, line, s->line_count, new_location);
1238         if (err < 0)
1239             return err;
1240         if (err == 0)
1241             break;
1242         s->line_count++;
1243     }
1244
1245     if (s->seekable == -1 && s->is_mediagateway && s->filesize == 2000000000)
1246         h->is_streamed = 1; /* we can in fact _not_ seek */
1247
1248     // add any new cookies into the existing cookie string
1249     cookie_string(s->cookie_dict, &s->cookies);
1250     av_dict_free(&s->cookie_dict);
1251
1252     return err;
1253 }
1254
1255 /**
1256  * Escape unsafe characters in path in order to pass them safely to the HTTP
1257  * request. Insipred by the algorithm in GNU wget:
1258  * - escape "%" characters not followed by two hex digits
1259  * - escape all "unsafe" characters except which are also "reserved"
1260  * - pass through everything else
1261  */
1262 static void bprint_escaped_path(AVBPrint *bp, const char *path)
1263 {
1264 #define NEEDS_ESCAPE(ch) \
1265     ((ch) <= ' ' || (ch) >= '\x7f' || \
1266      (ch) == '"' || (ch) == '%' || (ch) == '<' || (ch) == '>' || (ch) == '\\' || \
1267      (ch) == '^' || (ch) == '`' || (ch) == '{' || (ch) == '}' || (ch) == '|')
1268     while (*path) {
1269         char buf[1024];
1270         char *q = buf;
1271         while (*path && q - buf < sizeof(buf) - 4) {
1272             if (path[0] == '%' && av_isxdigit(path[1]) && av_isxdigit(path[2])) {
1273                 *q++ = *path++;
1274                 *q++ = *path++;
1275                 *q++ = *path++;
1276             } else if (NEEDS_ESCAPE(*path)) {
1277                 q += snprintf(q, 4, "%%%02X", (uint8_t)*path++);
1278             } else {
1279                 *q++ = *path++;
1280             }
1281         }
1282         av_bprint_append_data(bp, buf, q - buf);
1283     }
1284 }
1285
1286 static int http_connect(URLContext *h, const char *path, const char *local_path,
1287                         const char *hoststr, const char *auth,
1288                         const char *proxyauth, int *new_location)
1289 {
1290     HTTPContext *s = h->priv_data;
1291     int post, err;
1292     AVBPrint request;
1293     char *authstr = NULL, *proxyauthstr = NULL;
1294     uint64_t off = s->off;
1295     const char *method;
1296     int send_expect_100 = 0;
1297
1298     av_bprint_init_for_buffer(&request, s->buffer, sizeof(s->buffer));
1299
1300     /* send http header */
1301     post = h->flags & AVIO_FLAG_WRITE;
1302
1303     if (s->post_data) {
1304         /* force POST method and disable chunked encoding when
1305          * custom HTTP post data is set */
1306         post            = 1;
1307         s->chunked_post = 0;
1308     }
1309
1310     if (s->method)
1311         method = s->method;
1312     else
1313         method = post ? "POST" : "GET";
1314
1315     authstr      = ff_http_auth_create_response(&s->auth_state, auth,
1316                                                 local_path, method);
1317     proxyauthstr = ff_http_auth_create_response(&s->proxy_auth_state, proxyauth,
1318                                                 local_path, method);
1319
1320      if (post && !s->post_data) {
1321         if (s->send_expect_100 != -1) {
1322             send_expect_100 = s->send_expect_100;
1323         } else {
1324             send_expect_100 = 0;
1325             /* The user has supplied authentication but we don't know the auth type,
1326              * send Expect: 100-continue to get the 401 response including the
1327              * WWW-Authenticate header, or an 100 continue if no auth actually
1328              * is needed. */
1329             if (auth && *auth &&
1330                 s->auth_state.auth_type == HTTP_AUTH_NONE &&
1331                 s->http_code != 401)
1332                 send_expect_100 = 1;
1333         }
1334     }
1335
1336     av_bprintf(&request, "%s ", method);
1337     bprint_escaped_path(&request, path);
1338     av_bprintf(&request, " HTTP/1.1\r\n");
1339
1340     if (post && s->chunked_post)
1341         av_bprintf(&request, "Transfer-Encoding: chunked\r\n");
1342     /* set default headers if needed */
1343     if (!has_header(s->headers, "\r\nUser-Agent: "))
1344         av_bprintf(&request, "User-Agent: %s\r\n", s->user_agent);
1345     if (s->referer) {
1346         /* set default headers if needed */
1347         if (!has_header(s->headers, "\r\nReferer: "))
1348             av_bprintf(&request, "Referer: %s\r\n", s->referer);
1349     }
1350     if (!has_header(s->headers, "\r\nAccept: "))
1351         av_bprintf(&request, "Accept: */*\r\n");
1352     // Note: we send this on purpose even when s->off is 0 when we're probing,
1353     // since it allows us to detect more reliably if a (non-conforming)
1354     // server supports seeking by analysing the reply headers.
1355     if (!has_header(s->headers, "\r\nRange: ") && !post && (s->off > 0 || s->end_off || s->seekable == -1)) {
1356         av_bprintf(&request, "Range: bytes=%"PRIu64"-", s->off);
1357         if (s->end_off)
1358             av_bprintf(&request, "%"PRId64, s->end_off - 1);
1359         av_bprintf(&request, "\r\n");
1360     }
1361     if (send_expect_100 && !has_header(s->headers, "\r\nExpect: "))
1362         av_bprintf(&request, "Expect: 100-continue\r\n");
1363
1364     if (!has_header(s->headers, "\r\nConnection: "))
1365         av_bprintf(&request, "Connection: %s\r\n", s->multiple_requests ? "keep-alive" : "close");
1366
1367     if (!has_header(s->headers, "\r\nHost: "))
1368         av_bprintf(&request, "Host: %s\r\n", hoststr);
1369     if (!has_header(s->headers, "\r\nContent-Length: ") && s->post_data)
1370         av_bprintf(&request, "Content-Length: %d\r\n", s->post_datalen);
1371
1372     if (!has_header(s->headers, "\r\nContent-Type: ") && s->content_type)
1373         av_bprintf(&request, "Content-Type: %s\r\n", s->content_type);
1374     if (!has_header(s->headers, "\r\nCookie: ") && s->cookies) {
1375         char *cookies = NULL;
1376         if (!get_cookies(s, &cookies, path, hoststr) && cookies) {
1377             av_bprintf(&request, "Cookie: %s\r\n", cookies);
1378             av_free(cookies);
1379         }
1380     }
1381     if (!has_header(s->headers, "\r\nIcy-MetaData: ") && s->icy)
1382         av_bprintf(&request, "Icy-MetaData: 1\r\n");
1383
1384     /* now add in custom headers */
1385     if (s->headers)
1386         av_bprintf(&request, "%s", s->headers);
1387
1388     if (authstr)
1389         av_bprintf(&request, "%s", authstr);
1390     if (proxyauthstr)
1391         av_bprintf(&request, "Proxy-%s", proxyauthstr);
1392     av_bprintf(&request, "\r\n");
1393
1394     av_log(h, AV_LOG_DEBUG, "request: %s\n", request.str);
1395
1396     if (!av_bprint_is_complete(&request)) {
1397         av_log(h, AV_LOG_ERROR, "overlong headers\n");
1398         err = AVERROR(EINVAL);
1399         goto done;
1400     }
1401
1402     if ((err = ffurl_write(s->hd, request.str, request.len)) < 0)
1403         goto done;
1404
1405     if (s->post_data)
1406         if ((err = ffurl_write(s->hd, s->post_data, s->post_datalen)) < 0)
1407             goto done;
1408
1409     /* init input buffer */
1410     s->buf_ptr          = s->buffer;
1411     s->buf_end          = s->buffer;
1412     s->line_count       = 0;
1413     s->off              = 0;
1414     s->icy_data_read    = 0;
1415     s->filesize         = UINT64_MAX;
1416     s->willclose        = 0;
1417     s->end_chunked_post = 0;
1418     s->end_header       = 0;
1419 #if CONFIG_ZLIB
1420     s->compressed       = 0;
1421 #endif
1422     if (post && !s->post_data && !send_expect_100) {
1423         /* Pretend that it did work. We didn't read any header yet, since
1424          * we've still to send the POST data, but the code calling this
1425          * function will check http_code after we return. */
1426         s->http_code = 200;
1427         err = 0;
1428         goto done;
1429     }
1430
1431     /* wait for header */
1432     err = http_read_header(h, new_location);
1433     if (err < 0)
1434         goto done;
1435
1436     if (*new_location)
1437         s->off = off;
1438
1439     err = (off == s->off) ? 0 : -1;
1440 done:
1441     av_freep(&authstr);
1442     av_freep(&proxyauthstr);
1443     return err;
1444 }
1445
1446 static int http_buf_read(URLContext *h, uint8_t *buf, int size)
1447 {
1448     HTTPContext *s = h->priv_data;
1449     int len;
1450
1451     if (s->chunksize != UINT64_MAX) {
1452         if (s->chunkend) {
1453             return AVERROR_EOF;
1454         }
1455         if (!s->chunksize) {
1456             char line[32];
1457             int err;
1458
1459             do {
1460                 if ((err = http_get_line(s, line, sizeof(line))) < 0)
1461                     return err;
1462             } while (!*line);    /* skip CR LF from last chunk */
1463
1464             s->chunksize = strtoull(line, NULL, 16);
1465
1466             av_log(h, AV_LOG_TRACE,
1467                    "Chunked encoding data size: %"PRIu64"\n",
1468                     s->chunksize);
1469
1470             if (!s->chunksize && s->multiple_requests) {
1471                 http_get_line(s, line, sizeof(line)); // read empty chunk
1472                 s->chunkend = 1;
1473                 return 0;
1474             }
1475             else if (!s->chunksize) {
1476                 av_log(h, AV_LOG_DEBUG, "Last chunk received, closing conn\n");
1477                 ffurl_closep(&s->hd);
1478                 return 0;
1479             }
1480             else if (s->chunksize == UINT64_MAX) {
1481                 av_log(h, AV_LOG_ERROR, "Invalid chunk size %"PRIu64"\n",
1482                        s->chunksize);
1483                 return AVERROR(EINVAL);
1484             }
1485         }
1486         size = FFMIN(size, s->chunksize);
1487     }
1488
1489     /* read bytes from input buffer first */
1490     len = s->buf_end - s->buf_ptr;
1491     if (len > 0) {
1492         if (len > size)
1493             len = size;
1494         memcpy(buf, s->buf_ptr, len);
1495         s->buf_ptr += len;
1496     } else {
1497         uint64_t target_end = s->end_off ? s->end_off : s->filesize;
1498         if ((!s->willclose || s->chunksize == UINT64_MAX) && s->off >= target_end)
1499             return AVERROR_EOF;
1500         len = ffurl_read(s->hd, buf, size);
1501         if ((!len || len == AVERROR_EOF) &&
1502             (!s->willclose || s->chunksize == UINT64_MAX) && s->off < target_end) {
1503             av_log(h, AV_LOG_ERROR,
1504                    "Stream ends prematurely at %"PRIu64", should be %"PRIu64"\n",
1505                    s->off, target_end
1506                   );
1507             return AVERROR(EIO);
1508         }
1509     }
1510     if (len > 0) {
1511         s->off += len;
1512         if (s->chunksize > 0 && s->chunksize != UINT64_MAX) {
1513             av_assert0(s->chunksize >= len);
1514             s->chunksize -= len;
1515         }
1516     }
1517     return len;
1518 }
1519
1520 #if CONFIG_ZLIB
1521 #define DECOMPRESS_BUF_SIZE (256 * 1024)
1522 static int http_buf_read_compressed(URLContext *h, uint8_t *buf, int size)
1523 {
1524     HTTPContext *s = h->priv_data;
1525     int ret;
1526
1527     if (!s->inflate_buffer) {
1528         s->inflate_buffer = av_malloc(DECOMPRESS_BUF_SIZE);
1529         if (!s->inflate_buffer)
1530             return AVERROR(ENOMEM);
1531     }
1532
1533     if (s->inflate_stream.avail_in == 0) {
1534         int read = http_buf_read(h, s->inflate_buffer, DECOMPRESS_BUF_SIZE);
1535         if (read <= 0)
1536             return read;
1537         s->inflate_stream.next_in  = s->inflate_buffer;
1538         s->inflate_stream.avail_in = read;
1539     }
1540
1541     s->inflate_stream.avail_out = size;
1542     s->inflate_stream.next_out  = buf;
1543
1544     ret = inflate(&s->inflate_stream, Z_SYNC_FLUSH);
1545     if (ret != Z_OK && ret != Z_STREAM_END)
1546         av_log(h, AV_LOG_WARNING, "inflate return value: %d, %s\n",
1547                ret, s->inflate_stream.msg);
1548
1549     return size - s->inflate_stream.avail_out;
1550 }
1551 #endif /* CONFIG_ZLIB */
1552
1553 static int64_t http_seek_internal(URLContext *h, int64_t off, int whence, int force_reconnect);
1554
1555 static int http_read_stream(URLContext *h, uint8_t *buf, int size)
1556 {
1557     HTTPContext *s = h->priv_data;
1558     int err, new_location, read_ret;
1559     int64_t seek_ret;
1560     int reconnect_delay = 0;
1561
1562     if (!s->hd)
1563         return AVERROR_EOF;
1564
1565     if (s->end_chunked_post && !s->end_header) {
1566         err = http_read_header(h, &new_location);
1567         if (err < 0)
1568             return err;
1569     }
1570
1571 #if CONFIG_ZLIB
1572     if (s->compressed)
1573         return http_buf_read_compressed(h, buf, size);
1574 #endif /* CONFIG_ZLIB */
1575     read_ret = http_buf_read(h, buf, size);
1576     while (read_ret < 0) {
1577         uint64_t target = h->is_streamed ? 0 : s->off;
1578
1579         if (read_ret == AVERROR_EXIT)
1580             break;
1581
1582         if (h->is_streamed && !s->reconnect_streamed)
1583             break;
1584
1585         if (!(s->reconnect && s->filesize > 0 && s->off < s->filesize) &&
1586             !(s->reconnect_at_eof && read_ret == AVERROR_EOF))
1587             break;
1588
1589         if (reconnect_delay > s->reconnect_delay_max)
1590             return AVERROR(EIO);
1591
1592         av_log(h, AV_LOG_WARNING, "Will reconnect at %"PRIu64" in %d second(s), error=%s.\n", s->off, reconnect_delay, av_err2str(read_ret));
1593         err = ff_network_sleep_interruptible(1000U*1000*reconnect_delay, &h->interrupt_callback);
1594         if (err != AVERROR(ETIMEDOUT))
1595             return err;
1596         reconnect_delay = 1 + 2*reconnect_delay;
1597         seek_ret = http_seek_internal(h, target, SEEK_SET, 1);
1598         if (seek_ret >= 0 && seek_ret != target) {
1599             av_log(h, AV_LOG_ERROR, "Failed to reconnect at %"PRIu64".\n", target);
1600             return read_ret;
1601         }
1602
1603         read_ret = http_buf_read(h, buf, size);
1604     }
1605
1606     return read_ret;
1607 }
1608
1609 // Like http_read_stream(), but no short reads.
1610 // Assumes partial reads are an error.
1611 static int http_read_stream_all(URLContext *h, uint8_t *buf, int size)
1612 {
1613     int pos = 0;
1614     while (pos < size) {
1615         int len = http_read_stream(h, buf + pos, size - pos);
1616         if (len < 0)
1617             return len;
1618         pos += len;
1619     }
1620     return pos;
1621 }
1622
1623 static void update_metadata(URLContext *h, char *data)
1624 {
1625     char *key;
1626     char *val;
1627     char *end;
1628     char *next = data;
1629     HTTPContext *s = h->priv_data;
1630
1631     while (*next) {
1632         key = next;
1633         val = strstr(key, "='");
1634         if (!val)
1635             break;
1636         end = strstr(val, "';");
1637         if (!end)
1638             break;
1639
1640         *val = '\0';
1641         *end = '\0';
1642         val += 2;
1643
1644         av_dict_set(&s->metadata, key, val, 0);
1645         av_log(h, AV_LOG_VERBOSE, "Metadata update for %s: %s\n", key, val);
1646
1647         next = end + 2;
1648     }
1649 }
1650
1651 static int store_icy(URLContext *h, int size)
1652 {
1653     HTTPContext *s = h->priv_data;
1654     /* until next metadata packet */
1655     uint64_t remaining;
1656
1657     if (s->icy_metaint < s->icy_data_read)
1658         return AVERROR_INVALIDDATA;
1659     remaining = s->icy_metaint - s->icy_data_read;
1660
1661     if (!remaining) {
1662         /* The metadata packet is variable sized. It has a 1 byte header
1663          * which sets the length of the packet (divided by 16). If it's 0,
1664          * the metadata doesn't change. After the packet, icy_metaint bytes
1665          * of normal data follows. */
1666         uint8_t ch;
1667         int len = http_read_stream_all(h, &ch, 1);
1668         if (len < 0)
1669             return len;
1670         if (ch > 0) {
1671             char data[255 * 16 + 1];
1672             int ret;
1673             len = ch * 16;
1674             ret = http_read_stream_all(h, data, len);
1675             if (ret < 0)
1676                 return ret;
1677             data[len + 1] = 0;
1678             if ((ret = av_opt_set(s, "icy_metadata_packet", data, 0)) < 0)
1679                 return ret;
1680             update_metadata(h, data);
1681         }
1682         s->icy_data_read = 0;
1683         remaining        = s->icy_metaint;
1684     }
1685
1686     return FFMIN(size, remaining);
1687 }
1688
1689 static int http_read(URLContext *h, uint8_t *buf, int size)
1690 {
1691     HTTPContext *s = h->priv_data;
1692
1693     if (s->icy_metaint > 0) {
1694         size = store_icy(h, size);
1695         if (size < 0)
1696             return size;
1697     }
1698
1699     size = http_read_stream(h, buf, size);
1700     if (size > 0)
1701         s->icy_data_read += size;
1702     return size;
1703 }
1704
1705 /* used only when posting data */
1706 static int http_write(URLContext *h, const uint8_t *buf, int size)
1707 {
1708     char temp[11] = "";  /* 32-bit hex + CRLF + nul */
1709     int ret;
1710     char crlf[] = "\r\n";
1711     HTTPContext *s = h->priv_data;
1712
1713     if (!s->chunked_post) {
1714         /* non-chunked data is sent without any special encoding */
1715         return ffurl_write(s->hd, buf, size);
1716     }
1717
1718     /* silently ignore zero-size data since chunk encoding that would
1719      * signal EOF */
1720     if (size > 0) {
1721         /* upload data using chunked encoding */
1722         snprintf(temp, sizeof(temp), "%x\r\n", size);
1723
1724         if ((ret = ffurl_write(s->hd, temp, strlen(temp))) < 0 ||
1725             (ret = ffurl_write(s->hd, buf, size)) < 0          ||
1726             (ret = ffurl_write(s->hd, crlf, sizeof(crlf) - 1)) < 0)
1727             return ret;
1728     }
1729     return size;
1730 }
1731
1732 static int http_shutdown(URLContext *h, int flags)
1733 {
1734     int ret = 0;
1735     char footer[] = "0\r\n\r\n";
1736     HTTPContext *s = h->priv_data;
1737
1738     /* signal end of chunked encoding if used */
1739     if (((flags & AVIO_FLAG_WRITE) && s->chunked_post) ||
1740         ((flags & AVIO_FLAG_READ) && s->chunked_post && s->listen)) {
1741         ret = ffurl_write(s->hd, footer, sizeof(footer) - 1);
1742         ret = ret > 0 ? 0 : ret;
1743         /* flush the receive buffer when it is write only mode */
1744         if (!(flags & AVIO_FLAG_READ)) {
1745             char buf[1024];
1746             int read_ret;
1747             s->hd->flags |= AVIO_FLAG_NONBLOCK;
1748             read_ret = ffurl_read(s->hd, buf, sizeof(buf));
1749             s->hd->flags &= ~AVIO_FLAG_NONBLOCK;
1750             if (read_ret < 0 && read_ret != AVERROR(EAGAIN)) {
1751                 av_log(h, AV_LOG_ERROR, "URL read error: %s\n", av_err2str(read_ret));
1752                 ret = read_ret;
1753             }
1754         }
1755         s->end_chunked_post = 1;
1756     }
1757
1758     return ret;
1759 }
1760
1761 static int http_close(URLContext *h)
1762 {
1763     int ret = 0;
1764     HTTPContext *s = h->priv_data;
1765
1766 #if CONFIG_ZLIB
1767     inflateEnd(&s->inflate_stream);
1768     av_freep(&s->inflate_buffer);
1769 #endif /* CONFIG_ZLIB */
1770
1771     if (s->hd && !s->end_chunked_post)
1772         /* Close the write direction by sending the end of chunked encoding. */
1773         ret = http_shutdown(h, h->flags);
1774
1775     if (s->hd)
1776         ffurl_closep(&s->hd);
1777     av_dict_free(&s->chained_options);
1778     return ret;
1779 }
1780
1781 static int64_t http_seek_internal(URLContext *h, int64_t off, int whence, int force_reconnect)
1782 {
1783     HTTPContext *s = h->priv_data;
1784     URLContext *old_hd = s->hd;
1785     uint64_t old_off = s->off;
1786     uint8_t old_buf[BUFFER_SIZE];
1787     int old_buf_size, ret;
1788     AVDictionary *options = NULL;
1789
1790     if (whence == AVSEEK_SIZE)
1791         return s->filesize;
1792     else if (!force_reconnect &&
1793              ((whence == SEEK_CUR && off == 0) ||
1794               (whence == SEEK_SET && off == s->off)))
1795         return s->off;
1796     else if ((s->filesize == UINT64_MAX && whence == SEEK_END))
1797         return AVERROR(ENOSYS);
1798
1799     if (whence == SEEK_CUR)
1800         off += s->off;
1801     else if (whence == SEEK_END)
1802         off += s->filesize;
1803     else if (whence != SEEK_SET)
1804         return AVERROR(EINVAL);
1805     if (off < 0)
1806         return AVERROR(EINVAL);
1807     s->off = off;
1808
1809     if (s->off && h->is_streamed)
1810         return AVERROR(ENOSYS);
1811
1812     /* do not try to make a new connection if seeking past the end of the file */
1813     if (s->end_off || s->filesize != UINT64_MAX) {
1814         uint64_t end_pos = s->end_off ? s->end_off : s->filesize;
1815         if (s->off >= end_pos)
1816             return s->off;
1817     }
1818
1819     /* we save the old context in case the seek fails */
1820     old_buf_size = s->buf_end - s->buf_ptr;
1821     memcpy(old_buf, s->buf_ptr, old_buf_size);
1822     s->hd = NULL;
1823
1824     /* if it fails, continue on old connection */
1825     if ((ret = http_open_cnx(h, &options)) < 0) {
1826         av_dict_free(&options);
1827         memcpy(s->buffer, old_buf, old_buf_size);
1828         s->buf_ptr = s->buffer;
1829         s->buf_end = s->buffer + old_buf_size;
1830         s->hd      = old_hd;
1831         s->off     = old_off;
1832         return ret;
1833     }
1834     av_dict_free(&options);
1835     ffurl_close(old_hd);
1836     return off;
1837 }
1838
1839 static int64_t http_seek(URLContext *h, int64_t off, int whence)
1840 {
1841     return http_seek_internal(h, off, whence, 0);
1842 }
1843
1844 static int http_get_file_handle(URLContext *h)
1845 {
1846     HTTPContext *s = h->priv_data;
1847     return ffurl_get_file_handle(s->hd);
1848 }
1849
1850 static int http_get_short_seek(URLContext *h)
1851 {
1852     HTTPContext *s = h->priv_data;
1853     return ffurl_get_short_seek(s->hd);
1854 }
1855
1856 #define HTTP_CLASS(flavor)                          \
1857 static const AVClass flavor ## _context_class = {   \
1858     .class_name = # flavor,                         \
1859     .item_name  = av_default_item_name,             \
1860     .option     = options,                          \
1861     .version    = LIBAVUTIL_VERSION_INT,            \
1862 }
1863
1864 #if CONFIG_HTTP_PROTOCOL
1865 HTTP_CLASS(http);
1866
1867 const URLProtocol ff_http_protocol = {
1868     .name                = "http",
1869     .url_open2           = http_open,
1870     .url_accept          = http_accept,
1871     .url_handshake       = http_handshake,
1872     .url_read            = http_read,
1873     .url_write           = http_write,
1874     .url_seek            = http_seek,
1875     .url_close           = http_close,
1876     .url_get_file_handle = http_get_file_handle,
1877     .url_get_short_seek  = http_get_short_seek,
1878     .url_shutdown        = http_shutdown,
1879     .priv_data_size      = sizeof(HTTPContext),
1880     .priv_data_class     = &http_context_class,
1881     .flags               = URL_PROTOCOL_FLAG_NETWORK,
1882     .default_whitelist   = "http,https,tls,rtp,tcp,udp,crypto,httpproxy,data"
1883 };
1884 #endif /* CONFIG_HTTP_PROTOCOL */
1885
1886 #if CONFIG_HTTPS_PROTOCOL
1887 HTTP_CLASS(https);
1888
1889 const URLProtocol ff_https_protocol = {
1890     .name                = "https",
1891     .url_open2           = http_open,
1892     .url_read            = http_read,
1893     .url_write           = http_write,
1894     .url_seek            = http_seek,
1895     .url_close           = http_close,
1896     .url_get_file_handle = http_get_file_handle,
1897     .url_get_short_seek  = http_get_short_seek,
1898     .url_shutdown        = http_shutdown,
1899     .priv_data_size      = sizeof(HTTPContext),
1900     .priv_data_class     = &https_context_class,
1901     .flags               = URL_PROTOCOL_FLAG_NETWORK,
1902     .default_whitelist   = "http,https,tls,rtp,tcp,udp,crypto,httpproxy"
1903 };
1904 #endif /* CONFIG_HTTPS_PROTOCOL */
1905
1906 #if CONFIG_HTTPPROXY_PROTOCOL
1907 static int http_proxy_close(URLContext *h)
1908 {
1909     HTTPContext *s = h->priv_data;
1910     if (s->hd)
1911         ffurl_closep(&s->hd);
1912     return 0;
1913 }
1914
1915 static int http_proxy_open(URLContext *h, const char *uri, int flags)
1916 {
1917     HTTPContext *s = h->priv_data;
1918     char hostname[1024], hoststr[1024];
1919     char auth[1024], pathbuf[1024], *path;
1920     char lower_url[100];
1921     int port, ret = 0, attempts = 0;
1922     HTTPAuthType cur_auth_type;
1923     char *authstr;
1924     int new_loc;
1925
1926     if( s->seekable == 1 )
1927         h->is_streamed = 0;
1928     else
1929         h->is_streamed = 1;
1930
1931     av_url_split(NULL, 0, auth, sizeof(auth), hostname, sizeof(hostname), &port,
1932                  pathbuf, sizeof(pathbuf), uri);
1933     ff_url_join(hoststr, sizeof(hoststr), NULL, NULL, hostname, port, NULL);
1934     path = pathbuf;
1935     if (*path == '/')
1936         path++;
1937
1938     ff_url_join(lower_url, sizeof(lower_url), "tcp", NULL, hostname, port,
1939                 NULL);
1940 redo:
1941     ret = ffurl_open_whitelist(&s->hd, lower_url, AVIO_FLAG_READ_WRITE,
1942                                &h->interrupt_callback, NULL,
1943                                h->protocol_whitelist, h->protocol_blacklist, h);
1944     if (ret < 0)
1945         return ret;
1946
1947     authstr = ff_http_auth_create_response(&s->proxy_auth_state, auth,
1948                                            path, "CONNECT");
1949     snprintf(s->buffer, sizeof(s->buffer),
1950              "CONNECT %s HTTP/1.1\r\n"
1951              "Host: %s\r\n"
1952              "Connection: close\r\n"
1953              "%s%s"
1954              "\r\n",
1955              path,
1956              hoststr,
1957              authstr ? "Proxy-" : "", authstr ? authstr : "");
1958     av_freep(&authstr);
1959
1960     if ((ret = ffurl_write(s->hd, s->buffer, strlen(s->buffer))) < 0)
1961         goto fail;
1962
1963     s->buf_ptr    = s->buffer;
1964     s->buf_end    = s->buffer;
1965     s->line_count = 0;
1966     s->filesize   = UINT64_MAX;
1967     cur_auth_type = s->proxy_auth_state.auth_type;
1968
1969     /* Note: This uses buffering, potentially reading more than the
1970      * HTTP header. If tunneling a protocol where the server starts
1971      * the conversation, we might buffer part of that here, too.
1972      * Reading that requires using the proper ffurl_read() function
1973      * on this URLContext, not using the fd directly (as the tls
1974      * protocol does). This shouldn't be an issue for tls though,
1975      * since the client starts the conversation there, so there
1976      * is no extra data that we might buffer up here.
1977      */
1978     ret = http_read_header(h, &new_loc);
1979     if (ret < 0)
1980         goto fail;
1981
1982     attempts++;
1983     if (s->http_code == 407 &&
1984         (cur_auth_type == HTTP_AUTH_NONE || s->proxy_auth_state.stale) &&
1985         s->proxy_auth_state.auth_type != HTTP_AUTH_NONE && attempts < 2) {
1986         ffurl_closep(&s->hd);
1987         goto redo;
1988     }
1989
1990     if (s->http_code < 400)
1991         return 0;
1992     ret = ff_http_averror(s->http_code, AVERROR(EIO));
1993
1994 fail:
1995     http_proxy_close(h);
1996     return ret;
1997 }
1998
1999 static int http_proxy_write(URLContext *h, const uint8_t *buf, int size)
2000 {
2001     HTTPContext *s = h->priv_data;
2002     return ffurl_write(s->hd, buf, size);
2003 }
2004
2005 const URLProtocol ff_httpproxy_protocol = {
2006     .name                = "httpproxy",
2007     .url_open            = http_proxy_open,
2008     .url_read            = http_buf_read,
2009     .url_write           = http_proxy_write,
2010     .url_close           = http_proxy_close,
2011     .url_get_file_handle = http_get_file_handle,
2012     .priv_data_size      = sizeof(HTTPContext),
2013     .flags               = URL_PROTOCOL_FLAG_NETWORK,
2014 };
2015 #endif /* CONFIG_HTTPPROXY_PROTOCOL */