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