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.

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