torgzip.c 14 KB

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