compress_zstd.c 13 KB

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