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.

1081 lines
34KB

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