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