2 * tinfgzip - tiny gzip decompressor
4 * Copyright (c) 2003 by Joergen Ibsen / Jibz
7 * http://www.ibsensoftware.com/
9 * This software is provided 'as-is', without any express
10 * or implied warranty. In no event will the authors be
11 * held liable for any damages arising from the use of
14 * Permission is granted to anyone to use this software
15 * for any purpose, including commercial applications,
16 * and to alter it and redistribute it freely, subject to
17 * the following restrictions:
19 * 1. The origin of this software must not be
20 * misrepresented; you must not claim that you
21 * wrote the original software. If you use this
22 * software in a product, an acknowledgment in
23 * the product documentation would be appreciated
24 * but is not required.
26 * 2. Altered source versions must be plainly marked
27 * as such, and must not be misrepresented as
28 * being the original software.
30 * 3. This notice may not be removed or altered from
31 * any source distribution.
42 int tinf_gzip_uncompress(void *dest, unsigned int *destLen,
43 const void *source, unsigned int sourceLen)
45 unsigned char *src = (unsigned char *)source;
46 unsigned char *dst = (unsigned char *)dest;
48 unsigned int dlen, crc32;
52 /* -- check format -- */
55 if (src[0] != 0x1f || src[1] != 0x8b) return TINF_DATA_ERROR;
57 /* check method is deflate */
58 if (src[2] != 8) return TINF_DATA_ERROR;
63 /* check that reserved bits are zero */
64 if (flg & 0xe0) return TINF_DATA_ERROR;
66 /* -- find start of compressed data -- */
68 /* skip base header of 10 bytes */
71 /* skip extra data if present */
74 unsigned int xlen = start[1];
75 xlen = 256*xlen + start[0];
79 /* skip file name if present */
80 if (flg & FNAME) { while (*start) ++start; ++start; }
82 /* skip file comment if present */
83 if (flg & FCOMMENT) { while (*start) ++start; ++start; }
85 /* check header crc if present */
88 unsigned int hcrc = start[1];
89 hcrc = 256*hcrc + start[0];
91 if (hcrc != (tinf_crc32(src, start - src) & 0x0000ffff))
92 return TINF_DATA_ERROR;
97 /* -- get decompressed length -- */
99 dlen = src[sourceLen - 1];
100 dlen = 256*dlen + src[sourceLen - 2];
101 dlen = 256*dlen + src[sourceLen - 3];
102 dlen = 256*dlen + src[sourceLen - 4];
104 /* -- get crc32 of decompressed data -- */
106 crc32 = src[sourceLen - 5];
107 crc32 = 256*crc32 + src[sourceLen - 6];
108 crc32 = 256*crc32 + src[sourceLen - 7];
109 crc32 = 256*crc32 + src[sourceLen - 8];
111 /* -- decompress data -- */
113 res = tinf_uncompress(dst, destLen, start, src + sourceLen - start - 8);
115 if (res != TINF_OK) return TINF_DATA_ERROR;
117 if (*destLen != dlen) return TINF_DATA_ERROR;
119 /* -- check CRC32 checksum -- */
121 if (crc32 != tinf_crc32(dst, dlen)) return TINF_DATA_ERROR;