compress_zlib.c 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524
  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_zlib.c
  7. * \brief Compression backend for gzip and zlib.
  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 "torgzip.h"
  16. #include "compress_zlib.h"
  17. /* zlib 1.2.4 and 1.2.5 do some "clever" things with macros. Instead of
  18. saying "(defined(FOO) ? FOO : 0)" they like to say "FOO-0", on the theory
  19. that nobody will care if the compile outputs a no-such-identifier warning.
  20. Sorry, but we like -Werror over here, so I guess we need to define these.
  21. I hope that zlib 1.2.6 doesn't break these too.
  22. */
  23. #ifndef _LARGEFILE64_SOURCE
  24. #define _LARGEFILE64_SOURCE 0
  25. #endif
  26. #ifndef _LFS64_LARGEFILE
  27. #define _LFS64_LARGEFILE 0
  28. #endif
  29. #ifndef _FILE_OFFSET_BITS
  30. #define _FILE_OFFSET_BITS 0
  31. #endif
  32. #ifndef off64_t
  33. #define off64_t int64_t
  34. #endif
  35. #include <zlib.h>
  36. #if defined ZLIB_VERNUM && ZLIB_VERNUM < 0x1200
  37. #error "We require zlib version 1.2 or later."
  38. #endif
  39. static size_t tor_zlib_state_size_precalc(int inflate,
  40. int windowbits, int memlevel);
  41. /** Total number of bytes allocated for zlib state */
  42. static size_t total_zlib_allocation = 0;
  43. /** Return the 'bits' value to tell zlib to use <b>method</b>.*/
  44. static inline int
  45. method_bits(compress_method_t method, compression_level_t level)
  46. {
  47. /* Bits+16 means "use gzip" in zlib >= 1.2 */
  48. const int flag = method == GZIP_METHOD ? 16 : 0;
  49. switch (level) {
  50. default:
  51. case HIGH_COMPRESSION: return flag + 15;
  52. case MEDIUM_COMPRESSION: return flag + 13;
  53. case LOW_COMPRESSION: return flag + 11;
  54. }
  55. }
  56. /** Return a string representation of the version of the currently running
  57. * version of zlib. */
  58. const char *
  59. tor_zlib_get_version_str(void)
  60. {
  61. return zlibVersion();
  62. }
  63. /** Return a string representation of the version of the version of zlib
  64. * used at compilation. */
  65. const char *
  66. tor_zlib_get_header_version_str(void)
  67. {
  68. return ZLIB_VERSION;
  69. }
  70. /** Given <b>in_len</b> bytes at <b>in</b>, compress them into a newly
  71. * allocated buffer, using the method described in <b>method</b>. Store the
  72. * compressed string in *<b>out</b>, and its length in *<b>out_len</b>. Return
  73. * 0 on success, -1 on failure.
  74. */
  75. int
  76. tor_zlib_compress(char **out, size_t *out_len,
  77. const char *in, size_t in_len,
  78. compress_method_t method)
  79. {
  80. struct z_stream_s *stream = NULL;
  81. size_t out_size, old_size;
  82. off_t offset;
  83. tor_assert(out);
  84. tor_assert(out_len);
  85. tor_assert(in);
  86. tor_assert(in_len < UINT_MAX);
  87. *out = NULL;
  88. stream = tor_malloc_zero(sizeof(struct z_stream_s));
  89. stream->zalloc = Z_NULL;
  90. stream->zfree = Z_NULL;
  91. stream->opaque = NULL;
  92. stream->next_in = (unsigned char*) in;
  93. stream->avail_in = (unsigned int)in_len;
  94. if (deflateInit2(stream, Z_BEST_COMPRESSION, Z_DEFLATED,
  95. method_bits(method, HIGH_COMPRESSION),
  96. tor_compress_memory_level(HIGH_COMPRESSION),
  97. Z_DEFAULT_STRATEGY) != Z_OK) {
  98. //LCOV_EXCL_START -- we can only provoke failure by giving junk arguments.
  99. log_warn(LD_GENERAL, "Error from deflateInit2: %s",
  100. stream->msg?stream->msg:"<no message>");
  101. goto err;
  102. //LCOV_EXCL_STOP
  103. }
  104. /* Guess 50% compression. */
  105. out_size = in_len / 2;
  106. if (out_size < 1024) out_size = 1024;
  107. *out = tor_malloc(out_size);
  108. stream->next_out = (unsigned char*)*out;
  109. stream->avail_out = (unsigned int)out_size;
  110. while (1) {
  111. switch (deflate(stream, Z_FINISH))
  112. {
  113. case Z_STREAM_END:
  114. goto done;
  115. case Z_OK:
  116. /* In case zlib doesn't work as I think .... */
  117. if (stream->avail_out >= stream->avail_in+16)
  118. break;
  119. case Z_BUF_ERROR:
  120. offset = stream->next_out - ((unsigned char*)*out);
  121. old_size = out_size;
  122. out_size *= 2;
  123. if (out_size < old_size) {
  124. log_warn(LD_GENERAL, "Size overflow in compression.");
  125. goto err;
  126. }
  127. *out = tor_realloc(*out, out_size);
  128. stream->next_out = (unsigned char*)(*out + offset);
  129. if (out_size - offset > UINT_MAX) {
  130. log_warn(LD_BUG, "Ran over unsigned int limit of zlib while "
  131. "uncompressing.");
  132. goto err;
  133. }
  134. stream->avail_out = (unsigned int)(out_size - offset);
  135. break;
  136. default:
  137. log_warn(LD_GENERAL, "Gzip compression didn't finish: %s",
  138. stream->msg ? stream->msg : "<no message>");
  139. goto err;
  140. }
  141. }
  142. done:
  143. *out_len = stream->total_out;
  144. #if defined(OpenBSD)
  145. /* "Hey Rocky! Watch me change an unsigned field to a signed field in a
  146. * third-party API!"
  147. * "Oh, that trick will just make people do unsafe casts to the unsigned
  148. * type in their cross-platform code!"
  149. * "Don't be foolish. I'm _sure_ they'll have the good sense to make sure
  150. * the newly unsigned field isn't negative." */
  151. tor_assert(stream->total_out >= 0);
  152. #endif
  153. if (deflateEnd(stream)!=Z_OK) {
  154. // LCOV_EXCL_START -- unreachable if we handled the zlib structure right
  155. tor_assert_nonfatal_unreached();
  156. log_warn(LD_BUG, "Error freeing gzip structures");
  157. goto err;
  158. // LCOV_EXCL_STOP
  159. }
  160. tor_free(stream);
  161. if (tor_compress_is_compression_bomb(*out_len, in_len)) {
  162. log_warn(LD_BUG, "We compressed something and got an insanely high "
  163. "compression factor; other Tors would think this was a zlib bomb.");
  164. goto err;
  165. }
  166. return 0;
  167. err:
  168. if (stream) {
  169. deflateEnd(stream);
  170. tor_free(stream);
  171. }
  172. tor_free(*out);
  173. return -1;
  174. }
  175. /** Given an Zlib/Gzip compressed string of total length <b>in_len</b> bytes
  176. * at <b>in</b>, uncompress them into a newly allocated buffer. Store the
  177. * uncompressed string in *<b>out</b>, and its length in *<b>out_len</b>.
  178. * Return 0 on success, -1 on failure.
  179. *
  180. * If <b>complete_only</b> is true, we consider a truncated input as a failure;
  181. * otherwise we decompress as much as we can. Warn about truncated or corrupt
  182. * inputs at <b>protocol_warn_level</b>.
  183. */
  184. int
  185. tor_zlib_uncompress(char **out, size_t *out_len,
  186. const char *in, size_t in_len,
  187. compress_method_t method,
  188. int complete_only,
  189. int protocol_warn_level)
  190. {
  191. struct z_stream_s *stream = NULL;
  192. size_t out_size, old_size;
  193. off_t offset;
  194. int r;
  195. tor_assert(out);
  196. tor_assert(out_len);
  197. tor_assert(in);
  198. tor_assert(in_len < UINT_MAX);
  199. *out = NULL;
  200. stream = tor_malloc_zero(sizeof(struct z_stream_s));
  201. stream->zalloc = Z_NULL;
  202. stream->zfree = Z_NULL;
  203. stream->opaque = NULL;
  204. stream->next_in = (unsigned char*) in;
  205. stream->avail_in = (unsigned int)in_len;
  206. if (inflateInit2(stream,
  207. method_bits(method, HIGH_COMPRESSION)) != Z_OK) {
  208. // LCOV_EXCL_START -- can only hit this if we give bad inputs.
  209. log_warn(LD_GENERAL, "Error from inflateInit2: %s",
  210. stream->msg?stream->msg:"<no message>");
  211. goto err;
  212. // LCOV_EXCL_STOP
  213. }
  214. out_size = in_len * 2; /* guess 50% compression. */
  215. if (out_size < 1024) out_size = 1024;
  216. if (out_size >= SIZE_T_CEILING || out_size > UINT_MAX)
  217. goto err;
  218. *out = tor_malloc(out_size);
  219. stream->next_out = (unsigned char*)*out;
  220. stream->avail_out = (unsigned int)out_size;
  221. while (1) {
  222. switch (inflate(stream, complete_only ? Z_FINISH : Z_SYNC_FLUSH))
  223. {
  224. case Z_STREAM_END:
  225. if (stream->avail_in == 0)
  226. goto done;
  227. /* There may be more compressed data here. */
  228. if ((r = inflateEnd(stream)) != Z_OK) {
  229. log_warn(LD_BUG, "Error freeing gzip structures");
  230. goto err;
  231. }
  232. if (inflateInit2(stream,
  233. method_bits(method,HIGH_COMPRESSION)) != Z_OK) {
  234. log_warn(LD_GENERAL, "Error from second inflateInit2: %s",
  235. stream->msg?stream->msg:"<no message>");
  236. goto err;
  237. }
  238. break;
  239. case Z_OK:
  240. if (!complete_only && stream->avail_in == 0)
  241. goto done;
  242. /* In case zlib doesn't work as I think.... */
  243. if (stream->avail_out >= stream->avail_in+16)
  244. break;
  245. case Z_BUF_ERROR:
  246. if (stream->avail_out > 0) {
  247. log_fn(protocol_warn_level, LD_PROTOCOL,
  248. "possible truncated or corrupt zlib data");
  249. goto err;
  250. }
  251. offset = stream->next_out - (unsigned char*)*out;
  252. old_size = out_size;
  253. out_size *= 2;
  254. if (out_size < old_size) {
  255. log_warn(LD_GENERAL, "Size overflow in uncompression.");
  256. goto err;
  257. }
  258. if (tor_compress_is_compression_bomb(in_len, out_size)) {
  259. log_warn(LD_GENERAL, "Input looks like a possible zlib bomb; "
  260. "not proceeding.");
  261. goto err;
  262. }
  263. if (out_size >= SIZE_T_CEILING) {
  264. log_warn(LD_BUG, "Hit SIZE_T_CEILING limit while uncompressing.");
  265. goto err;
  266. }
  267. *out = tor_realloc(*out, out_size);
  268. stream->next_out = (unsigned char*)(*out + offset);
  269. if (out_size - offset > UINT_MAX) {
  270. log_warn(LD_BUG, "Ran over unsigned int limit of zlib while "
  271. "uncompressing.");
  272. goto err;
  273. }
  274. stream->avail_out = (unsigned int)(out_size - offset);
  275. break;
  276. default:
  277. log_warn(LD_GENERAL, "Gzip decompression returned an error: %s",
  278. stream->msg ? stream->msg : "<no message>");
  279. goto err;
  280. }
  281. }
  282. done:
  283. *out_len = stream->next_out - (unsigned char*)*out;
  284. r = inflateEnd(stream);
  285. tor_free(stream);
  286. if (r != Z_OK) {
  287. log_warn(LD_BUG, "Error freeing gzip structures");
  288. goto err;
  289. }
  290. /* NUL-terminate output. */
  291. if (out_size == *out_len)
  292. *out = tor_realloc(*out, out_size + 1);
  293. (*out)[*out_len] = '\0';
  294. return 0;
  295. err:
  296. if (stream) {
  297. inflateEnd(stream);
  298. tor_free(stream);
  299. }
  300. if (*out) {
  301. tor_free(*out);
  302. }
  303. return -1;
  304. }
  305. /** Internal zlib state for an incremental compression/decompression.
  306. * The body of this struct is not exposed. */
  307. struct tor_zlib_compress_state_t {
  308. struct z_stream_s stream; /**< The zlib stream */
  309. int compress; /**< True if we are compressing; false if we are inflating */
  310. /** Number of bytes read so far. Used to detect zlib bombs. */
  311. size_t input_so_far;
  312. /** Number of bytes written so far. Used to detect zlib bombs. */
  313. size_t output_so_far;
  314. /** Approximate number of bytes allocated for this object. */
  315. size_t allocation;
  316. };
  317. /** Return an approximate number of bytes used in RAM to hold a state with
  318. * window bits <b>windowBits</b> and compression level 'memlevel' */
  319. static size_t
  320. tor_zlib_state_size_precalc(int inflate_, int windowbits, int memlevel)
  321. {
  322. windowbits &= 15;
  323. #define A_FEW_KILOBYTES 2048
  324. if (inflate_) {
  325. /* From zconf.h:
  326. "The memory requirements for inflate are (in bytes) 1 << windowBits
  327. that is, 32K for windowBits=15 (default value) plus a few kilobytes
  328. for small objects."
  329. */
  330. return sizeof(tor_zlib_compress_state_t) + sizeof(struct z_stream_s) +
  331. (1 << 15) + A_FEW_KILOBYTES;
  332. } else {
  333. /* Also from zconf.h:
  334. "The memory requirements for deflate are (in bytes):
  335. (1 << (windowBits+2)) + (1 << (memLevel+9))
  336. ... plus a few kilobytes for small objects."
  337. */
  338. return sizeof(tor_zlib_compress_state_t) + sizeof(struct z_stream_s) +
  339. (1 << (windowbits + 2)) + (1 << (memlevel + 9)) + A_FEW_KILOBYTES;
  340. }
  341. #undef A_FEW_KILOBYTES
  342. }
  343. /** Construct and return a tor_zlib_compress_state_t object using
  344. * <b>method</b>. If <b>compress</b>, it's for compression; otherwise it's for
  345. * decompression. */
  346. tor_zlib_compress_state_t *
  347. tor_zlib_compress_new(int compress,
  348. compress_method_t method,
  349. compression_level_t compression_level)
  350. {
  351. tor_zlib_compress_state_t *out;
  352. int bits, memlevel;
  353. if (! compress) {
  354. /* use this setting for decompression, since we might have the
  355. * max number of window bits */
  356. compression_level = HIGH_COMPRESSION;
  357. }
  358. out = tor_malloc_zero(sizeof(tor_zlib_compress_state_t));
  359. out->stream.zalloc = Z_NULL;
  360. out->stream.zfree = Z_NULL;
  361. out->stream.opaque = NULL;
  362. out->compress = compress;
  363. bits = method_bits(method, compression_level);
  364. memlevel = tor_compress_memory_level(compression_level);
  365. if (compress) {
  366. if (deflateInit2(&out->stream, Z_BEST_COMPRESSION, Z_DEFLATED,
  367. bits, memlevel,
  368. Z_DEFAULT_STRATEGY) != Z_OK)
  369. goto err; // LCOV_EXCL_LINE
  370. } else {
  371. if (inflateInit2(&out->stream, bits) != Z_OK)
  372. goto err; // LCOV_EXCL_LINE
  373. }
  374. out->allocation = tor_zlib_state_size_precalc(!compress, bits, memlevel);
  375. total_zlib_allocation += out->allocation;
  376. return out;
  377. err:
  378. tor_free(out);
  379. return NULL;
  380. }
  381. /** Compress/decompress some bytes using <b>state</b>. Read up to
  382. * *<b>in_len</b> bytes from *<b>in</b>, and write up to *<b>out_len</b> bytes
  383. * to *<b>out</b>, adjusting the values as we go. If <b>finish</b> is true,
  384. * we've reached the end of the input.
  385. *
  386. * Return TOR_COMPRESS_DONE if we've finished the entire
  387. * compression/decompression.
  388. * Return TOR_COMPRESS_OK if we're processed everything from the input.
  389. * Return TOR_COMPRESS_BUFFER_FULL if we're out of space on <b>out</b>.
  390. * Return TOR_COMPRESS_ERROR if the stream is corrupt.
  391. */
  392. tor_compress_output_t
  393. tor_zlib_compress_process(tor_zlib_compress_state_t *state,
  394. char **out, size_t *out_len,
  395. const char **in, size_t *in_len,
  396. int finish)
  397. {
  398. int err;
  399. tor_assert(state != NULL);
  400. tor_assert(*in_len <= UINT_MAX);
  401. tor_assert(*out_len <= UINT_MAX);
  402. state->stream.next_in = (unsigned char*) *in;
  403. state->stream.avail_in = (unsigned int)*in_len;
  404. state->stream.next_out = (unsigned char*) *out;
  405. state->stream.avail_out = (unsigned int)*out_len;
  406. if (state->compress) {
  407. err = deflate(&state->stream, finish ? Z_FINISH : Z_NO_FLUSH);
  408. } else {
  409. err = inflate(&state->stream, finish ? Z_FINISH : Z_SYNC_FLUSH);
  410. }
  411. state->input_so_far += state->stream.next_in - ((unsigned char*)*in);
  412. state->output_so_far += state->stream.next_out - ((unsigned char*)*out);
  413. *out = (char*) state->stream.next_out;
  414. *out_len = state->stream.avail_out;
  415. *in = (const char *) state->stream.next_in;
  416. *in_len = state->stream.avail_in;
  417. if (! state->compress &&
  418. tor_compress_is_compression_bomb(state->input_so_far,
  419. state->output_so_far)) {
  420. log_warn(LD_DIR, "Possible zlib bomb; abandoning stream.");
  421. return TOR_COMPRESS_ERROR;
  422. }
  423. switch (err)
  424. {
  425. case Z_STREAM_END:
  426. return TOR_COMPRESS_DONE;
  427. case Z_BUF_ERROR:
  428. if (state->stream.avail_in == 0 && !finish)
  429. return TOR_COMPRESS_OK;
  430. return TOR_COMPRESS_BUFFER_FULL;
  431. case Z_OK:
  432. if (state->stream.avail_out == 0 || finish)
  433. return TOR_COMPRESS_BUFFER_FULL;
  434. return TOR_COMPRESS_OK;
  435. default:
  436. log_warn(LD_GENERAL, "Gzip returned an error: %s",
  437. state->stream.msg ? state->stream.msg : "<no message>");
  438. return TOR_COMPRESS_ERROR;
  439. }
  440. }
  441. /** Deallocate <b>state</b>. */
  442. void
  443. tor_zlib_compress_free(tor_zlib_compress_state_t *state)
  444. {
  445. if (state == NULL)
  446. return;
  447. total_zlib_allocation -= state->allocation;
  448. if (state->compress)
  449. deflateEnd(&state->stream);
  450. else
  451. inflateEnd(&state->stream);
  452. tor_free(state);
  453. }
  454. /** Return the approximate number of bytes allocated for <b>state</b>. */
  455. size_t
  456. tor_zlib_compress_state_size(const tor_zlib_compress_state_t *state)
  457. {
  458. tor_assert(state != NULL);
  459. return state->allocation;
  460. }
  461. /** Return the approximate number of bytes allocated for all zlib states. */
  462. size_t
  463. tor_zlib_get_total_allocation(void)
  464. {
  465. return total_zlib_allocation;
  466. }