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