compress.c 16 KB

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