compress.c 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541
  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. /** Table of compression method names. These should have an "x-" prefix,
  257. * if they are not listed in the IANA content coding registry. */
  258. static const struct {
  259. const char *name;
  260. compress_method_t method;
  261. } compression_method_names[] = {
  262. { "gzip", GZIP_METHOD },
  263. { "deflate", ZLIB_METHOD },
  264. { "x-lzma2", LZMA_METHOD },
  265. { "x-zstd" , ZSTD_METHOD },
  266. { "identity", NO_METHOD },
  267. /* Later entries in this table are not canonical; these are recognized but
  268. * not emitted. */
  269. { "x-gzip", GZIP_METHOD },
  270. };
  271. /** Return the canonical string representation of the compression method
  272. * <b>method</b>, or NULL if the method isn't recognized. */
  273. const char *
  274. compression_method_get_name(compress_method_t method)
  275. {
  276. unsigned i;
  277. for (i = 0; i < ARRAY_LENGTH(compression_method_names); ++i) {
  278. if (method == compression_method_names[i].method)
  279. return compression_method_names[i].name;
  280. }
  281. return NULL;
  282. }
  283. /** Return the compression method represented by the string <b>name</b>, or
  284. * UNKNOWN_METHOD if the string isn't recognized. */
  285. compress_method_t
  286. compression_method_get_by_name(const char *name)
  287. {
  288. unsigned i;
  289. for (i = 0; i < ARRAY_LENGTH(compression_method_names); ++i) {
  290. if (!strcmp(compression_method_names[i].name, name))
  291. return compression_method_names[i].method;
  292. }
  293. return UNKNOWN_METHOD;
  294. }
  295. /** Return a string representation of the version of the library providing the
  296. * compression method given in <b>method</b>. Returns NULL if <b>method</b> is
  297. * unknown or unsupported. */
  298. const char *
  299. tor_compress_version_str(compress_method_t method)
  300. {
  301. switch (method) {
  302. case GZIP_METHOD:
  303. case ZLIB_METHOD:
  304. return tor_zlib_get_version_str();
  305. case LZMA_METHOD:
  306. return tor_lzma_get_version_str();
  307. case ZSTD_METHOD:
  308. return tor_zstd_get_version_str();
  309. case NO_METHOD:
  310. case UNKNOWN_METHOD:
  311. default:
  312. return NULL;
  313. }
  314. }
  315. /** Return a string representation of the version of the library, found at
  316. * compile time, providing the compression method given in <b>method</b>.
  317. * Returns NULL if <b>method</b> is unknown or unsupported. */
  318. const char *
  319. tor_compress_header_version_str(compress_method_t method)
  320. {
  321. switch (method) {
  322. case GZIP_METHOD:
  323. case ZLIB_METHOD:
  324. return tor_zlib_get_header_version_str();
  325. case LZMA_METHOD:
  326. return tor_lzma_get_header_version_str();
  327. case ZSTD_METHOD:
  328. return tor_zstd_get_header_version_str();
  329. case NO_METHOD:
  330. case UNKNOWN_METHOD:
  331. default:
  332. return NULL;
  333. }
  334. }
  335. /** Return the approximate number of bytes allocated for all
  336. * supported compression schemas. */
  337. size_t
  338. tor_compress_get_total_allocation(void)
  339. {
  340. return tor_zlib_get_total_allocation() +
  341. tor_lzma_get_total_allocation() +
  342. tor_zstd_get_total_allocation();
  343. }
  344. /** Internal state for an incremental compression/decompression. The body of
  345. * this struct is not exposed. */
  346. struct tor_compress_state_t {
  347. compress_method_t method; /**< The compression method. */
  348. union {
  349. tor_zlib_compress_state_t *zlib_state;
  350. tor_lzma_compress_state_t *lzma_state;
  351. tor_zstd_compress_state_t *zstd_state;
  352. } u; /**< Compression backend state. */
  353. };
  354. /** Construct and return a tor_compress_state_t object using <b>method</b>. If
  355. * <b>compress</b>, it's for compression; otherwise it's for decompression. */
  356. tor_compress_state_t *
  357. tor_compress_new(int compress, compress_method_t method,
  358. compression_level_t compression_level)
  359. {
  360. tor_compress_state_t *state;
  361. state = tor_malloc_zero(sizeof(tor_compress_state_t));
  362. state->method = method;
  363. switch (method) {
  364. case GZIP_METHOD:
  365. case ZLIB_METHOD: {
  366. tor_zlib_compress_state_t *zlib_state =
  367. tor_zlib_compress_new(compress, method, compression_level);
  368. if (zlib_state == NULL)
  369. goto err;
  370. state->u.zlib_state = zlib_state;
  371. break;
  372. }
  373. case LZMA_METHOD: {
  374. tor_lzma_compress_state_t *lzma_state =
  375. tor_lzma_compress_new(compress, method, compression_level);
  376. if (lzma_state == NULL)
  377. goto err;
  378. state->u.lzma_state = lzma_state;
  379. break;
  380. }
  381. case ZSTD_METHOD: {
  382. tor_zstd_compress_state_t *zstd_state =
  383. tor_zstd_compress_new(compress, method, compression_level);
  384. if (zstd_state == NULL)
  385. goto err;
  386. state->u.zstd_state = zstd_state;
  387. break;
  388. }
  389. case NO_METHOD:
  390. case UNKNOWN_METHOD:
  391. goto err;
  392. }
  393. return state;
  394. err:
  395. tor_free(state);
  396. return NULL;
  397. }
  398. /** Compress/decompress some bytes using <b>state</b>. Read up to
  399. * *<b>in_len</b> bytes from *<b>in</b>, and write up to *<b>out_len</b> bytes
  400. * to *<b>out</b>, adjusting the values as we go. If <b>finish</b> is true,
  401. * we've reached the end of the input.
  402. *
  403. * Return TOR_COMPRESS_DONE if we've finished the entire
  404. * compression/decompression.
  405. * Return TOR_COMPRESS_OK if we're processed everything from the input.
  406. * Return TOR_COMPRESS_BUFFER_FULL if we're out of space on <b>out</b>.
  407. * Return TOR_COMPRESS_ERROR if the stream is corrupt.
  408. */
  409. tor_compress_output_t
  410. tor_compress_process(tor_compress_state_t *state,
  411. char **out, size_t *out_len,
  412. const char **in, size_t *in_len,
  413. int finish)
  414. {
  415. tor_assert(state != NULL);
  416. switch (state->method) {
  417. case GZIP_METHOD:
  418. case ZLIB_METHOD:
  419. return tor_zlib_compress_process(state->u.zlib_state,
  420. out, out_len, in, in_len,
  421. finish);
  422. case LZMA_METHOD:
  423. return tor_lzma_compress_process(state->u.lzma_state,
  424. out, out_len, in, in_len,
  425. finish);
  426. case ZSTD_METHOD:
  427. return tor_zstd_compress_process(state->u.zstd_state,
  428. out, out_len, in, in_len,
  429. finish);
  430. case NO_METHOD:
  431. case UNKNOWN_METHOD:
  432. goto err;
  433. }
  434. err:
  435. return TOR_COMPRESS_ERROR;
  436. }
  437. /** Deallocate <b>state</b>. */
  438. void
  439. tor_compress_free(tor_compress_state_t *state)
  440. {
  441. if (state == NULL)
  442. return;
  443. switch (state->method) {
  444. case GZIP_METHOD:
  445. case ZLIB_METHOD:
  446. tor_zlib_compress_free(state->u.zlib_state);
  447. break;
  448. case LZMA_METHOD:
  449. tor_lzma_compress_free(state->u.lzma_state);
  450. break;
  451. case ZSTD_METHOD:
  452. tor_zstd_compress_free(state->u.zstd_state);
  453. break;
  454. case NO_METHOD:
  455. case UNKNOWN_METHOD:
  456. break;
  457. }
  458. tor_free(state);
  459. }
  460. /** Return the approximate number of bytes allocated for <b>state</b>. */
  461. size_t
  462. tor_compress_state_size(const tor_compress_state_t *state)
  463. {
  464. tor_assert(state != NULL);
  465. switch (state->method) {
  466. case GZIP_METHOD:
  467. case ZLIB_METHOD:
  468. return tor_zlib_compress_state_size(state->u.zlib_state);
  469. case LZMA_METHOD:
  470. return tor_lzma_compress_state_size(state->u.lzma_state);
  471. case ZSTD_METHOD:
  472. return tor_zstd_compress_state_size(state->u.zstd_state);
  473. case NO_METHOD:
  474. case UNKNOWN_METHOD:
  475. goto err;
  476. }
  477. err:
  478. return 0;
  479. }
  480. /** Initialize all compression modules. */
  481. void
  482. tor_compress_init(void)
  483. {
  484. tor_zlib_init();
  485. tor_lzma_init();
  486. tor_zstd_init();
  487. }