compress_zstd.c 13 KB

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