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