compress_zlib.c 16 KB

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