compress_zstd.c 15 KB

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