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.

1149 lines
36KB

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