FFmpeg
 All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Macros Groups Pages
http.c
Go to the documentation of this file.
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 "config.h"
23 
24 #if CONFIG_ZLIB
25 #include <zlib.h>
26 #endif /* CONFIG_ZLIB */
27 
28 #include "libavutil/avstring.h"
29 #include "libavutil/opt.h"
30 
31 #include "avformat.h"
32 #include "http.h"
33 #include "httpauth.h"
34 #include "internal.h"
35 #include "network.h"
36 #include "os_support.h"
37 #include "url.h"
38 
39 /* XXX: POST protocol is not completely implemented because ffmpeg uses
40  * only a subset of it. */
41 
42 /* The IO buffer size is unrelated to the max URL size in itself, but needs
43  * to be large enough to fit the full request headers (including long
44  * path names). */
45 #define BUFFER_SIZE MAX_URL_SIZE
46 #define MAX_REDIRECTS 8
47 
48 typedef struct {
49  const AVClass *class;
51  unsigned char buffer[BUFFER_SIZE], *buf_ptr, *buf_end;
53  int http_code;
54  /* Used if "Transfer-Encoding: chunked" otherwise -1. */
55  int64_t chunksize;
56  int64_t off, end_off, filesize;
57  char *location;
60  char *headers;
61  char *mime_type;
62  char *user_agent;
63  char *content_type;
64  /* Set if the server correctly handles Connection: close and will close
65  * the connection after feeding us the content. */
66  int willclose;
67  int seekable; /**< Control seekability, 0 = disable, 1 = enable, -1 = probe. */
69  /* A flag which indicates if the end of chunked encoding has been sent. */
71  /* A flag which indicates we have finished to read POST reply. */
73  /* A flag which indicates if we use persistent connections. */
77  int is_akamai;
79  char *cookies; ///< holds newline (\n) delimited Set-Cookie header field values (without the "Set-Cookie: " field name)
80  int icy;
81  /* how much data was read since the last ICY metadata packet */
83  /* after how many bytes of read data a new metadata packet will be found */
87 #if CONFIG_ZLIB
88  int compressed;
89  z_stream inflate_stream;
90  uint8_t *inflate_buffer;
91 #endif /* CONFIG_ZLIB */
94  char *method;
95 } HTTPContext;
96 
97 #define OFFSET(x) offsetof(HTTPContext, x)
98 #define D AV_OPT_FLAG_DECODING_PARAM
99 #define E AV_OPT_FLAG_ENCODING_PARAM
100 #define DEFAULT_USER_AGENT "Lavf/" AV_STRINGIFY(LIBAVFORMAT_VERSION)
101 
102 static const AVOption options[] = {
103  { "seekable", "control seekability of connection", OFFSET(seekable), AV_OPT_TYPE_INT, { .i64 = -1 }, -1, 1, D },
104  { "chunked_post", "use chunked transfer-encoding for posts", OFFSET(chunked_post), AV_OPT_TYPE_INT, { .i64 = 1 }, 0, 1, E },
105  { "headers", "set custom HTTP headers, can override built in default headers", OFFSET(headers), AV_OPT_TYPE_STRING, { 0 }, 0, 0, D | E },
106  { "content_type", "set a specific content type for the POST messages", OFFSET(content_type), AV_OPT_TYPE_STRING, { 0 }, 0, 0, D | E },
107  { "user_agent", "override User-Agent header", OFFSET(user_agent), AV_OPT_TYPE_STRING, { .str = DEFAULT_USER_AGENT }, 0, 0, D },
108  { "user-agent", "override User-Agent header", OFFSET(user_agent), AV_OPT_TYPE_STRING, { .str = DEFAULT_USER_AGENT }, 0, 0, D },
109  { "multiple_requests", "use persistent connections", OFFSET(multiple_requests), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 1, D | E },
110  { "post_data", "set custom HTTP post data", OFFSET(post_data), AV_OPT_TYPE_BINARY, .flags = D | E },
111  { "mime_type", "export the MIME type", OFFSET(mime_type), AV_OPT_TYPE_STRING, { 0 }, 0, 0, AV_OPT_FLAG_EXPORT | AV_OPT_FLAG_READONLY },
112  { "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, D },
113  { "icy", "request ICY metadata", OFFSET(icy), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 1, D },
114  { "icy_metadata_headers", "return ICY metadata headers", OFFSET(icy_metadata_headers), AV_OPT_TYPE_STRING, { 0 }, 0, 0, AV_OPT_FLAG_EXPORT },
115  { "icy_metadata_packet", "return current ICY metadata packet", OFFSET(icy_metadata_packet), AV_OPT_TYPE_STRING, { 0 }, 0, 0, AV_OPT_FLAG_EXPORT },
116  { "auth_type", "HTTP authentication type", OFFSET(auth_state.auth_type), AV_OPT_TYPE_INT, { .i64 = HTTP_AUTH_NONE }, HTTP_AUTH_NONE, HTTP_AUTH_BASIC, D | E, "auth_type"},
117  { "none", "No auth method set, autodetect", 0, AV_OPT_TYPE_CONST, { .i64 = HTTP_AUTH_NONE }, 0, 0, D | E, "auth_type"},
118  { "basic", "HTTP basic authentication", 0, AV_OPT_TYPE_CONST, { .i64 = HTTP_AUTH_BASIC }, 0, 0, D | E, "auth_type"},
119  { "send_expect_100", "Force sending an Expect: 100-continue header for POST", OFFSET(send_expect_100), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 1, E },
120  { "location", "The actual location of the data received", OFFSET(location), AV_OPT_TYPE_STRING, { 0 }, 0, 0, D | E },
121  { "offset", "initial byte offset", OFFSET(off), AV_OPT_TYPE_INT64, { .i64 = 0 }, 0, INT64_MAX, D },
122  { "end_offset", "try to limit the request to bytes preceding this offset", OFFSET(end_off), AV_OPT_TYPE_INT64, { .i64 = 0 }, 0, INT64_MAX, D },
123  { "method", "Override the HTTP method", OFFSET(method), AV_OPT_TYPE_STRING, { .str = NULL }, 0, 0, E },
124  { NULL }
125 };
126 
127 static int http_connect(URLContext *h, const char *path, const char *local_path,
128  const char *hoststr, const char *auth,
129  const char *proxyauth, int *new_location);
130 
132 {
133  memcpy(&((HTTPContext *)dest->priv_data)->auth_state,
134  &((HTTPContext *)src->priv_data)->auth_state,
135  sizeof(HTTPAuthState));
136  memcpy(&((HTTPContext *)dest->priv_data)->proxy_auth_state,
137  &((HTTPContext *)src->priv_data)->proxy_auth_state,
138  sizeof(HTTPAuthState));
139 }
140 
141 /* return non zero if error */
142 static int http_open_cnx(URLContext *h, AVDictionary **options)
143 {
144  const char *path, *proxy_path, *lower_proto = "tcp", *local_path;
145  char hostname[1024], hoststr[1024], proto[10];
146  char auth[1024], proxyauth[1024] = "";
147  char path1[MAX_URL_SIZE];
148  char buf[1024], urlbuf[MAX_URL_SIZE];
149  int port, use_proxy, err, location_changed = 0, redirects = 0, attempts = 0;
150  HTTPAuthType cur_auth_type, cur_proxy_auth_type;
151  HTTPContext *s = h->priv_data;
152 
153  /* fill the dest addr */
154 redo:
155  /* needed in any case to build the host string */
156  av_url_split(proto, sizeof(proto), auth, sizeof(auth),
157  hostname, sizeof(hostname), &port,
158  path1, sizeof(path1), s->location);
159  ff_url_join(hoststr, sizeof(hoststr), NULL, NULL, hostname, port, NULL);
160 
161  proxy_path = getenv("http_proxy");
162  use_proxy = !ff_http_match_no_proxy(getenv("no_proxy"), hostname) &&
163  proxy_path != NULL && av_strstart(proxy_path, "http://", NULL);
164 
165  if (!strcmp(proto, "https")) {
166  lower_proto = "tls";
167  use_proxy = 0;
168  if (port < 0)
169  port = 443;
170  }
171  if (port < 0)
172  port = 80;
173 
174  if (path1[0] == '\0')
175  path = "/";
176  else
177  path = path1;
178  local_path = path;
179  if (use_proxy) {
180  /* Reassemble the request URL without auth string - we don't
181  * want to leak the auth to the proxy. */
182  ff_url_join(urlbuf, sizeof(urlbuf), proto, NULL, hostname, port, "%s",
183  path1);
184  path = urlbuf;
185  av_url_split(NULL, 0, proxyauth, sizeof(proxyauth),
186  hostname, sizeof(hostname), &port, NULL, 0, proxy_path);
187  }
188 
189  ff_url_join(buf, sizeof(buf), lower_proto, NULL, hostname, port, NULL);
190 
191  if (!s->hd) {
192  err = ffurl_open(&s->hd, buf, AVIO_FLAG_READ_WRITE,
193  &h->interrupt_callback, options);
194  if (err < 0)
195  goto fail;
196  }
197 
198  cur_auth_type = s->auth_state.auth_type;
199  cur_proxy_auth_type = s->auth_state.auth_type;
200  if (http_connect(h, path, local_path, hoststr,
201  auth, proxyauth, &location_changed) < 0)
202  goto fail;
203  attempts++;
204  if (s->http_code == 401) {
205  if ((cur_auth_type == HTTP_AUTH_NONE || s->auth_state.stale) &&
206  s->auth_state.auth_type != HTTP_AUTH_NONE && attempts < 4) {
207  ffurl_closep(&s->hd);
208  goto redo;
209  } else
210  goto fail;
211  }
212  if (s->http_code == 407) {
213  if ((cur_proxy_auth_type == HTTP_AUTH_NONE || s->proxy_auth_state.stale) &&
214  s->proxy_auth_state.auth_type != HTTP_AUTH_NONE && attempts < 4) {
215  ffurl_closep(&s->hd);
216  goto redo;
217  } else
218  goto fail;
219  }
220  if ((s->http_code == 301 || s->http_code == 302 ||
221  s->http_code == 303 || s->http_code == 307) &&
222  location_changed == 1) {
223  /* url moved, get next */
224  ffurl_closep(&s->hd);
225  if (redirects++ >= MAX_REDIRECTS)
226  return AVERROR(EIO);
227  /* Restart the authentication process with the new target, which
228  * might use a different auth mechanism. */
229  memset(&s->auth_state, 0, sizeof(s->auth_state));
230  attempts = 0;
231  location_changed = 0;
232  goto redo;
233  }
234  return 0;
235 
236 fail:
237  if (s->hd)
238  ffurl_closep(&s->hd);
239  return AVERROR(EIO);
240 }
241 
242 int ff_http_do_new_request(URLContext *h, const char *uri)
243 {
244  HTTPContext *s = h->priv_data;
245  AVDictionary *options = NULL;
246  int ret;
247 
248  s->off = 0;
249  s->icy_data_read = 0;
250  av_free(s->location);
251  s->location = av_strdup(uri);
252  if (!s->location)
253  return AVERROR(ENOMEM);
254 
255  av_dict_copy(&options, s->chained_options, 0);
256  ret = http_open_cnx(h, &options);
257  av_dict_free(&options);
258  return ret;
259 }
260 
261 static int http_open(URLContext *h, const char *uri, int flags,
262  AVDictionary **options)
263 {
264  HTTPContext *s = h->priv_data;
265  int ret;
266 
267  if( s->seekable == 1 )
268  h->is_streamed = 0;
269  else
270  h->is_streamed = 1;
271 
272  s->filesize = -1;
273  s->location = av_strdup(uri);
274  if (!s->location)
275  return AVERROR(ENOMEM);
276  if (options)
277  av_dict_copy(&s->chained_options, *options, 0);
278 
279  if (s->headers) {
280  int len = strlen(s->headers);
281  if (len < 2 || strcmp("\r\n", s->headers + len - 2))
283  "No trailing CRLF found in HTTP header.\n");
284  }
285 
286  ret = http_open_cnx(h, options);
287  if (ret < 0)
289  return ret;
290 }
291 
292 static int http_getc(HTTPContext *s)
293 {
294  int len;
295  if (s->buf_ptr >= s->buf_end) {
296  len = ffurl_read(s->hd, s->buffer, BUFFER_SIZE);
297  if (len < 0) {
298  return len;
299  } else if (len == 0) {
300  return AVERROR_EOF;
301  } else {
302  s->buf_ptr = s->buffer;
303  s->buf_end = s->buffer + len;
304  }
305  }
306  return *s->buf_ptr++;
307 }
308 
309 static int http_get_line(HTTPContext *s, char *line, int line_size)
310 {
311  int ch;
312  char *q;
313 
314  q = line;
315  for (;;) {
316  ch = http_getc(s);
317  if (ch < 0)
318  return ch;
319  if (ch == '\n') {
320  /* process line */
321  if (q > line && q[-1] == '\r')
322  q--;
323  *q = '\0';
324 
325  return 0;
326  } else {
327  if ((q - line) < line_size - 1)
328  *q++ = ch;
329  }
330  }
331 }
332 
333 static int check_http_code(URLContext *h, int http_code, const char *end)
334 {
335  HTTPContext *s = h->priv_data;
336  /* error codes are 4xx and 5xx, but regard 401 as a success, so we
337  * don't abort until all headers have been parsed. */
338  if (http_code >= 400 && http_code < 600 &&
339  (http_code != 401 || s->auth_state.auth_type != HTTP_AUTH_NONE) &&
340  (http_code != 407 || s->proxy_auth_state.auth_type != HTTP_AUTH_NONE)) {
341  end += strspn(end, SPACE_CHARS);
342  av_log(h, AV_LOG_WARNING, "HTTP error %d %s\n", http_code, end);
343  return AVERROR(EIO);
344  }
345  return 0;
346 }
347 
348 static int parse_location(HTTPContext *s, const char *p)
349 {
350  char redirected_location[MAX_URL_SIZE], *new_loc;
351  ff_make_absolute_url(redirected_location, sizeof(redirected_location),
352  s->location, p);
353  new_loc = av_strdup(redirected_location);
354  if (!new_loc)
355  return AVERROR(ENOMEM);
356  av_free(s->location);
357  s->location = new_loc;
358  return 0;
359 }
360 
361 /* "bytes $from-$to/$document_size" */
362 static void parse_content_range(URLContext *h, const char *p)
363 {
364  HTTPContext *s = h->priv_data;
365  const char *slash;
366 
367  if (!strncmp(p, "bytes ", 6)) {
368  p += 6;
369  s->off = strtoll(p, NULL, 10);
370  if ((slash = strchr(p, '/')) && strlen(slash) > 0)
371  s->filesize = strtoll(slash + 1, NULL, 10);
372  }
373  if (s->seekable == -1 && (!s->is_akamai || s->filesize != 2147483647))
374  h->is_streamed = 0; /* we _can_ in fact seek */
375 }
376 
377 static int parse_content_encoding(URLContext *h, const char *p)
378 {
379  HTTPContext *s = h->priv_data;
380 
381  if (!av_strncasecmp(p, "gzip", 4) ||
382  !av_strncasecmp(p, "deflate", 7)) {
383 #if CONFIG_ZLIB
384  s->compressed = 1;
385  inflateEnd(&s->inflate_stream);
386  if (inflateInit2(&s->inflate_stream, 32 + 15) != Z_OK) {
387  av_log(h, AV_LOG_WARNING, "Error during zlib initialisation: %s\n",
388  s->inflate_stream.msg);
389  return AVERROR(ENOSYS);
390  }
391  if (zlibCompileFlags() & (1 << 17)) {
393  "Your zlib was compiled without gzip support.\n");
394  return AVERROR(ENOSYS);
395  }
396 #else
398  "Compressed (%s) content, need zlib with gzip support\n", p);
399  return AVERROR(ENOSYS);
400 #endif /* CONFIG_ZLIB */
401  } else if (!av_strncasecmp(p, "identity", 8)) {
402  // The normal, no-encoding case (although servers shouldn't include
403  // the header at all if this is the case).
404  } else {
405  av_log(h, AV_LOG_WARNING, "Unknown content coding: %s\n", p);
406  }
407  return 0;
408 }
409 
410 // Concat all Icy- header lines
411 static int parse_icy(HTTPContext *s, const char *tag, const char *p)
412 {
413  int len = 4 + strlen(p) + strlen(tag);
414  int is_first = !s->icy_metadata_headers;
415  int ret;
416 
417  if (s->icy_metadata_headers)
418  len += strlen(s->icy_metadata_headers);
419 
420  if ((ret = av_reallocp(&s->icy_metadata_headers, len)) < 0)
421  return ret;
422 
423  if (is_first)
424  *s->icy_metadata_headers = '\0';
425 
426  av_strlcatf(s->icy_metadata_headers, len, "%s: %s\n", tag, p);
427 
428  return 0;
429 }
430 
431 static int process_line(URLContext *h, char *line, int line_count,
432  int *new_location)
433 {
434  HTTPContext *s = h->priv_data;
435  char *tag, *p, *end;
436  int ret;
437 
438  /* end of header */
439  if (line[0] == '\0') {
440  s->end_header = 1;
441  return 0;
442  }
443 
444  p = line;
445  if (line_count == 0) {
446  while (!av_isspace(*p) && *p != '\0')
447  p++;
448  while (av_isspace(*p))
449  p++;
450  s->http_code = strtol(p, &end, 10);
451 
452  av_log(h, AV_LOG_DEBUG, "http_code=%d\n", s->http_code);
453 
454  if ((ret = check_http_code(h, s->http_code, end)) < 0)
455  return ret;
456  } else {
457  while (*p != '\0' && *p != ':')
458  p++;
459  if (*p != ':')
460  return 1;
461 
462  *p = '\0';
463  tag = line;
464  p++;
465  while (av_isspace(*p))
466  p++;
467  if (!av_strcasecmp(tag, "Location")) {
468  if ((ret = parse_location(s, p)) < 0)
469  return ret;
470  *new_location = 1;
471  } else if (!av_strcasecmp(tag, "Content-Length") && s->filesize == -1) {
472  s->filesize = strtoll(p, NULL, 10);
473  } else if (!av_strcasecmp(tag, "Content-Range")) {
474  parse_content_range(h, p);
475  } else if (!av_strcasecmp(tag, "Accept-Ranges") &&
476  !strncmp(p, "bytes", 5) &&
477  s->seekable == -1) {
478  h->is_streamed = 0;
479  } else if (!av_strcasecmp(tag, "Transfer-Encoding") &&
480  !av_strncasecmp(p, "chunked", 7)) {
481  s->filesize = -1;
482  s->chunksize = 0;
483  } else if (!av_strcasecmp(tag, "WWW-Authenticate")) {
485  } else if (!av_strcasecmp(tag, "Authentication-Info")) {
487  } else if (!av_strcasecmp(tag, "Proxy-Authenticate")) {
489  } else if (!av_strcasecmp(tag, "Connection")) {
490  if (!strcmp(p, "close"))
491  s->willclose = 1;
492  } else if (!av_strcasecmp(tag, "Server")) {
493  if (!av_strcasecmp(p, "AkamaiGHost")) {
494  s->is_akamai = 1;
495  } else if (!av_strncasecmp(p, "MediaGateway", 12)) {
496  s->is_mediagateway = 1;
497  }
498  } else if (!av_strcasecmp(tag, "Content-Type")) {
499  av_free(s->mime_type);
500  s->mime_type = av_strdup(p);
501  } else if (!av_strcasecmp(tag, "Set-Cookie")) {
502  if (!s->cookies) {
503  if (!(s->cookies = av_strdup(p)))
504  return AVERROR(ENOMEM);
505  } else {
506  char *tmp = s->cookies;
507  size_t str_size = strlen(tmp) + strlen(p) + 2;
508  if (!(s->cookies = av_malloc(str_size))) {
509  s->cookies = tmp;
510  return AVERROR(ENOMEM);
511  }
512  snprintf(s->cookies, str_size, "%s\n%s", tmp, p);
513  av_free(tmp);
514  }
515  } else if (!av_strcasecmp(tag, "Icy-MetaInt")) {
516  s->icy_metaint = strtoll(p, NULL, 10);
517  } else if (!av_strncasecmp(tag, "Icy-", 4)) {
518  if ((ret = parse_icy(s, tag, p)) < 0)
519  return ret;
520  } else if (!av_strcasecmp(tag, "Content-Encoding")) {
521  if ((ret = parse_content_encoding(h, p)) < 0)
522  return ret;
523  }
524  }
525  return 1;
526 }
527 
528 /**
529  * Create a string containing cookie values for use as a HTTP cookie header
530  * field value for a particular path and domain from the cookie values stored in
531  * the HTTP protocol context. The cookie string is stored in *cookies.
532  *
533  * @return a negative value if an error condition occurred, 0 otherwise
534  */
535 static int get_cookies(HTTPContext *s, char **cookies, const char *path,
536  const char *domain)
537 {
538  // cookie strings will look like Set-Cookie header field values. Multiple
539  // Set-Cookie fields will result in multiple values delimited by a newline
540  int ret = 0;
541  char *next, *cookie, *set_cookies = av_strdup(s->cookies), *cset_cookies = set_cookies;
542 
543  if (!set_cookies) return AVERROR(EINVAL);
544 
545  *cookies = NULL;
546  while ((cookie = av_strtok(set_cookies, "\n", &next))) {
547  int domain_offset = 0;
548  char *param, *next_param, *cdomain = NULL, *cpath = NULL, *cvalue = NULL;
549  set_cookies = NULL;
550 
551  while ((param = av_strtok(cookie, "; ", &next_param))) {
552  cookie = NULL;
553  if (!av_strncasecmp("path=", param, 5)) {
554  av_free(cpath);
555  cpath = av_strdup(&param[5]);
556  } else if (!av_strncasecmp("domain=", param, 7)) {
557  // if the cookie specifies a sub-domain, skip the leading dot thereby
558  // supporting URLs that point to sub-domains and the master domain
559  int leading_dot = (param[7] == '.');
560  av_free(cdomain);
561  cdomain = av_strdup(&param[7+leading_dot]);
562  } else if (!av_strncasecmp("secure", param, 6) ||
563  !av_strncasecmp("comment", param, 7) ||
564  !av_strncasecmp("max-age", param, 7) ||
565  !av_strncasecmp("version", param, 7)) {
566  // ignore Comment, Max-Age, Secure and Version
567  } else {
568  av_free(cvalue);
569  cvalue = av_strdup(param);
570  }
571  }
572  if (!cdomain)
573  cdomain = av_strdup(domain);
574 
575  // ensure all of the necessary values are valid
576  if (!cdomain || !cpath || !cvalue) {
578  "Invalid cookie found, no value, path or domain specified\n");
579  goto done_cookie;
580  }
581 
582  // check if the request path matches the cookie path
583  if (av_strncasecmp(path, cpath, strlen(cpath)))
584  goto done_cookie;
585 
586  // the domain should be at least the size of our cookie domain
587  domain_offset = strlen(domain) - strlen(cdomain);
588  if (domain_offset < 0)
589  goto done_cookie;
590 
591  // match the cookie domain
592  if (av_strcasecmp(&domain[domain_offset], cdomain))
593  goto done_cookie;
594 
595  // cookie parameters match, so copy the value
596  if (!*cookies) {
597  if (!(*cookies = av_strdup(cvalue))) {
598  ret = AVERROR(ENOMEM);
599  goto done_cookie;
600  }
601  } else {
602  char *tmp = *cookies;
603  size_t str_size = strlen(cvalue) + strlen(*cookies) + 3;
604  if (!(*cookies = av_malloc(str_size))) {
605  ret = AVERROR(ENOMEM);
606  goto done_cookie;
607  }
608  snprintf(*cookies, str_size, "%s; %s", tmp, cvalue);
609  av_free(tmp);
610  }
611 
612  done_cookie:
613  av_free(cdomain);
614  av_free(cpath);
615  av_free(cvalue);
616  if (ret < 0) {
617  if (*cookies) av_freep(cookies);
618  av_free(cset_cookies);
619  return ret;
620  }
621  }
622 
623  av_free(cset_cookies);
624 
625  return 0;
626 }
627 
628 static inline int has_header(const char *str, const char *header)
629 {
630  /* header + 2 to skip over CRLF prefix. (make sure you have one!) */
631  if (!str)
632  return 0;
633  return av_stristart(str, header + 2, NULL) || av_stristr(str, header);
634 }
635 
636 static int http_read_header(URLContext *h, int *new_location)
637 {
638  HTTPContext *s = h->priv_data;
639  char line[MAX_URL_SIZE];
640  int err = 0;
641 
642  s->chunksize = -1;
643 
644  for (;;) {
645  if ((err = http_get_line(s, line, sizeof(line))) < 0)
646  return err;
647 
648  av_log(h, AV_LOG_DEBUG, "header='%s'\n", line);
649 
650  err = process_line(h, line, s->line_count, new_location);
651  if (err < 0)
652  return err;
653  if (err == 0)
654  break;
655  s->line_count++;
656  }
657 
658  if (s->seekable == -1 && s->is_mediagateway && s->filesize == 2000000000)
659  h->is_streamed = 1; /* we can in fact _not_ seek */
660 
661  return err;
662 }
663 
664 static int http_connect(URLContext *h, const char *path, const char *local_path,
665  const char *hoststr, const char *auth,
666  const char *proxyauth, int *new_location)
667 {
668  HTTPContext *s = h->priv_data;
669  int post, err;
670  char headers[HTTP_HEADERS_SIZE] = "";
671  char *authstr = NULL, *proxyauthstr = NULL;
672  int64_t off = s->off;
673  int len = 0;
674  const char *method;
675  int send_expect_100 = 0;
676 
677  /* send http header */
678  post = h->flags & AVIO_FLAG_WRITE;
679 
680  if (s->post_data) {
681  /* force POST method and disable chunked encoding when
682  * custom HTTP post data is set */
683  post = 1;
684  s->chunked_post = 0;
685  }
686 
687  if (s->method)
688  method = s->method;
689  else
690  method = post ? "POST" : "GET";
691 
692  authstr = ff_http_auth_create_response(&s->auth_state, auth,
693  local_path, method);
694  proxyauthstr = ff_http_auth_create_response(&s->proxy_auth_state, proxyauth,
695  local_path, method);
696  if (post && !s->post_data) {
697  send_expect_100 = s->send_expect_100;
698  /* The user has supplied authentication but we don't know the auth type,
699  * send Expect: 100-continue to get the 401 response including the
700  * WWW-Authenticate header, or an 100 continue if no auth actually
701  * is needed. */
702  if (auth && *auth &&
704  s->http_code != 401)
705  send_expect_100 = 1;
706  }
707 
708  /* set default headers if needed */
709  if (!has_header(s->headers, "\r\nUser-Agent: "))
710  len += av_strlcatf(headers + len, sizeof(headers) - len,
711  "User-Agent: %s\r\n", s->user_agent);
712  if (!has_header(s->headers, "\r\nAccept: "))
713  len += av_strlcpy(headers + len, "Accept: */*\r\n",
714  sizeof(headers) - len);
715  // Note: we send this on purpose even when s->off is 0 when we're probing,
716  // since it allows us to detect more reliably if a (non-conforming)
717  // server supports seeking by analysing the reply headers.
718  if (!has_header(s->headers, "\r\nRange: ") && !post && (s->off > 0 || s->end_off || s->seekable == -1)) {
719  len += av_strlcatf(headers + len, sizeof(headers) - len,
720  "Range: bytes=%"PRId64"-", s->off);
721  if (s->end_off)
722  len += av_strlcatf(headers + len, sizeof(headers) - len,
723  "%"PRId64, s->end_off - 1);
724  len += av_strlcpy(headers + len, "\r\n",
725  sizeof(headers) - len);
726  }
727  if (send_expect_100 && !has_header(s->headers, "\r\nExpect: "))
728  len += av_strlcatf(headers + len, sizeof(headers) - len,
729  "Expect: 100-continue\r\n");
730 
731  if (!has_header(s->headers, "\r\nConnection: ")) {
732  if (s->multiple_requests)
733  len += av_strlcpy(headers + len, "Connection: keep-alive\r\n",
734  sizeof(headers) - len);
735  else
736  len += av_strlcpy(headers + len, "Connection: close\r\n",
737  sizeof(headers) - len);
738  }
739 
740  if (!has_header(s->headers, "\r\nHost: "))
741  len += av_strlcatf(headers + len, sizeof(headers) - len,
742  "Host: %s\r\n", hoststr);
743  if (!has_header(s->headers, "\r\nContent-Length: ") && s->post_data)
744  len += av_strlcatf(headers + len, sizeof(headers) - len,
745  "Content-Length: %d\r\n", s->post_datalen);
746 
747  if (!has_header(s->headers, "\r\nContent-Type: ") && s->content_type)
748  len += av_strlcatf(headers + len, sizeof(headers) - len,
749  "Content-Type: %s\r\n", s->content_type);
750  if (!has_header(s->headers, "\r\nCookie: ") && s->cookies) {
751  char *cookies = NULL;
752  if (!get_cookies(s, &cookies, path, hoststr) && cookies) {
753  len += av_strlcatf(headers + len, sizeof(headers) - len,
754  "Cookie: %s\r\n", cookies);
755  av_free(cookies);
756  }
757  }
758  if (!has_header(s->headers, "\r\nIcy-MetaData: ") && s->icy)
759  len += av_strlcatf(headers + len, sizeof(headers) - len,
760  "Icy-MetaData: %d\r\n", 1);
761 
762  /* now add in custom headers */
763  if (s->headers)
764  av_strlcpy(headers + len, s->headers, sizeof(headers) - len);
765 
766  snprintf(s->buffer, sizeof(s->buffer),
767  "%s %s HTTP/1.1\r\n"
768  "%s"
769  "%s"
770  "%s"
771  "%s%s"
772  "\r\n",
773  method,
774  path,
775  post && s->chunked_post ? "Transfer-Encoding: chunked\r\n" : "",
776  headers,
777  authstr ? authstr : "",
778  proxyauthstr ? "Proxy-" : "", proxyauthstr ? proxyauthstr : "");
779 
780  av_log(h, AV_LOG_DEBUG, "request: %s\n", s->buffer);
781 
782  if ((err = ffurl_write(s->hd, s->buffer, strlen(s->buffer))) < 0)
783  goto done;
784 
785  if (s->post_data)
786  if ((err = ffurl_write(s->hd, s->post_data, s->post_datalen)) < 0)
787  goto done;
788 
789  /* init input buffer */
790  s->buf_ptr = s->buffer;
791  s->buf_end = s->buffer;
792  s->line_count = 0;
793  s->off = 0;
794  s->icy_data_read = 0;
795  s->filesize = -1;
796  s->willclose = 0;
797  s->end_chunked_post = 0;
798  s->end_header = 0;
799  if (post && !s->post_data && !send_expect_100) {
800  /* Pretend that it did work. We didn't read any header yet, since
801  * we've still to send the POST data, but the code calling this
802  * function will check http_code after we return. */
803  s->http_code = 200;
804  err = 0;
805  goto done;
806  }
807 
808  /* wait for header */
809  err = http_read_header(h, new_location);
810  if (err < 0)
811  goto done;
812 
813  err = (off == s->off) ? 0 : -1;
814 done:
815  av_freep(&authstr);
816  av_freep(&proxyauthstr);
817  return err;
818 }
819 
820 static int http_buf_read(URLContext *h, uint8_t *buf, int size)
821 {
822  HTTPContext *s = h->priv_data;
823  int len;
824  /* read bytes from input buffer first */
825  len = s->buf_end - s->buf_ptr;
826  if (len > 0) {
827  if (len > size)
828  len = size;
829  memcpy(buf, s->buf_ptr, len);
830  s->buf_ptr += len;
831  } else {
832  if (!s->willclose && s->filesize >= 0 && s->off >= s->filesize)
833  return AVERROR_EOF;
834  len = ffurl_read(s->hd, buf, size);
835  }
836  if (len > 0) {
837  s->off += len;
838  if (s->chunksize > 0)
839  s->chunksize -= len;
840  }
841  return len;
842 }
843 
844 #if CONFIG_ZLIB
845 #define DECOMPRESS_BUF_SIZE (256 * 1024)
846 static int http_buf_read_compressed(URLContext *h, uint8_t *buf, int size)
847 {
848  HTTPContext *s = h->priv_data;
849  int ret;
850 
851  if (!s->inflate_buffer) {
852  s->inflate_buffer = av_malloc(DECOMPRESS_BUF_SIZE);
853  if (!s->inflate_buffer)
854  return AVERROR(ENOMEM);
855  }
856 
857  if (s->inflate_stream.avail_in == 0) {
858  int read = http_buf_read(h, s->inflate_buffer, DECOMPRESS_BUF_SIZE);
859  if (read <= 0)
860  return read;
861  s->inflate_stream.next_in = s->inflate_buffer;
862  s->inflate_stream.avail_in = read;
863  }
864 
865  s->inflate_stream.avail_out = size;
866  s->inflate_stream.next_out = buf;
867 
868  ret = inflate(&s->inflate_stream, Z_SYNC_FLUSH);
869  if (ret != Z_OK && ret != Z_STREAM_END)
870  av_log(h, AV_LOG_WARNING, "inflate return value: %d, %s\n",
871  ret, s->inflate_stream.msg);
872 
873  return size - s->inflate_stream.avail_out;
874 }
875 #endif /* CONFIG_ZLIB */
876 
877 static int http_read_stream(URLContext *h, uint8_t *buf, int size)
878 {
879  HTTPContext *s = h->priv_data;
880  int err, new_location;
881 
882  if (!s->hd)
883  return AVERROR_EOF;
884 
885  if (s->end_chunked_post && !s->end_header) {
886  err = http_read_header(h, &new_location);
887  if (err < 0)
888  return err;
889  }
890 
891  if (s->chunksize >= 0) {
892  if (!s->chunksize) {
893  char line[32];
894 
895  do {
896  if ((err = http_get_line(s, line, sizeof(line))) < 0)
897  return err;
898  } while (!*line); /* skip CR LF from last chunk */
899 
900  s->chunksize = strtoll(line, NULL, 16);
901 
902  av_dlog(NULL, "Chunked encoding data size: %"PRId64"'\n",
903  s->chunksize);
904 
905  if (!s->chunksize)
906  return 0;
907  }
908  size = FFMIN(size, s->chunksize);
909  }
910 #if CONFIG_ZLIB
911  if (s->compressed)
912  return http_buf_read_compressed(h, buf, size);
913 #endif /* CONFIG_ZLIB */
914  return http_buf_read(h, buf, size);
915 }
916 
917 // Like http_read_stream(), but no short reads.
918 // Assumes partial reads are an error.
919 static int http_read_stream_all(URLContext *h, uint8_t *buf, int size)
920 {
921  int pos = 0;
922  while (pos < size) {
923  int len = http_read_stream(h, buf + pos, size - pos);
924  if (len < 0)
925  return len;
926  pos += len;
927  }
928  return pos;
929 }
930 
931 static int store_icy(URLContext *h, int size)
932 {
933  HTTPContext *s = h->priv_data;
934  /* until next metadata packet */
935  int remaining = s->icy_metaint - s->icy_data_read;
936 
937  if (remaining < 0)
938  return AVERROR_INVALIDDATA;
939 
940  if (!remaining) {
941  /* The metadata packet is variable sized. It has a 1 byte header
942  * which sets the length of the packet (divided by 16). If it's 0,
943  * the metadata doesn't change. After the packet, icy_metaint bytes
944  * of normal data follows. */
945  uint8_t ch;
946  int len = http_read_stream_all(h, &ch, 1);
947  if (len < 0)
948  return len;
949  if (ch > 0) {
950  char data[255 * 16 + 1];
951  int ret;
952  len = ch * 16;
953  ret = http_read_stream_all(h, data, len);
954  if (ret < 0)
955  return ret;
956  data[len + 1] = 0;
957  if ((ret = av_opt_set(s, "icy_metadata_packet", data, 0)) < 0)
958  return ret;
959  }
960  s->icy_data_read = 0;
961  remaining = s->icy_metaint;
962  }
963 
964  return FFMIN(size, remaining);
965 }
966 
967 static int http_read(URLContext *h, uint8_t *buf, int size)
968 {
969  HTTPContext *s = h->priv_data;
970 
971  if (s->icy_metaint > 0) {
972  size = store_icy(h, size);
973  if (size < 0)
974  return size;
975  }
976 
977  size = http_read_stream(h, buf, size);
978  if (size > 0)
979  s->icy_data_read += size;
980  return size;
981 }
982 
983 /* used only when posting data */
984 static int http_write(URLContext *h, const uint8_t *buf, int size)
985 {
986  char temp[11] = ""; /* 32-bit hex + CRLF + nul */
987  int ret;
988  char crlf[] = "\r\n";
989  HTTPContext *s = h->priv_data;
990 
991  if (!s->chunked_post) {
992  /* non-chunked data is sent without any special encoding */
993  return ffurl_write(s->hd, buf, size);
994  }
995 
996  /* silently ignore zero-size data since chunk encoding that would
997  * signal EOF */
998  if (size > 0) {
999  /* upload data using chunked encoding */
1000  snprintf(temp, sizeof(temp), "%x\r\n", size);
1001 
1002  if ((ret = ffurl_write(s->hd, temp, strlen(temp))) < 0 ||
1003  (ret = ffurl_write(s->hd, buf, size)) < 0 ||
1004  (ret = ffurl_write(s->hd, crlf, sizeof(crlf) - 1)) < 0)
1005  return ret;
1006  }
1007  return size;
1008 }
1009 
1010 static int http_shutdown(URLContext *h, int flags)
1011 {
1012  int ret = 0;
1013  char footer[] = "0\r\n\r\n";
1014  HTTPContext *s = h->priv_data;
1015 
1016  /* signal end of chunked encoding if used */
1017  if ((flags & AVIO_FLAG_WRITE) && s->chunked_post) {
1018  ret = ffurl_write(s->hd, footer, sizeof(footer) - 1);
1019  ret = ret > 0 ? 0 : ret;
1020  s->end_chunked_post = 1;
1021  }
1022 
1023  return ret;
1024 }
1025 
1026 static int http_close(URLContext *h)
1027 {
1028  int ret = 0;
1029  HTTPContext *s = h->priv_data;
1030 
1031 #if CONFIG_ZLIB
1032  inflateEnd(&s->inflate_stream);
1033  av_freep(&s->inflate_buffer);
1034 #endif /* CONFIG_ZLIB */
1035 
1036  if (!s->end_chunked_post)
1037  /* Close the write direction by sending the end of chunked encoding. */
1038  ret = http_shutdown(h, h->flags);
1039 
1040  if (s->hd)
1041  ffurl_closep(&s->hd);
1043  return ret;
1044 }
1045 
1046 static int64_t http_seek(URLContext *h, int64_t off, int whence)
1047 {
1048  HTTPContext *s = h->priv_data;
1049  URLContext *old_hd = s->hd;
1050  int64_t old_off = s->off;
1051  uint8_t old_buf[BUFFER_SIZE];
1052  int old_buf_size, ret;
1053  AVDictionary *options = NULL;
1054 
1055  if (whence == AVSEEK_SIZE)
1056  return s->filesize;
1057  else if ((whence == SEEK_CUR && off == 0) ||
1058  (whence == SEEK_SET && off == s->off))
1059  return s->off;
1060  else if ((s->filesize == -1 && whence == SEEK_END) || h->is_streamed)
1061  return AVERROR(ENOSYS);
1062 
1063  if (whence == SEEK_CUR)
1064  off += s->off;
1065  else if (whence == SEEK_END)
1066  off += s->filesize;
1067  else if (whence != SEEK_SET)
1068  return AVERROR(EINVAL);
1069  if (off < 0)
1070  return AVERROR(EINVAL);
1071  s->off = off;
1072 
1073  /* we save the old context in case the seek fails */
1074  old_buf_size = s->buf_end - s->buf_ptr;
1075  memcpy(old_buf, s->buf_ptr, old_buf_size);
1076  s->hd = NULL;
1077 
1078  /* if it fails, continue on old connection */
1079  av_dict_copy(&options, s->chained_options, 0);
1080  if ((ret = http_open_cnx(h, &options)) < 0) {
1081  av_dict_free(&options);
1082  memcpy(s->buffer, old_buf, old_buf_size);
1083  s->buf_ptr = s->buffer;
1084  s->buf_end = s->buffer + old_buf_size;
1085  s->hd = old_hd;
1086  s->off = old_off;
1087  return ret;
1088  }
1089  av_dict_free(&options);
1090  ffurl_close(old_hd);
1091  return off;
1092 }
1093 
1095 {
1096  HTTPContext *s = h->priv_data;
1097  return ffurl_get_file_handle(s->hd);
1098 }
1099 
1100 #define HTTP_CLASS(flavor) \
1101 static const AVClass flavor ## _context_class = { \
1102  .class_name = # flavor, \
1103  .item_name = av_default_item_name, \
1104  .option = options, \
1105  .version = LIBAVUTIL_VERSION_INT, \
1106 }
1107 
1108 #if CONFIG_HTTP_PROTOCOL
1109 HTTP_CLASS(http);
1110 
1111 URLProtocol ff_http_protocol = {
1112  .name = "http",
1113  .url_open2 = http_open,
1114  .url_read = http_read,
1115  .url_write = http_write,
1116  .url_seek = http_seek,
1117  .url_close = http_close,
1118  .url_get_file_handle = http_get_file_handle,
1119  .url_shutdown = http_shutdown,
1120  .priv_data_size = sizeof(HTTPContext),
1121  .priv_data_class = &http_context_class,
1123 };
1124 #endif /* CONFIG_HTTP_PROTOCOL */
1125 
1126 #if CONFIG_HTTPS_PROTOCOL
1127 HTTP_CLASS(https);
1128 
1129 URLProtocol ff_https_protocol = {
1130  .name = "https",
1131  .url_open2 = http_open,
1132  .url_read = http_read,
1133  .url_write = http_write,
1134  .url_seek = http_seek,
1135  .url_close = http_close,
1136  .url_get_file_handle = http_get_file_handle,
1137  .url_shutdown = http_shutdown,
1138  .priv_data_size = sizeof(HTTPContext),
1139  .priv_data_class = &https_context_class,
1141 };
1142 #endif /* CONFIG_HTTPS_PROTOCOL */
1143 
1144 #if CONFIG_HTTPPROXY_PROTOCOL
1145 static int http_proxy_close(URLContext *h)
1146 {
1147  HTTPContext *s = h->priv_data;
1148  if (s->hd)
1149  ffurl_closep(&s->hd);
1150  return 0;
1151 }
1152 
1153 static int http_proxy_open(URLContext *h, const char *uri, int flags)
1154 {
1155  HTTPContext *s = h->priv_data;
1156  char hostname[1024], hoststr[1024];
1157  char auth[1024], pathbuf[1024], *path;
1158  char lower_url[100];
1159  int port, ret = 0, attempts = 0;
1160  HTTPAuthType cur_auth_type;
1161  char *authstr;
1162  int new_loc;
1163 
1164  if( s->seekable == 1 )
1165  h->is_streamed = 0;
1166  else
1167  h->is_streamed = 1;
1168 
1169  av_url_split(NULL, 0, auth, sizeof(auth), hostname, sizeof(hostname), &port,
1170  pathbuf, sizeof(pathbuf), uri);
1171  ff_url_join(hoststr, sizeof(hoststr), NULL, NULL, hostname, port, NULL);
1172  path = pathbuf;
1173  if (*path == '/')
1174  path++;
1175 
1176  ff_url_join(lower_url, sizeof(lower_url), "tcp", NULL, hostname, port,
1177  NULL);
1178 redo:
1179  ret = ffurl_open(&s->hd, lower_url, AVIO_FLAG_READ_WRITE,
1180  &h->interrupt_callback, NULL);
1181  if (ret < 0)
1182  return ret;
1183 
1184  authstr = ff_http_auth_create_response(&s->proxy_auth_state, auth,
1185  path, "CONNECT");
1186  snprintf(s->buffer, sizeof(s->buffer),
1187  "CONNECT %s HTTP/1.1\r\n"
1188  "Host: %s\r\n"
1189  "Connection: close\r\n"
1190  "%s%s"
1191  "\r\n",
1192  path,
1193  hoststr,
1194  authstr ? "Proxy-" : "", authstr ? authstr : "");
1195  av_freep(&authstr);
1196 
1197  if ((ret = ffurl_write(s->hd, s->buffer, strlen(s->buffer))) < 0)
1198  goto fail;
1199 
1200  s->buf_ptr = s->buffer;
1201  s->buf_end = s->buffer;
1202  s->line_count = 0;
1203  s->filesize = -1;
1204  cur_auth_type = s->proxy_auth_state.auth_type;
1205 
1206  /* Note: This uses buffering, potentially reading more than the
1207  * HTTP header. If tunneling a protocol where the server starts
1208  * the conversation, we might buffer part of that here, too.
1209  * Reading that requires using the proper ffurl_read() function
1210  * on this URLContext, not using the fd directly (as the tls
1211  * protocol does). This shouldn't be an issue for tls though,
1212  * since the client starts the conversation there, so there
1213  * is no extra data that we might buffer up here.
1214  */
1215  ret = http_read_header(h, &new_loc);
1216  if (ret < 0)
1217  goto fail;
1218 
1219  attempts++;
1220  if (s->http_code == 407 &&
1221  (cur_auth_type == HTTP_AUTH_NONE || s->proxy_auth_state.stale) &&
1222  s->proxy_auth_state.auth_type != HTTP_AUTH_NONE && attempts < 2) {
1223  ffurl_closep(&s->hd);
1224  goto redo;
1225  }
1226 
1227  if (s->http_code < 400)
1228  return 0;
1229  ret = AVERROR(EIO);
1230 
1231 fail:
1232  http_proxy_close(h);
1233  return ret;
1234 }
1235 
1236 static int http_proxy_write(URLContext *h, const uint8_t *buf, int size)
1237 {
1238  HTTPContext *s = h->priv_data;
1239  return ffurl_write(s->hd, buf, size);
1240 }
1241 
1242 URLProtocol ff_httpproxy_protocol = {
1243  .name = "httpproxy",
1244  .url_open = http_proxy_open,
1245  .url_read = http_buf_read,
1246  .url_write = http_proxy_write,
1247  .url_close = http_proxy_close,
1248  .url_get_file_handle = http_get_file_handle,
1249  .priv_data_size = sizeof(HTTPContext),
1250  .flags = URL_PROTOCOL_FLAG_NETWORK,
1251 };
1252 #endif /* CONFIG_HTTPPROXY_PROTOCOL */