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