compress_zstd.c 16 KB

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