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.

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