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