torgzip.c 13 KB

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