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