torgzip.c 15 KB

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