compress_zlib.c 16 KB

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