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