torgzip.c 15 KB

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