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