]> git.sesse.net Git - ffmpeg/blob - libavformat/http.c
Merge commit 'b146d74730ab9ec5abede9066f770ad851e45fbc'
[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 "libavutil/avstring.h"
23 #include "avformat.h"
24 #include "internal.h"
25 #include "network.h"
26 #include "http.h"
27 #include "os_support.h"
28 #include "httpauth.h"
29 #include "url.h"
30 #include "libavutil/opt.h"
31
32 /* XXX: POST protocol is not completely implemented because ffmpeg uses
33    only a subset of it. */
34
35 /* The IO buffer size is unrelated to the max URL size in itself, but needs
36  * to be large enough to fit the full request headers (including long
37  * path names).
38  */
39 #define BUFFER_SIZE MAX_URL_SIZE
40 #define MAX_REDIRECTS 8
41
42 typedef struct {
43     const AVClass *class;
44     URLContext *hd;
45     unsigned char buffer[BUFFER_SIZE], *buf_ptr, *buf_end;
46     int line_count;
47     int http_code;
48     int64_t chunksize;      /**< Used if "Transfer-Encoding: chunked" otherwise -1. */
49     char *user_agent;
50     int64_t off, filesize;
51     char location[MAX_URL_SIZE];
52     HTTPAuthState auth_state;
53     HTTPAuthState proxy_auth_state;
54     char *headers;
55     int willclose;          /**< Set if the server correctly handles Connection: close and will close the connection after feeding us the content. */
56     int chunked_post;
57     int end_chunked_post;   /**< A flag which indicates if the end of chunked encoding has been sent. */
58     int end_header;         /**< A flag which indicates we have finished to read POST reply. */
59     int multiple_requests;  /**< A flag which indicates if we use persistent connections. */
60     uint8_t *post_data;
61     int post_datalen;
62     int is_akamai;
63 } HTTPContext;
64
65 #define OFFSET(x) offsetof(HTTPContext, x)
66 #define D AV_OPT_FLAG_DECODING_PARAM
67 #define E AV_OPT_FLAG_ENCODING_PARAM
68 #define DEC AV_OPT_FLAG_DECODING_PARAM
69 static const AVOption options[] = {
70 {"chunked_post", "use chunked transfer-encoding for posts", OFFSET(chunked_post), AV_OPT_TYPE_INT, {.i64 = 1}, 0, 1, E },
71 {"headers", "custom HTTP headers, can override built in default headers", OFFSET(headers), AV_OPT_TYPE_STRING, { 0 }, 0, 0, D|E },
72 {"user-agent", "override User-Agent header", OFFSET(user_agent), AV_OPT_TYPE_STRING, {.str = NULL}, 0, 0, DEC},
73 {"multiple_requests", "use persistent connections", OFFSET(multiple_requests), AV_OPT_TYPE_INT, {.i64 = 0}, 0, 1, D|E },
74 {"post_data", "custom HTTP post data", OFFSET(post_data), AV_OPT_TYPE_BINARY, .flags = D|E },
75 {NULL}
76 };
77 #define HTTP_CLASS(flavor)\
78 static const AVClass flavor ## _context_class = {\
79     .class_name     = #flavor,\
80     .item_name      = av_default_item_name,\
81     .option         = options,\
82     .version        = LIBAVUTIL_VERSION_INT,\
83 }
84
85 HTTP_CLASS(http);
86 HTTP_CLASS(https);
87
88 static int http_connect(URLContext *h, const char *path, const char *local_path,
89                         const char *hoststr, const char *auth,
90                         const char *proxyauth, int *new_location);
91
92 void ff_http_init_auth_state(URLContext *dest, const URLContext *src)
93 {
94     memcpy(&((HTTPContext*)dest->priv_data)->auth_state,
95            &((HTTPContext*)src->priv_data)->auth_state, sizeof(HTTPAuthState));
96     memcpy(&((HTTPContext*)dest->priv_data)->proxy_auth_state,
97            &((HTTPContext*)src->priv_data)->proxy_auth_state,
98            sizeof(HTTPAuthState));
99 }
100
101 /* return non zero if error */
102 static int http_open_cnx(URLContext *h)
103 {
104     const char *path, *proxy_path, *lower_proto = "tcp", *local_path;
105     char hostname[1024], hoststr[1024], proto[10];
106     char auth[1024], proxyauth[1024] = "";
107     char path1[MAX_URL_SIZE];
108     char buf[1024], urlbuf[MAX_URL_SIZE];
109     int port, use_proxy, err, location_changed = 0, redirects = 0, attempts = 0;
110     HTTPAuthType cur_auth_type, cur_proxy_auth_type;
111     HTTPContext *s = h->priv_data;
112
113     proxy_path = getenv("http_proxy");
114     use_proxy = (proxy_path != NULL) && !getenv("no_proxy") &&
115         av_strstart(proxy_path, "http://", NULL);
116
117     /* fill the dest addr */
118  redo:
119     /* needed in any case to build the host string */
120     av_url_split(proto, sizeof(proto), auth, sizeof(auth),
121                  hostname, sizeof(hostname), &port,
122                  path1, sizeof(path1), s->location);
123     ff_url_join(hoststr, sizeof(hoststr), NULL, NULL, hostname, port, NULL);
124
125     if (!strcmp(proto, "https")) {
126         lower_proto = "tls";
127         use_proxy = 0;
128         if (port < 0)
129             port = 443;
130     }
131     if (port < 0)
132         port = 80;
133
134     if (path1[0] == '\0')
135         path = "/";
136     else
137         path = path1;
138     local_path = path;
139     if (use_proxy) {
140         /* Reassemble the request URL without auth string - we don't
141          * want to leak the auth to the proxy. */
142         ff_url_join(urlbuf, sizeof(urlbuf), proto, NULL, hostname, port, "%s",
143                     path1);
144         path = urlbuf;
145         av_url_split(NULL, 0, proxyauth, sizeof(proxyauth),
146                      hostname, sizeof(hostname), &port, NULL, 0, proxy_path);
147     }
148
149     ff_url_join(buf, sizeof(buf), lower_proto, NULL, hostname, port, NULL);
150
151     if (!s->hd) {
152         err = ffurl_open(&s->hd, buf, AVIO_FLAG_READ_WRITE,
153                          &h->interrupt_callback, NULL);
154         if (err < 0)
155             goto fail;
156     }
157
158     cur_auth_type = s->auth_state.auth_type;
159     cur_proxy_auth_type = s->auth_state.auth_type;
160     if (http_connect(h, path, local_path, hoststr, auth, proxyauth, &location_changed) < 0)
161         goto fail;
162     attempts++;
163     if (s->http_code == 401) {
164         if ((cur_auth_type == HTTP_AUTH_NONE || s->auth_state.stale) &&
165             s->auth_state.auth_type != HTTP_AUTH_NONE && attempts < 4) {
166             ffurl_closep(&s->hd);
167             goto redo;
168         } else
169             goto fail;
170     }
171     if (s->http_code == 407) {
172         if ((cur_proxy_auth_type == HTTP_AUTH_NONE || s->proxy_auth_state.stale) &&
173             s->proxy_auth_state.auth_type != HTTP_AUTH_NONE && attempts < 4) {
174             ffurl_closep(&s->hd);
175             goto redo;
176         } else
177             goto fail;
178     }
179     if ((s->http_code == 301 || s->http_code == 302 || s->http_code == 303 || s->http_code == 307)
180         && location_changed == 1) {
181         /* url moved, get next */
182         ffurl_closep(&s->hd);
183         if (redirects++ >= MAX_REDIRECTS)
184             return AVERROR(EIO);
185         /* Restart the authentication process with the new target, which
186          * might use a different auth mechanism. */
187         memset(&s->auth_state, 0, sizeof(s->auth_state));
188         attempts = 0;
189         location_changed = 0;
190         goto redo;
191     }
192     return 0;
193  fail:
194     if (s->hd)
195         ffurl_closep(&s->hd);
196     return AVERROR(EIO);
197 }
198
199 int ff_http_do_new_request(URLContext *h, const char *uri)
200 {
201     HTTPContext *s = h->priv_data;
202
203     s->off = 0;
204     av_strlcpy(s->location, uri, sizeof(s->location));
205
206     return http_open_cnx(h);
207 }
208
209 static int http_open(URLContext *h, const char *uri, int flags)
210 {
211     HTTPContext *s = h->priv_data;
212
213     h->is_streamed = 1;
214
215     s->filesize = -1;
216     av_strlcpy(s->location, uri, sizeof(s->location));
217
218     if (s->headers) {
219         int len = strlen(s->headers);
220         if (len < 2 || strcmp("\r\n", s->headers + len - 2))
221             av_log(h, AV_LOG_WARNING, "No trailing CRLF found in HTTP header.\n");
222     }
223
224     return http_open_cnx(h);
225 }
226 static int http_getc(HTTPContext *s)
227 {
228     int len;
229     if (s->buf_ptr >= s->buf_end) {
230         len = ffurl_read(s->hd, s->buffer, BUFFER_SIZE);
231         if (len < 0) {
232             return len;
233         } else if (len == 0) {
234             return -1;
235         } else {
236             s->buf_ptr = s->buffer;
237             s->buf_end = s->buffer + len;
238         }
239     }
240     return *s->buf_ptr++;
241 }
242
243 static int http_get_line(HTTPContext *s, char *line, int line_size)
244 {
245     int ch;
246     char *q;
247
248     q = line;
249     for(;;) {
250         ch = http_getc(s);
251         if (ch < 0)
252             return ch;
253         if (ch == '\n') {
254             /* process line */
255             if (q > line && q[-1] == '\r')
256                 q--;
257             *q = '\0';
258
259             return 0;
260         } else {
261             if ((q - line) < line_size - 1)
262                 *q++ = ch;
263         }
264     }
265 }
266
267 static int process_line(URLContext *h, char *line, int line_count,
268                         int *new_location)
269 {
270     HTTPContext *s = h->priv_data;
271     char *tag, *p, *end;
272
273     /* end of header */
274     if (line[0] == '\0') {
275         s->end_header = 1;
276         return 0;
277     }
278
279     p = line;
280     if (line_count == 0) {
281         while (!isspace(*p) && *p != '\0')
282             p++;
283         while (isspace(*p))
284             p++;
285         s->http_code = strtol(p, &end, 10);
286
287         av_dlog(NULL, "http_code=%d\n", s->http_code);
288
289         /* error codes are 4xx and 5xx, but regard 401 as a success, so we
290          * don't abort until all headers have been parsed. */
291         if (s->http_code >= 400 && s->http_code < 600 && (s->http_code != 401
292             || s->auth_state.auth_type != HTTP_AUTH_NONE) &&
293             (s->http_code != 407 || s->proxy_auth_state.auth_type != HTTP_AUTH_NONE)) {
294             end += strspn(end, SPACE_CHARS);
295             av_log(h, AV_LOG_WARNING, "HTTP error %d %s\n",
296                    s->http_code, end);
297             return -1;
298         }
299     } else {
300         while (*p != '\0' && *p != ':')
301             p++;
302         if (*p != ':')
303             return 1;
304
305         *p = '\0';
306         tag = line;
307         p++;
308         while (isspace(*p))
309             p++;
310         if (!av_strcasecmp(tag, "Location")) {
311             strcpy(s->location, p);
312             *new_location = 1;
313         } else if (!av_strcasecmp (tag, "Content-Length") && s->filesize == -1) {
314             s->filesize = strtoll(p, NULL, 10);
315         } else if (!av_strcasecmp (tag, "Content-Range")) {
316             /* "bytes $from-$to/$document_size" */
317             const char *slash;
318             if (!strncmp (p, "bytes ", 6)) {
319                 p += 6;
320                 s->off = strtoll(p, NULL, 10);
321                 if ((slash = strchr(p, '/')) && strlen(slash) > 0)
322                     s->filesize = strtoll(slash+1, NULL, 10);
323             }
324             if (!s->is_akamai || s->filesize != 2147483647)
325                 h->is_streamed = 0; /* we _can_ in fact seek */
326         } else if (!av_strcasecmp(tag, "Accept-Ranges") && !strncmp(p, "bytes", 5)) {
327             h->is_streamed = 0;
328         } else if (!av_strcasecmp (tag, "Transfer-Encoding") && !av_strncasecmp(p, "chunked", 7)) {
329             s->filesize = -1;
330             s->chunksize = 0;
331         } else if (!av_strcasecmp (tag, "WWW-Authenticate")) {
332             ff_http_auth_handle_header(&s->auth_state, tag, p);
333         } else if (!av_strcasecmp (tag, "Authentication-Info")) {
334             ff_http_auth_handle_header(&s->auth_state, tag, p);
335         } else if (!av_strcasecmp (tag, "Proxy-Authenticate")) {
336             ff_http_auth_handle_header(&s->proxy_auth_state, tag, p);
337         } else if (!av_strcasecmp (tag, "Connection")) {
338             if (!strcmp(p, "close"))
339                 s->willclose = 1;
340         } else if (!av_strcasecmp (tag, "Server") && !av_strcasecmp (p, "AkamaiGHost")) {
341             s->is_akamai = 1;
342         }
343     }
344     return 1;
345 }
346
347 static inline int has_header(const char *str, const char *header)
348 {
349     /* header + 2 to skip over CRLF prefix. (make sure you have one!) */
350     if (!str)
351         return 0;
352     return av_stristart(str, header + 2, NULL) || av_stristr(str, header);
353 }
354
355 static int http_read_header(URLContext *h, int *new_location)
356 {
357     HTTPContext *s = h->priv_data;
358     char line[MAX_URL_SIZE];
359     int err = 0;
360
361     s->chunksize = -1;
362
363     for (;;) {
364         if ((err = http_get_line(s, line, sizeof(line))) < 0)
365             return err;
366
367         av_dlog(NULL, "header='%s'\n", line);
368
369         err = process_line(h, line, s->line_count, new_location);
370         if (err < 0)
371             return err;
372         if (err == 0)
373             break;
374         s->line_count++;
375     }
376
377     return err;
378 }
379
380 static int http_connect(URLContext *h, const char *path, const char *local_path,
381                         const char *hoststr, const char *auth,
382                         const char *proxyauth, int *new_location)
383 {
384     HTTPContext *s = h->priv_data;
385     int post, err;
386     char headers[4096] = "";
387     char *authstr = NULL, *proxyauthstr = NULL;
388     int64_t off = s->off;
389     int len = 0;
390     const char *method;
391
392
393     /* send http header */
394     post = h->flags & AVIO_FLAG_WRITE;
395
396     if (s->post_data) {
397         /* force POST method and disable chunked encoding when
398          * custom HTTP post data is set */
399         post = 1;
400         s->chunked_post = 0;
401     }
402
403     method = post ? "POST" : "GET";
404     authstr = ff_http_auth_create_response(&s->auth_state, auth, local_path,
405                                            method);
406     proxyauthstr = ff_http_auth_create_response(&s->proxy_auth_state, proxyauth,
407                                                 local_path, method);
408
409     /* set default headers if needed */
410     if (!has_header(s->headers, "\r\nUser-Agent: "))
411         len += av_strlcatf(headers + len, sizeof(headers) - len,
412                            "User-Agent: %s\r\n",
413                            s->user_agent ? s->user_agent : LIBAVFORMAT_IDENT);
414     if (!has_header(s->headers, "\r\nAccept: "))
415         len += av_strlcpy(headers + len, "Accept: */*\r\n",
416                           sizeof(headers) - len);
417     // Note: we send this on purpose even when s->off is 0,
418     // since it allows us to detect more reliably if a (non-conforming)
419     // server supports seeking by analysing the reply headers.
420     if (!has_header(s->headers, "\r\nRange: ") && !post)
421         len += av_strlcatf(headers + len, sizeof(headers) - len,
422                            "Range: bytes=%"PRId64"-\r\n", s->off);
423
424     if (!has_header(s->headers, "\r\nConnection: ")) {
425         if (s->multiple_requests) {
426             len += av_strlcpy(headers + len, "Connection: keep-alive\r\n",
427                               sizeof(headers) - len);
428         } else {
429             len += av_strlcpy(headers + len, "Connection: close\r\n",
430                               sizeof(headers) - len);
431         }
432     }
433
434     if (!has_header(s->headers, "\r\nHost: "))
435         len += av_strlcatf(headers + len, sizeof(headers) - len,
436                            "Host: %s\r\n", hoststr);
437     if (!has_header(s->headers, "\r\nContent-Length: ") && s->post_data)
438         len += av_strlcatf(headers + len, sizeof(headers) - len,
439                            "Content-Length: %d\r\n", s->post_datalen);
440
441     /* now add in custom headers */
442     if (s->headers)
443         av_strlcpy(headers + len, s->headers, sizeof(headers) - len);
444
445     snprintf(s->buffer, sizeof(s->buffer),
446              "%s %s HTTP/1.1\r\n"
447              "%s"
448              "%s"
449              "%s"
450              "%s%s"
451              "\r\n",
452              method,
453              path,
454              post && s->chunked_post ? "Transfer-Encoding: chunked\r\n" : "",
455              headers,
456              authstr ? authstr : "",
457              proxyauthstr ? "Proxy-" : "", proxyauthstr ? proxyauthstr : "");
458
459     av_freep(&authstr);
460     av_freep(&proxyauthstr);
461     if ((err = ffurl_write(s->hd, s->buffer, strlen(s->buffer))) < 0)
462         return err;
463
464     if (s->post_data)
465         if ((err = ffurl_write(s->hd, s->post_data, s->post_datalen)) < 0)
466             return err;
467
468     /* init input buffer */
469     s->buf_ptr = s->buffer;
470     s->buf_end = s->buffer;
471     s->line_count = 0;
472     s->off = 0;
473     s->filesize = -1;
474     s->willclose = 0;
475     s->end_chunked_post = 0;
476     s->end_header = 0;
477     if (post && !s->post_data) {
478         /* Pretend that it did work. We didn't read any header yet, since
479          * we've still to send the POST data, but the code calling this
480          * function will check http_code after we return. */
481         s->http_code = 200;
482         return 0;
483     }
484
485     /* wait for header */
486     err = http_read_header(h, new_location);
487     if (err < 0)
488         return err;
489
490     return (off == s->off) ? 0 : -1;
491 }
492
493
494 static int http_buf_read(URLContext *h, uint8_t *buf, int size)
495 {
496     HTTPContext *s = h->priv_data;
497     int len;
498     /* read bytes from input buffer first */
499     len = s->buf_end - s->buf_ptr;
500     if (len > 0) {
501         if (len > size)
502             len = size;
503         memcpy(buf, s->buf_ptr, len);
504         s->buf_ptr += len;
505     } else {
506         if (!s->willclose && s->filesize >= 0 && s->off >= s->filesize)
507             return AVERROR_EOF;
508         len = ffurl_read(s->hd, buf, size);
509     }
510     if (len > 0) {
511         s->off += len;
512         if (s->chunksize > 0)
513             s->chunksize -= len;
514     }
515     return len;
516 }
517
518 static int http_read(URLContext *h, uint8_t *buf, int size)
519 {
520     HTTPContext *s = h->priv_data;
521     int err, new_location;
522
523     if (!s->hd)
524         return AVERROR_EOF;
525
526     if (s->end_chunked_post && !s->end_header) {
527         err = http_read_header(h, &new_location);
528         if (err < 0)
529             return err;
530     }
531
532     if (s->chunksize >= 0) {
533         if (!s->chunksize) {
534             char line[32];
535
536             for(;;) {
537                 do {
538                     if ((err = http_get_line(s, line, sizeof(line))) < 0)
539                         return err;
540                 } while (!*line);    /* skip CR LF from last chunk */
541
542                 s->chunksize = strtoll(line, NULL, 16);
543
544                 av_dlog(NULL, "Chunked encoding data size: %"PRId64"'\n", s->chunksize);
545
546                 if (!s->chunksize)
547                     return 0;
548                 break;
549             }
550         }
551         size = FFMIN(size, s->chunksize);
552     }
553     return http_buf_read(h, buf, size);
554 }
555
556 /* used only when posting data */
557 static int http_write(URLContext *h, const uint8_t *buf, int size)
558 {
559     char temp[11] = "";  /* 32-bit hex + CRLF + nul */
560     int ret;
561     char crlf[] = "\r\n";
562     HTTPContext *s = h->priv_data;
563
564     if (!s->chunked_post) {
565         /* non-chunked data is sent without any special encoding */
566         return ffurl_write(s->hd, buf, size);
567     }
568
569     /* silently ignore zero-size data since chunk encoding that would
570      * signal EOF */
571     if (size > 0) {
572         /* upload data using chunked encoding */
573         snprintf(temp, sizeof(temp), "%x\r\n", size);
574
575         if ((ret = ffurl_write(s->hd, temp, strlen(temp))) < 0 ||
576             (ret = ffurl_write(s->hd, buf, size)) < 0 ||
577             (ret = ffurl_write(s->hd, crlf, sizeof(crlf) - 1)) < 0)
578             return ret;
579     }
580     return size;
581 }
582
583 static int http_shutdown(URLContext *h, int flags)
584 {
585     int ret = 0;
586     char footer[] = "0\r\n\r\n";
587     HTTPContext *s = h->priv_data;
588
589     /* signal end of chunked encoding if used */
590     if ((flags & AVIO_FLAG_WRITE) && s->chunked_post) {
591         ret = ffurl_write(s->hd, footer, sizeof(footer) - 1);
592         ret = ret > 0 ? 0 : ret;
593         s->end_chunked_post = 1;
594     }
595
596     return ret;
597 }
598
599 static int http_close(URLContext *h)
600 {
601     int ret = 0;
602     HTTPContext *s = h->priv_data;
603
604     if (!s->end_chunked_post) {
605         /* Close the write direction by sending the end of chunked encoding. */
606         ret = http_shutdown(h, h->flags);
607     }
608
609     if (s->hd)
610         ffurl_closep(&s->hd);
611     return ret;
612 }
613
614 static int64_t http_seek(URLContext *h, int64_t off, int whence)
615 {
616     HTTPContext *s = h->priv_data;
617     URLContext *old_hd = s->hd;
618     int64_t old_off = s->off;
619     uint8_t old_buf[BUFFER_SIZE];
620     int old_buf_size;
621
622     if (whence == AVSEEK_SIZE)
623         return s->filesize;
624     else if ((s->filesize == -1 && whence == SEEK_END) || h->is_streamed)
625         return -1;
626
627     /* we save the old context in case the seek fails */
628     old_buf_size = s->buf_end - s->buf_ptr;
629     memcpy(old_buf, s->buf_ptr, old_buf_size);
630     s->hd = NULL;
631     if (whence == SEEK_CUR)
632         off += s->off;
633     else if (whence == SEEK_END)
634         off += s->filesize;
635     s->off = off;
636
637     /* if it fails, continue on old connection */
638     if (http_open_cnx(h) < 0) {
639         memcpy(s->buffer, old_buf, old_buf_size);
640         s->buf_ptr = s->buffer;
641         s->buf_end = s->buffer + old_buf_size;
642         s->hd = old_hd;
643         s->off = old_off;
644         return -1;
645     }
646     ffurl_close(old_hd);
647     return off;
648 }
649
650 static int
651 http_get_file_handle(URLContext *h)
652 {
653     HTTPContext *s = h->priv_data;
654     return ffurl_get_file_handle(s->hd);
655 }
656
657 #if CONFIG_HTTP_PROTOCOL
658 URLProtocol ff_http_protocol = {
659     .name                = "http",
660     .url_open            = http_open,
661     .url_read            = http_read,
662     .url_write           = http_write,
663     .url_seek            = http_seek,
664     .url_close           = http_close,
665     .url_get_file_handle = http_get_file_handle,
666     .url_shutdown        = http_shutdown,
667     .priv_data_size      = sizeof(HTTPContext),
668     .priv_data_class     = &http_context_class,
669     .flags               = URL_PROTOCOL_FLAG_NETWORK,
670 };
671 #endif
672 #if CONFIG_HTTPS_PROTOCOL
673 URLProtocol ff_https_protocol = {
674     .name                = "https",
675     .url_open            = http_open,
676     .url_read            = http_read,
677     .url_write           = http_write,
678     .url_seek            = http_seek,
679     .url_close           = http_close,
680     .url_get_file_handle = http_get_file_handle,
681     .url_shutdown        = http_shutdown,
682     .priv_data_size      = sizeof(HTTPContext),
683     .priv_data_class     = &https_context_class,
684     .flags               = URL_PROTOCOL_FLAG_NETWORK,
685 };
686 #endif
687
688 #if CONFIG_HTTPPROXY_PROTOCOL
689 static int http_proxy_close(URLContext *h)
690 {
691     HTTPContext *s = h->priv_data;
692     if (s->hd)
693         ffurl_closep(&s->hd);
694     return 0;
695 }
696
697 static int http_proxy_open(URLContext *h, const char *uri, int flags)
698 {
699     HTTPContext *s = h->priv_data;
700     char hostname[1024], hoststr[1024];
701     char auth[1024], pathbuf[1024], *path;
702     char lower_url[100];
703     int port, ret = 0, attempts = 0;
704     HTTPAuthType cur_auth_type;
705     char *authstr;
706     int new_loc;
707
708     h->is_streamed = 1;
709
710     av_url_split(NULL, 0, auth, sizeof(auth), hostname, sizeof(hostname), &port,
711                  pathbuf, sizeof(pathbuf), uri);
712     ff_url_join(hoststr, sizeof(hoststr), NULL, NULL, hostname, port, NULL);
713     path = pathbuf;
714     if (*path == '/')
715         path++;
716
717     ff_url_join(lower_url, sizeof(lower_url), "tcp", NULL, hostname, port,
718                 NULL);
719 redo:
720     ret = ffurl_open(&s->hd, lower_url, AVIO_FLAG_READ_WRITE,
721                      &h->interrupt_callback, NULL);
722     if (ret < 0)
723         return ret;
724
725     authstr = ff_http_auth_create_response(&s->proxy_auth_state, auth,
726                                            path, "CONNECT");
727     snprintf(s->buffer, sizeof(s->buffer),
728              "CONNECT %s HTTP/1.1\r\n"
729              "Host: %s\r\n"
730              "Connection: close\r\n"
731              "%s%s"
732              "\r\n",
733              path,
734              hoststr,
735              authstr ? "Proxy-" : "", authstr ? authstr : "");
736     av_freep(&authstr);
737
738     if ((ret = ffurl_write(s->hd, s->buffer, strlen(s->buffer))) < 0)
739         goto fail;
740
741     s->buf_ptr = s->buffer;
742     s->buf_end = s->buffer;
743     s->line_count = 0;
744     s->filesize = -1;
745     cur_auth_type = s->proxy_auth_state.auth_type;
746
747     /* Note: This uses buffering, potentially reading more than the
748      * HTTP header. If tunneling a protocol where the server starts
749      * the conversation, we might buffer part of that here, too.
750      * Reading that requires using the proper ffurl_read() function
751      * on this URLContext, not using the fd directly (as the tls
752      * protocol does). This shouldn't be an issue for tls though,
753      * since the client starts the conversation there, so there
754      * is no extra data that we might buffer up here.
755      */
756     ret = http_read_header(h, &new_loc);
757     if (ret < 0)
758         goto fail;
759
760     attempts++;
761     if (s->http_code == 407 &&
762         (cur_auth_type == HTTP_AUTH_NONE || s->proxy_auth_state.stale) &&
763         s->proxy_auth_state.auth_type != HTTP_AUTH_NONE && attempts < 2) {
764         ffurl_closep(&s->hd);
765         goto redo;
766     }
767
768     if (s->http_code < 400)
769         return 0;
770     ret = AVERROR(EIO);
771
772 fail:
773     http_proxy_close(h);
774     return ret;
775 }
776
777 static int http_proxy_write(URLContext *h, const uint8_t *buf, int size)
778 {
779     HTTPContext *s = h->priv_data;
780     return ffurl_write(s->hd, buf, size);
781 }
782
783 URLProtocol ff_httpproxy_protocol = {
784     .name                = "httpproxy",
785     .url_open            = http_proxy_open,
786     .url_read            = http_buf_read,
787     .url_write           = http_proxy_write,
788     .url_close           = http_proxy_close,
789     .url_get_file_handle = http_get_file_handle,
790     .priv_data_size      = sizeof(HTTPContext),
791     .flags               = URL_PROTOCOL_FLAG_NETWORK,
792 };
793 #endif