torgzip.c 15 KB

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