compress_zstd.c 15 KB

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