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