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