compress_zstd.c 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537
  1. /* Copyright (c) 2004, Roger Dingledine.
  2. * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson.
  3. * Copyright (c) 2007-2018, The Tor Project, Inc. */
  4. /* See LICENSE for licensing information */
  5. /**
  6. * \file compress_zstd.c
  7. * \brief Compression backend for Zstandard.
  8. *
  9. * This module should never be invoked directly. Use the compress module
  10. * instead.
  11. **/
  12. #include "orconfig.h"
  13. #include "lib/log/log.h"
  14. #include "lib/log/util_bug.h"
  15. #include "lib/compress/compress.h"
  16. #include "lib/compress/compress_zstd.h"
  17. #include "lib/string/printf.h"
  18. #include "lib/thread/threads.h"
  19. #ifdef ENABLE_ZSTD_ADVANCED_APIS
  20. /* This is a lie, but we make sure it doesn't get us in trouble by wrapping
  21. * all invocations of zstd's static-only functions in a check to make sure
  22. * that the compile-time version matches the run-time version. */
  23. #define ZSTD_STATIC_LINKING_ONLY
  24. #endif
  25. #ifdef HAVE_ZSTD
  26. DISABLE_GCC_WARNING(unused-const-variable)
  27. #include <zstd.h>
  28. ENABLE_GCC_WARNING(unused-const-variable)
  29. #endif
  30. /** Total number of bytes allocated for Zstandard state. */
  31. static atomic_counter_t total_zstd_allocation;
  32. #ifdef HAVE_ZSTD
  33. /** Given <b>level</b> return the memory level. */
  34. static int
  35. memory_level(compression_level_t level)
  36. {
  37. switch (level) {
  38. default:
  39. case BEST_COMPRESSION:
  40. case HIGH_COMPRESSION: return 9;
  41. case MEDIUM_COMPRESSION: return 8;
  42. case LOW_COMPRESSION: return 7;
  43. }
  44. }
  45. #endif /* defined(HAVE_ZSTD) */
  46. /** Return 1 if Zstandard compression is supported; otherwise 0. */
  47. int
  48. tor_zstd_method_supported(void)
  49. {
  50. #ifdef HAVE_ZSTD
  51. return 1;
  52. #else
  53. return 0;
  54. #endif
  55. }
  56. #ifdef HAVE_ZSTD
  57. /** Format a zstd version number as a string in <b>buf</b>. */
  58. static void
  59. tor_zstd_format_version(char *buf, size_t buflen, unsigned version_number)
  60. {
  61. tor_snprintf(buf, buflen,
  62. "%u.%u.%u",
  63. version_number / 10000 % 100,
  64. version_number / 100 % 100,
  65. version_number % 100);
  66. }
  67. #endif
  68. #define VERSION_STR_MAX_LEN 16 /* more than enough space for 99.99.99 */
  69. /** Return a string representation of the version of the currently running
  70. * version of libzstd. Returns NULL if Zstandard is unsupported. */
  71. const char *
  72. tor_zstd_get_version_str(void)
  73. {
  74. #ifdef HAVE_ZSTD
  75. static char version_str[VERSION_STR_MAX_LEN];
  76. tor_zstd_format_version(version_str, sizeof(version_str),
  77. ZSTD_versionNumber());
  78. return version_str;
  79. #else /* !(defined(HAVE_ZSTD)) */
  80. return NULL;
  81. #endif /* defined(HAVE_ZSTD) */
  82. }
  83. /** Return a string representation of the version of the version of libzstd
  84. * used at compilation time. Returns NULL if Zstandard is unsupported. */
  85. const char *
  86. tor_zstd_get_header_version_str(void)
  87. {
  88. #ifdef HAVE_ZSTD
  89. return ZSTD_VERSION_STRING;
  90. #else
  91. return NULL;
  92. #endif
  93. }
  94. #ifdef TOR_UNIT_TESTS
  95. static int static_apis_disable_for_testing = 0;
  96. #endif
  97. /** Return true iff we can use the "static-only" APIs. */
  98. int
  99. tor_zstd_can_use_static_apis(void)
  100. {
  101. #if defined(ZSTD_STATIC_LINKING_ONLY) && defined(HAVE_ZSTD)
  102. #ifdef TOR_UNIT_TESTS
  103. if (static_apis_disable_for_testing) {
  104. return 0;
  105. }
  106. #endif
  107. return (ZSTD_VERSION_NUMBER == ZSTD_versionNumber());
  108. #else
  109. return 0;
  110. #endif
  111. }
  112. /** Internal Zstandard state for incremental compression/decompression.
  113. * The body of this struct is not exposed. */
  114. struct tor_zstd_compress_state_t {
  115. #ifdef HAVE_ZSTD
  116. union {
  117. /** Compression stream. Used when <b>compress</b> is true. */
  118. ZSTD_CStream *compress_stream;
  119. /** Decompression stream. Used when <b>compress</b> is false. */
  120. ZSTD_DStream *decompress_stream;
  121. } u; /**< Zstandard stream objects. */
  122. #endif /* defined(HAVE_ZSTD) */
  123. int compress; /**< True if we are compressing; false if we are inflating */
  124. int have_called_end; /**< True if we are compressing and we've called
  125. * ZSTD_endStream */
  126. /** Number of bytes read so far. Used to detect compression bombs. */
  127. size_t input_so_far;
  128. /** Number of bytes written so far. Used to detect compression bombs. */
  129. size_t output_so_far;
  130. /** Approximate number of bytes allocated for this object. */
  131. size_t allocation;
  132. };
  133. #ifdef HAVE_ZSTD
  134. /** Return an approximate number of bytes stored in memory to hold the
  135. * Zstandard compression/decompression state. This is a fake estimate
  136. * based on inspecting the zstd source: tor_zstd_state_size_precalc() is
  137. * more accurate when it's allowed to use "static-only" functions */
  138. static size_t
  139. tor_zstd_state_size_precalc_fake(int compress, int preset)
  140. {
  141. tor_assert(preset > 0);
  142. size_t memory_usage = sizeof(tor_zstd_compress_state_t);
  143. // The Zstandard library provides a number of functions that would be useful
  144. // here, but they are, unfortunately, still considered experimental and are
  145. // thus only available in libzstd if we link against the library statically.
  146. //
  147. // The code in this function tries to approximate the calculations without
  148. // being able to use the following:
  149. //
  150. // - We do not have access to neither the internal members of ZSTD_CStream
  151. // and ZSTD_DStream and their internal context objects.
  152. //
  153. // - We cannot use ZSTD_sizeof_CStream() and ZSTD_sizeof_DStream() since they
  154. // are unexposed.
  155. //
  156. // In the future it might be useful to check if libzstd have started
  157. // providing these functions in a stable manner and simplify this function.
  158. if (compress) {
  159. // We try to approximate the ZSTD_sizeof_CStream(ZSTD_CStream *stream)
  160. // function here. This function uses the following fields to make its
  161. // estimate:
  162. // - sizeof(ZSTD_CStream): Around 192 bytes on a 64-bit machine:
  163. memory_usage += 192;
  164. // - ZSTD_sizeof_CCtx(stream->cctx): This function requires access to
  165. // variables that are not exposed via the public API. We use a _very_
  166. // simplified function to calculate the estimated amount of bytes used in
  167. // this struct.
  168. // memory_usage += (preset - 0.5) * 1024 * 1024;
  169. memory_usage += (preset * 1024 * 1024) - (512 * 1024);
  170. // - ZSTD_sizeof_CDict(stream->cdictLocal): Unused in Tor: 0 bytes.
  171. // - stream->outBuffSize: 128 KB:
  172. memory_usage += 128 * 1024;
  173. // - stream->inBuffSize: 2048 KB:
  174. memory_usage += 2048 * 1024;
  175. } else {
  176. // We try to approximate the ZSTD_sizeof_DStream(ZSTD_DStream *stream)
  177. // function here. This function uses the following fields to make its
  178. // estimate:
  179. // - sizeof(ZSTD_DStream): Around 208 bytes on a 64-bit machine:
  180. memory_usage += 208;
  181. // - ZSTD_sizeof_DCtx(stream->dctx): Around 150 KB.
  182. memory_usage += 150 * 1024;
  183. // - ZSTD_sizeof_DDict(stream->ddictLocal): Unused in Tor: 0 bytes.
  184. // - stream->inBuffSize: 0 KB.
  185. // - stream->outBuffSize: 0 KB.
  186. }
  187. return memory_usage;
  188. }
  189. /** Return an approximate number of bytes stored in memory to hold the
  190. * Zstandard compression/decompression state. */
  191. static size_t
  192. tor_zstd_state_size_precalc(int compress, int preset)
  193. {
  194. #ifdef ZSTD_STATIC_LINKING_ONLY
  195. if (tor_zstd_can_use_static_apis()) {
  196. if (compress) {
  197. #ifdef HAVE_ZSTD_ESTIMATECSTREAMSIZE
  198. return ZSTD_estimateCStreamSize(preset);
  199. #endif
  200. } else {
  201. #ifdef HAVE_ZSTD_ESTIMATEDCTXSIZE
  202. /* Could use DStream, but that takes a windowSize. */
  203. return ZSTD_estimateDCtxSize();
  204. #endif
  205. }
  206. }
  207. #endif
  208. return tor_zstd_state_size_precalc_fake(compress, preset);
  209. }
  210. #endif /* defined(HAVE_ZSTD) */
  211. /** Construct and return a tor_zstd_compress_state_t object using
  212. * <b>method</b>. If <b>compress</b>, it's for compression; otherwise it's for
  213. * decompression. */
  214. tor_zstd_compress_state_t *
  215. tor_zstd_compress_new(int compress,
  216. compress_method_t method,
  217. compression_level_t level)
  218. {
  219. tor_assert(method == ZSTD_METHOD);
  220. #ifdef HAVE_ZSTD
  221. const int preset = memory_level(level);
  222. tor_zstd_compress_state_t *result;
  223. size_t retval;
  224. result = tor_malloc_zero(sizeof(tor_zstd_compress_state_t));
  225. result->compress = compress;
  226. result->allocation = tor_zstd_state_size_precalc(compress, preset);
  227. if (compress) {
  228. result->u.compress_stream = ZSTD_createCStream();
  229. if (result->u.compress_stream == NULL) {
  230. // LCOV_EXCL_START
  231. log_warn(LD_GENERAL, "Error while creating Zstandard compression "
  232. "stream");
  233. goto err;
  234. // LCOV_EXCL_STOP
  235. }
  236. retval = ZSTD_initCStream(result->u.compress_stream, preset);
  237. if (ZSTD_isError(retval)) {
  238. // LCOV_EXCL_START
  239. log_warn(LD_GENERAL, "Zstandard stream initialization error: %s",
  240. ZSTD_getErrorName(retval));
  241. goto err;
  242. // LCOV_EXCL_STOP
  243. }
  244. } else {
  245. result->u.decompress_stream = ZSTD_createDStream();
  246. if (result->u.decompress_stream == NULL) {
  247. // LCOV_EXCL_START
  248. log_warn(LD_GENERAL, "Error while creating Zstandard decompression "
  249. "stream");
  250. goto err;
  251. // LCOV_EXCL_STOP
  252. }
  253. retval = ZSTD_initDStream(result->u.decompress_stream);
  254. if (ZSTD_isError(retval)) {
  255. // LCOV_EXCL_START
  256. log_warn(LD_GENERAL, "Zstandard stream initialization error: %s",
  257. ZSTD_getErrorName(retval));
  258. goto err;
  259. // LCOV_EXCL_STOP
  260. }
  261. }
  262. atomic_counter_add(&total_zstd_allocation, result->allocation);
  263. return result;
  264. err:
  265. // LCOV_EXCL_START
  266. if (compress) {
  267. ZSTD_freeCStream(result->u.compress_stream);
  268. } else {
  269. ZSTD_freeDStream(result->u.decompress_stream);
  270. }
  271. tor_free(result);
  272. return NULL;
  273. // LCOV_EXCL_STOP
  274. #else /* !(defined(HAVE_ZSTD)) */
  275. (void)compress;
  276. (void)method;
  277. (void)level;
  278. return NULL;
  279. #endif /* defined(HAVE_ZSTD) */
  280. }
  281. /** Compress/decompress some bytes using <b>state</b>. Read up to
  282. * *<b>in_len</b> bytes from *<b>in</b>, and write up to *<b>out_len</b> bytes
  283. * to *<b>out</b>, adjusting the values as we go. If <b>finish</b> is true,
  284. * we've reached the end of the input.
  285. *
  286. * Return TOR_COMPRESS_DONE if we've finished the entire
  287. * compression/decompression.
  288. * Return TOR_COMPRESS_OK if we're processed everything from the input.
  289. * Return TOR_COMPRESS_BUFFER_FULL if we're out of space on <b>out</b>.
  290. * Return TOR_COMPRESS_ERROR if the stream is corrupt.
  291. */
  292. tor_compress_output_t
  293. tor_zstd_compress_process(tor_zstd_compress_state_t *state,
  294. char **out, size_t *out_len,
  295. const char **in, size_t *in_len,
  296. int finish)
  297. {
  298. #ifdef HAVE_ZSTD
  299. size_t retval;
  300. tor_assert(state != NULL);
  301. tor_assert(*in_len <= UINT_MAX);
  302. tor_assert(*out_len <= UINT_MAX);
  303. ZSTD_inBuffer input = { *in, *in_len, 0 };
  304. ZSTD_outBuffer output = { *out, *out_len, 0 };
  305. if (BUG(finish == 0 && state->have_called_end)) {
  306. finish = 1;
  307. }
  308. if (state->compress) {
  309. if (! state->have_called_end)
  310. retval = ZSTD_compressStream(state->u.compress_stream,
  311. &output, &input);
  312. else
  313. retval = 0;
  314. } else {
  315. retval = ZSTD_decompressStream(state->u.decompress_stream,
  316. &output, &input);
  317. }
  318. state->input_so_far += input.pos;
  319. state->output_so_far += output.pos;
  320. *out = (char *)output.dst + output.pos;
  321. *out_len = output.size - output.pos;
  322. *in = (char *)input.src + input.pos;
  323. *in_len = input.size - input.pos;
  324. if (! state->compress &&
  325. tor_compress_is_compression_bomb(state->input_so_far,
  326. state->output_so_far)) {
  327. log_warn(LD_DIR, "Possible compression bomb; abandoning stream.");
  328. return TOR_COMPRESS_ERROR;
  329. }
  330. if (ZSTD_isError(retval)) {
  331. log_warn(LD_GENERAL, "Zstandard %s didn't finish: %s.",
  332. state->compress ? "compression" : "decompression",
  333. ZSTD_getErrorName(retval));
  334. return TOR_COMPRESS_ERROR;
  335. }
  336. if (state->compress && !state->have_called_end) {
  337. retval = ZSTD_flushStream(state->u.compress_stream, &output);
  338. *out = (char *)output.dst + output.pos;
  339. *out_len = output.size - output.pos;
  340. if (ZSTD_isError(retval)) {
  341. log_warn(LD_GENERAL, "Zstandard compression unable to flush: %s.",
  342. ZSTD_getErrorName(retval));
  343. return TOR_COMPRESS_ERROR;
  344. }
  345. // ZSTD_flushStream returns 0 if the frame is done, or >0 if it
  346. // is incomplete.
  347. if (retval > 0) {
  348. return TOR_COMPRESS_BUFFER_FULL;
  349. }
  350. }
  351. if (!finish) {
  352. // The caller says we're not done with the input, so no need to write an
  353. // epilogue.
  354. return TOR_COMPRESS_OK;
  355. } else if (state->compress) {
  356. if (*in_len) {
  357. // We say that we're not done with the input, so we can't write an
  358. // epilogue.
  359. return TOR_COMPRESS_OK;
  360. }
  361. retval = ZSTD_endStream(state->u.compress_stream, &output);
  362. state->have_called_end = 1;
  363. *out = (char *)output.dst + output.pos;
  364. *out_len = output.size - output.pos;
  365. if (ZSTD_isError(retval)) {
  366. log_warn(LD_GENERAL, "Zstandard compression unable to write "
  367. "epilogue: %s.",
  368. ZSTD_getErrorName(retval));
  369. return TOR_COMPRESS_ERROR;
  370. }
  371. // endStream returns the number of bytes that is needed to write the
  372. // epilogue.
  373. if (retval > 0)
  374. return TOR_COMPRESS_BUFFER_FULL;
  375. return TOR_COMPRESS_DONE;
  376. } else /* if (!state->compress) */ {
  377. // ZSTD_decompressStream returns 0 if the frame is done, or >0 if it
  378. // is incomplete.
  379. // We check this above.
  380. tor_assert_nonfatal(!ZSTD_isError(retval));
  381. // Start a new frame if this frame is done
  382. if (retval == 0)
  383. return TOR_COMPRESS_DONE;
  384. // Don't check out_len, it might have some space left if the next output
  385. // chunk is larger than the remaining space
  386. else if (*in_len > 0)
  387. return TOR_COMPRESS_BUFFER_FULL;
  388. else
  389. return TOR_COMPRESS_OK;
  390. }
  391. #else /* !(defined(HAVE_ZSTD)) */
  392. (void)state;
  393. (void)out;
  394. (void)out_len;
  395. (void)in;
  396. (void)in_len;
  397. (void)finish;
  398. return TOR_COMPRESS_ERROR;
  399. #endif /* defined(HAVE_ZSTD) */
  400. }
  401. /** Deallocate <b>state</b>. */
  402. void
  403. tor_zstd_compress_free_(tor_zstd_compress_state_t *state)
  404. {
  405. if (state == NULL)
  406. return;
  407. atomic_counter_sub(&total_zstd_allocation, state->allocation);
  408. #ifdef HAVE_ZSTD
  409. if (state->compress) {
  410. ZSTD_freeCStream(state->u.compress_stream);
  411. } else {
  412. ZSTD_freeDStream(state->u.decompress_stream);
  413. }
  414. #endif /* defined(HAVE_ZSTD) */
  415. tor_free(state);
  416. }
  417. /** Return the approximate number of bytes allocated for <b>state</b>. */
  418. size_t
  419. tor_zstd_compress_state_size(const tor_zstd_compress_state_t *state)
  420. {
  421. tor_assert(state != NULL);
  422. return state->allocation;
  423. }
  424. /** Return the approximate number of bytes allocated for all Zstandard
  425. * states. */
  426. size_t
  427. tor_zstd_get_total_allocation(void)
  428. {
  429. return atomic_counter_get(&total_zstd_allocation);
  430. }
  431. /** Initialize the zstd module */
  432. void
  433. tor_zstd_init(void)
  434. {
  435. atomic_counter_init(&total_zstd_allocation);
  436. }
  437. /** Warn if the header and library versions don't match. */
  438. void
  439. tor_zstd_warn_if_version_mismatched(void)
  440. {
  441. #if defined(HAVE_ZSTD) && defined(ENABLE_ZSTD_ADVANCED_APIS)
  442. if (! tor_zstd_can_use_static_apis()) {
  443. char header_version[VERSION_STR_MAX_LEN];
  444. char runtime_version[VERSION_STR_MAX_LEN];
  445. tor_zstd_format_version(header_version, sizeof(header_version),
  446. ZSTD_VERSION_NUMBER);
  447. tor_zstd_format_version(runtime_version, sizeof(runtime_version),
  448. ZSTD_versionNumber());
  449. log_warn(LD_GENERAL,
  450. "Tor was compiled with zstd %s, but is running with zstd %s. "
  451. "For safety, we'll avoid using advanced zstd functionality.",
  452. header_version, runtime_version);
  453. }
  454. #endif
  455. }
  456. #ifdef TOR_UNIT_TESTS
  457. /** Testing only: disable usage of static-only APIs, so we can make sure that
  458. * we still work without them. */
  459. void
  460. tor_zstd_set_static_apis_disabled_for_testing(int disabled)
  461. {
  462. static_apis_disable_for_testing = disabled;
  463. }
  464. #endif