torgzip.c 18 KB

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