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/avassert.h"
29 #include "libavutil/avstring.h"
30 #include "libavutil/opt.h"
31 #include "libavutil/time.h"
32 #include "libavutil/parseutils.h"
33 
34 #include "avformat.h"
35 #include "http.h"
36 #include "httpauth.h"
37 #include "internal.h"
38 #include "network.h"
39 #include "os_support.h"
40 #include "url.h"
41 
42 /* XXX: POST protocol is not completely implemented because ffmpeg uses
43  * only a subset of it. */
44 
45 /* The IO buffer size is unrelated to the max URL size in itself, but needs
46  * to be large enough to fit the full request headers (including long
47  * path names). */
48 #define BUFFER_SIZE MAX_URL_SIZE
49 #define MAX_REDIRECTS 8
50 #define HTTP_SINGLE 1
51 #define HTTP_MUTLI 2
52 #define MAX_EXPIRY 19
53 #define WHITESPACES " \n\t\r"
54 typedef enum {
60 
61 typedef struct HTTPContext {
62  const AVClass *class;
64  unsigned char buffer[BUFFER_SIZE], *buf_ptr, *buf_end;
66  int http_code;
67  /* Used if "Transfer-Encoding: chunked" otherwise -1. */
68  uint64_t chunksize;
69  uint64_t off, end_off, filesize;
70  char *location;
73  char *http_proxy;
74  char *headers;
75  char *mime_type;
76  char *user_agent;
77 #if FF_API_HTTP_USER_AGENT
78  char *user_agent_deprecated;
79 #endif
80  char *content_type;
81  /* Set if the server correctly handles Connection: close and will close
82  * the connection after feeding us the content. */
83  int willclose;
84  int seekable; /**< Control seekability, 0 = disable, 1 = enable, -1 = probe. */
86  /* A flag which indicates if the end of chunked encoding has been sent. */
88  /* A flag which indicates we have finished to read POST reply. */
90  /* A flag which indicates if we use persistent connections. */
94  int is_akamai;
96  char *cookies; ///< holds newline (\n) delimited Set-Cookie header field values (without the "Set-Cookie: " field name)
97  /* A dictionary containing cookies keyed by cookie name */
99  int icy;
100  /* how much data was read since the last ICY metadata packet */
101  uint64_t icy_data_read;
102  /* after how many bytes of read data a new metadata packet will be found */
103  uint64_t icy_metaint;
107 #if CONFIG_ZLIB
108  int compressed;
109  z_stream inflate_stream;
110  uint8_t *inflate_buffer;
111 #endif /* CONFIG_ZLIB */
114  char *method;
120  int listen;
121  char *resource;
126 } HTTPContext;
127 
128 #define OFFSET(x) offsetof(HTTPContext, x)
129 #define D AV_OPT_FLAG_DECODING_PARAM
130 #define E AV_OPT_FLAG_ENCODING_PARAM
131 #define DEFAULT_USER_AGENT "Lavf/" AV_STRINGIFY(LIBAVFORMAT_VERSION)
132 
133 static const AVOption options[] = {
134  { "seekable", "control seekability of connection", OFFSET(seekable), AV_OPT_TYPE_BOOL, { .i64 = -1 }, -1, 1, D },
135  { "chunked_post", "use chunked transfer-encoding for posts", OFFSET(chunked_post), AV_OPT_TYPE_BOOL, { .i64 = 1 }, 0, 1, E },
136  { "http_proxy", "set HTTP proxy to tunnel through", OFFSET(http_proxy), AV_OPT_TYPE_STRING, { .str = NULL }, 0, 0, D | E },
137  { "headers", "set custom HTTP headers, can override built in default headers", OFFSET(headers), AV_OPT_TYPE_STRING, { .str = NULL }, 0, 0, D | E },
138  { "content_type", "set a specific content type for the POST messages", OFFSET(content_type), AV_OPT_TYPE_STRING, { .str = NULL }, 0, 0, D | E },
139  { "user_agent", "override User-Agent header", OFFSET(user_agent), AV_OPT_TYPE_STRING, { .str = DEFAULT_USER_AGENT }, 0, 0, D },
140 #if FF_API_HTTP_USER_AGENT
141  { "user-agent", "override User-Agent header", OFFSET(user_agent_deprecated), AV_OPT_TYPE_STRING, { .str = DEFAULT_USER_AGENT }, 0, 0, D },
142 #endif
143  { "multiple_requests", "use persistent connections", OFFSET(multiple_requests), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, D | E },
144  { "post_data", "set custom HTTP post data", OFFSET(post_data), AV_OPT_TYPE_BINARY, .flags = D | E },
145  { "mime_type", "export the MIME type", OFFSET(mime_type), AV_OPT_TYPE_STRING, { .str = NULL }, 0, 0, AV_OPT_FLAG_EXPORT | AV_OPT_FLAG_READONLY },
146  { "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, { .str = NULL }, 0, 0, D },
147  { "icy", "request ICY metadata", OFFSET(icy), AV_OPT_TYPE_BOOL, { .i64 = 1 }, 0, 1, D },
148  { "icy_metadata_headers", "return ICY metadata headers", OFFSET(icy_metadata_headers), AV_OPT_TYPE_STRING, { .str = NULL }, 0, 0, AV_OPT_FLAG_EXPORT },
149  { "icy_metadata_packet", "return current ICY metadata packet", OFFSET(icy_metadata_packet), AV_OPT_TYPE_STRING, { .str = NULL }, 0, 0, AV_OPT_FLAG_EXPORT },
150  { "metadata", "metadata read from the bitstream", OFFSET(metadata), AV_OPT_TYPE_DICT, {0}, 0, 0, AV_OPT_FLAG_EXPORT },
151  { "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"},
152  { "none", "No auth method set, autodetect", 0, AV_OPT_TYPE_CONST, { .i64 = HTTP_AUTH_NONE }, 0, 0, D | E, "auth_type"},
153  { "basic", "HTTP basic authentication", 0, AV_OPT_TYPE_CONST, { .i64 = HTTP_AUTH_BASIC }, 0, 0, D | E, "auth_type"},
154  { "send_expect_100", "Force sending an Expect: 100-continue header for POST", OFFSET(send_expect_100), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, E },
155  { "location", "The actual location of the data received", OFFSET(location), AV_OPT_TYPE_STRING, { .str = NULL }, 0, 0, D | E },
156  { "offset", "initial byte offset", OFFSET(off), AV_OPT_TYPE_INT64, { .i64 = 0 }, 0, INT64_MAX, D },
157  { "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 },
158  { "method", "Override the HTTP method or set the expected HTTP method from a client", OFFSET(method), AV_OPT_TYPE_STRING, { .str = NULL }, 0, 0, D | E },
159  { "reconnect", "auto reconnect after disconnect before EOF", OFFSET(reconnect), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, D },
160  { "reconnect_at_eof", "auto reconnect at EOF", OFFSET(reconnect_at_eof), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, D },
161  { "reconnect_streamed", "auto reconnect streamed / non seekable streams", OFFSET(reconnect_streamed), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, D },
162  { "reconnect_delay_max", "max reconnect delay in seconds after which to give up", OFFSET(reconnect_delay_max), AV_OPT_TYPE_INT, { .i64 = 120 }, 0, UINT_MAX/1000/1000, D },
163  { "listen", "listen on HTTP", OFFSET(listen), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 2, D | E },
164  { "resource", "The resource requested by a client", OFFSET(resource), AV_OPT_TYPE_STRING, { .str = NULL }, 0, 0, E },
165  { "reply_code", "The http status code to return to a client", OFFSET(reply_code), AV_OPT_TYPE_INT, { .i64 = 200}, INT_MIN, 599, E},
166  { NULL }
167 };
168 
169 static int http_connect(URLContext *h, const char *path, const char *local_path,
170  const char *hoststr, const char *auth,
171  const char *proxyauth, int *new_location);
172 static int http_read_header(URLContext *h, int *new_location);
173 
175 {
176  memcpy(&((HTTPContext *)dest->priv_data)->auth_state,
177  &((HTTPContext *)src->priv_data)->auth_state,
178  sizeof(HTTPAuthState));
179  memcpy(&((HTTPContext *)dest->priv_data)->proxy_auth_state,
180  &((HTTPContext *)src->priv_data)->proxy_auth_state,
181  sizeof(HTTPAuthState));
182 }
183 
185 {
186  const char *path, *proxy_path, *lower_proto = "tcp", *local_path;
187  char hostname[1024], hoststr[1024], proto[10];
188  char auth[1024], proxyauth[1024] = "";
189  char path1[MAX_URL_SIZE];
190  char buf[1024], urlbuf[MAX_URL_SIZE];
191  int port, use_proxy, err, location_changed = 0;
192  HTTPContext *s = h->priv_data;
193 
194  av_url_split(proto, sizeof(proto), auth, sizeof(auth),
195  hostname, sizeof(hostname), &port,
196  path1, sizeof(path1), s->location);
197  ff_url_join(hoststr, sizeof(hoststr), NULL, NULL, hostname, port, NULL);
198 
199  proxy_path = s->http_proxy ? s->http_proxy : getenv("http_proxy");
200  use_proxy = !ff_http_match_no_proxy(getenv("no_proxy"), hostname) &&
201  proxy_path && av_strstart(proxy_path, "http://", NULL);
202 
203  if (!strcmp(proto, "https")) {
204  lower_proto = "tls";
205  use_proxy = 0;
206  if (port < 0)
207  port = 443;
208  }
209  if (port < 0)
210  port = 80;
211 
212  if (path1[0] == '\0')
213  path = "/";
214  else
215  path = path1;
216  local_path = path;
217  if (use_proxy) {
218  /* Reassemble the request URL without auth string - we don't
219  * want to leak the auth to the proxy. */
220  ff_url_join(urlbuf, sizeof(urlbuf), proto, NULL, hostname, port, "%s",
221  path1);
222  path = urlbuf;
223  av_url_split(NULL, 0, proxyauth, sizeof(proxyauth),
224  hostname, sizeof(hostname), &port, NULL, 0, proxy_path);
225  }
226 
227  ff_url_join(buf, sizeof(buf), lower_proto, NULL, hostname, port, NULL);
228 
229  if (!s->hd) {
231  &h->interrupt_callback, options,
233  if (err < 0)
234  return err;
235  }
236 
237  err = http_connect(h, path, local_path, hoststr,
238  auth, proxyauth, &location_changed);
239  if (err < 0)
240  return err;
241 
242  return location_changed;
243 }
244 
245 /* return non zero if error */
246 static int http_open_cnx(URLContext *h, AVDictionary **options)
247 {
248  HTTPAuthType cur_auth_type, cur_proxy_auth_type;
249  HTTPContext *s = h->priv_data;
250  int location_changed, attempts = 0, redirects = 0;
251 redo:
252  av_dict_copy(options, s->chained_options, 0);
253 
254  cur_auth_type = s->auth_state.auth_type;
255  cur_proxy_auth_type = s->auth_state.auth_type;
256 
257  location_changed = http_open_cnx_internal(h, options);
258  if (location_changed < 0)
259  goto fail;
260 
261  attempts++;
262  if (s->http_code == 401) {
263  if ((cur_auth_type == HTTP_AUTH_NONE || s->auth_state.stale) &&
264  s->auth_state.auth_type != HTTP_AUTH_NONE && attempts < 4) {
265  ffurl_closep(&s->hd);
266  goto redo;
267  } else
268  goto fail;
269  }
270  if (s->http_code == 407) {
271  if ((cur_proxy_auth_type == HTTP_AUTH_NONE || s->proxy_auth_state.stale) &&
272  s->proxy_auth_state.auth_type != HTTP_AUTH_NONE && attempts < 4) {
273  ffurl_closep(&s->hd);
274  goto redo;
275  } else
276  goto fail;
277  }
278  if ((s->http_code == 301 || s->http_code == 302 ||
279  s->http_code == 303 || s->http_code == 307) &&
280  location_changed == 1) {
281  /* url moved, get next */
282  ffurl_closep(&s->hd);
283  if (redirects++ >= MAX_REDIRECTS)
284  return AVERROR(EIO);
285  /* Restart the authentication process with the new target, which
286  * might use a different auth mechanism. */
287  memset(&s->auth_state, 0, sizeof(s->auth_state));
288  attempts = 0;
289  location_changed = 0;
290  goto redo;
291  }
292  return 0;
293 
294 fail:
295  if (s->hd)
296  ffurl_closep(&s->hd);
297  if (location_changed < 0)
298  return location_changed;
299  return ff_http_averror(s->http_code, AVERROR(EIO));
300 }
301 
302 int ff_http_do_new_request(URLContext *h, const char *uri)
303 {
304  HTTPContext *s = h->priv_data;
305  AVDictionary *options = NULL;
306  int ret;
307 
308  s->off = 0;
309  s->icy_data_read = 0;
310  av_free(s->location);
311  s->location = av_strdup(uri);
312  if (!s->location)
313  return AVERROR(ENOMEM);
314 
315  ret = http_open_cnx(h, &options);
316  av_dict_free(&options);
317  return ret;
318 }
319 
320 int ff_http_averror(int status_code, int default_averror)
321 {
322  switch (status_code) {
323  case 400: return AVERROR_HTTP_BAD_REQUEST;
324  case 401: return AVERROR_HTTP_UNAUTHORIZED;
325  case 403: return AVERROR_HTTP_FORBIDDEN;
326  case 404: return AVERROR_HTTP_NOT_FOUND;
327  default: break;
328  }
329  if (status_code >= 400 && status_code <= 499)
330  return AVERROR_HTTP_OTHER_4XX;
331  else if (status_code >= 500)
333  else
334  return default_averror;
335 }
336 
337 static int http_write_reply(URLContext* h, int status_code)
338 {
339  int ret, body = 0, reply_code, message_len;
340  const char *reply_text, *content_type;
341  HTTPContext *s = h->priv_data;
342  char message[BUFFER_SIZE];
343  content_type = "text/plain";
344 
345  if (status_code < 0)
346  body = 1;
347  switch (status_code) {
349  case 400:
350  reply_code = 400;
351  reply_text = "Bad Request";
352  break;
354  case 403:
355  reply_code = 403;
356  reply_text = "Forbidden";
357  break;
359  case 404:
360  reply_code = 404;
361  reply_text = "Not Found";
362  break;
363  case 200:
364  reply_code = 200;
365  reply_text = "OK";
366  content_type = s->content_type ? s->content_type : "application/octet-stream";
367  break;
369  case 500:
370  reply_code = 500;
371  reply_text = "Internal server error";
372  break;
373  default:
374  return AVERROR(EINVAL);
375  }
376  if (body) {
377  s->chunked_post = 0;
378  message_len = snprintf(message, sizeof(message),
379  "HTTP/1.1 %03d %s\r\n"
380  "Content-Type: %s\r\n"
381  "Content-Length: %"SIZE_SPECIFIER"\r\n"
382  "%s"
383  "\r\n"
384  "%03d %s\r\n",
385  reply_code,
386  reply_text,
387  content_type,
388  strlen(reply_text) + 6, // 3 digit status code + space + \r\n
389  s->headers ? s->headers : "",
390  reply_code,
391  reply_text);
392  } else {
393  s->chunked_post = 1;
394  message_len = snprintf(message, sizeof(message),
395  "HTTP/1.1 %03d %s\r\n"
396  "Content-Type: %s\r\n"
397  "Transfer-Encoding: chunked\r\n"
398  "%s"
399  "\r\n",
400  reply_code,
401  reply_text,
402  content_type,
403  s->headers ? s->headers : "");
404  }
405  av_log(h, AV_LOG_TRACE, "HTTP reply header: \n%s----\n", message);
406  if ((ret = ffurl_write(s->hd, message, message_len)) < 0)
407  return ret;
408  return 0;
409 }
410 
412 {
413  av_assert0(error < 0);
414  http_write_reply(h, error);
415 }
416 
418 {
419  int ret, err, new_location;
420  HTTPContext *ch = c->priv_data;
421  URLContext *cl = ch->hd;
422  switch (ch->handshake_step) {
423  case LOWER_PROTO:
424  av_log(c, AV_LOG_TRACE, "Lower protocol\n");
425  if ((ret = ffurl_handshake(cl)) > 0)
426  return 2 + ret;
427  if (ret < 0)
428  return ret;
430  ch->is_connected_server = 1;
431  return 2;
432  case READ_HEADERS:
433  av_log(c, AV_LOG_TRACE, "Read headers\n");
434  if ((err = http_read_header(c, &new_location)) < 0) {
435  handle_http_errors(c, err);
436  return err;
437  }
439  return 1;
440  case WRITE_REPLY_HEADERS:
441  av_log(c, AV_LOG_TRACE, "Reply code: %d\n", ch->reply_code);
442  if ((err = http_write_reply(c, ch->reply_code)) < 0)
443  return err;
444  ch->handshake_step = FINISH;
445  return 1;
446  case FINISH:
447  return 0;
448  }
449  // this should never be reached.
450  return AVERROR(EINVAL);
451 }
452 
453 static int http_listen(URLContext *h, const char *uri, int flags,
454  AVDictionary **options) {
455  HTTPContext *s = h->priv_data;
456  int ret;
457  char hostname[1024], proto[10];
458  char lower_url[100];
459  const char *lower_proto = "tcp";
460  int port;
461  av_url_split(proto, sizeof(proto), NULL, 0, hostname, sizeof(hostname), &port,
462  NULL, 0, uri);
463  if (!strcmp(proto, "https"))
464  lower_proto = "tls";
465  ff_url_join(lower_url, sizeof(lower_url), lower_proto, NULL, hostname, port,
466  NULL);
467  if ((ret = av_dict_set_int(options, "listen", s->listen, 0)) < 0)
468  goto fail;
469  if ((ret = ffurl_open_whitelist(&s->hd, lower_url, AVIO_FLAG_READ_WRITE,
470  &h->interrupt_callback, options,
472  )) < 0)
473  goto fail;
475  if (s->listen == HTTP_SINGLE) { /* single client */
476  s->reply_code = 200;
477  while ((ret = http_handshake(h)) > 0);
478  }
479 fail:
481  return ret;
482 }
483 
484 static int http_open(URLContext *h, const char *uri, int flags,
485  AVDictionary **options)
486 {
487  HTTPContext *s = h->priv_data;
488  int ret;
489 
490  if( s->seekable == 1 )
491  h->is_streamed = 0;
492  else
493  h->is_streamed = 1;
494 
495  s->filesize = UINT64_MAX;
496  s->location = av_strdup(uri);
497  if (!s->location)
498  return AVERROR(ENOMEM);
499  if (options)
500  av_dict_copy(&s->chained_options, *options, 0);
501 
502  if (s->headers) {
503  int len = strlen(s->headers);
504  if (len < 2 || strcmp("\r\n", s->headers + len - 2)) {
506  "No trailing CRLF found in HTTP header.\n");
507  ret = av_reallocp(&s->headers, len + 3);
508  if (ret < 0)
509  return ret;
510  s->headers[len] = '\r';
511  s->headers[len + 1] = '\n';
512  s->headers[len + 2] = '\0';
513  }
514  }
515 
516  if (s->listen) {
517  return http_listen(h, uri, flags, options);
518  }
519  ret = http_open_cnx(h, options);
520  if (ret < 0)
522  return ret;
523 }
524 
526 {
527  int ret;
528  HTTPContext *sc = s->priv_data;
529  HTTPContext *cc;
530  URLContext *sl = sc->hd;
531  URLContext *cl = NULL;
532 
533  av_assert0(sc->listen);
534  if ((ret = ffurl_alloc(c, s->filename, s->flags, &sl->interrupt_callback)) < 0)
535  goto fail;
536  cc = (*c)->priv_data;
537  if ((ret = ffurl_accept(sl, &cl)) < 0)
538  goto fail;
539  cc->hd = cl;
540  cc->is_multi_client = 1;
541 fail:
542  return ret;
543 }
544 
545 static int http_getc(HTTPContext *s)
546 {
547  int len;
548  if (s->buf_ptr >= s->buf_end) {
549  len = ffurl_read(s->hd, s->buffer, BUFFER_SIZE);
550  if (len < 0) {
551  return len;
552  } else if (len == 0) {
553  return AVERROR_EOF;
554  } else {
555  s->buf_ptr = s->buffer;
556  s->buf_end = s->buffer + len;
557  }
558  }
559  return *s->buf_ptr++;
560 }
561 
562 static int http_get_line(HTTPContext *s, char *line, int line_size)
563 {
564  int ch;
565  char *q;
566 
567  q = line;
568  for (;;) {
569  ch = http_getc(s);
570  if (ch < 0)
571  return ch;
572  if (ch == '\n') {
573  /* process line */
574  if (q > line && q[-1] == '\r')
575  q--;
576  *q = '\0';
577 
578  return 0;
579  } else {
580  if ((q - line) < line_size - 1)
581  *q++ = ch;
582  }
583  }
584 }
585 
586 static int check_http_code(URLContext *h, int http_code, const char *end)
587 {
588  HTTPContext *s = h->priv_data;
589  /* error codes are 4xx and 5xx, but regard 401 as a success, so we
590  * don't abort until all headers have been parsed. */
591  if (http_code >= 400 && http_code < 600 &&
592  (http_code != 401 || s->auth_state.auth_type != HTTP_AUTH_NONE) &&
593  (http_code != 407 || s->proxy_auth_state.auth_type != HTTP_AUTH_NONE)) {
594  end += strspn(end, SPACE_CHARS);
595  av_log(h, AV_LOG_WARNING, "HTTP error %d %s\n", http_code, end);
596  return ff_http_averror(http_code, AVERROR(EIO));
597  }
598  return 0;
599 }
600 
601 static int parse_location(HTTPContext *s, const char *p)
602 {
603  char redirected_location[MAX_URL_SIZE], *new_loc;
604  ff_make_absolute_url(redirected_location, sizeof(redirected_location),
605  s->location, p);
606  new_loc = av_strdup(redirected_location);
607  if (!new_loc)
608  return AVERROR(ENOMEM);
609  av_free(s->location);
610  s->location = new_loc;
611  return 0;
612 }
613 
614 /* "bytes $from-$to/$document_size" */
615 static void parse_content_range(URLContext *h, const char *p)
616 {
617  HTTPContext *s = h->priv_data;
618  const char *slash;
619 
620  if (!strncmp(p, "bytes ", 6)) {
621  p += 6;
622  s->off = strtoull(p, NULL, 10);
623  if ((slash = strchr(p, '/')) && strlen(slash) > 0)
624  s->filesize = strtoull(slash + 1, NULL, 10);
625  }
626  if (s->seekable == -1 && (!s->is_akamai || s->filesize != 2147483647))
627  h->is_streamed = 0; /* we _can_ in fact seek */
628 }
629 
630 static int parse_content_encoding(URLContext *h, const char *p)
631 {
632  if (!av_strncasecmp(p, "gzip", 4) ||
633  !av_strncasecmp(p, "deflate", 7)) {
634 #if CONFIG_ZLIB
635  HTTPContext *s = h->priv_data;
636 
637  s->compressed = 1;
638  inflateEnd(&s->inflate_stream);
639  if (inflateInit2(&s->inflate_stream, 32 + 15) != Z_OK) {
640  av_log(h, AV_LOG_WARNING, "Error during zlib initialisation: %s\n",
641  s->inflate_stream.msg);
642  return AVERROR(ENOSYS);
643  }
644  if (zlibCompileFlags() & (1 << 17)) {
646  "Your zlib was compiled without gzip support.\n");
647  return AVERROR(ENOSYS);
648  }
649 #else
651  "Compressed (%s) content, need zlib with gzip support\n", p);
652  return AVERROR(ENOSYS);
653 #endif /* CONFIG_ZLIB */
654  } else if (!av_strncasecmp(p, "identity", 8)) {
655  // The normal, no-encoding case (although servers shouldn't include
656  // the header at all if this is the case).
657  } else {
658  av_log(h, AV_LOG_WARNING, "Unknown content coding: %s\n", p);
659  }
660  return 0;
661 }
662 
663 // Concat all Icy- header lines
664 static int parse_icy(HTTPContext *s, const char *tag, const char *p)
665 {
666  int len = 4 + strlen(p) + strlen(tag);
667  int is_first = !s->icy_metadata_headers;
668  int ret;
669 
670  av_dict_set(&s->metadata, tag, p, 0);
671 
672  if (s->icy_metadata_headers)
673  len += strlen(s->icy_metadata_headers);
674 
675  if ((ret = av_reallocp(&s->icy_metadata_headers, len)) < 0)
676  return ret;
677 
678  if (is_first)
679  *s->icy_metadata_headers = '\0';
680 
681  av_strlcatf(s->icy_metadata_headers, len, "%s: %s\n", tag, p);
682 
683  return 0;
684 }
685 
686 static int parse_set_cookie_expiry_time(const char *exp_str, struct tm *buf)
687 {
688  char exp_buf[MAX_EXPIRY];
689  int i, j, exp_buf_len = MAX_EXPIRY-1;
690  char *expiry;
691 
692  // strip off any punctuation or whitespace
693  for (i = 0, j = 0; exp_str[i] != '\0' && j < exp_buf_len; i++) {
694  if ((exp_str[i] >= '0' && exp_str[i] <= '9') ||
695  (exp_str[i] >= 'A' && exp_str[i] <= 'Z') ||
696  (exp_str[i] >= 'a' && exp_str[i] <= 'z')) {
697  exp_buf[j] = exp_str[i];
698  j++;
699  }
700  }
701  exp_buf[j] = '\0';
702  expiry = exp_buf;
703 
704  // move the string beyond the day of week
705  while ((*expiry < '0' || *expiry > '9') && *expiry != '\0')
706  expiry++;
707 
708  return av_small_strptime(expiry, "%d%b%Y%H%M%S", buf) ? 0 : AVERROR(EINVAL);
709 }
710 
711 static int parse_set_cookie(const char *set_cookie, AVDictionary **dict)
712 {
713  char *param, *next_param, *cstr, *back;
714 
715  if (!(cstr = av_strdup(set_cookie)))
716  return AVERROR(EINVAL);
717 
718  // strip any trailing whitespace
719  back = &cstr[strlen(cstr)-1];
720  while (strchr(WHITESPACES, *back)) {
721  *back='\0';
722  back--;
723  }
724 
725  next_param = cstr;
726  while ((param = av_strtok(next_param, ";", &next_param))) {
727  char *name, *value;
728  param += strspn(param, WHITESPACES);
729  if ((name = av_strtok(param, "=", &value))) {
730  if (av_dict_set(dict, name, value, 0) < 0) {
731  av_free(cstr);
732  return -1;
733  }
734  }
735  }
736 
737  av_free(cstr);
738  return 0;
739 }
740 
741 static int parse_cookie(HTTPContext *s, const char *p, AVDictionary **cookies)
742 {
743  AVDictionary *new_params = NULL;
744  AVDictionaryEntry *e, *cookie_entry;
745  char *eql, *name;
746 
747  // ensure the cookie is parsable
748  if (parse_set_cookie(p, &new_params))
749  return -1;
750 
751  // if there is no cookie value there is nothing to parse
752  cookie_entry = av_dict_get(new_params, "", NULL, AV_DICT_IGNORE_SUFFIX);
753  if (!cookie_entry || !cookie_entry->value) {
754  av_dict_free(&new_params);
755  return -1;
756  }
757 
758  // ensure the cookie is not expired or older than an existing value
759  if ((e = av_dict_get(new_params, "expires", NULL, 0)) && e->value) {
760  struct tm new_tm = {0};
761  if (!parse_set_cookie_expiry_time(e->value, &new_tm)) {
762  AVDictionaryEntry *e2;
763 
764  // if the cookie has already expired ignore it
765  if (av_timegm(&new_tm) < av_gettime() / 1000000) {
766  av_dict_free(&new_params);
767  return -1;
768  }
769 
770  // only replace an older cookie with the same name
771  e2 = av_dict_get(*cookies, cookie_entry->key, NULL, 0);
772  if (e2 && e2->value) {
773  AVDictionary *old_params = NULL;
774  if (!parse_set_cookie(p, &old_params)) {
775  e2 = av_dict_get(old_params, "expires", NULL, 0);
776  if (e2 && e2->value) {
777  struct tm old_tm = {0};
778  if (!parse_set_cookie_expiry_time(e->value, &old_tm)) {
779  if (av_timegm(&new_tm) < av_timegm(&old_tm)) {
780  av_dict_free(&new_params);
781  av_dict_free(&old_params);
782  return -1;
783  }
784  }
785  }
786  }
787  av_dict_free(&old_params);
788  }
789  }
790  }
791 
792  // duplicate the cookie name (dict will dupe the value)
793  if (!(eql = strchr(p, '='))) return AVERROR(EINVAL);
794  if (!(name = av_strndup(p, eql - p))) return AVERROR(ENOMEM);
795 
796  // add the cookie to the dictionary
797  av_dict_set(cookies, name, eql, AV_DICT_DONT_STRDUP_KEY);
798 
799  return 0;
800 }
801 
802 static int cookie_string(AVDictionary *dict, char **cookies)
803 {
804  AVDictionaryEntry *e = NULL;
805  int len = 1;
806 
807  // determine how much memory is needed for the cookies string
808  while (e = av_dict_get(dict, "", e, AV_DICT_IGNORE_SUFFIX))
809  len += strlen(e->key) + strlen(e->value) + 1;
810 
811  // reallocate the cookies
812  e = NULL;
813  if (*cookies) av_free(*cookies);
814  *cookies = av_malloc(len);
815  if (!*cookies) return AVERROR(ENOMEM);
816  *cookies[0] = '\0';
817 
818  // write out the cookies
819  while (e = av_dict_get(dict, "", e, AV_DICT_IGNORE_SUFFIX))
820  av_strlcatf(*cookies, len, "%s%s\n", e->key, e->value);
821 
822  return 0;
823 }
824 
825 static int process_line(URLContext *h, char *line, int line_count,
826  int *new_location)
827 {
828  HTTPContext *s = h->priv_data;
829  const char *auto_method = h->flags & AVIO_FLAG_READ ? "POST" : "GET";
830  char *tag, *p, *end, *method, *resource, *version;
831  int ret;
832 
833  /* end of header */
834  if (line[0] == '\0') {
835  s->end_header = 1;
836  return 0;
837  }
838 
839  p = line;
840  if (line_count == 0) {
841  if (s->is_connected_server) {
842  // HTTP method
843  method = p;
844  while (*p && !av_isspace(*p))
845  p++;
846  *(p++) = '\0';
847  av_log(h, AV_LOG_TRACE, "Received method: %s\n", method);
848  if (s->method) {
849  if (av_strcasecmp(s->method, method)) {
850  av_log(h, AV_LOG_ERROR, "Received and expected HTTP method do not match. (%s expected, %s received)\n",
851  s->method, method);
852  return ff_http_averror(400, AVERROR(EIO));
853  }
854  } else {
855  // use autodetected HTTP method to expect
856  av_log(h, AV_LOG_TRACE, "Autodetected %s HTTP method\n", auto_method);
857  if (av_strcasecmp(auto_method, method)) {
858  av_log(h, AV_LOG_ERROR, "Received and autodetected HTTP method did not match "
859  "(%s autodetected %s received)\n", auto_method, method);
860  return ff_http_averror(400, AVERROR(EIO));
861  }
862  if (!(s->method = av_strdup(method)))
863  return AVERROR(ENOMEM);
864  }
865 
866  // HTTP resource
867  while (av_isspace(*p))
868  p++;
869  resource = p;
870  while (!av_isspace(*p))
871  p++;
872  *(p++) = '\0';
873  av_log(h, AV_LOG_TRACE, "Requested resource: %s\n", resource);
874  if (!(s->resource = av_strdup(resource)))
875  return AVERROR(ENOMEM);
876 
877  // HTTP version
878  while (av_isspace(*p))
879  p++;
880  version = p;
881  while (*p && !av_isspace(*p))
882  p++;
883  *p = '\0';
884  if (av_strncasecmp(version, "HTTP/", 5)) {
885  av_log(h, AV_LOG_ERROR, "Malformed HTTP version string.\n");
886  return ff_http_averror(400, AVERROR(EIO));
887  }
888  av_log(h, AV_LOG_TRACE, "HTTP version string: %s\n", version);
889  } else {
890  while (!av_isspace(*p) && *p != '\0')
891  p++;
892  while (av_isspace(*p))
893  p++;
894  s->http_code = strtol(p, &end, 10);
895 
896  av_log(h, AV_LOG_TRACE, "http_code=%d\n", s->http_code);
897 
898  if ((ret = check_http_code(h, s->http_code, end)) < 0)
899  return ret;
900  }
901  } else {
902  while (*p != '\0' && *p != ':')
903  p++;
904  if (*p != ':')
905  return 1;
906 
907  *p = '\0';
908  tag = line;
909  p++;
910  while (av_isspace(*p))
911  p++;
912  if (!av_strcasecmp(tag, "Location")) {
913  if ((ret = parse_location(s, p)) < 0)
914  return ret;
915  *new_location = 1;
916  } else if (!av_strcasecmp(tag, "Content-Length") &&
917  s->filesize == UINT64_MAX) {
918  s->filesize = strtoull(p, NULL, 10);
919  } else if (!av_strcasecmp(tag, "Content-Range")) {
920  parse_content_range(h, p);
921  } else if (!av_strcasecmp(tag, "Accept-Ranges") &&
922  !strncmp(p, "bytes", 5) &&
923  s->seekable == -1) {
924  h->is_streamed = 0;
925  } else if (!av_strcasecmp(tag, "Transfer-Encoding") &&
926  !av_strncasecmp(p, "chunked", 7)) {
927  s->filesize = UINT64_MAX;
928  s->chunksize = 0;
929  } else if (!av_strcasecmp(tag, "WWW-Authenticate")) {
931  } else if (!av_strcasecmp(tag, "Authentication-Info")) {
933  } else if (!av_strcasecmp(tag, "Proxy-Authenticate")) {
935  } else if (!av_strcasecmp(tag, "Connection")) {
936  if (!strcmp(p, "close"))
937  s->willclose = 1;
938  } else if (!av_strcasecmp(tag, "Server")) {
939  if (!av_strcasecmp(p, "AkamaiGHost")) {
940  s->is_akamai = 1;
941  } else if (!av_strncasecmp(p, "MediaGateway", 12)) {
942  s->is_mediagateway = 1;
943  }
944  } else if (!av_strcasecmp(tag, "Content-Type")) {
945  av_free(s->mime_type);
946  s->mime_type = av_strdup(p);
947  } else if (!av_strcasecmp(tag, "Set-Cookie")) {
948  if (parse_cookie(s, p, &s->cookie_dict))
949  av_log(h, AV_LOG_WARNING, "Unable to parse '%s'\n", p);
950  } else if (!av_strcasecmp(tag, "Icy-MetaInt")) {
951  s->icy_metaint = strtoull(p, NULL, 10);
952  } else if (!av_strncasecmp(tag, "Icy-", 4)) {
953  if ((ret = parse_icy(s, tag, p)) < 0)
954  return ret;
955  } else if (!av_strcasecmp(tag, "Content-Encoding")) {
956  if ((ret = parse_content_encoding(h, p)) < 0)
957  return ret;
958  }
959  }
960  return 1;
961 }
962 
963 /**
964  * Create a string containing cookie values for use as a HTTP cookie header
965  * field value for a particular path and domain from the cookie values stored in
966  * the HTTP protocol context. The cookie string is stored in *cookies.
967  *
968  * @return a negative value if an error condition occurred, 0 otherwise
969  */
970 static int get_cookies(HTTPContext *s, char **cookies, const char *path,
971  const char *domain)
972 {
973  // cookie strings will look like Set-Cookie header field values. Multiple
974  // Set-Cookie fields will result in multiple values delimited by a newline
975  int ret = 0;
976  char *cookie, *set_cookies = av_strdup(s->cookies), *next = set_cookies;
977 
978  if (!set_cookies) return AVERROR(EINVAL);
979 
980  // destroy any cookies in the dictionary.
982 
983  *cookies = NULL;
984  while ((cookie = av_strtok(next, "\n", &next))) {
985  AVDictionary *cookie_params = NULL;
986  AVDictionaryEntry *cookie_entry, *e;
987 
988  // store the cookie in a dict in case it is updated in the response
989  if (parse_cookie(s, cookie, &s->cookie_dict))
990  av_log(s, AV_LOG_WARNING, "Unable to parse '%s'\n", cookie);
991 
992  // continue on to the next cookie if this one cannot be parsed
993  if (parse_set_cookie(cookie, &cookie_params))
994  continue;
995 
996  // if the cookie has no value, skip it
997  cookie_entry = av_dict_get(cookie_params, "", NULL, AV_DICT_IGNORE_SUFFIX);
998  if (!cookie_entry || !cookie_entry->value) {
999  av_dict_free(&cookie_params);
1000  continue;
1001  }
1002 
1003  // if the cookie has expired, don't add it
1004  if ((e = av_dict_get(cookie_params, "expires", NULL, 0)) && e->value) {
1005  struct tm tm_buf = {0};
1006  if (!parse_set_cookie_expiry_time(e->value, &tm_buf)) {
1007  if (av_timegm(&tm_buf) < av_gettime() / 1000000) {
1008  av_dict_free(&cookie_params);
1009  continue;
1010  }
1011  }
1012  }
1013 
1014  // if no domain in the cookie assume it appied to this request
1015  if ((e = av_dict_get(cookie_params, "domain", NULL, 0)) && e->value) {
1016  // find the offset comparison is on the min domain (b.com, not a.b.com)
1017  int domain_offset = strlen(domain) - strlen(e->value);
1018  if (domain_offset < 0) {
1019  av_dict_free(&cookie_params);
1020  continue;
1021  }
1022 
1023  // match the cookie domain
1024  if (av_strcasecmp(&domain[domain_offset], e->value)) {
1025  av_dict_free(&cookie_params);
1026  continue;
1027  }
1028  }
1029 
1030  // ensure this cookie matches the path
1031  e = av_dict_get(cookie_params, "path", NULL, 0);
1032  if (!e || av_strncasecmp(path, e->value, strlen(e->value))) {
1033  av_dict_free(&cookie_params);
1034  continue;
1035  }
1036 
1037  // cookie parameters match, so copy the value
1038  if (!*cookies) {
1039  if (!(*cookies = av_asprintf("%s=%s", cookie_entry->key, cookie_entry->value))) {
1040  ret = AVERROR(ENOMEM);
1041  break;
1042  }
1043  } else {
1044  char *tmp = *cookies;
1045  size_t str_size = strlen(cookie_entry->key) + strlen(cookie_entry->value) + strlen(*cookies) + 4;
1046  if (!(*cookies = av_malloc(str_size))) {
1047  ret = AVERROR(ENOMEM);
1048  av_free(tmp);
1049  break;
1050  }
1051  snprintf(*cookies, str_size, "%s; %s=%s", tmp, cookie_entry->key, cookie_entry->value);
1052  av_free(tmp);
1053  }
1054  }
1055 
1056  av_free(set_cookies);
1057 
1058  return ret;
1059 }
1060 
1061 static inline int has_header(const char *str, const char *header)
1062 {
1063  /* header + 2 to skip over CRLF prefix. (make sure you have one!) */
1064  if (!str)
1065  return 0;
1066  return av_stristart(str, header + 2, NULL) || av_stristr(str, header);
1067 }
1068 
1069 static int http_read_header(URLContext *h, int *new_location)
1070 {
1071  HTTPContext *s = h->priv_data;
1072  char line[MAX_URL_SIZE];
1073  int err = 0;
1074 
1075  s->chunksize = UINT64_MAX;
1076 
1077  for (;;) {
1078  if ((err = http_get_line(s, line, sizeof(line))) < 0)
1079  return err;
1080 
1081  av_log(h, AV_LOG_TRACE, "header='%s'\n", line);
1082 
1083  err = process_line(h, line, s->line_count, new_location);
1084  if (err < 0)
1085  return err;
1086  if (err == 0)
1087  break;
1088  s->line_count++;
1089  }
1090 
1091  if (s->seekable == -1 && s->is_mediagateway && s->filesize == 2000000000)
1092  h->is_streamed = 1; /* we can in fact _not_ seek */
1093 
1094  // add any new cookies into the existing cookie string
1097 
1098  return err;
1099 }
1100 
1101 static int http_connect(URLContext *h, const char *path, const char *local_path,
1102  const char *hoststr, const char *auth,
1103  const char *proxyauth, int *new_location)
1104 {
1105  HTTPContext *s = h->priv_data;
1106  int post, err;
1107  char headers[HTTP_HEADERS_SIZE] = "";
1108  char *authstr = NULL, *proxyauthstr = NULL;
1109  uint64_t off = s->off;
1110  int len = 0;
1111  const char *method;
1112  int send_expect_100 = 0;
1113  int ret;
1114 
1115  /* send http header */
1116  post = h->flags & AVIO_FLAG_WRITE;
1117 
1118  if (s->post_data) {
1119  /* force POST method and disable chunked encoding when
1120  * custom HTTP post data is set */
1121  post = 1;
1122  s->chunked_post = 0;
1123  }
1124 
1125  if (s->method)
1126  method = s->method;
1127  else
1128  method = post ? "POST" : "GET";
1129 
1130  authstr = ff_http_auth_create_response(&s->auth_state, auth,
1131  local_path, method);
1132  proxyauthstr = ff_http_auth_create_response(&s->proxy_auth_state, proxyauth,
1133  local_path, method);
1134  if (post && !s->post_data) {
1135  send_expect_100 = s->send_expect_100;
1136  /* The user has supplied authentication but we don't know the auth type,
1137  * send Expect: 100-continue to get the 401 response including the
1138  * WWW-Authenticate header, or an 100 continue if no auth actually
1139  * is needed. */
1140  if (auth && *auth &&
1142  s->http_code != 401)
1143  send_expect_100 = 1;
1144  }
1145 
1146 #if FF_API_HTTP_USER_AGENT
1147  if (strcmp(s->user_agent_deprecated, DEFAULT_USER_AGENT)) {
1148  av_log(s, AV_LOG_WARNING, "the user-agent option is deprecated, please use user_agent option\n");
1149  s->user_agent = av_strdup(s->user_agent_deprecated);
1150  }
1151 #endif
1152  /* set default headers if needed */
1153  if (!has_header(s->headers, "\r\nUser-Agent: "))
1154  len += av_strlcatf(headers + len, sizeof(headers) - len,
1155  "User-Agent: %s\r\n", s->user_agent);
1156  if (!has_header(s->headers, "\r\nAccept: "))
1157  len += av_strlcpy(headers + len, "Accept: */*\r\n",
1158  sizeof(headers) - len);
1159  // Note: we send this on purpose even when s->off is 0 when we're probing,
1160  // since it allows us to detect more reliably if a (non-conforming)
1161  // server supports seeking by analysing the reply headers.
1162  if (!has_header(s->headers, "\r\nRange: ") && !post && (s->off > 0 || s->end_off || s->seekable == -1)) {
1163  len += av_strlcatf(headers + len, sizeof(headers) - len,
1164  "Range: bytes=%"PRIu64"-", s->off);
1165  if (s->end_off)
1166  len += av_strlcatf(headers + len, sizeof(headers) - len,
1167  "%"PRId64, s->end_off - 1);
1168  len += av_strlcpy(headers + len, "\r\n",
1169  sizeof(headers) - len);
1170  }
1171  if (send_expect_100 && !has_header(s->headers, "\r\nExpect: "))
1172  len += av_strlcatf(headers + len, sizeof(headers) - len,
1173  "Expect: 100-continue\r\n");
1174 
1175  if (!has_header(s->headers, "\r\nConnection: ")) {
1176  if (s->multiple_requests)
1177  len += av_strlcpy(headers + len, "Connection: keep-alive\r\n",
1178  sizeof(headers) - len);
1179  else
1180  len += av_strlcpy(headers + len, "Connection: close\r\n",
1181  sizeof(headers) - len);
1182  }
1183 
1184  if (!has_header(s->headers, "\r\nHost: "))
1185  len += av_strlcatf(headers + len, sizeof(headers) - len,
1186  "Host: %s\r\n", hoststr);
1187  if (!has_header(s->headers, "\r\nContent-Length: ") && s->post_data)
1188  len += av_strlcatf(headers + len, sizeof(headers) - len,
1189  "Content-Length: %d\r\n", s->post_datalen);
1190 
1191  if (!has_header(s->headers, "\r\nContent-Type: ") && s->content_type)
1192  len += av_strlcatf(headers + len, sizeof(headers) - len,
1193  "Content-Type: %s\r\n", s->content_type);
1194  if (!has_header(s->headers, "\r\nCookie: ") && s->cookies) {
1195  char *cookies = NULL;
1196  if (!get_cookies(s, &cookies, path, hoststr) && cookies) {
1197  len += av_strlcatf(headers + len, sizeof(headers) - len,
1198  "Cookie: %s\r\n", cookies);
1199  av_free(cookies);
1200  }
1201  }
1202  if (!has_header(s->headers, "\r\nIcy-MetaData: ") && s->icy)
1203  len += av_strlcatf(headers + len, sizeof(headers) - len,
1204  "Icy-MetaData: %d\r\n", 1);
1205 
1206  /* now add in custom headers */
1207  if (s->headers)
1208  av_strlcpy(headers + len, s->headers, sizeof(headers) - len);
1209 
1210  ret = snprintf(s->buffer, sizeof(s->buffer),
1211  "%s %s HTTP/1.1\r\n"
1212  "%s"
1213  "%s"
1214  "%s"
1215  "%s%s"
1216  "\r\n",
1217  method,
1218  path,
1219  post && s->chunked_post ? "Transfer-Encoding: chunked\r\n" : "",
1220  headers,
1221  authstr ? authstr : "",
1222  proxyauthstr ? "Proxy-" : "", proxyauthstr ? proxyauthstr : "");
1223 
1224  av_log(h, AV_LOG_DEBUG, "request: %s\n", s->buffer);
1225 
1226  if (strlen(headers) + 1 == sizeof(headers) ||
1227  ret >= sizeof(s->buffer)) {
1228  av_log(h, AV_LOG_ERROR, "overlong headers\n");
1229  err = AVERROR(EINVAL);
1230  goto done;
1231  }
1232 
1233 
1234  if ((err = ffurl_write(s->hd, s->buffer, strlen(s->buffer))) < 0)
1235  goto done;
1236 
1237  if (s->post_data)
1238  if ((err = ffurl_write(s->hd, s->post_data, s->post_datalen)) < 0)
1239  goto done;
1240 
1241  /* init input buffer */
1242  s->buf_ptr = s->buffer;
1243  s->buf_end = s->buffer;
1244  s->line_count = 0;
1245  s->off = 0;
1246  s->icy_data_read = 0;
1247  s->filesize = UINT64_MAX;
1248  s->willclose = 0;
1249  s->end_chunked_post = 0;
1250  s->end_header = 0;
1251  if (post && !s->post_data && !send_expect_100) {
1252  /* Pretend that it did work. We didn't read any header yet, since
1253  * we've still to send the POST data, but the code calling this
1254  * function will check http_code after we return. */
1255  s->http_code = 200;
1256  err = 0;
1257  goto done;
1258  }
1259 
1260  /* wait for header */
1261  err = http_read_header(h, new_location);
1262  if (err < 0)
1263  goto done;
1264 
1265  if (*new_location)
1266  s->off = off;
1267 
1268  err = (off == s->off) ? 0 : -1;
1269 done:
1270  av_freep(&authstr);
1271  av_freep(&proxyauthstr);
1272  return err;
1273 }
1274 
1276 {
1277  HTTPContext *s = h->priv_data;
1278  int len;
1279 
1280  if (s->chunksize != UINT64_MAX) {
1281  if (!s->chunksize) {
1282  char line[32];
1283  int err;
1284 
1285  do {
1286  if ((err = http_get_line(s, line, sizeof(line))) < 0)
1287  return err;
1288  } while (!*line); /* skip CR LF from last chunk */
1289 
1290  s->chunksize = strtoull(line, NULL, 16);
1291 
1292  av_log(h, AV_LOG_TRACE,
1293  "Chunked encoding data size: %"PRIu64"'\n",
1294  s->chunksize);
1295 
1296  if (!s->chunksize)
1297  return 0;
1298  else if (s->chunksize == UINT64_MAX) {
1299  av_log(h, AV_LOG_ERROR, "Invalid chunk size %"PRIu64"\n",
1300  s->chunksize);
1301  return AVERROR(EINVAL);
1302  }
1303  }
1304  size = FFMIN(size, s->chunksize);
1305  }
1306 
1307  /* read bytes from input buffer first */
1308  len = s->buf_end - s->buf_ptr;
1309  if (len > 0) {
1310  if (len > size)
1311  len = size;
1312  memcpy(buf, s->buf_ptr, len);
1313  s->buf_ptr += len;
1314  } else {
1315  uint64_t target_end = s->end_off ? s->end_off : s->filesize;
1316  if ((!s->willclose || s->chunksize == UINT64_MAX) && s->off >= target_end)
1317  return AVERROR_EOF;
1318  len = ffurl_read(s->hd, buf, size);
1319  if (!len && (!s->willclose || s->chunksize == UINT64_MAX) && s->off < target_end) {
1320  av_log(h, AV_LOG_ERROR,
1321  "Stream ends prematurely at %"PRIu64", should be %"PRIu64"\n",
1322  s->off, target_end
1323  );
1324  return AVERROR(EIO);
1325  }
1326  }
1327  if (len > 0) {
1328  s->off += len;
1329  if (s->chunksize > 0 && s->chunksize != UINT64_MAX) {
1330  av_assert0(s->chunksize >= len);
1331  s->chunksize -= len;
1332  }
1333  }
1334  return len;
1335 }
1336 
1337 #if CONFIG_ZLIB
1338 #define DECOMPRESS_BUF_SIZE (256 * 1024)
1339 static int http_buf_read_compressed(URLContext *h, uint8_t *buf, int size)
1340 {
1341  HTTPContext *s = h->priv_data;
1342  int ret;
1343 
1344  if (!s->inflate_buffer) {
1345  s->inflate_buffer = av_malloc(DECOMPRESS_BUF_SIZE);
1346  if (!s->inflate_buffer)
1347  return AVERROR(ENOMEM);
1348  }
1349 
1350  if (s->inflate_stream.avail_in == 0) {
1351  int read = http_buf_read(h, s->inflate_buffer, DECOMPRESS_BUF_SIZE);
1352  if (read <= 0)
1353  return read;
1354  s->inflate_stream.next_in = s->inflate_buffer;
1355  s->inflate_stream.avail_in = read;
1356  }
1357 
1358  s->inflate_stream.avail_out = size;
1359  s->inflate_stream.next_out = buf;
1360 
1361  ret = inflate(&s->inflate_stream, Z_SYNC_FLUSH);
1362  if (ret != Z_OK && ret != Z_STREAM_END)
1363  av_log(h, AV_LOG_WARNING, "inflate return value: %d, %s\n",
1364  ret, s->inflate_stream.msg);
1365 
1366  return size - s->inflate_stream.avail_out;
1367 }
1368 #endif /* CONFIG_ZLIB */
1369 
1370 static int64_t http_seek_internal(URLContext *h, int64_t off, int whence, int force_reconnect);
1371 
1372 static int http_read_stream(URLContext *h, uint8_t *buf, int size)
1373 {
1374  HTTPContext *s = h->priv_data;
1375  int err, new_location, read_ret;
1376  int64_t seek_ret;
1377 
1378  if (!s->hd)
1379  return AVERROR_EOF;
1380 
1381  if (s->end_chunked_post && !s->end_header) {
1382  err = http_read_header(h, &new_location);
1383  if (err < 0)
1384  return err;
1385  }
1386 
1387 #if CONFIG_ZLIB
1388  if (s->compressed)
1389  return http_buf_read_compressed(h, buf, size);
1390 #endif /* CONFIG_ZLIB */
1391  read_ret = http_buf_read(h, buf, size);
1392  if ( (read_ret < 0 && s->reconnect && (!h->is_streamed || s->reconnect_streamed) && s->filesize > 0 && s->off < s->filesize)
1393  || (read_ret == 0 && s->reconnect_at_eof && (!h->is_streamed || s->reconnect_streamed))) {
1394  uint64_t target = h->is_streamed ? 0 : s->off;
1395 
1397  return AVERROR(EIO);
1398 
1399  av_log(h, AV_LOG_INFO, "Will reconnect at %"PRIu64" error=%s.\n", s->off, av_err2str(read_ret));
1400  av_usleep(1000U*1000*s->reconnect_delay);
1401  s->reconnect_delay = 1 + 2*s->reconnect_delay;
1402  seek_ret = http_seek_internal(h, target, SEEK_SET, 1);
1403  if (seek_ret != target) {
1404  av_log(h, AV_LOG_ERROR, "Failed to reconnect at %"PRIu64".\n", target);
1405  return read_ret;
1406  }
1407 
1408  read_ret = http_buf_read(h, buf, size);
1409  } else
1410  s->reconnect_delay = 0;
1411 
1412  return read_ret;
1413 }
1414 
1415 // Like http_read_stream(), but no short reads.
1416 // Assumes partial reads are an error.
1417 static int http_read_stream_all(URLContext *h, uint8_t *buf, int size)
1418 {
1419  int pos = 0;
1420  while (pos < size) {
1421  int len = http_read_stream(h, buf + pos, size - pos);
1422  if (len < 0)
1423  return len;
1424  pos += len;
1425  }
1426  return pos;
1427 }
1428 
1429 static void update_metadata(HTTPContext *s, char *data)
1430 {
1431  char *key;
1432  char *val;
1433  char *end;
1434  char *next = data;
1435 
1436  while (*next) {
1437  key = next;
1438  val = strstr(key, "='");
1439  if (!val)
1440  break;
1441  end = strstr(val, "';");
1442  if (!end)
1443  break;
1444 
1445  *val = '\0';
1446  *end = '\0';
1447  val += 2;
1448 
1449  av_dict_set(&s->metadata, key, val, 0);
1450 
1451  next = end + 2;
1452  }
1453 }
1454 
1455 static int store_icy(URLContext *h, int size)
1456 {
1457  HTTPContext *s = h->priv_data;
1458  /* until next metadata packet */
1459  uint64_t remaining;
1460 
1461  if (s->icy_metaint < s->icy_data_read)
1462  return AVERROR_INVALIDDATA;
1463  remaining = s->icy_metaint - s->icy_data_read;
1464 
1465  if (!remaining) {
1466  /* The metadata packet is variable sized. It has a 1 byte header
1467  * which sets the length of the packet (divided by 16). If it's 0,
1468  * the metadata doesn't change. After the packet, icy_metaint bytes
1469  * of normal data follows. */
1470  uint8_t ch;
1471  int len = http_read_stream_all(h, &ch, 1);
1472  if (len < 0)
1473  return len;
1474  if (ch > 0) {
1475  char data[255 * 16 + 1];
1476  int ret;
1477  len = ch * 16;
1478  ret = http_read_stream_all(h, data, len);
1479  if (ret < 0)
1480  return ret;
1481  data[len + 1] = 0;
1482  if ((ret = av_opt_set(s, "icy_metadata_packet", data, 0)) < 0)
1483  return ret;
1484  update_metadata(s, data);
1485  }
1486  s->icy_data_read = 0;
1487  remaining = s->icy_metaint;
1488  }
1489 
1490  return FFMIN(size, remaining);
1491 }
1492 
1493 static int http_read(URLContext *h, uint8_t *buf, int size)
1494 {
1495  HTTPContext *s = h->priv_data;
1496 
1497  if (s->icy_metaint > 0) {
1498  size = store_icy(h, size);
1499  if (size < 0)
1500  return size;
1501  }
1502 
1503  size = http_read_stream(h, buf, size);
1504  if (size > 0)
1505  s->icy_data_read += size;
1506  return size;
1507 }
1508 
1509 /* used only when posting data */
1510 static int http_write(URLContext *h, const uint8_t *buf, int size)
1511 {
1512  char temp[11] = ""; /* 32-bit hex + CRLF + nul */
1513  int ret;
1514  char crlf[] = "\r\n";
1515  HTTPContext *s = h->priv_data;
1516 
1517  if (!s->chunked_post) {
1518  /* non-chunked data is sent without any special encoding */
1519  return ffurl_write(s->hd, buf, size);
1520  }
1521 
1522  /* silently ignore zero-size data since chunk encoding that would
1523  * signal EOF */
1524  if (size > 0) {
1525  /* upload data using chunked encoding */
1526  snprintf(temp, sizeof(temp), "%x\r\n", size);
1527 
1528  if ((ret = ffurl_write(s->hd, temp, strlen(temp))) < 0 ||
1529  (ret = ffurl_write(s->hd, buf, size)) < 0 ||
1530  (ret = ffurl_write(s->hd, crlf, sizeof(crlf) - 1)) < 0)
1531  return ret;
1532  }
1533  return size;
1534 }
1535 
1536 static int http_shutdown(URLContext *h, int flags)
1537 {
1538  int ret = 0;
1539  char footer[] = "0\r\n\r\n";
1540  HTTPContext *s = h->priv_data;
1541 
1542  /* signal end of chunked encoding if used */
1543  if (((flags & AVIO_FLAG_WRITE) && s->chunked_post) ||
1544  ((flags & AVIO_FLAG_READ) && s->chunked_post && s->listen)) {
1545  ret = ffurl_write(s->hd, footer, sizeof(footer) - 1);
1546  ret = ret > 0 ? 0 : ret;
1547  s->end_chunked_post = 1;
1548  }
1549 
1550  return ret;
1551 }
1552 
1553 static int http_close(URLContext *h)
1554 {
1555  int ret = 0;
1556  HTTPContext *s = h->priv_data;
1557 
1558 #if CONFIG_ZLIB
1559  inflateEnd(&s->inflate_stream);
1560  av_freep(&s->inflate_buffer);
1561 #endif /* CONFIG_ZLIB */
1562 
1563  if (!s->end_chunked_post)
1564  /* Close the write direction by sending the end of chunked encoding. */
1565  ret = http_shutdown(h, h->flags);
1566 
1567  if (s->hd)
1568  ffurl_closep(&s->hd);
1570  return ret;
1571 }
1572 
1573 static int64_t http_seek_internal(URLContext *h, int64_t off, int whence, int force_reconnect)
1574 {
1575  HTTPContext *s = h->priv_data;
1576  URLContext *old_hd = s->hd;
1577  uint64_t old_off = s->off;
1578  uint8_t old_buf[BUFFER_SIZE];
1579  int old_buf_size, ret;
1580  AVDictionary *options = NULL;
1581 
1582  if (whence == AVSEEK_SIZE)
1583  return s->filesize;
1584  else if (!force_reconnect &&
1585  ((whence == SEEK_CUR && off == 0) ||
1586  (whence == SEEK_SET && off == s->off)))
1587  return s->off;
1588  else if ((s->filesize == UINT64_MAX && whence == SEEK_END))
1589  return AVERROR(ENOSYS);
1590 
1591  if (whence == SEEK_CUR)
1592  off += s->off;
1593  else if (whence == SEEK_END)
1594  off += s->filesize;
1595  else if (whence != SEEK_SET)
1596  return AVERROR(EINVAL);
1597  if (off < 0)
1598  return AVERROR(EINVAL);
1599  s->off = off;
1600 
1601  if (s->off && h->is_streamed)
1602  return AVERROR(ENOSYS);
1603 
1604  /* we save the old context in case the seek fails */
1605  old_buf_size = s->buf_end - s->buf_ptr;
1606  memcpy(old_buf, s->buf_ptr, old_buf_size);
1607  s->hd = NULL;
1608 
1609  /* if it fails, continue on old connection */
1610  if ((ret = http_open_cnx(h, &options)) < 0) {
1611  av_dict_free(&options);
1612  memcpy(s->buffer, old_buf, old_buf_size);
1613  s->buf_ptr = s->buffer;
1614  s->buf_end = s->buffer + old_buf_size;
1615  s->hd = old_hd;
1616  s->off = old_off;
1617  return ret;
1618  }
1619  av_dict_free(&options);
1620  ffurl_close(old_hd);
1621  return off;
1622 }
1623 
1624 static int64_t http_seek(URLContext *h, int64_t off, int whence)
1625 {
1626  return http_seek_internal(h, off, whence, 0);
1627 }
1628 
1630 {
1631  HTTPContext *s = h->priv_data;
1632  return ffurl_get_file_handle(s->hd);
1633 }
1634 
1636 {
1637  HTTPContext *s = h->priv_data;
1638  return ffurl_get_short_seek(s->hd);
1639 }
1640 
1641 #define HTTP_CLASS(flavor) \
1642 static const AVClass flavor ## _context_class = { \
1643  .class_name = # flavor, \
1644  .item_name = av_default_item_name, \
1645  .option = options, \
1646  .version = LIBAVUTIL_VERSION_INT, \
1647 }
1648 
1649 #if CONFIG_HTTP_PROTOCOL
1650 HTTP_CLASS(http);
1651 
1652 const URLProtocol ff_http_protocol = {
1653  .name = "http",
1654  .url_open2 = http_open,
1655  .url_accept = http_accept,
1656  .url_handshake = http_handshake,
1657  .url_read = http_read,
1658  .url_write = http_write,
1659  .url_seek = http_seek,
1660  .url_close = http_close,
1661  .url_get_file_handle = http_get_file_handle,
1662  .url_get_short_seek = http_get_short_seek,
1663  .url_shutdown = http_shutdown,
1664  .priv_data_size = sizeof(HTTPContext),
1665  .priv_data_class = &http_context_class,
1667  .default_whitelist = "http,https,tls,rtp,tcp,udp,crypto,httpproxy"
1668 };
1669 #endif /* CONFIG_HTTP_PROTOCOL */
1670 
1671 #if CONFIG_HTTPS_PROTOCOL
1672 HTTP_CLASS(https);
1673 
1675  .name = "https",
1676  .url_open2 = http_open,
1677  .url_read = http_read,
1678  .url_write = http_write,
1679  .url_seek = http_seek,
1680  .url_close = http_close,
1681  .url_get_file_handle = http_get_file_handle,
1682  .url_get_short_seek = http_get_short_seek,
1683  .url_shutdown = http_shutdown,
1684  .priv_data_size = sizeof(HTTPContext),
1685  .priv_data_class = &https_context_class,
1687  .default_whitelist = "http,https,tls,rtp,tcp,udp,crypto,httpproxy"
1688 };
1689 #endif /* CONFIG_HTTPS_PROTOCOL */
1690 
1691 #if CONFIG_HTTPPROXY_PROTOCOL
1692 static int http_proxy_close(URLContext *h)
1693 {
1694  HTTPContext *s = h->priv_data;
1695  if (s->hd)
1696  ffurl_closep(&s->hd);
1697  return 0;
1698 }
1699 
1700 static int http_proxy_open(URLContext *h, const char *uri, int flags)
1701 {
1702  HTTPContext *s = h->priv_data;
1703  char hostname[1024], hoststr[1024];
1704  char auth[1024], pathbuf[1024], *path;
1705  char lower_url[100];
1706  int port, ret = 0, attempts = 0;
1707  HTTPAuthType cur_auth_type;
1708  char *authstr;
1709  int new_loc;
1710 
1711  if( s->seekable == 1 )
1712  h->is_streamed = 0;
1713  else
1714  h->is_streamed = 1;
1715 
1716  av_url_split(NULL, 0, auth, sizeof(auth), hostname, sizeof(hostname), &port,
1717  pathbuf, sizeof(pathbuf), uri);
1718  ff_url_join(hoststr, sizeof(hoststr), NULL, NULL, hostname, port, NULL);
1719  path = pathbuf;
1720  if (*path == '/')
1721  path++;
1722 
1723  ff_url_join(lower_url, sizeof(lower_url), "tcp", NULL, hostname, port,
1724  NULL);
1725 redo:
1726  ret = ffurl_open_whitelist(&s->hd, lower_url, AVIO_FLAG_READ_WRITE,
1727  &h->interrupt_callback, NULL,
1729  if (ret < 0)
1730  return ret;
1731 
1732  authstr = ff_http_auth_create_response(&s->proxy_auth_state, auth,
1733  path, "CONNECT");
1734  snprintf(s->buffer, sizeof(s->buffer),
1735  "CONNECT %s HTTP/1.1\r\n"
1736  "Host: %s\r\n"
1737  "Connection: close\r\n"
1738  "%s%s"
1739  "\r\n",
1740  path,
1741  hoststr,
1742  authstr ? "Proxy-" : "", authstr ? authstr : "");
1743  av_freep(&authstr);
1744 
1745  if ((ret = ffurl_write(s->hd, s->buffer, strlen(s->buffer))) < 0)
1746  goto fail;
1747 
1748  s->buf_ptr = s->buffer;
1749  s->buf_end = s->buffer;
1750  s->line_count = 0;
1751  s->filesize = UINT64_MAX;
1752  cur_auth_type = s->proxy_auth_state.auth_type;
1753 
1754  /* Note: This uses buffering, potentially reading more than the
1755  * HTTP header. If tunneling a protocol where the server starts
1756  * the conversation, we might buffer part of that here, too.
1757  * Reading that requires using the proper ffurl_read() function
1758  * on this URLContext, not using the fd directly (as the tls
1759  * protocol does). This shouldn't be an issue for tls though,
1760  * since the client starts the conversation there, so there
1761  * is no extra data that we might buffer up here.
1762  */
1763  ret = http_read_header(h, &new_loc);
1764  if (ret < 0)
1765  goto fail;
1766 
1767  attempts++;
1768  if (s->http_code == 407 &&
1769  (cur_auth_type == HTTP_AUTH_NONE || s->proxy_auth_state.stale) &&
1770  s->proxy_auth_state.auth_type != HTTP_AUTH_NONE && attempts < 2) {
1771  ffurl_closep(&s->hd);
1772  goto redo;
1773  }
1774 
1775  if (s->http_code < 400)
1776  return 0;
1777  ret = ff_http_averror(s->http_code, AVERROR(EIO));
1778 
1779 fail:
1780  http_proxy_close(h);
1781  return ret;
1782 }
1783 
1784 static int http_proxy_write(URLContext *h, const uint8_t *buf, int size)
1785 {
1786  HTTPContext *s = h->priv_data;
1787  return ffurl_write(s->hd, buf, size);
1788 }
1789 
1791  .name = "httpproxy",
1792  .url_open = http_proxy_open,
1793  .url_read = http_buf_read,
1794  .url_write = http_proxy_write,
1795  .url_close = http_proxy_close,
1796  .url_get_file_handle = http_get_file_handle,
1797  .priv_data_size = sizeof(HTTPContext),
1798  .flags = URL_PROTOCOL_FLAG_NETWORK,
1799 };
1800 #endif /* CONFIG_HTTPPROXY_PROTOCOL */
static int http_get_line(HTTPContext *s, char *line, int line_size)
Definition: http.c:562
time_t av_timegm(struct tm *tm)
Convert the decomposed UTC time in tm to a time_t value.
Definition: parseutils.c:568
void av_url_split(char *proto, int proto_size, char *authorization, int authorization_size, char *hostname, int hostname_size, int *port_ptr, char *path, int path_size, const char *url)
Split a URL string into components.
Definition: utils.c:4619
static void parse_content_range(URLContext *h, const char *p)
Definition: http.c:615
AVDictionary * metadata
Definition: http.c:106
#define NULL
Definition: coverity.c:32
static int http_connect(URLContext *h, const char *path, const char *local_path, const char *hoststr, const char *auth, const char *proxyauth, int *new_location)
Definition: http.c:1101
const char const char void * val
Definition: avisynth_c.h:771
void ff_make_absolute_url(char *buf, int size, const char *base, const char *rel)
Convert a relative url into an absolute url, given a base url.
Definition: url.c:80
const char * s
Definition: avisynth_c.h:768
#define AVERROR_INVALIDDATA
Invalid data found when processing input.
Definition: error.h:59
int ffurl_open_whitelist(URLContext **puc, const char *filename, int flags, const AVIOInterruptCB *int_cb, AVDictionary **options, const char *whitelist, const char *blacklist, URLContext *parent)
Create an URLContext for accessing to the resource indicated by url, and open it. ...
Definition: avio.c:309
#define URL_PROTOCOL_FLAG_NETWORK
Definition: url.h:34
uint8_t * post_data
Definition: http.c:92
int reconnect_delay
Definition: http.c:118
AVOption.
Definition: opt.h:246
ptrdiff_t const GLvoid * data
Definition: opengl_enc.c:101
#define AV_OPT_FLAG_EXPORT
The option is intended for exporting values to the caller.
Definition: opt.h:287
HTTPAuthType
Authentication types, ordered from weakest to strongest.
Definition: httpauth.h:28
#define BUFFER_SIZE
Definition: http.c:48
#define AV_LOG_WARNING
Something somehow does not look correct.
Definition: log.h:182
static int http_close(URLContext *h)
Definition: http.c:1553
else temp
Definition: vf_mcdeint.c:259
int ffurl_write(URLContext *h, const unsigned char *buf, int size)
Write size bytes from buf to the resource accessed by h.
Definition: avio.c:421
char * av_stristr(const char *s1, const char *s2)
Locate the first case-independent occurrence in the string haystack of the string needle...
Definition: avstring.c:56
int is_streamed
true if streamed (no seek possible), default = false
Definition: url.h:45
AVIOInterruptCB interrupt_callback
Definition: url.h:47
HTTPAuthState proxy_auth_state
Definition: http.c:72
Definition: http.c:58
#define AVIO_FLAG_READ
read-only
Definition: avio.h:643
char * icy_metadata_headers
Definition: http.c:104
static av_const int av_isspace(int c)
Locale-independent conversion of ASCII isspace.
Definition: avstring.h:222
const URLProtocol ff_http_protocol
#define AVIO_FLAG_WRITE
write-only
Definition: avio.h:644
int av_strncasecmp(const char *a, const char *b, size_t n)
Locale-independent case-insensitive compare.
Definition: avstring.c:223
uint64_t icy_metaint
Definition: http.c:103
#define AVERROR_HTTP_NOT_FOUND
Definition: error.h:79
int av_dict_copy(AVDictionary **dst, const AVDictionary *src, int flags)
Copy entries from one AVDictionary struct into another.
Definition: dict.c:217
int flags
Definition: url.h:43
static int http_listen(URLContext *h, const char *uri, int flags, AVDictionary **options)
Definition: http.c:453
char * content_type
Definition: http.c:80
uint64_t filesize
Definition: http.c:69
int version
Definition: avisynth_c.h:766
int av_usleep(unsigned usec)
Sleep for a period of time.
Definition: time.c:84
static int http_getc(HTTPContext *s)
Definition: http.c:545
HTTP Authentication state structure.
Definition: httpauth.h:55
#define src
Definition: vp8dsp.c:254
int auth_type
The currently chosen auth type.
Definition: httpauth.h:59
#define WHITESPACES
Definition: http.c:53
int is_connected_server
Definition: http.c:125
#define AV_DICT_DONT_STRDUP_KEY
Take ownership of a key that's been allocated with av_malloc() or another memory allocation function...
Definition: dict.h:73
#define HTTP_SINGLE
Definition: http.c:50
#define MAX_URL_SIZE
Definition: internal.h:30
static int parse_cookie(HTTPContext *s, const char *p, AVDictionary **cookies)
Definition: http.c:741
#define av_assert0(cond)
assert() equivalent, that is always enabled.
Definition: avassert.h:37
int end_chunked_post
Definition: http.c:87
int av_stristart(const char *str, const char *pfx, const char **ptr)
Return non-zero if pfx is a prefix of str independent of case.
Definition: avstring.c:45
static int http_get_file_handle(URLContext *h)
Definition: http.c:1629
static int http_buf_read(URLContext *h, uint8_t *buf, int size)
Definition: http.c:1275
uint8_t
#define av_malloc(s)
int post_datalen
Definition: http.c:93
AVOptions.
int ff_http_averror(int status_code, int default_averror)
Definition: http.c:320
miscellaneous OS support macros and functions.
#define AV_LOG_TRACE
Extremely verbose debugging, useful for libav* development.
Definition: log.h:202
static int http_read_header(URLContext *h, int *new_location)
Definition: http.c:1069
static av_cold int end(AVCodecContext *avctx)
Definition: avrndec.c:90
uint8_t pi<< 24) CONV_FUNC(AV_SAMPLE_FMT_S64, int64_t, AV_SAMPLE_FMT_U8,(uint64_t)((*(constuint8_t *) pi-0x80U))<< 56) CONV_FUNC(AV_SAMPLE_FMT_FLT, float, AV_SAMPLE_FMT_U8,(*(constuint8_t *) pi-0x80)*(1.0f/(1<< 7))) CONV_FUNC(AV_SAMPLE_FMT_DBL, double, AV_SAMPLE_FMT_U8,(*(constuint8_t *) pi-0x80)*(1.0/(1<< 7))) CONV_FUNC(AV_SAMPLE_FMT_U8, uint8_t, AV_SAMPLE_FMT_S16,(*(constint16_t *) pi >>8)+0x80) CONV_FUNC(AV_SAMPLE_FMT_S64, int64_t, AV_SAMPLE_FMT_S16,(uint64_t)(*(constint16_t *) pi)<< 48) CONV_FUNC(AV_SAMPLE_FMT_FLT, float, AV_SAMPLE_FMT_S16,*(constint16_t *) pi *(1.0f/(1<< 15))) CONV_FUNC(AV_SAMPLE_FMT_DBL, double, AV_SAMPLE_FMT_S16,*(constint16_t *) pi *(1.0/(1<< 15))) CONV_FUNC(AV_SAMPLE_FMT_U8, uint8_t, AV_SAMPLE_FMT_S32,(*(constint32_t *) pi >>24)+0x80) CONV_FUNC(AV_SAMPLE_FMT_S64, int64_t, AV_SAMPLE_FMT_S32,(uint64_t)(*(constint32_t *) pi)<< 32) CONV_FUNC(AV_SAMPLE_FMT_FLT, float, AV_SAMPLE_FMT_S32,*(constint32_t *) pi *(1.0f/(1U<< 31))) CONV_FUNC(AV_SAMPLE_FMT_DBL, double, AV_SAMPLE_FMT_S32,*(constint32_t *) pi *(1.0/(1U<< 31))) CONV_FUNC(AV_SAMPLE_FMT_U8, uint8_t, AV_SAMPLE_FMT_S64,(*(constint64_t *) pi >>56)+0x80) CONV_FUNC(AV_SAMPLE_FMT_FLT, float, AV_SAMPLE_FMT_S64,*(constint64_t *) pi *(1.0f/(INT64_C(1)<< 63))) CONV_FUNC(AV_SAMPLE_FMT_DBL, double, AV_SAMPLE_FMT_S64,*(constint64_t *) pi *(1.0/(INT64_C(1)<< 63))) CONV_FUNC(AV_SAMPLE_FMT_U8, uint8_t, AV_SAMPLE_FMT_FLT, av_clip_uint8(lrintf(*(constfloat *) pi *(1<< 7))+0x80)) CONV_FUNC(AV_SAMPLE_FMT_S16, int16_t, AV_SAMPLE_FMT_FLT, av_clip_int16(lrintf(*(constfloat *) pi *(1<< 15)))) CONV_FUNC(AV_SAMPLE_FMT_S32, int32_t, AV_SAMPLE_FMT_FLT, av_clipl_int32(llrintf(*(constfloat *) pi *(1U<< 31)))) CONV_FUNC(AV_SAMPLE_FMT_S64, int64_t, AV_SAMPLE_FMT_FLT, llrintf(*(constfloat *) pi *(INT64_C(1)<< 63))) CONV_FUNC(AV_SAMPLE_FMT_U8, uint8_t, AV_SAMPLE_FMT_DBL, av_clip_uint8(lrint(*(constdouble *) pi *(1<< 7))+0x80)) CONV_FUNC(AV_SAMPLE_FMT_S16, int16_t, AV_SAMPLE_FMT_DBL, av_clip_int16(lrint(*(constdouble *) pi *(1<< 15)))) CONV_FUNC(AV_SAMPLE_FMT_S32, int32_t, AV_SAMPLE_FMT_DBL, av_clipl_int32(llrint(*(constdouble *) pi *(1U<< 31)))) CONV_FUNC(AV_SAMPLE_FMT_S64, int64_t, AV_SAMPLE_FMT_DBL, llrint(*(constdouble *) pi *(INT64_C(1)<< 63)))#defineFMT_PAIR_FUNC(out, in) staticconv_func_type *constfmt_pair_to_conv_functions[AV_SAMPLE_FMT_NB *AV_SAMPLE_FMT_NB]={FMT_PAIR_FUNC(AV_SAMPLE_FMT_U8, AV_SAMPLE_FMT_U8), FMT_PAIR_FUNC(AV_SAMPLE_FMT_S16, AV_SAMPLE_FMT_U8), FMT_PAIR_FUNC(AV_SAMPLE_FMT_S32, AV_SAMPLE_FMT_U8), FMT_PAIR_FUNC(AV_SAMPLE_FMT_FLT, AV_SAMPLE_FMT_U8), FMT_PAIR_FUNC(AV_SAMPLE_FMT_DBL, AV_SAMPLE_FMT_U8), FMT_PAIR_FUNC(AV_SAMPLE_FMT_S64, AV_SAMPLE_FMT_U8), FMT_PAIR_FUNC(AV_SAMPLE_FMT_U8, AV_SAMPLE_FMT_S16), FMT_PAIR_FUNC(AV_SAMPLE_FMT_S16, AV_SAMPLE_FMT_S16), FMT_PAIR_FUNC(AV_SAMPLE_FMT_S32, AV_SAMPLE_FMT_S16), FMT_PAIR_FUNC(AV_SAMPLE_FMT_FLT, AV_SAMPLE_FMT_S16), FMT_PAIR_FUNC(AV_SAMPLE_FMT_DBL, AV_SAMPLE_FMT_S16), FMT_PAIR_FUNC(AV_SAMPLE_FMT_S64, AV_SAMPLE_FMT_S16), FMT_PAIR_FUNC(AV_SAMPLE_FMT_U8, AV_SAMPLE_FMT_S32), FMT_PAIR_FUNC(AV_SAMPLE_FMT_S16, AV_SAMPLE_FMT_S32), FMT_PAIR_FUNC(AV_SAMPLE_FMT_S32, AV_SAMPLE_FMT_S32), FMT_PAIR_FUNC(AV_SAMPLE_FMT_FLT, AV_SAMPLE_FMT_S32), FMT_PAIR_FUNC(AV_SAMPLE_FMT_DBL, AV_SAMPLE_FMT_S32), FMT_PAIR_FUNC(AV_SAMPLE_FMT_S64, AV_SAMPLE_FMT_S32), FMT_PAIR_FUNC(AV_SAMPLE_FMT_U8, AV_SAMPLE_FMT_FLT), FMT_PAIR_FUNC(AV_SAMPLE_FMT_S16, AV_SAMPLE_FMT_FLT), FMT_PAIR_FUNC(AV_SAMPLE_FMT_S32, AV_SAMPLE_FMT_FLT), FMT_PAIR_FUNC(AV_SAMPLE_FMT_FLT, AV_SAMPLE_FMT_FLT), FMT_PAIR_FUNC(AV_SAMPLE_FMT_DBL, AV_SAMPLE_FMT_FLT), FMT_PAIR_FUNC(AV_SAMPLE_FMT_S64, AV_SAMPLE_FMT_FLT), FMT_PAIR_FUNC(AV_SAMPLE_FMT_U8, AV_SAMPLE_FMT_DBL), FMT_PAIR_FUNC(AV_SAMPLE_FMT_S16, AV_SAMPLE_FMT_DBL), FMT_PAIR_FUNC(AV_SAMPLE_FMT_S32, AV_SAMPLE_FMT_DBL), FMT_PAIR_FUNC(AV_SAMPLE_FMT_FLT, AV_SAMPLE_FMT_DBL), FMT_PAIR_FUNC(AV_SAMPLE_FMT_DBL, AV_SAMPLE_FMT_DBL), FMT_PAIR_FUNC(AV_SAMPLE_FMT_S64, AV_SAMPLE_FMT_DBL), FMT_PAIR_FUNC(AV_SAMPLE_FMT_U8, AV_SAMPLE_FMT_S64), FMT_PAIR_FUNC(AV_SAMPLE_FMT_S16, AV_SAMPLE_FMT_S64), FMT_PAIR_FUNC(AV_SAMPLE_FMT_S32, AV_SAMPLE_FMT_S64), FMT_PAIR_FUNC(AV_SAMPLE_FMT_FLT, AV_SAMPLE_FMT_S64), FMT_PAIR_FUNC(AV_SAMPLE_FMT_DBL, AV_SAMPLE_FMT_S64), FMT_PAIR_FUNC(AV_SAMPLE_FMT_S64, AV_SAMPLE_FMT_S64),};staticvoidcpy1(uint8_t **dst, constuint8_t **src, intlen){memcpy(*dst,*src, len);}staticvoidcpy2(uint8_t **dst, constuint8_t **src, intlen){memcpy(*dst,*src, 2 *len);}staticvoidcpy4(uint8_t **dst, constuint8_t **src, intlen){memcpy(*dst,*src, 4 *len);}staticvoidcpy8(uint8_t **dst, constuint8_t **src, intlen){memcpy(*dst,*src, 8 *len);}AudioConvert *swri_audio_convert_alloc(enumAVSampleFormatout_fmt, enumAVSampleFormatin_fmt, intchannels, constint *ch_map, intflags){AudioConvert *ctx;conv_func_type *f=fmt_pair_to_conv_functions[av_get_packed_sample_fmt(out_fmt)+AV_SAMPLE_FMT_NB *av_get_packed_sample_fmt(in_fmt)];if(!f) returnNULL;ctx=av_mallocz(sizeof(*ctx));if(!ctx) returnNULL;if(channels==1){in_fmt=av_get_planar_sample_fmt(in_fmt);out_fmt=av_get_planar_sample_fmt(out_fmt);}ctx->channels=channels;ctx->conv_f=f;ctx->ch_map=ch_map;if(in_fmt==AV_SAMPLE_FMT_U8||in_fmt==AV_SAMPLE_FMT_U8P) memset(ctx->silence, 0x80, sizeof(ctx->silence));if(out_fmt==in_fmt &&!ch_map){switch(av_get_bytes_per_sample(in_fmt)){case1:ctx->simd_f=cpy1;break;case2:ctx->simd_f=cpy2;break;case4:ctx->simd_f=cpy4;break;case8:ctx->simd_f=cpy8;break;}}if(HAVE_X86ASM &&1) swri_audio_convert_init_x86(ctx, out_fmt, in_fmt, channels);if(ARCH_ARM) swri_audio_convert_init_arm(ctx, out_fmt, in_fmt, channels);if(ARCH_AARCH64) swri_audio_convert_init_aarch64(ctx, out_fmt, in_fmt, channels);returnctx;}voidswri_audio_convert_free(AudioConvert **ctx){av_freep(ctx);}intswri_audio_convert(AudioConvert *ctx, AudioData *out, AudioData *in, intlen){intch;intoff=0;constintos=(out->planar?1:out->ch_count)*out->bps;unsignedmisaligned=0;av_assert0(ctx->channels==out->ch_count);if(ctx->in_simd_align_mask){intplanes=in->planar?in->ch_count:1;unsignedm=0;for(ch=0;ch< planes;ch++) m|=(intptr_t) in->ch[ch];misaligned|=m &ctx->in_simd_align_mask;}if(ctx->out_simd_align_mask){intplanes=out->planar?out->ch_count:1;unsignedm=0;for(ch=0;ch< planes;ch++) m|=(intptr_t) out->ch[ch];misaligned|=m &ctx->out_simd_align_mask;}if(ctx->simd_f &&!ctx->ch_map &&!misaligned){off=len &~15;av_assert1(off >=0);av_assert1(off<=len);av_assert2(ctx->channels==SWR_CH_MAX||!in->ch[ctx->channels]);if(off >0){if(out->planar==in->planar){intplanes=out->planar?out->ch_count:1;for(ch=0;ch< planes;ch++){ctx->simd_f(out-> ch ch
Definition: audioconvert.c:56
#define HTTP_HEADERS_SIZE
Definition: http.h:27
int is_akamai
Definition: http.c:94
#define SPACE_CHARS
static int http_open_cnx(URLContext *h, AVDictionary **options)
Definition: http.c:246
char * av_small_strptime(const char *p, const char *fmt, struct tm *dt)
Simplified version of strptime.
Definition: parseutils.c:489
AVDictionaryEntry * av_dict_get(const AVDictionary *m, const char *key, const AVDictionaryEntry *prev, int flags)
Get a dictionary entry with matching key.
Definition: dict.c:40
static void inflate(uint8_t *dst, const uint8_t *p1, int width, int threshold, const uint8_t *coordinates[], int coord)
Definition: vf_neighbor.c:129
static int flags
Definition: log.c:57
uint32_t tag
Definition: movenc.c:1456
#define DEFAULT_USER_AGENT
Definition: http.c:131
#define AVERROR_EOF
End of file.
Definition: error.h:55
void ff_http_init_auth_state(URLContext *dest, const URLContext *src)
Initialize the authentication state based on another HTTP URLContext.
Definition: http.c:174
uint64_t icy_data_read
Definition: http.c:101
HTTP 1.0 Basic auth from RFC 1945 (also in RFC 2617)
Definition: httpauth.h:30
ptrdiff_t size
Definition: opengl_enc.c:101
static const uint8_t header[24]
Definition: sdr2.c:67
static int http_open_cnx_internal(URLContext *h, AVDictionary **options)
Definition: http.c:184
int line_count
Definition: http.c:65
#define av_log(a,...)
unsigned char * buf_end
Definition: http.c:64
static void update_metadata(HTTPContext *s, char *data)
Definition: http.c:1429
static void body(uint32_t ABCD[4], const uint8_t *src, int nblocks)
Definition: md5.c:101
#define U(x)
Definition: vp56_arith.h:37
int is_multi_client
Definition: http.c:123
int chunked_post
Definition: http.c:85
static int64_t http_seek_internal(URLContext *h, int64_t off, int whence, int force_reconnect)
Definition: http.c:1573
int ffurl_alloc(URLContext **puc, const char *filename, int flags, const AVIOInterruptCB *int_cb)
Create a URLContext for accessing to the resource indicated by url, but do not initiate the connectio...
Definition: avio.c:292
#define AV_LOG_ERROR
Something went wrong and cannot losslessly be recovered.
Definition: log.h:176
int reconnect_delay_max
Definition: http.c:119
#define E
Definition: http.c:130
const char * protocol_whitelist
Definition: url.h:49
#define AVERROR(e)
Definition: error.h:43
static int http_write(URLContext *h, const uint8_t *buf, int size)
Definition: http.c:1510
static const AVOption options[]
Definition: http.c:133
#define AV_LOG_DEBUG
Stuff which is only useful for libav* developers.
Definition: log.h:197
void av_dict_free(AVDictionary **pm)
Free all the memory allocated for an AVDictionary struct and all keys and values. ...
Definition: dict.c:203
static int http_handshake(URLContext *c)
Definition: http.c:417
Definition: graph2dot.c:48
uint64_t off
Definition: http.c:69
simple assert() macros that are a bit more flexible than ISO C assert().
#define OFFSET(x)
Definition: http.c:128
size_t av_strlcpy(char *dst, const char *src, size_t size)
Copy the string src to dst, but no more than size - 1 bytes, and null-terminate dst.
Definition: avstring.c:83
#define fail()
Definition: checkasm.h:95
uint64_t chunksize
Definition: http.c:68
AVDictionary * chained_options
Definition: http.c:112
#define AVERROR_HTTP_SERVER_ERROR
Definition: error.h:81
char * av_asprintf(const char *fmt,...)
Definition: avstring.c:113
static int store_icy(URLContext *h, int size)
Definition: http.c:1455
char * headers
Definition: http.c:74
char * user_agent
Definition: http.c:76
#define AVERROR_HTTP_UNAUTHORIZED
Definition: error.h:77
char * icy_metadata_packet
Definition: http.c:105
char method[16]
Definition: ffserver.c:165
int ffurl_get_short_seek(URLContext *h)
Return the current short seek threshold value for this URL.
Definition: avio.c:648
#define FFMIN(a, b)
Definition: common.h:96
static int http_get_short_seek(URLContext *h)
Definition: http.c:1635
const URLProtocol ff_httpproxy_protocol
int av_strcasecmp(const char *a, const char *b)
Locale-independent case-insensitive compare.
Definition: avstring.c:213
GLsizei GLboolean const GLfloat * value
Definition: opengl_enc.c:109
int send_expect_100
Definition: http.c:113
#define av_err2str(errnum)
Convenience macro, the return value should be used only directly in function arguments but never stan...
Definition: error.h:119
int willclose
Definition: http.c:83
int is_mediagateway
Definition: http.c:95
int ffurl_handshake(URLContext *c)
Perform one step of the protocol handshake to accept a new client.
Definition: avio.c:234
int reconnect
Definition: http.c:115
int ff_http_match_no_proxy(const char *no_proxy, const char *hostname)
Definition: network.c:307
int ffurl_get_file_handle(URLContext *h)
Return the file descriptor associated with this URL.
Definition: avio.c:626
int ffurl_accept(URLContext *s, URLContext **c)
Accept an URLContext c on an URLContext s.
Definition: avio.c:226
AVDictionary * cookie_dict
Definition: http.c:98
static void error(const char *err)
int stale
Auth ok, but needs to be resent with a new nonce.
Definition: httpauth.h:71
offset must point to a pointer immediately followed by an int for the length
Definition: opt.h:229
int ffurl_closep(URLContext **hh)
Close the resource accessed by the URLContext h, and free the memory used by it.
Definition: avio.c:444
int64_t av_gettime(void)
Get the current time in microseconds.
Definition: time.c:39
int ff_url_join(char *str, int size, const char *proto, const char *authorization, const char *hostname, int port, const char *fmt,...)
Definition: url.c:36
int reconnect_streamed
Definition: http.c:117
static int http_read(URLContext *h, uint8_t *buf, int size)
Definition: http.c:1493
#define AV_LOG_INFO
Standard information.
Definition: log.h:187
int av_reallocp(void *ptr, size_t size)
Allocate, reallocate, or free a block of memory through a pointer to a pointer.
Definition: mem.c:163
char * av_strdup(const char *s)
Duplicate a string.
Definition: mem.c:237
const char * protocol_blacklist
Definition: url.h:50
char * http_proxy
Definition: http.c:73
HandshakeState handshake_step
Definition: http.c:124
int seekable
Control seekability, 0 = disable, 1 = enable, -1 = probe.
Definition: http.c:84
#define MAX_EXPIRY
Definition: http.c:52
void * buf
Definition: avisynth_c.h:690
Definition: url.h:38
#define AVIO_FLAG_READ_WRITE
read-write pseudo flag
Definition: avio.h:645
int av_dict_set(AVDictionary **pm, const char *key, const char *value, int flags)
Set the given entry in *pm, overwriting an existing entry.
Definition: dict.c:70
Describe the class of an AVClass context structure.
Definition: log.h:67
void * priv_data
Definition: url.h:41
#define AVERROR_HTTP_OTHER_4XX
Definition: error.h:80
size_t av_strlcatf(char *dst, size_t size, const char *fmt,...)
Definition: avstring.c:101
#define snprintf
Definition: snprintf.h:34
int icy
Definition: http.c:99
misc parsing utilities
char * ff_http_auth_create_response(HTTPAuthState *state, const char *auth, const char *path, const char *method)
Definition: httpauth.c:245
const char * name
Definition: url.h:55
URLContext * hd
Definition: http.c:63
static int has_header(const char *str, const char *header)
Definition: http.c:1061
char * mime_type
Definition: http.c:75
#define SIZE_SPECIFIER
Definition: internal.h:255
#define AVERROR_HTTP_FORBIDDEN
Definition: error.h:78
int ffurl_close(URLContext *h)
Definition: avio.c:467
static int process_line(URLContext *h, char *line, int line_count, int *new_location)
Definition: http.c:825
int ff_http_do_new_request(URLContext *h, const char *uri)
Send a new HTTP request, reusing the old connection.
Definition: http.c:302
char * av_strtok(char *s, const char *delim, char **saveptr)
Split the string into several tokens which can be accessed by successive calls to av_strtok()...
Definition: avstring.c:184
int av_strstart(const char *str, const char *pfx, const char **ptr)
Return non-zero if pfx is a prefix of str.
Definition: avstring.c:34
Main libavformat public API header.
char * cookies
holds newline ( ) delimited Set-Cookie header field values (without the "Set-Cookie: " field name) ...
Definition: http.c:96
#define MAX_REDIRECTS
Definition: http.c:49
static int parse_content_encoding(URLContext *h, const char *p)
Definition: http.c:630
int reconnect_at_eof
Definition: http.c:116
static double c[64]
int av_dict_set_int(AVDictionary **pm, const char *key, int64_t value, int flags)
Convenience wrapper for av_dict_set that converts the value to a string and stores it...
Definition: dict.c:147
HandshakeState
Definition: http.c:54
static int get_cookies(HTTPContext *s, char **cookies, const char *path, const char *domain)
Create a string containing cookie values for use as a HTTP cookie header field value for a particular...
Definition: http.c:970
int http_code
Definition: http.c:66
char * filename
specified URL
Definition: url.h:42
int listen
Definition: http.c:120
static int http_open(URLContext *h, const char *uri, int flags, AVDictionary **options)
Definition: http.c:484
#define AVSEEK_SIZE
ORing this as the "whence" parameter to a seek function causes it to return the filesize without seek...
Definition: avio.h:522
char * key
Definition: dict.h:86
void ff_http_auth_handle_header(HTTPAuthState *state, const char *key, const char *value)
Definition: httpauth.c:90
int multiple_requests
Definition: http.c:91
HTTPAuthState auth_state
Definition: http.c:71
#define av_free(p)
static int cookie_string(AVDictionary *dict, char **cookies)
Definition: http.c:802
char * value
Definition: dict.h:87
const URLProtocol ff_https_protocol
int len
static int parse_location(HTTPContext *s, const char *p)
Definition: http.c:601
uint8_t * buffer
Definition: ffserver.c:169
char * resource
Definition: http.c:121
char * location
Definition: http.c:70
static int http_shutdown(URLContext *h, int flags)
Definition: http.c:1536
static int http_write_reply(URLContext *h, int status_code)
Definition: http.c:337
#define AV_OPT_FLAG_READONLY
The option may not be set through the AVOptions API, only read.
Definition: opt.h:292
int end_header
Definition: http.c:89
unsigned char * buf_ptr
Definition: http.c:64
#define D
Definition: http.c:129
#define AVERROR_HTTP_BAD_REQUEST
Definition: error.h:76
char * method
Definition: http.c:114
static int parse_icy(HTTPContext *s, const char *tag, const char *p)
Definition: http.c:664
uint64_t end_off
Definition: http.c:69
static int parse_set_cookie_expiry_time(const char *exp_str, struct tm *buf)
Definition: http.c:686
static int http_read_stream(URLContext *h, uint8_t *buf, int size)
Definition: http.c:1372
#define av_freep(p)
static int http_read_stream_all(URLContext *h, uint8_t *buf, int size)
Definition: http.c:1417
#define AV_DICT_IGNORE_SUFFIX
Return first entry in a dictionary whose first part corresponds to the search key, ignoring the suffix of the found key string.
Definition: dict.h:70
unbuffered private I/O API
static void handle_http_errors(URLContext *h, int error)
Definition: http.c:411
static int parse_set_cookie(const char *set_cookie, AVDictionary **dict)
Definition: http.c:711
static int64_t http_seek(URLContext *h, int64_t off, int whence)
Definition: http.c:1624
int reply_code
Definition: http.c:122
int av_opt_set(void *obj, const char *name, const char *val, int search_flags)
Definition: opt.c:449
int ffurl_read(URLContext *h, unsigned char *buf, int size)
Read up to size bytes from the resource accessed by h, and store the read bytes in buf...
Definition: avio.c:407
char * av_strndup(const char *s, size_t len)
Duplicate a substring of a string.
Definition: mem.c:249
static int http_accept(URLContext *s, URLContext **c)
Definition: http.c:525
GLuint buffer
Definition: opengl_enc.c:102
#define HTTP_CLASS(flavor)
Definition: http.c:1641
No authentication specified.
Definition: httpauth.h:29
static int check_http_code(URLContext *h, int http_code, const char *end)
Definition: http.c:586
const char * name
Definition: opengl_enc.c:103
static uint8_t tmp[11]
Definition: aes_ctr.c:26