You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1157 lines
37KB

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