Libav
http.c
Go to the documentation of this file.
1 /*
2  * HTTP protocol for avconv client
3  * Copyright (c) 2000, 2001 Fabrice Bellard
4  *
5  * This file is part of Libav.
6  *
7  * Libav 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  * Libav 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 Libav; 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 #if CONFIG_ZLIB
33 #include <zlib.h>
34 #endif
35 
36 /* XXX: POST protocol is not completely implemented because avconv uses
37  only a subset of it. */
38 
39 /* The IO buffer size is unrelated to the max URL size in itself, but needs
40  * to be large enough to fit the full request headers (including long
41  * path names).
42  */
43 #define BUFFER_SIZE MAX_URL_SIZE
44 #define MAX_REDIRECTS 8
45 
46 typedef struct {
47  const AVClass *class;
49  unsigned char buffer[BUFFER_SIZE], *buf_ptr, *buf_end;
51  int http_code;
52  /* Used if "Transfer-Encoding: chunked" otherwise -1. */
53  int64_t chunksize;
54  int64_t off, end_off, filesize;
55  char *location;
58  char *headers;
59  char *mime_type;
60  char *user_agent;
61  char *content_type;
62  /* Set if the server correctly handles Connection: close and will close
63  * the connection after feeding us the content. */
64  int willclose;
66  /* A flag which indicates if the end of chunked encoding has been sent. */
68  /* A flag which indicates we have finished to read POST reply. */
70  /* A flag which indicates if we use persistent connections. */
74  int icy;
75  /* how much data was read since the last ICY metadata packet */
77  /* after how many bytes of read data a new metadata packet will be found */
81 #if CONFIG_ZLIB
82  int compressed;
83  z_stream inflate_stream;
84  uint8_t *inflate_buffer;
85 #endif
88 } HTTPContext;
89 
90 #define OFFSET(x) offsetof(HTTPContext, x)
91 #define D AV_OPT_FLAG_DECODING_PARAM
92 #define E AV_OPT_FLAG_ENCODING_PARAM
93 #define DEFAULT_USER_AGENT "Lavf/" AV_STRINGIFY(LIBAVFORMAT_VERSION)
94 static const AVOption options[] = {
95 {"chunked_post", "use chunked transfer-encoding for posts", OFFSET(chunked_post), AV_OPT_TYPE_INT, {.i64 = 1}, 0, 1, E },
96 {"headers", "set custom HTTP headers, can override built in default headers", OFFSET(headers), AV_OPT_TYPE_STRING, { 0 }, 0, 0, D|E },
97 {"content_type", "set a specific content type for the POST messages", OFFSET(content_type), AV_OPT_TYPE_STRING, { 0 }, 0, 0, D|E },
98 {"user_agent", "override User-Agent header", OFFSET(user_agent), AV_OPT_TYPE_STRING, {.str = DEFAULT_USER_AGENT}, 0, 0, D },
99 {"user-agent", "override User-Agent header, for compatibility with ffmpeg", OFFSET(user_agent), AV_OPT_TYPE_STRING, {.str = DEFAULT_USER_AGENT}, 0, 0, D },
100 {"multiple_requests", "use persistent connections", OFFSET(multiple_requests), AV_OPT_TYPE_INT, {.i64 = 0}, 0, 1, D|E },
101 {"post_data", "set custom HTTP post data", OFFSET(post_data), AV_OPT_TYPE_BINARY, .flags = D|E },
102 {"mime_type", "export the MIME type", OFFSET(mime_type), AV_OPT_TYPE_STRING, {0}, 0, 0, 0 },
103 {"icy", "request ICY metadata", OFFSET(icy), AV_OPT_TYPE_INT, {.i64 = 0}, 0, 1, D },
104 {"icy_metadata_headers", "return ICY metadata headers", OFFSET(icy_metadata_headers), AV_OPT_TYPE_STRING, {0}, 0, 0, 0 },
105 {"icy_metadata_packet", "return current ICY metadata packet", OFFSET(icy_metadata_packet), AV_OPT_TYPE_STRING, {0}, 0, 0, 0 },
106 {"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" },
107 {"none", "No auth method set, autodetect", 0, AV_OPT_TYPE_CONST, {.i64 = HTTP_AUTH_NONE}, 0, 0, D|E, "auth_type" },
108 {"basic", "HTTP basic authentication", 0, AV_OPT_TYPE_CONST, {.i64 = HTTP_AUTH_BASIC}, 0, 0, D|E, "auth_type" },
109 {"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 },
110 {"location", "The actual location of the data received", OFFSET(location), AV_OPT_TYPE_STRING, { 0 }, 0, 0, D|E },
111 {"offset", "initial byte offset", OFFSET(off), AV_OPT_TYPE_INT64, {.i64 = 0}, 0, INT64_MAX, D },
112 {"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 },
113 {NULL}
114 };
115 #define HTTP_CLASS(flavor)\
116 static const AVClass flavor ## _context_class = {\
117  .class_name = #flavor,\
118  .item_name = av_default_item_name,\
119  .option = options,\
120  .version = LIBAVUTIL_VERSION_INT,\
121 }
122 
123 HTTP_CLASS(http);
124 HTTP_CLASS(https);
125 
126 static int http_connect(URLContext *h, const char *path, const char *local_path,
127  const char *hoststr, const char *auth,
128  const char *proxyauth, int *new_location);
129 
131 {
132  memcpy(&((HTTPContext*)dest->priv_data)->auth_state,
133  &((HTTPContext*)src->priv_data)->auth_state, sizeof(HTTPAuthState));
134  memcpy(&((HTTPContext*)dest->priv_data)->proxy_auth_state,
135  &((HTTPContext*)src->priv_data)->proxy_auth_state,
136  sizeof(HTTPAuthState));
137 }
138 
139 /* return non zero if error */
140 static int http_open_cnx(URLContext *h, AVDictionary **options)
141 {
142  const char *path, *proxy_path, *lower_proto = "tcp", *local_path;
143  char hostname[1024], hoststr[1024], proto[10];
144  char auth[1024], proxyauth[1024] = "";
145  char path1[MAX_URL_SIZE];
146  char buf[1024], urlbuf[MAX_URL_SIZE];
147  int port, use_proxy, err, location_changed = 0, redirects = 0, attempts = 0;
148  HTTPAuthType cur_auth_type, cur_proxy_auth_type;
149  HTTPContext *s = h->priv_data;
150 
151  /* fill the dest addr */
152  redo:
153  /* needed in any case to build the host string */
154  av_url_split(proto, sizeof(proto), auth, sizeof(auth),
155  hostname, sizeof(hostname), &port,
156  path1, sizeof(path1), s->location);
157  ff_url_join(hoststr, sizeof(hoststr), NULL, NULL, hostname, port, NULL);
158 
159  proxy_path = getenv("http_proxy");
160  use_proxy = !ff_http_match_no_proxy(getenv("no_proxy"), hostname) &&
161  proxy_path != NULL && av_strstart(proxy_path, "http://", NULL);
162 
163  if (!strcmp(proto, "https")) {
164  lower_proto = "tls";
165  use_proxy = 0;
166  if (port < 0)
167  port = 443;
168  }
169  if (port < 0)
170  port = 80;
171 
172  if (path1[0] == '\0')
173  path = "/";
174  else
175  path = path1;
176  local_path = path;
177  if (use_proxy) {
178  /* Reassemble the request URL without auth string - we don't
179  * want to leak the auth to the proxy. */
180  ff_url_join(urlbuf, sizeof(urlbuf), proto, NULL, hostname, port, "%s",
181  path1);
182  path = urlbuf;
183  av_url_split(NULL, 0, proxyauth, sizeof(proxyauth),
184  hostname, sizeof(hostname), &port, NULL, 0, proxy_path);
185  }
186 
187  ff_url_join(buf, sizeof(buf), lower_proto, NULL, hostname, port, NULL);
188 
189  if (!s->hd) {
190  err = ffurl_open(&s->hd, buf, AVIO_FLAG_READ_WRITE,
191  &h->interrupt_callback, options);
192  if (err < 0)
193  goto fail;
194  }
195 
196  cur_auth_type = s->auth_state.auth_type;
197  cur_proxy_auth_type = s->auth_state.auth_type;
198  if (http_connect(h, path, local_path, hoststr, auth, proxyauth, &location_changed) < 0)
199  goto fail;
200  attempts++;
201  if (s->http_code == 401) {
202  if ((cur_auth_type == HTTP_AUTH_NONE || s->auth_state.stale) &&
203  s->auth_state.auth_type != HTTP_AUTH_NONE && attempts < 4) {
204  ffurl_close(s->hd);
205  s->hd = NULL;
206  goto redo;
207  } else
208  goto fail;
209  }
210  if (s->http_code == 407) {
211  if ((cur_proxy_auth_type == HTTP_AUTH_NONE || s->proxy_auth_state.stale) &&
212  s->proxy_auth_state.auth_type != HTTP_AUTH_NONE && attempts < 4) {
213  ffurl_close(s->hd);
214  s->hd = NULL;
215  goto redo;
216  } else
217  goto fail;
218  }
219  if ((s->http_code == 301 || s->http_code == 302 || s->http_code == 303 || s->http_code == 307)
220  && location_changed == 1) {
221  /* url moved, get next */
222  ffurl_close(s->hd);
223  s->hd = NULL;
224  if (redirects++ >= MAX_REDIRECTS)
225  return AVERROR(EIO);
226  /* Restart the authentication process with the new target, which
227  * might use a different auth mechanism. */
228  memset(&s->auth_state, 0, sizeof(s->auth_state));
229  attempts = 0;
230  location_changed = 0;
231  goto redo;
232  }
233  return 0;
234  fail:
235  if (s->hd)
236  ffurl_close(s->hd);
237  s->hd = NULL;
238  return AVERROR(EIO);
239 }
240 
241 int ff_http_do_new_request(URLContext *h, const char *uri)
242 {
243  HTTPContext *s = h->priv_data;
244  AVDictionary *options = NULL;
245  int ret;
246 
247  s->off = 0;
248  s->icy_data_read = 0;
249  av_free(s->location);
250  s->location = av_strdup(uri);
251  if (!s->location)
252  return AVERROR(ENOMEM);
253 
254  av_dict_copy(&options, s->chained_options, 0);
255  ret = http_open_cnx(h, &options);
256  av_dict_free(&options);
257  return ret;
258 }
259 
260 static int http_open(URLContext *h, const char *uri, int flags,
261  AVDictionary **options)
262 {
263  HTTPContext *s = h->priv_data;
264  int ret;
265 
266  h->is_streamed = 1;
267 
268  s->filesize = -1;
269  s->location = av_strdup(uri);
270  if (!s->location)
271  return AVERROR(ENOMEM);
272  if (options)
273  av_dict_copy(&s->chained_options, *options, 0);
274 
275  if (s->headers) {
276  int len = strlen(s->headers);
277  if (len < 2 || strcmp("\r\n", s->headers + len - 2))
278  av_log(h, AV_LOG_WARNING, "No trailing CRLF found in HTTP header.\n");
279  }
280 
281  ret = http_open_cnx(h, options);
282  if (ret < 0)
284  return ret;
285 }
286 static int http_getc(HTTPContext *s)
287 {
288  int len;
289  if (s->buf_ptr >= s->buf_end) {
290  len = ffurl_read(s->hd, s->buffer, BUFFER_SIZE);
291  if (len < 0) {
292  return len;
293  } else if (len == 0) {
294  return AVERROR_EOF;
295  } else {
296  s->buf_ptr = s->buffer;
297  s->buf_end = s->buffer + len;
298  }
299  }
300  return *s->buf_ptr++;
301 }
302 
303 static int http_get_line(HTTPContext *s, char *line, int line_size)
304 {
305  int ch;
306  char *q;
307 
308  q = line;
309  for(;;) {
310  ch = http_getc(s);
311  if (ch < 0)
312  return ch;
313  if (ch == '\n') {
314  /* process line */
315  if (q > line && q[-1] == '\r')
316  q--;
317  *q = '\0';
318 
319  return 0;
320  } else {
321  if ((q - line) < line_size - 1)
322  *q++ = ch;
323  }
324  }
325 }
326 
327 static int check_http_code(URLContext *h, int http_code, const char *end)
328 {
329  HTTPContext *s = h->priv_data;
330  /* error codes are 4xx and 5xx, but regard 401 as a success, so we
331  * don't abort until all headers have been parsed. */
332  if (http_code >= 400 && http_code < 600 &&
333  (http_code != 401 || s->auth_state.auth_type != HTTP_AUTH_NONE) &&
334  (http_code != 407 || s->proxy_auth_state.auth_type != HTTP_AUTH_NONE)) {
335  end += strspn(end, SPACE_CHARS);
336  av_log(h, AV_LOG_WARNING, "HTTP error %d %s\n", http_code, end);
337  return AVERROR(EIO);
338  }
339  return 0;
340 }
341 
342 static int parse_location(HTTPContext *s, const char *p)
343 {
344  char redirected_location[MAX_URL_SIZE], *new_loc;
345  ff_make_absolute_url(redirected_location, sizeof(redirected_location),
346  s->location, p);
347  new_loc = av_strdup(redirected_location);
348  if (!new_loc)
349  return AVERROR(ENOMEM);
350  av_free(s->location);
351  s->location = new_loc;
352  return 0;
353 }
354 
355 /* "bytes $from-$to/$document_size" */
356 static void parse_content_range(URLContext *h, const char *p)
357 {
358  HTTPContext *s = h->priv_data;
359  const char *slash;
360 
361  if (!strncmp(p, "bytes ", 6)) {
362  p += 6;
363  s->off = strtoll(p, NULL, 10);
364  if ((slash = strchr(p, '/')) && strlen(slash) > 0)
365  s->filesize = strtoll(slash+1, NULL, 10);
366  }
367  h->is_streamed = 0; /* we _can_ in fact seek */
368 }
369 
370 static int parse_content_encoding(URLContext *h, const char *p)
371 {
372  HTTPContext *s = h->priv_data;
373 
374  if (!av_strncasecmp(p, "gzip", 4) ||
375  !av_strncasecmp(p, "deflate", 7)) {
376 #if CONFIG_ZLIB
377  s->compressed = 1;
378  inflateEnd(&s->inflate_stream);
379  if (inflateInit2(&s->inflate_stream, 32 + 15) != Z_OK) {
380  av_log(h, AV_LOG_WARNING, "Error during zlib initialisation: %s\n",
381  s->inflate_stream.msg);
382  return AVERROR(ENOSYS);
383  }
384  if (zlibCompileFlags() & (1 << 17)) {
386  "Your zlib was compiled without gzip support.\n");
387  return AVERROR(ENOSYS);
388  }
389 #else
391  "Compressed (%s) content, need zlib with gzip support\n", p);
392  return AVERROR(ENOSYS);
393 #endif
394  } else if (!av_strncasecmp(p, "identity", 8)) {
395  // The normal, no-encoding case (although servers shouldn't include
396  // the header at all if this is the case).
397  } else {
398  av_log(h, AV_LOG_WARNING, "Unknown content coding: %s\n", p);
399  return AVERROR(ENOSYS);
400  }
401  return 0;
402 }
403 
404 // Concat all Icy- header lines
405 static int parse_icy(HTTPContext *s, const char *tag, const char *p)
406 {
407  int len = 4 + strlen(p) + strlen(tag);
408  int is_first = !s->icy_metadata_headers;
409  int ret;
410 
411  if (s->icy_metadata_headers)
412  len += strlen(s->icy_metadata_headers);
413 
414  if ((ret = av_reallocp(&s->icy_metadata_headers, len)) < 0)
415  return ret;
416 
417  if (is_first)
418  *s->icy_metadata_headers = '\0';
419 
420  av_strlcatf(s->icy_metadata_headers, len, "%s: %s\n", tag, p);
421 
422  return 0;
423 }
424 
425 static int process_line(URLContext *h, char *line, int line_count,
426  int *new_location)
427 {
428  HTTPContext *s = h->priv_data;
429  char *tag, *p, *end;
430  int ret;
431 
432  /* end of header */
433  if (line[0] == '\0') {
434  s->end_header = 1;
435  return 0;
436  }
437 
438  p = line;
439  if (line_count == 0) {
440  while (!av_isspace(*p) && *p != '\0')
441  p++;
442  while (av_isspace(*p))
443  p++;
444  s->http_code = strtol(p, &end, 10);
445 
446  av_dlog(NULL, "http_code=%d\n", s->http_code);
447 
448  if ((ret = check_http_code(h, s->http_code, end)) < 0)
449  return ret;
450  } else {
451  while (*p != '\0' && *p != ':')
452  p++;
453  if (*p != ':')
454  return 1;
455 
456  *p = '\0';
457  tag = line;
458  p++;
459  while (av_isspace(*p))
460  p++;
461  if (!av_strcasecmp(tag, "Location")) {
462  if ((ret = parse_location(s, p)) < 0)
463  return ret;
464  *new_location = 1;
465  } else if (!av_strcasecmp(tag, "Content-Length") && s->filesize == -1) {
466  s->filesize = strtoll(p, NULL, 10);
467  } else if (!av_strcasecmp(tag, "Content-Range")) {
468  parse_content_range(h, p);
469  } else if (!av_strcasecmp(tag, "Accept-Ranges") &&
470  !strncmp(p, "bytes", 5)) {
471  h->is_streamed = 0;
472  } else if (!av_strcasecmp(tag, "Transfer-Encoding") &&
473  !av_strncasecmp(p, "chunked", 7)) {
474  s->filesize = -1;
475  s->chunksize = 0;
476  } else if (!av_strcasecmp(tag, "WWW-Authenticate")) {
478  } else if (!av_strcasecmp(tag, "Authentication-Info")) {
480  } else if (!av_strcasecmp(tag, "Proxy-Authenticate")) {
482  } else if (!av_strcasecmp(tag, "Connection")) {
483  if (!strcmp(p, "close"))
484  s->willclose = 1;
485  } else if (!av_strcasecmp (tag, "Content-Type")) {
486  av_free(s->mime_type);
487  s->mime_type = av_strdup(p);
488  } else if (!av_strcasecmp (tag, "Icy-MetaInt")) {
489  s->icy_metaint = strtoll(p, NULL, 10);
490  } else if (!av_strncasecmp(tag, "Icy-", 4)) {
491  if ((ret = parse_icy(s, tag, p)) < 0)
492  return ret;
493  } else if (!av_strcasecmp(tag, "Content-Encoding")) {
494  if ((ret = parse_content_encoding(h, p)) < 0)
495  return ret;
496  }
497  }
498  return 1;
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[1024] = "";
541  char *authstr = NULL, *proxyauthstr = NULL;
542  int64_t off = s->off;
543  int len = 0;
544  const char *method;
545  int send_expect_100 = 0;
546 
547 
548  /* send http header */
549  post = h->flags & AVIO_FLAG_WRITE;
550 
551  if (s->post_data) {
552  /* force POST method and disable chunked encoding when
553  * custom HTTP post data is set */
554  post = 1;
555  s->chunked_post = 0;
556  }
557 
558  method = post ? "POST" : "GET";
559  authstr = ff_http_auth_create_response(&s->auth_state, auth, local_path,
560  method);
561  proxyauthstr = ff_http_auth_create_response(&s->proxy_auth_state, proxyauth,
562  local_path, method);
563  if (post && !s->post_data) {
564  send_expect_100 = s->send_expect_100;
565  /* The user has supplied authentication but we don't know the auth type,
566  * send Expect: 100-continue to get the 401 response including the
567  * WWW-Authenticate header, or an 100 continue if no auth actually
568  * is needed. */
569  if (auth && *auth &&
571  s->http_code != 401)
572  send_expect_100 = 1;
573  }
574 
575  /* set default headers if needed */
576  if (!has_header(s->headers, "\r\nUser-Agent: "))
577  len += av_strlcatf(headers + len, sizeof(headers) - len,
578  "User-Agent: %s\r\n", s->user_agent);
579  if (!has_header(s->headers, "\r\nAccept: "))
580  len += av_strlcpy(headers + len, "Accept: */*\r\n",
581  sizeof(headers) - len);
582  // Note: we send this on purpose even when s->off is 0 when we're probing,
583  // since it allows us to detect more reliably if a (non-conforming)
584  // server supports seeking by analysing the reply headers.
585  if (!has_header(s->headers, "\r\nRange: ") && !post) {
586  len += av_strlcatf(headers + len, sizeof(headers) - len,
587  "Range: bytes=%"PRId64"-", s->off);
588  if (s->end_off)
589  len += av_strlcatf(headers + len, sizeof(headers) - len,
590  "%"PRId64, s->end_off - 1);
591  len += av_strlcpy(headers + len, "\r\n",
592  sizeof(headers) - len);
593  }
594  if (send_expect_100 && !has_header(s->headers, "\r\nExpect: "))
595  len += av_strlcatf(headers + len, sizeof(headers) - len,
596  "Expect: 100-continue\r\n");
597 
598  if (!has_header(s->headers, "\r\nConnection: ")) {
599  if (s->multiple_requests) {
600  len += av_strlcpy(headers + len, "Connection: keep-alive\r\n",
601  sizeof(headers) - len);
602  } else {
603  len += av_strlcpy(headers + len, "Connection: close\r\n",
604  sizeof(headers) - len);
605  }
606  }
607 
608  if (!has_header(s->headers, "\r\nHost: "))
609  len += av_strlcatf(headers + len, sizeof(headers) - len,
610  "Host: %s\r\n", hoststr);
611  if (!has_header(s->headers, "\r\nContent-Length: ") && s->post_data)
612  len += av_strlcatf(headers + len, sizeof(headers) - len,
613  "Content-Length: %d\r\n", s->post_datalen);
614 
615  if (!has_header(s->headers, "\r\nContent-Type: ") && s->content_type)
616  len += av_strlcatf(headers + len, sizeof(headers) - len,
617  "Content-Type: %s\r\n", s->content_type);
618  if (!has_header(s->headers, "\r\nIcy-MetaData: ") && s->icy) {
619  len += av_strlcatf(headers + len, sizeof(headers) - len,
620  "Icy-MetaData: %d\r\n", 1);
621  }
622 
623  /* now add in custom headers */
624  if (s->headers)
625  av_strlcpy(headers + len, s->headers, sizeof(headers) - len);
626 
627  snprintf(s->buffer, sizeof(s->buffer),
628  "%s %s HTTP/1.1\r\n"
629  "%s"
630  "%s"
631  "%s"
632  "%s%s"
633  "\r\n",
634  method,
635  path,
636  post && s->chunked_post ? "Transfer-Encoding: chunked\r\n" : "",
637  headers,
638  authstr ? authstr : "",
639  proxyauthstr ? "Proxy-" : "", proxyauthstr ? proxyauthstr : "");
640 
641  av_freep(&authstr);
642  av_freep(&proxyauthstr);
643  if ((err = ffurl_write(s->hd, s->buffer, strlen(s->buffer))) < 0)
644  return err;
645 
646  if (s->post_data)
647  if ((err = ffurl_write(s->hd, s->post_data, s->post_datalen)) < 0)
648  return err;
649 
650  /* init input buffer */
651  s->buf_ptr = s->buffer;
652  s->buf_end = s->buffer;
653  s->line_count = 0;
654  s->off = 0;
655  s->icy_data_read = 0;
656  s->filesize = -1;
657  s->willclose = 0;
658  s->end_chunked_post = 0;
659  s->end_header = 0;
660  if (post && !s->post_data && !send_expect_100) {
661  /* Pretend that it did work. We didn't read any header yet, since
662  * we've still to send the POST data, but the code calling this
663  * function will check http_code after we return. */
664  s->http_code = 200;
665  return 0;
666  }
667 
668  /* wait for header */
669  err = http_read_header(h, new_location);
670  if (err < 0)
671  return err;
672 
673  return (off == s->off) ? 0 : -1;
674 }
675 
676 
677 static int http_buf_read(URLContext *h, uint8_t *buf, int size)
678 {
679  HTTPContext *s = h->priv_data;
680  int len;
681  /* read bytes from input buffer first */
682  len = s->buf_end - s->buf_ptr;
683  if (len > 0) {
684  if (len > size)
685  len = size;
686  memcpy(buf, s->buf_ptr, len);
687  s->buf_ptr += len;
688  } else {
689  if (!s->willclose && s->filesize >= 0 && s->off >= s->filesize)
690  return AVERROR_EOF;
691  len = ffurl_read(s->hd, buf, size);
692  }
693  if (len > 0) {
694  s->off += len;
695  if (s->chunksize > 0)
696  s->chunksize -= len;
697  }
698  return len;
699 }
700 
701 #if CONFIG_ZLIB
702 #define DECOMPRESS_BUF_SIZE (256 * 1024)
703 static int http_buf_read_compressed(URLContext *h, uint8_t *buf, int size)
704 {
705  HTTPContext *s = h->priv_data;
706  int ret;
707 
708  if (!s->inflate_buffer) {
709  s->inflate_buffer = av_malloc(DECOMPRESS_BUF_SIZE);
710  if (!s->inflate_buffer)
711  return AVERROR(ENOMEM);
712  }
713 
714  if (s->inflate_stream.avail_in == 0) {
715  int read = http_buf_read(h, s->inflate_buffer, DECOMPRESS_BUF_SIZE);
716  if (read <= 0)
717  return read;
718  s->inflate_stream.next_in = s->inflate_buffer;
719  s->inflate_stream.avail_in = read;
720  }
721 
722  s->inflate_stream.avail_out = size;
723  s->inflate_stream.next_out = buf;
724 
725  ret = inflate(&s->inflate_stream, Z_SYNC_FLUSH);
726  if (ret != Z_OK && ret != Z_STREAM_END)
727  av_log(h, AV_LOG_WARNING, "inflate return value: %d, %s\n", ret, s->inflate_stream.msg);
728 
729  return size - s->inflate_stream.avail_out;
730 }
731 #endif
732 
733 static int http_read_stream(URLContext *h, uint8_t *buf, int size)
734 {
735  HTTPContext *s = h->priv_data;
736  int err, new_location;
737 
738  if (!s->hd)
739  return AVERROR_EOF;
740 
741  if (s->end_chunked_post && !s->end_header) {
742  err = http_read_header(h, &new_location);
743  if (err < 0)
744  return err;
745  }
746 
747  if (s->chunksize >= 0) {
748  if (!s->chunksize) {
749  char line[32];
750 
751  for(;;) {
752  do {
753  if ((err = http_get_line(s, line, sizeof(line))) < 0)
754  return err;
755  } while (!*line); /* skip CR LF from last chunk */
756 
757  s->chunksize = strtoll(line, NULL, 16);
758 
759  av_dlog(NULL, "Chunked encoding data size: %"PRId64"'\n", s->chunksize);
760 
761  if (!s->chunksize)
762  return 0;
763  break;
764  }
765  }
766  size = FFMIN(size, s->chunksize);
767  }
768 #if CONFIG_ZLIB
769  if (s->compressed)
770  return http_buf_read_compressed(h, buf, size);
771 #endif
772  return http_buf_read(h, buf, size);
773 }
774 
775 static int http_read_stream_all(URLContext *h, uint8_t *buf, int size)
776 {
777  int pos = 0;
778  while (pos < size) {
779  int len = http_read_stream(h, buf + pos, size - pos);
780  if (len < 0)
781  return len;
782  pos += len;
783  }
784  return pos;
785 }
786 
787 static int store_icy(URLContext *h, int size)
788 {
789  HTTPContext *s = h->priv_data;
790  /* until next metadata packet */
791  int remaining = s->icy_metaint - s->icy_data_read;
792 
793  if (remaining < 0)
794  return AVERROR_INVALIDDATA;
795 
796  if (!remaining) {
797  // The metadata packet is variable sized. It has a 1 byte header
798  // which sets the length of the packet (divided by 16). If it's 0,
799  // the metadata doesn't change. After the packet, icy_metaint bytes
800  // of normal data follow.
801  uint8_t ch;
802  int len = http_read_stream_all(h, &ch, 1);
803  if (len < 0)
804  return len;
805  if (ch > 0) {
806  char data[255 * 16 + 1];
807  int ret;
808  len = ch * 16;
809  ret = http_read_stream_all(h, data, len);
810  if (ret < 0)
811  return ret;
812  data[len + 1] = 0;
813  if ((ret = av_opt_set(s, "icy_metadata_packet", data, 0)) < 0)
814  return ret;
815  }
816  s->icy_data_read = 0;
817  remaining = s->icy_metaint;
818  }
819 
820  return FFMIN(size, remaining);
821 }
822 
823 static int http_read(URLContext *h, uint8_t *buf, int size)
824 {
825  HTTPContext *s = h->priv_data;
826 
827  if (s->icy_metaint > 0) {
828  size = store_icy(h, size);
829  if (size < 0)
830  return size;
831  }
832 
833  size = http_read_stream(h, buf, size);
834  if (size > 0)
835  s->icy_data_read += size;
836  return size;
837 }
838 
839 /* used only when posting data */
840 static int http_write(URLContext *h, const uint8_t *buf, int size)
841 {
842  char temp[11] = ""; /* 32-bit hex + CRLF + nul */
843  int ret;
844  char crlf[] = "\r\n";
845  HTTPContext *s = h->priv_data;
846 
847  if (!s->chunked_post) {
848  /* non-chunked data is sent without any special encoding */
849  return ffurl_write(s->hd, buf, size);
850  }
851 
852  /* silently ignore zero-size data since chunk encoding that would
853  * signal EOF */
854  if (size > 0) {
855  /* upload data using chunked encoding */
856  snprintf(temp, sizeof(temp), "%x\r\n", size);
857 
858  if ((ret = ffurl_write(s->hd, temp, strlen(temp))) < 0 ||
859  (ret = ffurl_write(s->hd, buf, size)) < 0 ||
860  (ret = ffurl_write(s->hd, crlf, sizeof(crlf) - 1)) < 0)
861  return ret;
862  }
863  return size;
864 }
865 
866 static int http_shutdown(URLContext *h, int flags)
867 {
868  int ret = 0;
869  char footer[] = "0\r\n\r\n";
870  HTTPContext *s = h->priv_data;
871 
872  /* signal end of chunked encoding if used */
873  if ((flags & AVIO_FLAG_WRITE) && s->chunked_post) {
874  ret = ffurl_write(s->hd, footer, sizeof(footer) - 1);
875  ret = ret > 0 ? 0 : ret;
876  s->end_chunked_post = 1;
877  }
878 
879  return ret;
880 }
881 
882 static int http_close(URLContext *h)
883 {
884  int ret = 0;
885  HTTPContext *s = h->priv_data;
886 
887 #if CONFIG_ZLIB
888  inflateEnd(&s->inflate_stream);
889  av_freep(&s->inflate_buffer);
890 #endif
891 
892  if (!s->end_chunked_post) {
893  /* Close the write direction by sending the end of chunked encoding. */
894  ret = http_shutdown(h, h->flags);
895  }
896 
897  if (s->hd)
898  ffurl_close(s->hd);
900  return ret;
901 }
902 
903 static int64_t http_seek(URLContext *h, int64_t off, int whence)
904 {
905  HTTPContext *s = h->priv_data;
906  URLContext *old_hd = s->hd;
907  int64_t old_off = s->off;
908  uint8_t old_buf[BUFFER_SIZE];
909  int old_buf_size, ret;
910  AVDictionary *options = NULL;
911 
912  if (whence == AVSEEK_SIZE)
913  return s->filesize;
914  else if ((whence == SEEK_CUR && off == 0) ||
915  (whence == SEEK_SET && off == s->off))
916  return s->off;
917  else if ((s->filesize == -1 && whence == SEEK_END) || h->is_streamed)
918  return AVERROR(ENOSYS);
919 
920  /* we save the old context in case the seek fails */
921  old_buf_size = s->buf_end - s->buf_ptr;
922  memcpy(old_buf, s->buf_ptr, old_buf_size);
923  s->hd = NULL;
924  if (whence == SEEK_CUR)
925  off += s->off;
926  else if (whence == SEEK_END)
927  off += s->filesize;
928  s->off = off;
929 
930  /* if it fails, continue on old connection */
931  av_dict_copy(&options, s->chained_options, 0);
932  if ((ret = http_open_cnx(h, &options)) < 0) {
933  av_dict_free(&options);
934  memcpy(s->buffer, old_buf, old_buf_size);
935  s->buf_ptr = s->buffer;
936  s->buf_end = s->buffer + old_buf_size;
937  s->hd = old_hd;
938  s->off = old_off;
939  return ret;
940  }
941  av_dict_free(&options);
942  ffurl_close(old_hd);
943  return off;
944 }
945 
946 static int
948 {
949  HTTPContext *s = h->priv_data;
950  return ffurl_get_file_handle(s->hd);
951 }
952 
953 #if CONFIG_HTTP_PROTOCOL
954 URLProtocol ff_http_protocol = {
955  .name = "http",
956  .url_open2 = http_open,
957  .url_read = http_read,
958  .url_write = http_write,
959  .url_seek = http_seek,
960  .url_close = http_close,
961  .url_get_file_handle = http_get_file_handle,
962  .url_shutdown = http_shutdown,
963  .priv_data_size = sizeof(HTTPContext),
964  .priv_data_class = &http_context_class,
966 };
967 #endif
968 #if CONFIG_HTTPS_PROTOCOL
969 URLProtocol ff_https_protocol = {
970  .name = "https",
971  .url_open2 = http_open,
972  .url_read = http_read,
973  .url_write = http_write,
974  .url_seek = http_seek,
975  .url_close = http_close,
976  .url_get_file_handle = http_get_file_handle,
977  .url_shutdown = http_shutdown,
978  .priv_data_size = sizeof(HTTPContext),
979  .priv_data_class = &https_context_class,
981 };
982 #endif
983 
984 #if CONFIG_HTTPPROXY_PROTOCOL
985 static int http_proxy_close(URLContext *h)
986 {
987  HTTPContext *s = h->priv_data;
988  if (s->hd)
989  ffurl_close(s->hd);
990  return 0;
991 }
992 
993 static int http_proxy_open(URLContext *h, const char *uri, int flags)
994 {
995  HTTPContext *s = h->priv_data;
996  char hostname[1024], hoststr[1024];
997  char auth[1024], pathbuf[1024], *path;
998  char lower_url[100];
999  int port, ret = 0, attempts = 0;
1000  HTTPAuthType cur_auth_type;
1001  char *authstr;
1002  int new_loc;
1003 
1004  h->is_streamed = 1;
1005 
1006  av_url_split(NULL, 0, auth, sizeof(auth), hostname, sizeof(hostname), &port,
1007  pathbuf, sizeof(pathbuf), uri);
1008  ff_url_join(hoststr, sizeof(hoststr), NULL, NULL, hostname, port, NULL);
1009  path = pathbuf;
1010  if (*path == '/')
1011  path++;
1012 
1013  ff_url_join(lower_url, sizeof(lower_url), "tcp", NULL, hostname, port,
1014  NULL);
1015 redo:
1016  ret = ffurl_open(&s->hd, lower_url, AVIO_FLAG_READ_WRITE,
1017  &h->interrupt_callback, NULL);
1018  if (ret < 0)
1019  return ret;
1020 
1021  authstr = ff_http_auth_create_response(&s->proxy_auth_state, auth,
1022  path, "CONNECT");
1023  snprintf(s->buffer, sizeof(s->buffer),
1024  "CONNECT %s HTTP/1.1\r\n"
1025  "Host: %s\r\n"
1026  "Connection: close\r\n"
1027  "%s%s"
1028  "\r\n",
1029  path,
1030  hoststr,
1031  authstr ? "Proxy-" : "", authstr ? authstr : "");
1032  av_freep(&authstr);
1033 
1034  if ((ret = ffurl_write(s->hd, s->buffer, strlen(s->buffer))) < 0)
1035  goto fail;
1036 
1037  s->buf_ptr = s->buffer;
1038  s->buf_end = s->buffer;
1039  s->line_count = 0;
1040  s->filesize = -1;
1041  cur_auth_type = s->proxy_auth_state.auth_type;
1042 
1043  /* Note: This uses buffering, potentially reading more than the
1044  * HTTP header. If tunneling a protocol where the server starts
1045  * the conversation, we might buffer part of that here, too.
1046  * Reading that requires using the proper ffurl_read() function
1047  * on this URLContext, not using the fd directly (as the tls
1048  * protocol does). This shouldn't be an issue for tls though,
1049  * since the client starts the conversation there, so there
1050  * is no extra data that we might buffer up here.
1051  */
1052  ret = http_read_header(h, &new_loc);
1053  if (ret < 0)
1054  goto fail;
1055 
1056  attempts++;
1057  if (s->http_code == 407 &&
1058  (cur_auth_type == HTTP_AUTH_NONE || s->proxy_auth_state.stale) &&
1059  s->proxy_auth_state.auth_type != HTTP_AUTH_NONE && attempts < 2) {
1060  ffurl_close(s->hd);
1061  s->hd = NULL;
1062  goto redo;
1063  }
1064 
1065  if (s->http_code < 400)
1066  return 0;
1067  ret = AVERROR(EIO);
1068 
1069 fail:
1070  http_proxy_close(h);
1071  return ret;
1072 }
1073 
1074 static int http_proxy_write(URLContext *h, const uint8_t *buf, int size)
1075 {
1076  HTTPContext *s = h->priv_data;
1077  return ffurl_write(s->hd, buf, size);
1078 }
1079 
1080 URLProtocol ff_httpproxy_protocol = {
1081  .name = "httpproxy",
1082  .url_open = http_proxy_open,
1083  .url_read = http_buf_read,
1084  .url_write = http_proxy_write,
1085  .url_close = http_proxy_close,
1086  .url_get_file_handle = http_get_file_handle,
1087  .priv_data_size = sizeof(HTTPContext),
1088  .flags = URL_PROTOCOL_FLAG_NETWORK,
1089 };
1090 #endif