compress_zstd.c 15 KB

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