compress.c 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619
  1. /* Copyright (c) 2004, Roger Dingledine.
  2. * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
  3. * Copyright (c) 2007-2017, The Tor Project, Inc. */
  4. /* See LICENSE for licensing information */
  5. /**
  6. * \file compress.c
  7. * \brief Common compression API.
  8. **/
  9. #include "orconfig.h"
  10. #include <stdlib.h>
  11. #include <stdio.h>
  12. #include <assert.h>
  13. #include <string.h>
  14. #include "torint.h"
  15. #ifdef HAVE_NETINET_IN_H
  16. #include <netinet/in.h>
  17. #endif
  18. #include "util.h"
  19. #include "torlog.h"
  20. #include "compress.h"
  21. #include "compress_lzma.h"
  22. #include "compress_none.h"
  23. #include "compress_zlib.h"
  24. #include "compress_zstd.h"
  25. /** Total number of bytes allocated for compression state overhead. */
  26. static atomic_counter_t total_compress_allocation;
  27. /** @{ */
  28. /* These macros define the maximum allowable compression factor. Anything of
  29. * size greater than CHECK_FOR_COMPRESSION_BOMB_AFTER is not allowed to
  30. * have an uncompression factor (uncompressed size:compressed size ratio) of
  31. * any greater than MAX_UNCOMPRESSION_FACTOR.
  32. *
  33. * Picking a value for MAX_UNCOMPRESSION_FACTOR is a trade-off: we want it to
  34. * be small to limit the attack multiplier, but we also want it to be large
  35. * enough so that no legitimate document --even ones we might invent in the
  36. * future -- ever compresses by a factor of greater than
  37. * MAX_UNCOMPRESSION_FACTOR. Within those parameters, there's a reasonably
  38. * large range of possible values. IMO, anything over 8 is probably safe; IMO
  39. * anything under 50 is probably sufficient.
  40. */
  41. #define MAX_UNCOMPRESSION_FACTOR 25
  42. #define CHECK_FOR_COMPRESSION_BOMB_AFTER (1024*64)
  43. /** @} */
  44. /** Return true if uncompressing an input of size <b>in_size</b> to an input of
  45. * size at least <b>size_out</b> looks like a compression bomb. */
  46. int
  47. tor_compress_is_compression_bomb(size_t size_in, size_t size_out)
  48. {
  49. if (size_in == 0 || size_out < CHECK_FOR_COMPRESSION_BOMB_AFTER)
  50. return 0;
  51. return (size_out / size_in > MAX_UNCOMPRESSION_FACTOR);
  52. }
  53. /** Guess the size that <b>in_len</b> will be after compression or
  54. * decompression. */
  55. static size_t
  56. guess_compress_size(int compress, compress_method_t method,
  57. compression_level_t compression_level,
  58. size_t in_len)
  59. {
  60. // ignore these for now.
  61. (void)compression_level;
  62. if (method == NO_METHOD) {
  63. /* Guess that we'll need an extra byte, to avoid a needless realloc
  64. * for nul-termination */
  65. return (in_len < SIZE_MAX) ? in_len + 1 : in_len;
  66. }
  67. /* Always guess a factor of 2. */
  68. if (compress) {
  69. in_len /= 2;
  70. } else {
  71. if (in_len < SIZE_T_CEILING/2)
  72. in_len *= 2;
  73. }
  74. return MAX(in_len, 1024);
  75. }
  76. /** Internal function to implement tor_compress/tor_uncompress, depending on
  77. * whether <b>compress</b> is set. All arguments are as for tor_compress or
  78. * tor_uncompress. */
  79. static int
  80. tor_compress_impl(int compress,
  81. char **out, size_t *out_len,
  82. const char *in, size_t in_len,
  83. compress_method_t method,
  84. compression_level_t compression_level,
  85. int complete_only,
  86. int protocol_warn_level)
  87. {
  88. tor_compress_state_t *stream;
  89. int rv;
  90. stream = tor_compress_new(compress, method, compression_level);
  91. if (stream == NULL)
  92. return -1;
  93. size_t in_len_orig = in_len;
  94. size_t out_remaining, out_alloc;
  95. char *outptr;
  96. out_remaining = out_alloc =
  97. guess_compress_size(compress, method, compression_level, in_len);
  98. *out = outptr = tor_malloc(out_remaining);
  99. const int finish = complete_only || compress;
  100. while (1) {
  101. switch (tor_compress_process(stream,
  102. &outptr, &out_remaining,
  103. &in, &in_len, finish)) {
  104. case TOR_COMPRESS_DONE:
  105. if (in_len == 0 || compress) {
  106. goto done;
  107. } else {
  108. // More data is present, and we're decompressing. So we may need to
  109. // reinitialize the stream if we are handling multiple concatenated
  110. // inputs.
  111. tor_compress_free(stream);
  112. stream = tor_compress_new(compress, method, compression_level);
  113. }
  114. break;
  115. case TOR_COMPRESS_OK:
  116. if (compress || complete_only) {
  117. goto err;
  118. } else {
  119. goto done;
  120. }
  121. break;
  122. case TOR_COMPRESS_BUFFER_FULL: {
  123. if (!compress && outptr < *out+out_alloc) {
  124. // A buffer error in this case means that we have a problem
  125. // with our input.
  126. log_fn(protocol_warn_level, LD_PROTOCOL,
  127. "Possible truncated or corrupt compressed data");
  128. goto err;
  129. }
  130. if (out_alloc >= SIZE_T_CEILING / 2) {
  131. log_warn(LD_GENERAL, "While %scompresing data: ran out of space.",
  132. compress?"":"un");
  133. goto err;
  134. }
  135. if (!compress &&
  136. tor_compress_is_compression_bomb(in_len_orig, out_alloc)) {
  137. // This should already have been caught down in the backend logic.
  138. // LCOV_EXCL_START
  139. tor_assert_nonfatal_unreached();
  140. goto err;
  141. // LCOV_EXCL_STOP
  142. }
  143. const size_t offset = outptr - *out;
  144. out_alloc *= 2;
  145. *out = tor_realloc(*out, out_alloc);
  146. outptr = *out + offset;
  147. out_remaining = out_alloc - offset;
  148. break;
  149. }
  150. case TOR_COMPRESS_ERROR:
  151. log_fn(protocol_warn_level, LD_GENERAL,
  152. "Error while %scompresing data: bad input?",
  153. compress?"":"un");
  154. goto err; // bad data.
  155. default:
  156. // LCOV_EXCL_START
  157. tor_assert_nonfatal_unreached();
  158. goto err;
  159. // LCOV_EXCL_STOP
  160. }
  161. }
  162. done:
  163. *out_len = outptr - *out;
  164. if (compress && tor_compress_is_compression_bomb(*out_len, in_len_orig)) {
  165. log_warn(LD_BUG, "We compressed something and got an insanely high "
  166. "compression factor; other Tors would think this was a "
  167. "compression bomb.");
  168. goto err;
  169. }
  170. if (!compress) {
  171. // NUL-terminate our output.
  172. if (out_alloc == *out_len)
  173. *out = tor_realloc(*out, out_alloc + 1);
  174. (*out)[*out_len] = '\0';
  175. }
  176. rv = 0;
  177. goto out;
  178. err:
  179. tor_free(*out);
  180. *out_len = 0;
  181. rv = -1;
  182. goto out;
  183. out:
  184. tor_compress_free(stream);
  185. return rv;
  186. }
  187. /** Given <b>in_len</b> bytes at <b>in</b>, compress them into a newly
  188. * allocated buffer, using the method described in <b>method</b>. Store the
  189. * compressed string in *<b>out</b>, and its length in *<b>out_len</b>.
  190. * Return 0 on success, -1 on failure.
  191. */
  192. int
  193. tor_compress(char **out, size_t *out_len,
  194. const char *in, size_t in_len,
  195. compress_method_t method)
  196. {
  197. return tor_compress_impl(1, out, out_len, in, in_len, method,
  198. BEST_COMPRESSION,
  199. 1, LOG_WARN);
  200. }
  201. /** Given zero or more compressed strings of total length <b>in_len</b> bytes
  202. * at <b>in</b>, uncompress them into a newly allocated buffer, using the
  203. * method described in <b>method</b>. Store the uncompressed string in
  204. * *<b>out</b>, and its length in *<b>out_len</b>. Return 0 on success, -1 on
  205. * failure.
  206. *
  207. * If any bytes are written to <b>out</b>, an extra byte NUL is always
  208. * written at the end, but not counted in <b>out_len</b>. This is a
  209. * safety feature to ensure that the output can be treated as a
  210. * NUL-terminated string -- though of course, callers should check
  211. * out_len anyway.
  212. *
  213. * If <b>complete_only</b> is true, we consider a truncated input as a
  214. * failure; otherwise we decompress as much as we can. Warn about truncated
  215. * or corrupt inputs at <b>protocol_warn_level</b>.
  216. */
  217. int
  218. tor_uncompress(char **out, size_t *out_len,
  219. const char *in, size_t in_len,
  220. compress_method_t method,
  221. int complete_only,
  222. int protocol_warn_level)
  223. {
  224. return tor_compress_impl(0, out, out_len, in, in_len, method,
  225. BEST_COMPRESSION,
  226. complete_only, protocol_warn_level);
  227. }
  228. /** Try to tell whether the <b>in_len</b>-byte string in <b>in</b> is likely
  229. * to be compressed or not. If it is, return the likeliest compression method.
  230. * Otherwise, return UNKNOWN_METHOD.
  231. */
  232. compress_method_t
  233. detect_compression_method(const char *in, size_t in_len)
  234. {
  235. if (in_len > 2 && fast_memeq(in, "\x1f\x8b", 2)) {
  236. return GZIP_METHOD;
  237. } else if (in_len > 2 && (in[0] & 0x0f) == 8 &&
  238. (ntohs(get_uint16(in)) % 31) == 0) {
  239. return ZLIB_METHOD;
  240. } else if (in_len > 2 &&
  241. fast_memeq(in, "\x5d\x00\x00", 3)) {
  242. return LZMA_METHOD;
  243. } else if (in_len > 3 &&
  244. fast_memeq(in, "\x28\xb5\x2f\xfd", 4)) {
  245. return ZSTD_METHOD;
  246. } else {
  247. return UNKNOWN_METHOD;
  248. }
  249. }
  250. /** Return 1 if a given <b>method</b> is supported; otherwise 0. */
  251. int
  252. tor_compress_supports_method(compress_method_t method)
  253. {
  254. switch (method) {
  255. case GZIP_METHOD:
  256. case ZLIB_METHOD:
  257. return tor_zlib_method_supported();
  258. case LZMA_METHOD:
  259. return tor_lzma_method_supported();
  260. case ZSTD_METHOD:
  261. return tor_zstd_method_supported();
  262. case NO_METHOD:
  263. return 1;
  264. case UNKNOWN_METHOD:
  265. default:
  266. return 0;
  267. }
  268. }
  269. /**
  270. * Return a bitmask of the supported compression types, where 1&lt;&lt;m is
  271. * set in the bitmask if and only if compression with method <b>m</b> is
  272. * supported.
  273. */
  274. unsigned
  275. tor_compress_get_supported_method_bitmask(void)
  276. {
  277. static unsigned supported = 0;
  278. if (supported == 0) {
  279. compress_method_t m;
  280. for (m = NO_METHOD; m <= UNKNOWN_METHOD; ++m) {
  281. if (tor_compress_supports_method(m)) {
  282. supported |= (1u << m);
  283. }
  284. }
  285. }
  286. return supported;
  287. }
  288. /** Table of compression method names. These should have an "x-" prefix,
  289. * if they are not listed in the IANA content coding registry. */
  290. static const struct {
  291. const char *name;
  292. compress_method_t method;
  293. } compression_method_names[] = {
  294. { "gzip", GZIP_METHOD },
  295. { "deflate", ZLIB_METHOD },
  296. // We call this "x-tor-lzma" rather than "x-lzma", because we impose a
  297. // lower maximum memory usage on the decoding side.
  298. { "x-tor-lzma", LZMA_METHOD },
  299. { "x-zstd" , ZSTD_METHOD },
  300. { "identity", NO_METHOD },
  301. /* Later entries in this table are not canonical; these are recognized but
  302. * not emitted. */
  303. { "x-gzip", GZIP_METHOD },
  304. };
  305. /** Return the canonical string representation of the compression method
  306. * <b>method</b>, or NULL if the method isn't recognized. */
  307. const char *
  308. compression_method_get_name(compress_method_t method)
  309. {
  310. unsigned i;
  311. for (i = 0; i < ARRAY_LENGTH(compression_method_names); ++i) {
  312. if (method == compression_method_names[i].method)
  313. return compression_method_names[i].name;
  314. }
  315. return NULL;
  316. }
  317. /** Table of compression human readable method names. */
  318. static const struct {
  319. compress_method_t method;
  320. const char *name;
  321. } compression_method_human_names[] = {
  322. { NO_METHOD, "uncompressed" },
  323. { GZIP_METHOD, "gzipped" },
  324. { ZLIB_METHOD, "deflated" },
  325. { LZMA_METHOD, "LZMA compressed" },
  326. { ZSTD_METHOD, "Zstandard compressed" },
  327. { UNKNOWN_METHOD, "unknown encoding" },
  328. };
  329. /** Return a human readable string representation of the compression method
  330. * <b>method</b>, or NULL if the method isn't recognized. */
  331. const char *
  332. compression_method_get_human_name(compress_method_t method)
  333. {
  334. unsigned i;
  335. for (i = 0; i < ARRAY_LENGTH(compression_method_human_names); ++i) {
  336. if (method == compression_method_human_names[i].method)
  337. return compression_method_human_names[i].name;
  338. }
  339. return NULL;
  340. }
  341. /** Return the compression method represented by the string <b>name</b>, or
  342. * UNKNOWN_METHOD if the string isn't recognized. */
  343. compress_method_t
  344. compression_method_get_by_name(const char *name)
  345. {
  346. unsigned i;
  347. for (i = 0; i < ARRAY_LENGTH(compression_method_names); ++i) {
  348. if (!strcmp(compression_method_names[i].name, name))
  349. return compression_method_names[i].method;
  350. }
  351. return UNKNOWN_METHOD;
  352. }
  353. /** Return a string representation of the version of the library providing the
  354. * compression method given in <b>method</b>. Returns NULL if <b>method</b> is
  355. * unknown or unsupported. */
  356. const char *
  357. tor_compress_version_str(compress_method_t method)
  358. {
  359. switch (method) {
  360. case GZIP_METHOD:
  361. case ZLIB_METHOD:
  362. return tor_zlib_get_version_str();
  363. case LZMA_METHOD:
  364. return tor_lzma_get_version_str();
  365. case ZSTD_METHOD:
  366. return tor_zstd_get_version_str();
  367. case NO_METHOD:
  368. case UNKNOWN_METHOD:
  369. default:
  370. return NULL;
  371. }
  372. }
  373. /** Return a string representation of the version of the library, found at
  374. * compile time, providing the compression method given in <b>method</b>.
  375. * Returns NULL if <b>method</b> is unknown or unsupported. */
  376. const char *
  377. tor_compress_header_version_str(compress_method_t method)
  378. {
  379. switch (method) {
  380. case GZIP_METHOD:
  381. case ZLIB_METHOD:
  382. return tor_zlib_get_header_version_str();
  383. case LZMA_METHOD:
  384. return tor_lzma_get_header_version_str();
  385. case ZSTD_METHOD:
  386. return tor_zstd_get_header_version_str();
  387. case NO_METHOD:
  388. case UNKNOWN_METHOD:
  389. default:
  390. return NULL;
  391. }
  392. }
  393. /** Return the approximate number of bytes allocated for all
  394. * supported compression schemas. */
  395. size_t
  396. tor_compress_get_total_allocation(void)
  397. {
  398. return atomic_counter_get(&total_compress_allocation) +
  399. tor_zlib_get_total_allocation() +
  400. tor_lzma_get_total_allocation() +
  401. tor_zstd_get_total_allocation();
  402. }
  403. /** Internal state for an incremental compression/decompression. The body of
  404. * this struct is not exposed. */
  405. struct tor_compress_state_t {
  406. compress_method_t method; /**< The compression method. */
  407. union {
  408. tor_zlib_compress_state_t *zlib_state;
  409. tor_lzma_compress_state_t *lzma_state;
  410. tor_zstd_compress_state_t *zstd_state;
  411. } u; /**< Compression backend state. */
  412. };
  413. /** Construct and return a tor_compress_state_t object using <b>method</b>. If
  414. * <b>compress</b>, it's for compression; otherwise it's for decompression. */
  415. tor_compress_state_t *
  416. tor_compress_new(int compress, compress_method_t method,
  417. compression_level_t compression_level)
  418. {
  419. tor_compress_state_t *state;
  420. state = tor_malloc_zero(sizeof(tor_compress_state_t));
  421. state->method = method;
  422. switch (method) {
  423. case GZIP_METHOD:
  424. case ZLIB_METHOD: {
  425. tor_zlib_compress_state_t *zlib_state =
  426. tor_zlib_compress_new(compress, method, compression_level);
  427. if (zlib_state == NULL)
  428. goto err;
  429. state->u.zlib_state = zlib_state;
  430. break;
  431. }
  432. case LZMA_METHOD: {
  433. tor_lzma_compress_state_t *lzma_state =
  434. tor_lzma_compress_new(compress, method, compression_level);
  435. if (lzma_state == NULL)
  436. goto err;
  437. state->u.lzma_state = lzma_state;
  438. break;
  439. }
  440. case ZSTD_METHOD: {
  441. tor_zstd_compress_state_t *zstd_state =
  442. tor_zstd_compress_new(compress, method, compression_level);
  443. if (zstd_state == NULL)
  444. goto err;
  445. state->u.zstd_state = zstd_state;
  446. break;
  447. }
  448. case NO_METHOD: {
  449. break;
  450. }
  451. case UNKNOWN_METHOD:
  452. goto err;
  453. }
  454. atomic_counter_add(&total_compress_allocation,
  455. sizeof(tor_compress_state_t));
  456. return state;
  457. err:
  458. tor_free(state);
  459. return NULL;
  460. }
  461. /** Compress/decompress some bytes using <b>state</b>. Read up to
  462. * *<b>in_len</b> bytes from *<b>in</b>, and write up to *<b>out_len</b> bytes
  463. * to *<b>out</b>, adjusting the values as we go. If <b>finish</b> is true,
  464. * we've reached the end of the input.
  465. *
  466. * Return TOR_COMPRESS_DONE if we've finished the entire
  467. * compression/decompression.
  468. * Return TOR_COMPRESS_OK if we're processed everything from the input.
  469. * Return TOR_COMPRESS_BUFFER_FULL if we're out of space on <b>out</b>.
  470. * Return TOR_COMPRESS_ERROR if the stream is corrupt.
  471. */
  472. tor_compress_output_t
  473. tor_compress_process(tor_compress_state_t *state,
  474. char **out, size_t *out_len,
  475. const char **in, size_t *in_len,
  476. int finish)
  477. {
  478. tor_assert(state != NULL);
  479. switch (state->method) {
  480. case GZIP_METHOD:
  481. case ZLIB_METHOD:
  482. return tor_zlib_compress_process(state->u.zlib_state,
  483. out, out_len, in, in_len,
  484. finish);
  485. case LZMA_METHOD:
  486. return tor_lzma_compress_process(state->u.lzma_state,
  487. out, out_len, in, in_len,
  488. finish);
  489. case ZSTD_METHOD:
  490. return tor_zstd_compress_process(state->u.zstd_state,
  491. out, out_len, in, in_len,
  492. finish);
  493. case NO_METHOD:
  494. return tor_cnone_compress_process(out, out_len, in, in_len,
  495. finish);
  496. case UNKNOWN_METHOD:
  497. goto err;
  498. }
  499. err:
  500. return TOR_COMPRESS_ERROR;
  501. }
  502. /** Deallocate <b>state</b>. */
  503. void
  504. tor_compress_free(tor_compress_state_t *state)
  505. {
  506. if (state == NULL)
  507. return;
  508. switch (state->method) {
  509. case GZIP_METHOD:
  510. case ZLIB_METHOD:
  511. tor_zlib_compress_free(state->u.zlib_state);
  512. break;
  513. case LZMA_METHOD:
  514. tor_lzma_compress_free(state->u.lzma_state);
  515. break;
  516. case ZSTD_METHOD:
  517. tor_zstd_compress_free(state->u.zstd_state);
  518. break;
  519. case NO_METHOD:
  520. break;
  521. case UNKNOWN_METHOD:
  522. break;
  523. }
  524. atomic_counter_sub(&total_compress_allocation,
  525. sizeof(tor_compress_state_t));
  526. tor_free(state);
  527. }
  528. /** Return the approximate number of bytes allocated for <b>state</b>. */
  529. size_t
  530. tor_compress_state_size(const tor_compress_state_t *state)
  531. {
  532. tor_assert(state != NULL);
  533. size_t size = sizeof(tor_compress_state_t);
  534. switch (state->method) {
  535. case GZIP_METHOD:
  536. case ZLIB_METHOD:
  537. size += tor_zlib_compress_state_size(state->u.zlib_state);
  538. break;
  539. case LZMA_METHOD:
  540. size += tor_lzma_compress_state_size(state->u.lzma_state);
  541. break;
  542. case ZSTD_METHOD:
  543. size += tor_zstd_compress_state_size(state->u.zstd_state);
  544. break;
  545. case NO_METHOD:
  546. case UNKNOWN_METHOD:
  547. break;
  548. }
  549. return size;
  550. }
  551. /** Initialize all compression modules. */
  552. void
  553. tor_compress_init(void)
  554. {
  555. atomic_counter_init(&total_compress_allocation);
  556. tor_zlib_init();
  557. tor_lzma_init();
  558. tor_zstd_init();
  559. }