torgzip.c 17 KB

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