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 "libavutil/avstring.h"
23 #include "avformat.h"
24 #include "internal.h"
25 #include "network.h"
26 #include "http.h"
27 #include "os_support.h"
28 #include "httpauth.h"
29 #include "url.h"
30 #include "libavutil/opt.h"
31 
32 /* XXX: POST protocol is not completely implemented because ffmpeg uses
33  only a subset of it. */
34 
35 /* The IO buffer size is unrelated to the max URL size in itself, but needs
36  * to be large enough to fit the full request headers (including long
37  * path names).
38  */
39 #define BUFFER_SIZE MAX_URL_SIZE
40 #define MAX_REDIRECTS 8
41 
42 typedef struct {
43  const AVClass *class;
45  unsigned char buffer[BUFFER_SIZE], *buf_ptr, *buf_end;
47  int http_code;
48  int64_t chunksize; /**< Used if "Transfer-Encoding: chunked" otherwise -1. */
49  char *content_type;
50  char *user_agent;
51  int64_t off, filesize;
52  int icy_data_read; ///< how much data was read since last ICY metadata packet
53  int icy_metaint; ///< after how many bytes of read data a new metadata packet will be found
54  char location[MAX_URL_SIZE];
57  char *headers;
58  int willclose; /**< Set if the server correctly handles Connection: close and will close the connection after feeding us the content. */
59  int seekable; /**< Control seekability, 0 = disable, 1 = enable, -1 = probe. */
61  int end_chunked_post; /**< A flag which indicates if the end of chunked encoding has been sent. */
62  int end_header; /**< A flag which indicates we have finished to read POST reply. */
63  int multiple_requests; /**< A flag which indicates if we use persistent connections. */
66  int is_akamai;
68  char *mime_type;
69  char *cookies; ///< holds newline (\n) delimited Set-Cookie header field values (without the "Set-Cookie: " field name)
70  int icy;
73 } HTTPContext;
74 
75 #define OFFSET(x) offsetof(HTTPContext, x)
76 #define D AV_OPT_FLAG_DECODING_PARAM
77 #define E AV_OPT_FLAG_ENCODING_PARAM
78 #define DEFAULT_USER_AGENT "Lavf/" AV_STRINGIFY(LIBAVFORMAT_VERSION)
79 static const AVOption options[] = {
80 {"seekable", "control seekability of connection", OFFSET(seekable), AV_OPT_TYPE_INT, {.i64 = -1}, -1, 1, D },
81 {"chunked_post", "use chunked transfer-encoding for posts", OFFSET(chunked_post), AV_OPT_TYPE_INT, {.i64 = 1}, 0, 1, E },
82 {"headers", "set custom HTTP headers, can override built in default headers", OFFSET(headers), AV_OPT_TYPE_STRING, { 0 }, 0, 0, D|E },
83 {"content_type", "force a content type", OFFSET(content_type), AV_OPT_TYPE_STRING, { 0 }, 0, 0, D|E },
84 {"user-agent", "override User-Agent header", OFFSET(user_agent), AV_OPT_TYPE_STRING, {.str = DEFAULT_USER_AGENT}, 0, 0, D },
85 {"multiple_requests", "use persistent connections", OFFSET(multiple_requests), AV_OPT_TYPE_INT, {.i64 = 0}, 0, 1, D|E },
86 {"post_data", "set custom HTTP post data", OFFSET(post_data), AV_OPT_TYPE_BINARY, .flags = D|E },
87 {"timeout", "set timeout of socket I/O operations", OFFSET(rw_timeout), AV_OPT_TYPE_INT, {.i64 = -1}, -1, INT_MAX, D|E },
88 {"mime_type", "set MIME type", OFFSET(mime_type), AV_OPT_TYPE_STRING, {0}, 0, 0, 0 },
89 {"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, 0 },
90 {"icy", "request ICY metadata", OFFSET(icy), AV_OPT_TYPE_INT, {.i64 = 0}, 0, 1, D },
91 {"icy_metadata_headers", "return ICY metadata headers", OFFSET(icy_metadata_headers), AV_OPT_TYPE_STRING, {0}, 0, 0, 0 },
92 {"icy_metadata_packet", "return current ICY metadata packet", OFFSET(icy_metadata_packet), AV_OPT_TYPE_STRING, {0}, 0, 0, 0 },
93 {NULL}
94 };
95 #define HTTP_CLASS(flavor)\
96 static const AVClass flavor ## _context_class = {\
97  .class_name = #flavor,\
98  .item_name = av_default_item_name,\
99  .option = options,\
100  .version = LIBAVUTIL_VERSION_INT,\
101 }
102 
103 HTTP_CLASS(http);
104 HTTP_CLASS(https);
105 
106 static int http_connect(URLContext *h, const char *path, const char *local_path,
107  const char *hoststr, const char *auth,
108  const char *proxyauth, int *new_location);
109 
111 {
112  memcpy(&((HTTPContext*)dest->priv_data)->auth_state,
113  &((HTTPContext*)src->priv_data)->auth_state, sizeof(HTTPAuthState));
114  memcpy(&((HTTPContext*)dest->priv_data)->proxy_auth_state,
115  &((HTTPContext*)src->priv_data)->proxy_auth_state,
116  sizeof(HTTPAuthState));
117 }
118 
119 /* return non zero if error */
120 static int http_open_cnx(URLContext *h)
121 {
122  const char *path, *proxy_path, *lower_proto = "tcp", *local_path;
123  char hostname[1024], hoststr[1024], proto[10];
124  char auth[1024], proxyauth[1024] = "";
125  char path1[MAX_URL_SIZE];
126  char buf[1024], urlbuf[MAX_URL_SIZE];
127  int port, use_proxy, err, location_changed = 0, redirects = 0, attempts = 0;
128  HTTPAuthType cur_auth_type, cur_proxy_auth_type;
129  HTTPContext *s = h->priv_data;
130 
131  /* fill the dest addr */
132  redo:
133  /* needed in any case to build the host string */
134  av_url_split(proto, sizeof(proto), auth, sizeof(auth),
135  hostname, sizeof(hostname), &port,
136  path1, sizeof(path1), s->location);
137  ff_url_join(hoststr, sizeof(hoststr), NULL, NULL, hostname, port, NULL);
138 
139  proxy_path = getenv("http_proxy");
140  use_proxy = !ff_http_match_no_proxy(getenv("no_proxy"), hostname) &&
141  proxy_path != NULL && av_strstart(proxy_path, "http://", NULL);
142 
143  if (!strcmp(proto, "https")) {
144  lower_proto = "tls";
145  use_proxy = 0;
146  if (port < 0)
147  port = 443;
148  }
149  if (port < 0)
150  port = 80;
151 
152  if (path1[0] == '\0')
153  path = "/";
154  else
155  path = path1;
156  local_path = path;
157  if (use_proxy) {
158  /* Reassemble the request URL without auth string - we don't
159  * want to leak the auth to the proxy. */
160  ff_url_join(urlbuf, sizeof(urlbuf), proto, NULL, hostname, port, "%s",
161  path1);
162  path = urlbuf;
163  av_url_split(NULL, 0, proxyauth, sizeof(proxyauth),
164  hostname, sizeof(hostname), &port, NULL, 0, proxy_path);
165  }
166 
167  ff_url_join(buf, sizeof(buf), lower_proto, NULL, hostname, port, NULL);
168 
169  if (!s->hd) {
170  AVDictionary *opts = NULL;
171  char opts_format[20];
172  if (s->rw_timeout != -1) {
173  snprintf(opts_format, sizeof(opts_format), "%d", s->rw_timeout);
174  av_dict_set(&opts, "timeout", opts_format, 0);
175  } /* if option is not given, don't pass it and let tcp use its own default */
176  err = ffurl_open(&s->hd, buf, AVIO_FLAG_READ_WRITE,
177  &h->interrupt_callback, &opts);
178  av_dict_free(&opts);
179  if (err < 0)
180  goto fail;
181  }
182 
183  cur_auth_type = s->auth_state.auth_type;
184  cur_proxy_auth_type = s->auth_state.auth_type;
185  if (http_connect(h, path, local_path, hoststr, auth, proxyauth, &location_changed) < 0)
186  goto fail;
187  attempts++;
188  if (s->http_code == 401) {
189  if ((cur_auth_type == HTTP_AUTH_NONE || s->auth_state.stale) &&
190  s->auth_state.auth_type != HTTP_AUTH_NONE && attempts < 4) {
191  ffurl_closep(&s->hd);
192  goto redo;
193  } else
194  goto fail;
195  }
196  if (s->http_code == 407) {
197  if ((cur_proxy_auth_type == HTTP_AUTH_NONE || s->proxy_auth_state.stale) &&
198  s->proxy_auth_state.auth_type != HTTP_AUTH_NONE && attempts < 4) {
199  ffurl_closep(&s->hd);
200  goto redo;
201  } else
202  goto fail;
203  }
204  if ((s->http_code == 301 || s->http_code == 302 || s->http_code == 303 || s->http_code == 307)
205  && location_changed == 1) {
206  /* url moved, get next */
207  ffurl_closep(&s->hd);
208  if (redirects++ >= MAX_REDIRECTS)
209  return AVERROR(EIO);
210  /* Restart the authentication process with the new target, which
211  * might use a different auth mechanism. */
212  memset(&s->auth_state, 0, sizeof(s->auth_state));
213  attempts = 0;
214  location_changed = 0;
215  goto redo;
216  }
217  return 0;
218  fail:
219  if (s->hd)
220  ffurl_closep(&s->hd);
221  return AVERROR(EIO);
222 }
223 
224 int ff_http_do_new_request(URLContext *h, const char *uri)
225 {
226  HTTPContext *s = h->priv_data;
227 
228  s->off = 0;
229  s->icy_data_read = 0;
230  av_strlcpy(s->location, uri, sizeof(s->location));
231 
232  return http_open_cnx(h);
233 }
234 
235 static int http_open(URLContext *h, const char *uri, int flags)
236 {
237  HTTPContext *s = h->priv_data;
238 
239  if( s->seekable == 1 )
240  h->is_streamed = 0;
241  else
242  h->is_streamed = 1;
243 
244  s->filesize = -1;
245  av_strlcpy(s->location, uri, sizeof(s->location));
246 
247  if (s->headers) {
248  int len = strlen(s->headers);
249  if (len < 2 || strcmp("\r\n", s->headers + len - 2))
250  av_log(h, AV_LOG_WARNING, "No trailing CRLF found in HTTP header.\n");
251  }
252 
253  return http_open_cnx(h);
254 }
255 static int http_getc(HTTPContext *s)
256 {
257  int len;
258  if (s->buf_ptr >= s->buf_end) {
259  len = ffurl_read(s->hd, s->buffer, BUFFER_SIZE);
260  if (len < 0) {
261  return len;
262  } else if (len == 0) {
263  return -1;
264  } else {
265  s->buf_ptr = s->buffer;
266  s->buf_end = s->buffer + len;
267  }
268  }
269  return *s->buf_ptr++;
270 }
271 
272 static int http_get_line(HTTPContext *s, char *line, int line_size)
273 {
274  int ch;
275  char *q;
276 
277  q = line;
278  for(;;) {
279  ch = http_getc(s);
280  if (ch < 0)
281  return ch;
282  if (ch == '\n') {
283  /* process line */
284  if (q > line && q[-1] == '\r')
285  q--;
286  *q = '\0';
287 
288  return 0;
289  } else {
290  if ((q - line) < line_size - 1)
291  *q++ = ch;
292  }
293  }
294 }
295 
296 static int process_line(URLContext *h, char *line, int line_count,
297  int *new_location)
298 {
299  HTTPContext *s = h->priv_data;
300  char *tag, *p, *end;
301  char redirected_location[MAX_URL_SIZE];
302 
303  /* end of header */
304  if (line[0] == '\0') {
305  s->end_header = 1;
306  return 0;
307  }
308 
309  p = line;
310  if (line_count == 0) {
311  while (!av_isspace(*p) && *p != '\0')
312  p++;
313  while (av_isspace(*p))
314  p++;
315  s->http_code = strtol(p, &end, 10);
316 
317  av_dlog(NULL, "http_code=%d\n", s->http_code);
318 
319  /* error codes are 4xx and 5xx, but regard 401 as a success, so we
320  * don't abort until all headers have been parsed. */
321  if (s->http_code >= 400 && s->http_code < 600 && (s->http_code != 401
322  || s->auth_state.auth_type != HTTP_AUTH_NONE) &&
323  (s->http_code != 407 || s->proxy_auth_state.auth_type != HTTP_AUTH_NONE)) {
324  end += strspn(end, SPACE_CHARS);
325  av_log(h, AV_LOG_WARNING, "HTTP error %d %s\n",
326  s->http_code, end);
327  return -1;
328  }
329  } else {
330  while (*p != '\0' && *p != ':')
331  p++;
332  if (*p != ':')
333  return 1;
334 
335  *p = '\0';
336  tag = line;
337  p++;
338  while (av_isspace(*p))
339  p++;
340  if (!av_strcasecmp(tag, "Location")) {
341  ff_make_absolute_url(redirected_location, sizeof(redirected_location), s->location, p);
342  av_strlcpy(s->location, redirected_location, sizeof(s->location));
343  *new_location = 1;
344  } else if (!av_strcasecmp (tag, "Content-Length") && s->filesize == -1) {
345  s->filesize = strtoll(p, NULL, 10);
346  } else if (!av_strcasecmp (tag, "Content-Range")) {
347  /* "bytes $from-$to/$document_size" */
348  const char *slash;
349  if (!strncmp (p, "bytes ", 6)) {
350  p += 6;
351  s->off = strtoll(p, NULL, 10);
352  if ((slash = strchr(p, '/')) && strlen(slash) > 0)
353  s->filesize = strtoll(slash+1, NULL, 10);
354  }
355  if (s->seekable == -1 && (!s->is_akamai || s->filesize != 2147483647))
356  h->is_streamed = 0; /* we _can_ in fact seek */
357  } else if (!av_strcasecmp(tag, "Accept-Ranges") && !strncmp(p, "bytes", 5) && s->seekable == -1) {
358  h->is_streamed = 0;
359  } else if (!av_strcasecmp (tag, "Transfer-Encoding") && !av_strncasecmp(p, "chunked", 7)) {
360  s->filesize = -1;
361  s->chunksize = 0;
362  } else if (!av_strcasecmp (tag, "WWW-Authenticate")) {
364  } else if (!av_strcasecmp (tag, "Authentication-Info")) {
366  } else if (!av_strcasecmp (tag, "Proxy-Authenticate")) {
368  } else if (!av_strcasecmp (tag, "Connection")) {
369  if (!strcmp(p, "close"))
370  s->willclose = 1;
371  } else if (!av_strcasecmp (tag, "Server") && !av_strcasecmp (p, "AkamaiGHost")) {
372  s->is_akamai = 1;
373  } else if (!av_strcasecmp (tag, "Content-Type")) {
374  av_free(s->mime_type); s->mime_type = av_strdup(p);
375  } else if (!av_strcasecmp (tag, "Set-Cookie")) {
376  if (!s->cookies) {
377  if (!(s->cookies = av_strdup(p)))
378  return AVERROR(ENOMEM);
379  } else {
380  char *tmp = s->cookies;
381  size_t str_size = strlen(tmp) + strlen(p) + 2;
382  if (!(s->cookies = av_malloc(str_size))) {
383  s->cookies = tmp;
384  return AVERROR(ENOMEM);
385  }
386  snprintf(s->cookies, str_size, "%s\n%s", tmp, p);
387  av_free(tmp);
388  }
389  } else if (!av_strcasecmp (tag, "Icy-MetaInt")) {
390  s->icy_metaint = strtoll(p, NULL, 10);
391  } else if (!av_strncasecmp(tag, "Icy-", 4)) {
392  // Concat all Icy- header lines
393  char *buf = av_asprintf("%s%s: %s\n",
394  s->icy_metadata_headers ? s->icy_metadata_headers : "", tag, p);
395  if (!buf)
396  return AVERROR(ENOMEM);
399  }
400  }
401  return 1;
402 }
403 
404 /**
405  * Create a string containing cookie values for use as a HTTP cookie header
406  * field value for a particular path and domain from the cookie values stored in
407  * the HTTP protocol context. The cookie string is stored in *cookies.
408  *
409  * @return a negative value if an error condition occurred, 0 otherwise
410  */
411 static int get_cookies(HTTPContext *s, char **cookies, const char *path,
412  const char *domain)
413 {
414  // cookie strings will look like Set-Cookie header field values. Multiple
415  // Set-Cookie fields will result in multiple values delimited by a newline
416  int ret = 0;
417  char *next, *cookie, *set_cookies = av_strdup(s->cookies), *cset_cookies = set_cookies;
418 
419  if (!set_cookies) return AVERROR(EINVAL);
420 
421  *cookies = NULL;
422  while ((cookie = av_strtok(set_cookies, "\n", &next))) {
423  int domain_offset = 0;
424  char *param, *next_param, *cdomain = NULL, *cpath = NULL, *cvalue = NULL;
425  set_cookies = NULL;
426 
427  while ((param = av_strtok(cookie, "; ", &next_param))) {
428  cookie = NULL;
429  if (!av_strncasecmp("path=", param, 5)) {
430  av_free(cpath);
431  cpath = av_strdup(&param[5]);
432  } else if (!av_strncasecmp("domain=", param, 7)) {
433  av_free(cdomain);
434  cdomain = av_strdup(&param[7]);
435  } else if (!av_strncasecmp("secure", param, 6) ||
436  !av_strncasecmp("comment", param, 7) ||
437  !av_strncasecmp("max-age", param, 7) ||
438  !av_strncasecmp("version", param, 7)) {
439  // ignore Comment, Max-Age, Secure and Version
440  } else {
441  av_free(cvalue);
442  cvalue = av_strdup(param);
443  }
444  }
445  if (!cdomain)
446  cdomain = av_strdup(domain);
447 
448  // ensure all of the necessary values are valid
449  if (!cdomain || !cpath || !cvalue) {
451  "Invalid cookie found, no value, path or domain specified\n");
452  goto done_cookie;
453  }
454 
455  // check if the request path matches the cookie path
456  if (av_strncasecmp(path, cpath, strlen(cpath)))
457  goto done_cookie;
458 
459  // the domain should be at least the size of our cookie domain
460  domain_offset = strlen(domain) - strlen(cdomain);
461  if (domain_offset < 0)
462  goto done_cookie;
463 
464  // match the cookie domain
465  if (av_strcasecmp(&domain[domain_offset], cdomain))
466  goto done_cookie;
467 
468  // cookie parameters match, so copy the value
469  if (!*cookies) {
470  if (!(*cookies = av_strdup(cvalue))) {
471  ret = AVERROR(ENOMEM);
472  goto done_cookie;
473  }
474  } else {
475  char *tmp = *cookies;
476  size_t str_size = strlen(cvalue) + strlen(*cookies) + 3;
477  if (!(*cookies = av_malloc(str_size))) {
478  ret = AVERROR(ENOMEM);
479  goto done_cookie;
480  }
481  snprintf(*cookies, str_size, "%s; %s", tmp, cvalue);
482  av_free(tmp);
483  }
484 
485  done_cookie:
486  av_free(cdomain);
487  av_free(cpath);
488  av_free(cvalue);
489  if (ret < 0) {
490  if (*cookies) av_freep(cookies);
491  av_free(cset_cookies);
492  return ret;
493  }
494  }
495 
496  av_free(cset_cookies);
497 
498  return 0;
499 }
500 
501 static inline int has_header(const char *str, const char *header)
502 {
503  /* header + 2 to skip over CRLF prefix. (make sure you have one!) */
504  if (!str)
505  return 0;
506  return av_stristart(str, header + 2, NULL) || av_stristr(str, header);
507 }
508 
509 static int http_read_header(URLContext *h, int *new_location)
510 {
511  HTTPContext *s = h->priv_data;
512  char line[MAX_URL_SIZE];
513  int err = 0;
514 
515  s->chunksize = -1;
516 
517  for (;;) {
518  if ((err = http_get_line(s, line, sizeof(line))) < 0)
519  return err;
520 
521  av_dlog(NULL, "header='%s'\n", line);
522 
523  err = process_line(h, line, s->line_count, new_location);
524  if (err < 0)
525  return err;
526  if (err == 0)
527  break;
528  s->line_count++;
529  }
530 
531  return err;
532 }
533 
534 static int http_connect(URLContext *h, const char *path, const char *local_path,
535  const char *hoststr, const char *auth,
536  const char *proxyauth, int *new_location)
537 {
538  HTTPContext *s = h->priv_data;
539  int post, err;
540  char headers[4096] = "";
541  char *authstr = NULL, *proxyauthstr = NULL;
542  int64_t off = s->off;
543  int len = 0;
544  const char *method;
545 
546 
547  /* send http header */
548  post = h->flags & AVIO_FLAG_WRITE;
549 
550  if (s->post_data) {
551  /* force POST method and disable chunked encoding when
552  * custom HTTP post data is set */
553  post = 1;
554  s->chunked_post = 0;
555  }
556 
557  method = post ? "POST" : "GET";
558  authstr = ff_http_auth_create_response(&s->auth_state, auth, local_path,
559  method);
560  proxyauthstr = ff_http_auth_create_response(&s->proxy_auth_state, proxyauth,
561  local_path, method);
562 
563  /* set default headers if needed */
564  if (!has_header(s->headers, "\r\nUser-Agent: "))
565  len += av_strlcatf(headers + len, sizeof(headers) - len,
566  "User-Agent: %s\r\n", s->user_agent);
567  if (!has_header(s->headers, "\r\nAccept: "))
568  len += av_strlcpy(headers + len, "Accept: */*\r\n",
569  sizeof(headers) - len);
570  // Note: we send this on purpose even when s->off is 0 when we're probing,
571  // since it allows us to detect more reliably if a (non-conforming)
572  // server supports seeking by analysing the reply headers.
573  if (!has_header(s->headers, "\r\nRange: ") && !post && (s->off > 0 || s->seekable == -1))
574  len += av_strlcatf(headers + len, sizeof(headers) - len,
575  "Range: bytes=%"PRId64"-\r\n", s->off);
576 
577  if (!has_header(s->headers, "\r\nConnection: ")) {
578  if (s->multiple_requests) {
579  len += av_strlcpy(headers + len, "Connection: keep-alive\r\n",
580  sizeof(headers) - len);
581  } else {
582  len += av_strlcpy(headers + len, "Connection: close\r\n",
583  sizeof(headers) - len);
584  }
585  }
586 
587  if (!has_header(s->headers, "\r\nHost: "))
588  len += av_strlcatf(headers + len, sizeof(headers) - len,
589  "Host: %s\r\n", hoststr);
590  if (!has_header(s->headers, "\r\nContent-Length: ") && s->post_data)
591  len += av_strlcatf(headers + len, sizeof(headers) - len,
592  "Content-Length: %d\r\n", s->post_datalen);
593  if (!has_header(s->headers, "\r\nContent-Type: ") && s->content_type)
594  len += av_strlcatf(headers + len, sizeof(headers) - len,
595  "Content-Type: %s\r\n", s->content_type);
596  if (!has_header(s->headers, "\r\nCookie: ") && s->cookies) {
597  char *cookies = NULL;
598  if (!get_cookies(s, &cookies, path, hoststr)) {
599  len += av_strlcatf(headers + len, sizeof(headers) - len,
600  "Cookie: %s\r\n", cookies);
601  av_free(cookies);
602  }
603  }
604  if (!has_header(s->headers, "\r\nIcy-MetaData: ") && s->icy) {
605  len += av_strlcatf(headers + len, sizeof(headers) - len,
606  "Icy-MetaData: %d\r\n", 1);
607  }
608 
609  /* now add in custom headers */
610  if (s->headers)
611  av_strlcpy(headers + len, s->headers, sizeof(headers) - len);
612 
613  snprintf(s->buffer, sizeof(s->buffer),
614  "%s %s HTTP/1.1\r\n"
615  "%s"
616  "%s"
617  "%s"
618  "%s%s"
619  "\r\n",
620  method,
621  path,
622  post && s->chunked_post ? "Transfer-Encoding: chunked\r\n" : "",
623  headers,
624  authstr ? authstr : "",
625  proxyauthstr ? "Proxy-" : "", proxyauthstr ? proxyauthstr : "");
626 
627  av_freep(&authstr);
628  av_freep(&proxyauthstr);
629  if ((err = ffurl_write(s->hd, s->buffer, strlen(s->buffer))) < 0)
630  return err;
631 
632  if (s->post_data)
633  if ((err = ffurl_write(s->hd, s->post_data, s->post_datalen)) < 0)
634  return err;
635 
636  /* init input buffer */
637  s->buf_ptr = s->buffer;
638  s->buf_end = s->buffer;
639  s->line_count = 0;
640  s->off = 0;
641  s->icy_data_read = 0;
642  s->filesize = -1;
643  s->willclose = 0;
644  s->end_chunked_post = 0;
645  s->end_header = 0;
646  if (post && !s->post_data) {
647  /* Pretend that it did work. We didn't read any header yet, since
648  * we've still to send the POST data, but the code calling this
649  * function will check http_code after we return. */
650  s->http_code = 200;
651  return 0;
652  }
653 
654  /* wait for header */
655  err = http_read_header(h, new_location);
656  if (err < 0)
657  return err;
658 
659  return (off == s->off) ? 0 : -1;
660 }
661 
662 
663 static int http_buf_read(URLContext *h, uint8_t *buf, int size)
664 {
665  HTTPContext *s = h->priv_data;
666  int len;
667  /* read bytes from input buffer first */
668  len = s->buf_end - s->buf_ptr;
669  if (len > 0) {
670  if (len > size)
671  len = size;
672  memcpy(buf, s->buf_ptr, len);
673  s->buf_ptr += len;
674  } else {
675  if (!s->willclose && s->filesize >= 0 && s->off >= s->filesize)
676  return AVERROR_EOF;
677  len = ffurl_read(s->hd, buf, size);
678  }
679  if (len > 0) {
680  s->off += len;
681  s->icy_data_read += len;
682  if (s->chunksize > 0)
683  s->chunksize -= len;
684  }
685  return len;
686 }
687 
688 static int http_read(URLContext *h, uint8_t *buf, int size)
689 {
690  HTTPContext *s = h->priv_data;
691  int err, new_location;
692 
693  if (!s->hd)
694  return AVERROR_EOF;
695 
696  if (s->end_chunked_post && !s->end_header) {
697  err = http_read_header(h, &new_location);
698  if (err < 0)
699  return err;
700  }
701 
702  if (s->chunksize >= 0) {
703  if (!s->chunksize) {
704  char line[32];
705 
706  for(;;) {
707  do {
708  if ((err = http_get_line(s, line, sizeof(line))) < 0)
709  return err;
710  } while (!*line); /* skip CR LF from last chunk */
711 
712  s->chunksize = strtoll(line, NULL, 16);
713 
714  av_dlog(NULL, "Chunked encoding data size: %"PRId64"'\n", s->chunksize);
715 
716  if (!s->chunksize)
717  return 0;
718  break;
719  }
720  }
721  size = FFMIN(size, s->chunksize);
722  }
723  if (s->icy_metaint > 0) {
724  int remaining = s->icy_metaint - s->icy_data_read; /* until next metadata packet */
725  if (!remaining) {
726  // The metadata packet is variable sized. It has a 1 byte header
727  // which sets the length of the packet (divided by 16). If it's 0,
728  // the metadata doesn't change. After the packet, icy_metaint bytes
729  // of normal data follow.
730  int ch = http_getc(s);
731  if (ch < 0)
732  return ch;
733  if (ch > 0) {
734  char data[255 * 16 + 1];
735  int n;
736  int ret;
737  ch *= 16;
738  for (n = 0; n < ch; n++)
739  data[n] = http_getc(s);
740  data[ch + 1] = 0;
741  if ((ret = av_opt_set(s, "icy_metadata_packet", data, 0)) < 0)
742  return ret;
743  }
744  s->icy_data_read = 0;
745  remaining = s->icy_metaint;
746  }
747  size = FFMIN(size, remaining);
748  }
749  return http_buf_read(h, buf, size);
750 }
751 
752 /* used only when posting data */
753 static int http_write(URLContext *h, const uint8_t *buf, int size)
754 {
755  char temp[11] = ""; /* 32-bit hex + CRLF + nul */
756  int ret;
757  char crlf[] = "\r\n";
758  HTTPContext *s = h->priv_data;
759 
760  if (!s->chunked_post) {
761  /* non-chunked data is sent without any special encoding */
762  return ffurl_write(s->hd, buf, size);
763  }
764 
765  /* silently ignore zero-size data since chunk encoding that would
766  * signal EOF */
767  if (size > 0) {
768  /* upload data using chunked encoding */
769  snprintf(temp, sizeof(temp), "%x\r\n", size);
770 
771  if ((ret = ffurl_write(s->hd, temp, strlen(temp))) < 0 ||
772  (ret = ffurl_write(s->hd, buf, size)) < 0 ||
773  (ret = ffurl_write(s->hd, crlf, sizeof(crlf) - 1)) < 0)
774  return ret;
775  }
776  return size;
777 }
778 
779 static int http_shutdown(URLContext *h, int flags)
780 {
781  int ret = 0;
782  char footer[] = "0\r\n\r\n";
783  HTTPContext *s = h->priv_data;
784 
785  /* signal end of chunked encoding if used */
786  if ((flags & AVIO_FLAG_WRITE) && s->chunked_post) {
787  ret = ffurl_write(s->hd, footer, sizeof(footer) - 1);
788  ret = ret > 0 ? 0 : ret;
789  s->end_chunked_post = 1;
790  }
791 
792  return ret;
793 }
794 
795 static int http_close(URLContext *h)
796 {
797  int ret = 0;
798  HTTPContext *s = h->priv_data;
799 
800  if (!s->end_chunked_post) {
801  /* Close the write direction by sending the end of chunked encoding. */
802  ret = http_shutdown(h, h->flags);
803  }
804 
805  if (s->hd)
806  ffurl_closep(&s->hd);
807  return ret;
808 }
809 
810 static int64_t http_seek(URLContext *h, int64_t off, int whence)
811 {
812  HTTPContext *s = h->priv_data;
813  URLContext *old_hd = s->hd;
814  int64_t old_off = s->off;
815  uint8_t old_buf[BUFFER_SIZE];
816  int old_buf_size;
817 
818  if (whence == AVSEEK_SIZE)
819  return s->filesize;
820  else if ((s->filesize == -1 && whence == SEEK_END) || h->is_streamed)
821  return -1;
822 
823  /* we save the old context in case the seek fails */
824  old_buf_size = s->buf_end - s->buf_ptr;
825  memcpy(old_buf, s->buf_ptr, old_buf_size);
826  s->hd = NULL;
827  if (whence == SEEK_CUR)
828  off += s->off;
829  else if (whence == SEEK_END)
830  off += s->filesize;
831  s->off = off;
832 
833  /* if it fails, continue on old connection */
834  if (http_open_cnx(h) < 0) {
835  memcpy(s->buffer, old_buf, old_buf_size);
836  s->buf_ptr = s->buffer;
837  s->buf_end = s->buffer + old_buf_size;
838  s->hd = old_hd;
839  s->off = old_off;
840  return -1;
841  }
842  ffurl_close(old_hd);
843  return off;
844 }
845 
846 static int
848 {
849  HTTPContext *s = h->priv_data;
850  return ffurl_get_file_handle(s->hd);
851 }
852 
853 #if CONFIG_HTTP_PROTOCOL
854 URLProtocol ff_http_protocol = {
855  .name = "http",
856  .url_open = http_open,
857  .url_read = http_read,
858  .url_write = http_write,
859  .url_seek = http_seek,
860  .url_close = http_close,
861  .url_get_file_handle = http_get_file_handle,
862  .url_shutdown = http_shutdown,
863  .priv_data_size = sizeof(HTTPContext),
864  .priv_data_class = &http_context_class,
866 };
867 #endif
868 #if CONFIG_HTTPS_PROTOCOL
869 URLProtocol ff_https_protocol = {
870  .name = "https",
871  .url_open = http_open,
872  .url_read = http_read,
873  .url_write = http_write,
874  .url_seek = http_seek,
875  .url_close = http_close,
876  .url_get_file_handle = http_get_file_handle,
877  .url_shutdown = http_shutdown,
878  .priv_data_size = sizeof(HTTPContext),
879  .priv_data_class = &https_context_class,
881 };
882 #endif
883 
884 #if CONFIG_HTTPPROXY_PROTOCOL
885 static int http_proxy_close(URLContext *h)
886 {
887  HTTPContext *s = h->priv_data;
888  if (s->hd)
889  ffurl_closep(&s->hd);
890  return 0;
891 }
892 
893 static int http_proxy_open(URLContext *h, const char *uri, int flags)
894 {
895  HTTPContext *s = h->priv_data;
896  char hostname[1024], hoststr[1024];
897  char auth[1024], pathbuf[1024], *path;
898  char lower_url[100];
899  int port, ret = 0, attempts = 0;
900  HTTPAuthType cur_auth_type;
901  char *authstr;
902  int new_loc;
903  AVDictionary *opts = NULL;
904  char opts_format[20];
905 
906  if( s->seekable == 1 )
907  h->is_streamed = 0;
908  else
909  h->is_streamed = 1;
910 
911  av_url_split(NULL, 0, auth, sizeof(auth), hostname, sizeof(hostname), &port,
912  pathbuf, sizeof(pathbuf), uri);
913  ff_url_join(hoststr, sizeof(hoststr), NULL, NULL, hostname, port, NULL);
914  path = pathbuf;
915  if (*path == '/')
916  path++;
917 
918  ff_url_join(lower_url, sizeof(lower_url), "tcp", NULL, hostname, port,
919  NULL);
920 redo:
921  if (s->rw_timeout != -1) {
922  snprintf(opts_format, sizeof(opts_format), "%d", s->rw_timeout);
923  av_dict_set(&opts, "timeout", opts_format, 0);
924  } /* if option is not given, don't pass it and let tcp use its own default */
925  ret = ffurl_open(&s->hd, lower_url, AVIO_FLAG_READ_WRITE,
926  &h->interrupt_callback, &opts);
927  av_dict_free(&opts);
928  if (ret < 0)
929  return ret;
930 
932  path, "CONNECT");
933  snprintf(s->buffer, sizeof(s->buffer),
934  "CONNECT %s HTTP/1.1\r\n"
935  "Host: %s\r\n"
936  "Connection: close\r\n"
937  "%s%s"
938  "\r\n",
939  path,
940  hoststr,
941  authstr ? "Proxy-" : "", authstr ? authstr : "");
942  av_freep(&authstr);
943 
944  if ((ret = ffurl_write(s->hd, s->buffer, strlen(s->buffer))) < 0)
945  goto fail;
946 
947  s->buf_ptr = s->buffer;
948  s->buf_end = s->buffer;
949  s->line_count = 0;
950  s->filesize = -1;
951  cur_auth_type = s->proxy_auth_state.auth_type;
952 
953  /* Note: This uses buffering, potentially reading more than the
954  * HTTP header. If tunneling a protocol where the server starts
955  * the conversation, we might buffer part of that here, too.
956  * Reading that requires using the proper ffurl_read() function
957  * on this URLContext, not using the fd directly (as the tls
958  * protocol does). This shouldn't be an issue for tls though,
959  * since the client starts the conversation there, so there
960  * is no extra data that we might buffer up here.
961  */
962  ret = http_read_header(h, &new_loc);
963  if (ret < 0)
964  goto fail;
965 
966  attempts++;
967  if (s->http_code == 407 &&
968  (cur_auth_type == HTTP_AUTH_NONE || s->proxy_auth_state.stale) &&
969  s->proxy_auth_state.auth_type != HTTP_AUTH_NONE && attempts < 2) {
970  ffurl_closep(&s->hd);
971  goto redo;
972  }
973 
974  if (s->http_code < 400)
975  return 0;
976  ret = AVERROR(EIO);
977 
978 fail:
979  http_proxy_close(h);
980  return ret;
981 }
982 
983 static int http_proxy_write(URLContext *h, const uint8_t *buf, int size)
984 {
985  HTTPContext *s = h->priv_data;
986  return ffurl_write(s->hd, buf, size);
987 }
988 
989 URLProtocol ff_httpproxy_protocol = {
990  .name = "httpproxy",
991  .url_open = http_proxy_open,
992  .url_read = http_buf_read,
993  .url_write = http_proxy_write,
994  .url_close = http_proxy_close,
995  .url_get_file_handle = http_get_file_handle,
996  .priv_data_size = sizeof(HTTPContext),
997  .flags = URL_PROTOCOL_FLAG_NETWORK,
998 };
999 #endif