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