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