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