compress_zstd.c 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335
  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. #include <zstd_errors.h>
  20. #endif
  21. /** Total number of bytes allocated for Zstandard state. */
  22. static atomic_counter_t total_zstd_allocation;
  23. #ifdef HAVE_ZSTD
  24. /** Given <b>level</b> return the memory level. */
  25. static int
  26. memory_level(compression_level_t level)
  27. {
  28. switch (level) {
  29. default:
  30. case BEST_COMPRESSION:
  31. case HIGH_COMPRESSION: return 9;
  32. case MEDIUM_COMPRESSION: return 8;
  33. case LOW_COMPRESSION: return 7;
  34. }
  35. }
  36. #endif // HAVE_ZSTD.
  37. /** Return 1 if Zstandard compression is supported; otherwise 0. */
  38. int
  39. tor_zstd_method_supported(void)
  40. {
  41. #ifdef HAVE_ZSTD
  42. return 1;
  43. #else
  44. return 0;
  45. #endif
  46. }
  47. /** Return a string representation of the version of the currently running
  48. * version of libzstd. Returns NULL if Zstandard is unsupported. */
  49. const char *
  50. tor_zstd_get_version_str(void)
  51. {
  52. #ifdef HAVE_ZSTD
  53. static char version_str[16];
  54. size_t version_number;
  55. version_number = ZSTD_versionNumber();
  56. tor_snprintf(version_str, sizeof(version_str),
  57. "%lu.%lu.%lu",
  58. version_number / 10000 % 100,
  59. version_number / 100 % 100,
  60. version_number % 100);
  61. return version_str;
  62. #else
  63. return NULL;
  64. #endif
  65. }
  66. /** Return a string representation of the version of the version of libzstd
  67. * used at compilation time. Returns NULL if Zstandard is unsupported. */
  68. const char *
  69. tor_zstd_get_header_version_str(void)
  70. {
  71. #ifdef HAVE_ZSTD
  72. return ZSTD_VERSION_STRING;
  73. #else
  74. return NULL;
  75. #endif
  76. }
  77. /** Internal Zstandard state for incremental compression/decompression.
  78. * The body of this struct is not exposed. */
  79. struct tor_zstd_compress_state_t {
  80. #ifdef HAVE_ZSTD
  81. union {
  82. /** Compression stream. Used when <b>compress</b> is true. */
  83. ZSTD_CStream *compress_stream;
  84. /** Decompression stream. Used when <b>compress</b> is false. */
  85. ZSTD_DStream *decompress_stream;
  86. } u; /**< Zstandard stream objects. */
  87. #endif // HAVE_ZSTD.
  88. int compress; /**< True if we are compressing; false if we are inflating */
  89. /** Number of bytes read so far. Used to detect compression bombs. */
  90. size_t input_so_far;
  91. /** Number of bytes written so far. Used to detect compression bombs. */
  92. size_t output_so_far;
  93. /** Approximate number of bytes allocated for this object. */
  94. size_t allocation;
  95. };
  96. /** Construct and return a tor_zstd_compress_state_t object using
  97. * <b>method</b>. If <b>compress</b>, it's for compression; otherwise it's for
  98. * decompression. */
  99. tor_zstd_compress_state_t *
  100. tor_zstd_compress_new(int compress,
  101. compress_method_t method,
  102. compression_level_t compression_level)
  103. {
  104. tor_assert(method == ZSTD_METHOD);
  105. #ifdef HAVE_ZSTD
  106. tor_zstd_compress_state_t *result;
  107. size_t retval;
  108. result = tor_malloc_zero(sizeof(tor_zstd_compress_state_t));
  109. result->compress = compress;
  110. // FIXME(ahf): We should either try to do the pre-calculation that is done
  111. // with the zlib backend or use a custom allocator here where we pass our
  112. // tor_zstd_compress_state_t as the opaque value.
  113. result->allocation = 0;
  114. if (compress) {
  115. result->u.compress_stream = ZSTD_createCStream();
  116. if (result->u.compress_stream == NULL) {
  117. log_warn(LD_GENERAL, "Error while creating Zstandard stream");
  118. goto err;
  119. }
  120. retval = ZSTD_initCStream(result->u.compress_stream,
  121. memory_level(compression_level));
  122. if (ZSTD_isError(retval)) {
  123. log_warn(LD_GENERAL, "Zstandard stream initialization error: %s",
  124. ZSTD_getErrorName(retval));
  125. goto err;
  126. }
  127. } else {
  128. result->u.decompress_stream = ZSTD_createDStream();
  129. if (result->u.decompress_stream == NULL) {
  130. log_warn(LD_GENERAL, "Error while creating Zstandard stream");
  131. goto err;
  132. }
  133. retval = ZSTD_initDStream(result->u.decompress_stream);
  134. if (ZSTD_isError(retval)) {
  135. log_warn(LD_GENERAL, "Zstandard stream initialization error: %s",
  136. ZSTD_getErrorName(retval));
  137. goto err;
  138. }
  139. }
  140. atomic_counter_add(&total_zstd_allocation, result->allocation);
  141. return result;
  142. err:
  143. if (compress) {
  144. ZSTD_freeCStream(result->u.compress_stream);
  145. } else {
  146. ZSTD_freeDStream(result->u.decompress_stream);
  147. }
  148. tor_free(result);
  149. return NULL;
  150. #else // HAVE_ZSTD.
  151. (void)compress;
  152. (void)method;
  153. (void)compression_level;
  154. return NULL;
  155. #endif // HAVE_ZSTD.
  156. }
  157. /** Compress/decompress some bytes using <b>state</b>. Read up to
  158. * *<b>in_len</b> bytes from *<b>in</b>, and write up to *<b>out_len</b> bytes
  159. * to *<b>out</b>, adjusting the values as we go. If <b>finish</b> is true,
  160. * we've reached the end of the input.
  161. *
  162. * Return TOR_COMPRESS_DONE if we've finished the entire
  163. * compression/decompression.
  164. * Return TOR_COMPRESS_OK if we're processed everything from the input.
  165. * Return TOR_COMPRESS_BUFFER_FULL if we're out of space on <b>out</b>.
  166. * Return TOR_COMPRESS_ERROR if the stream is corrupt.
  167. */
  168. tor_compress_output_t
  169. tor_zstd_compress_process(tor_zstd_compress_state_t *state,
  170. char **out, size_t *out_len,
  171. const char **in, size_t *in_len,
  172. int finish)
  173. {
  174. #ifdef HAVE_ZSTD
  175. size_t retval;
  176. tor_assert(state != NULL);
  177. tor_assert(*in_len <= UINT_MAX);
  178. tor_assert(*out_len <= UINT_MAX);
  179. ZSTD_inBuffer input = { *in, *in_len, 0 };
  180. ZSTD_outBuffer output = { *out, *out_len, 0 };
  181. if (state->compress) {
  182. retval = ZSTD_compressStream(state->u.compress_stream,
  183. &output, &input);
  184. } else {
  185. retval = ZSTD_decompressStream(state->u.decompress_stream,
  186. &output, &input);
  187. }
  188. state->input_so_far += input.pos;
  189. state->output_so_far += output.pos;
  190. *out = (char *)output.dst + output.pos;
  191. *out_len = output.size - output.pos;
  192. *in = (char *)input.src + input.pos;
  193. *in_len = input.size - input.pos;
  194. if (! state->compress &&
  195. tor_compress_is_compression_bomb(state->input_so_far,
  196. state->output_so_far)) {
  197. log_warn(LD_DIR, "Possible compression bomb; abandoning stream.");
  198. return TOR_COMPRESS_ERROR;
  199. }
  200. if (ZSTD_isError(retval)) {
  201. log_warn(LD_GENERAL, "Zstandard %s didn't finish: %s.",
  202. state->compress ? "compression" : "decompression",
  203. ZSTD_getErrorName(retval));
  204. return TOR_COMPRESS_ERROR;
  205. }
  206. if (state->compress && !finish) {
  207. retval = ZSTD_flushStream(state->u.compress_stream, &output);
  208. *out = (char *)output.dst + output.pos;
  209. *out_len = output.size - output.pos;
  210. if (ZSTD_isError(retval)) {
  211. log_warn(LD_GENERAL, "Zstandard compression unable to flush: %s.",
  212. ZSTD_getErrorName(retval));
  213. return TOR_COMPRESS_ERROR;
  214. }
  215. if (retval > 0)
  216. return TOR_COMPRESS_BUFFER_FULL;
  217. }
  218. if (state->compress && finish) {
  219. retval = ZSTD_endStream(state->u.compress_stream, &output);
  220. *out = (char *)output.dst + output.pos;
  221. *out_len = output.size - output.pos;
  222. if (ZSTD_isError(retval)) {
  223. log_warn(LD_GENERAL, "Zstandard compression unable to write "
  224. "epilogue: %s.",
  225. ZSTD_getErrorName(retval));
  226. return TOR_COMPRESS_ERROR;
  227. }
  228. // endStream returns the number of bytes that is needed to write the
  229. // epilogue.
  230. if (retval > 0)
  231. return TOR_COMPRESS_BUFFER_FULL;
  232. }
  233. return finish ? TOR_COMPRESS_DONE : TOR_COMPRESS_OK;
  234. #else // HAVE_ZSTD.
  235. (void)state;
  236. (void)out;
  237. (void)out_len;
  238. (void)in;
  239. (void)in_len;
  240. (void)finish;
  241. return TOR_COMPRESS_ERROR;
  242. #endif // HAVE_ZSTD.
  243. }
  244. /** Deallocate <b>state</b>. */
  245. void
  246. tor_zstd_compress_free(tor_zstd_compress_state_t *state)
  247. {
  248. if (state == NULL)
  249. return;
  250. atomic_counter_sub(&total_zstd_allocation, state->allocation);
  251. #ifdef HAVE_ZSTD
  252. if (state->compress) {
  253. ZSTD_freeCStream(state->u.compress_stream);
  254. } else {
  255. ZSTD_freeDStream(state->u.decompress_stream);
  256. }
  257. #endif // HAVE_ZSTD.
  258. tor_free(state);
  259. }
  260. /** Return the approximate number of bytes allocated for <b>state</b>. */
  261. size_t
  262. tor_zstd_compress_state_size(const tor_zstd_compress_state_t *state)
  263. {
  264. tor_assert(state != NULL);
  265. return state->allocation;
  266. }
  267. /** Return the approximate number of bytes allocated for all Zstandard
  268. * states. */
  269. size_t
  270. tor_zstd_get_total_allocation(void)
  271. {
  272. return atomic_counter_get(&total_zstd_allocation);
  273. }
  274. /** Initialize the zstd module */
  275. void
  276. tor_zstd_init(void)
  277. {
  278. atomic_counter_init(&total_zstd_allocation);
  279. }