1/*
2 * Most parts of this file are not covered by:
3 * ----------------------------------------------------------------------------
4 * "THE BEER-WARE LICENSE" (Revision 42):
5 * <phk@FreeBSD.org> wrote this file.  As long as you retain this notice you
6 * can do whatever you want with this stuff. If we meet some day, and you think
7 * this stuff is worth it, you can buy me a beer in return.   Poul-Henning Kamp
8 * ----------------------------------------------------------------------------
9 */
10
11#include <sys/cdefs.h>
12__FBSDID("$FreeBSD: stable/11/sys/kern/subr_inflate.c 344379 2019-02-20 19:32:02Z kevans $");
13
14#include <sys/param.h>
15#include <sys/inflate.h>
16#ifdef _KERNEL
17#include <sys/systm.h>
18#include <sys/kernel.h>
19#endif
20#include <sys/malloc.h>
21
22#ifdef _KERNEL
23static MALLOC_DEFINE(M_GZIP, "gzip_trees", "Gzip trees");
24#endif
25
26/* needed to make inflate() work */
27#define	uch u_char
28#define	ush u_short
29#define	ulg u_long
30
31/* Stuff to make inflate() work */
32#ifdef _KERNEL
33#define memzero(dest,len)      bzero(dest,len)
34#endif
35#define NOMEMCPY
36#ifdef _KERNEL
37#define FPRINTF printf
38#else
39extern void putstr (char *);
40#define FPRINTF putstr
41#endif
42
43#define FLUSH(x,y) {						\
44	int foo = (*x->gz_output)(x->gz_private,x->gz_slide,y);	\
45	if (foo) 						\
46		return foo;					\
47	}
48
49static const int qflag = 0;
50
51#ifndef _KERNEL /* want to use this file in kzip also */
52extern unsigned char *kzipmalloc (int);
53extern void kzipfree (void*);
54#define malloc(x, y, z) kzipmalloc((x))
55#define free(x, y) kzipfree((x))
56#endif
57
58/*
59 * This came from unzip-5.12.  I have changed it the flow to pass
60 * a structure pointer around, thus hopefully making it re-entrant.
61 * Poul-Henning
62 */
63
64/* inflate.c -- put in the public domain by Mark Adler
65   version c14o, 23 August 1994 */
66
67/* You can do whatever you like with this source file, though I would
68   prefer that if you modify it and redistribute it that you include
69   comments to that effect with your name and the date.  Thank you.
70
71   History:
72   vers    date          who           what
73   ----  ---------  --------------  ------------------------------------
74    a    ~~ Feb 92  M. Adler        used full (large, one-step) lookup table
75    b1   21 Mar 92  M. Adler        first version with partial lookup tables
76    b2   21 Mar 92  M. Adler        fixed bug in fixed-code blocks
77    b3   22 Mar 92  M. Adler        sped up match copies, cleaned up some
78    b4   25 Mar 92  M. Adler        added prototypes; removed window[] (now
79                                    is the responsibility of unzip.h--also
80                                    changed name to slide[]), so needs diffs
81                                    for unzip.c and unzip.h (this allows
82                                    compiling in the small model on MSDOS);
83                                    fixed cast of q in huft_build();
84    b5   26 Mar 92  M. Adler        got rid of unintended macro recursion.
85    b6   27 Mar 92  M. Adler        got rid of nextbyte() routine.  fixed
86                                    bug in inflate_fixed().
87    c1   30 Mar 92  M. Adler        removed lbits, dbits environment variables.
88                                    changed BMAX to 16 for explode.  Removed
89                                    OUTB usage, and replaced it with flush()--
90                                    this was a 20% speed improvement!  Added
91                                    an explode.c (to replace unimplod.c) that
92                                    uses the huft routines here.  Removed
93                                    register union.
94    c2    4 Apr 92  M. Adler        fixed bug for file sizes a multiple of 32k.
95    c3   10 Apr 92  M. Adler        reduced memory of code tables made by
96                                    huft_build significantly (factor of two to
97                                    three).
98    c4   15 Apr 92  M. Adler        added NOMEMCPY do kill use of memcpy().
99                                    worked around a Turbo C optimization bug.
100    c5   21 Apr 92  M. Adler        added the GZ_WSIZE #define to allow reducing
101                                    the 32K window size for specialized
102                                    applications.
103    c6   31 May 92  M. Adler        added some typecasts to eliminate warnings
104    c7   27 Jun 92  G. Roelofs      added some more typecasts (444:  MSC bug).
105    c8    5 Oct 92  J-l. Gailly     added ifdef'd code to deal with PKZIP bug.
106    c9    9 Oct 92  M. Adler        removed a memory error message (~line 416).
107    c10  17 Oct 92  G. Roelofs      changed ULONG/UWORD/byte to ulg/ush/uch,
108                                    removed old inflate, renamed inflate_entry
109                                    to inflate, added Mark's fix to a comment.
110   c10.5 14 Dec 92  M. Adler        fix up error messages for incomplete trees.
111    c11   2 Jan 93  M. Adler        fixed bug in detection of incomplete
112                                    tables, and removed assumption that EOB is
113                                    the longest code (bad assumption).
114    c12   3 Jan 93  M. Adler        make tables for fixed blocks only once.
115    c13   5 Jan 93  M. Adler        allow all zero length codes (pkzip 2.04c
116                                    outputs one zero length code for an empty
117                                    distance tree).
118    c14  12 Mar 93  M. Adler        made inflate.c standalone with the
119                                    introduction of inflate.h.
120   c14b  16 Jul 93  G. Roelofs      added (unsigned) typecast to w at 470.
121   c14c  19 Jul 93  J. Bush         changed v[N_MAX], l[288], ll[28x+3x] arrays
122                                    to static for Amiga.
123   c14d  13 Aug 93  J-l. Gailly     de-complicatified Mark's c[*p++]++ thing.
124   c14e   8 Oct 93  G. Roelofs      changed memset() to memzero().
125   c14f  22 Oct 93  G. Roelofs      renamed quietflg to qflag; made Trace()
126                                    conditional; added inflate_free().
127   c14g  28 Oct 93  G. Roelofs      changed l/(lx+1) macro to pointer (Cray bug)
128   c14h   7 Dec 93  C. Ghisler      huft_build() optimizations.
129   c14i   9 Jan 94  A. Verheijen    set fixed_t{d,l} to NULL after freeing;
130                    G. Roelofs      check NEXTBYTE macro for GZ_EOF.
131   c14j  23 Jan 94  G. Roelofs      removed Ghisler "optimizations"; ifdef'd
132                                    GZ_EOF check.
133   c14k  27 Feb 94  G. Roelofs      added some typecasts to avoid warnings.
134   c14l   9 Apr 94  G. Roelofs      fixed split comments on preprocessor lines
135                                    to avoid bug in Encore compiler.
136   c14m   7 Jul 94  P. Kienitz      modified to allow assembler version of
137                                    inflate_codes() (define ASM_INFLATECODES)
138   c14n  22 Jul 94  G. Roelofs      changed fprintf to FPRINTF for DLL versions
139   c14o  23 Aug 94  C. Spieler      added a newline to a debug statement;
140                    G. Roelofs      added another typecast to avoid MSC warning
141 */
142
143
144/*
145   Inflate deflated (PKZIP's method 8 compressed) data.  The compression
146   method searches for as much of the current string of bytes (up to a
147   length of 258) in the previous 32K bytes.  If it doesn't find any
148   matches (of at least length 3), it codes the next byte.  Otherwise, it
149   codes the length of the matched string and its distance backwards from
150   the current position.  There is a single Huffman code that codes both
151   single bytes (called "literals") and match lengths.  A second Huffman
152   code codes the distance information, which follows a length code.  Each
153   length or distance code actually represents a base value and a number
154   of "extra" (sometimes zero) bits to get to add to the base value.  At
155   the end of each deflated block is a special end-of-block (EOB) literal/
156   length code.  The decoding process is basically: get a literal/length
157   code; if EOB then done; if a literal, emit the decoded byte; if a
158   length then get the distance and emit the referred-to bytes from the
159   sliding window of previously emitted data.
160
161   There are (currently) three kinds of inflate blocks: stored, fixed, and
162   dynamic.  The compressor outputs a chunk of data at a time and decides
163   which method to use on a chunk-by-chunk basis.  A chunk might typically
164   be 32K to 64K, uncompressed.  If the chunk is uncompressible, then the
165   "stored" method is used.  In this case, the bytes are simply stored as
166   is, eight bits per byte, with none of the above coding.  The bytes are
167   preceded by a count, since there is no longer an EOB code.
168
169   If the data is compressible, then either the fixed or dynamic methods
170   are used.  In the dynamic method, the compressed data is preceded by
171   an encoding of the literal/length and distance Huffman codes that are
172   to be used to decode this block.  The representation is itself Huffman
173   coded, and so is preceded by a description of that code.  These code
174   descriptions take up a little space, and so for small blocks, there is
175   a predefined set of codes, called the fixed codes.  The fixed method is
176   used if the block ends up smaller that way (usually for quite small
177   chunks); otherwise the dynamic method is used.  In the latter case, the
178   codes are customized to the probabilities in the current block and so
179   can code it much better than the pre-determined fixed codes can.
180
181   The Huffman codes themselves are decoded using a mutli-level table
182   lookup, in order to maximize the speed of decoding plus the speed of
183   building the decoding tables.  See the comments below that precede the
184   lbits and dbits tuning parameters.
185 */
186
187
188/*
189   Notes beyond the 1.93a appnote.txt:
190
191   1. Distance pointers never point before the beginning of the output
192      stream.
193   2. Distance pointers can point back across blocks, up to 32k away.
194   3. There is an implied maximum of 7 bits for the bit length table and
195      15 bits for the actual data.
196   4. If only one code exists, then it is encoded using one bit.  (Zero
197      would be more efficient, but perhaps a little confusing.)  If two
198      codes exist, they are coded using one bit each (0 and 1).
199   5. There is no way of sending zero distance codes--a dummy must be
200      sent if there are none.  (History: a pre 2.0 version of PKZIP would
201      store blocks with no distance codes, but this was discovered to be
202      too harsh a criterion.)  Valid only for 1.93a.  2.04c does allow
203      zero distance codes, which is sent as one code of zero bits in
204      length.
205   6. There are up to 286 literal/length codes.  Code 256 represents the
206      end-of-block.  Note however that the static length tree defines
207      288 codes just to fill out the Huffman codes.  Codes 286 and 287
208      cannot be used though, since there is no length base or extra bits
209      defined for them.  Similarly, there are up to 30 distance codes.
210      However, static trees define 32 codes (all 5 bits) to fill out the
211      Huffman codes, but the last two had better not show up in the data.
212   7. Unzip can check dynamic Huffman blocks for complete code sets.
213      The exception is that a single code would not be complete (see #4).
214   8. The five bits following the block type is really the number of
215      literal codes sent minus 257.
216   9. Length codes 8,16,16 are interpreted as 13 length codes of 8 bits
217      (1+6+6).  Therefore, to output three times the length, you output
218      three codes (1+1+1), whereas to output four times the same length,
219      you only need two codes (1+3).  Hmm.
220  10. In the tree reconstruction algorithm, Code = Code + Increment
221      only if BitLength(i) is not zero.  (Pretty obvious.)
222  11. Correction: 4 Bits: # of Bit Length codes - 4     (4 - 19)
223  12. Note: length code 284 can represent 227-258, but length code 285
224      really is 258.  The last length deserves its own, short code
225      since it gets used a lot in very redundant files.  The length
226      258 is special since 258 - 3 (the min match length) is 255.
227  13. The literal/length and distance code bit lengths are read as a
228      single stream of lengths.  It is possible (and advantageous) for
229      a repeat code (16, 17, or 18) to go across the boundary between
230      the two sets of lengths.
231 */
232
233
234#define PKZIP_BUG_WORKAROUND	/* PKZIP 1.93a problem--live with it */
235
236/*
237    inflate.h must supply the uch slide[GZ_WSIZE] array and the NEXTBYTE,
238    FLUSH() and memzero macros.  If the window size is not 32K, it
239    should also define GZ_WSIZE.  If INFMOD is defined, it can include
240    compiled functions to support the NEXTBYTE and/or FLUSH() macros.
241    There are defaults for NEXTBYTE and FLUSH() below for use as
242    examples of what those functions need to do.  Normally, you would
243    also want FLUSH() to compute a crc on the data.  inflate.h also
244    needs to provide these typedefs:
245
246        typedef unsigned char uch;
247        typedef unsigned short ush;
248        typedef unsigned long ulg;
249
250    This module uses the external functions malloc() and free() (and
251    probably memset() or bzero() in the memzero() macro).  Their
252    prototypes are normally found in <string.h> and <stdlib.h>.
253 */
254#define INFMOD			/* tell inflate.h to include code to be
255				 * compiled */
256
257/* Huffman code lookup table entry--this entry is four bytes for machines
258   that have 16-bit pointers (e.g. PC's in the small or medium model).
259   Valid extra bits are 0..13.  e == 15 is EOB (end of block), e == 16
260   means that v is a literal, 16 < e < 32 means that v is a pointer to
261   the next table, which codes e - 16 bits, and lastly e == 99 indicates
262   an unused code.  If a code with e == 99 is looked up, this implies an
263   error in the data. */
264struct huft {
265	uch             e;	/* number of extra bits or operation */
266	uch             b;	/* number of bits in this code or subcode */
267	union {
268		ush             n;	/* literal, length base, or distance
269					 * base */
270		struct huft    *t;	/* pointer to next level of table */
271	}               v;
272};
273
274
275/* Function prototypes */
276static int huft_build(struct inflate *, unsigned *, unsigned, unsigned, const ush *, const ush *, struct huft **, int *);
277static int huft_free(struct inflate *, struct huft *);
278static int inflate_codes(struct inflate *, struct huft *, struct huft *, int, int);
279static int inflate_stored(struct inflate *);
280static int xinflate(struct inflate *);
281static int inflate_fixed(struct inflate *);
282static int inflate_dynamic(struct inflate *);
283static int inflate_block(struct inflate *, int *);
284
285/* The inflate algorithm uses a sliding 32K byte window on the uncompressed
286   stream to find repeated byte strings.  This is implemented here as a
287   circular buffer.  The index is updated simply by incrementing and then
288   and'ing with 0x7fff (32K-1). */
289/* It is left to other modules to supply the 32K area.  It is assumed
290   to be usable as if it were declared "uch slide[32768];" or as just
291   "uch *slide;" and then malloc'ed in the latter case.  The definition
292   must be in unzip.h, included above. */
293
294
295/* Tables for deflate from PKZIP's appnote.txt. */
296
297/* Order of the bit length code lengths */
298static const unsigned border[] = {
299	16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15};
300
301static const ush cplens[] = {	/* Copy lengths for literal codes 257..285 */
302	3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,
303	35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0};
304 /* note: see note #13 above about the 258 in this list. */
305
306static const ush cplext[] = {	/* Extra bits for literal codes 257..285 */
307	0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2,
308	3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0, 99, 99};	/* 99==invalid */
309
310static const ush cpdist[] = {	/* Copy offsets for distance codes 0..29 */
311	1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,
312	257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,
313	8193, 12289, 16385, 24577};
314
315static const ush cpdext[] = {	/* Extra bits for distance codes */
316	0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6,
317	7, 7, 8, 8, 9, 9, 10, 10, 11, 11,
318	12, 12, 13, 13};
319
320/* And'ing with mask[n] masks the lower n bits */
321static const ush mask[] = {
322	0x0000,
323	0x0001, 0x0003, 0x0007, 0x000f, 0x001f, 0x003f, 0x007f, 0x00ff,
324	0x01ff, 0x03ff, 0x07ff, 0x0fff, 0x1fff, 0x3fff, 0x7fff, 0xffff
325};
326
327
328/* Macros for inflate() bit peeking and grabbing.
329   The usage is:
330
331        NEEDBITS(glbl,j)
332        x = b & mask[j];
333        DUMPBITS(j)
334
335   where NEEDBITS makes sure that b has at least j bits in it, and
336   DUMPBITS removes the bits from b.  The macros use the variable k
337   for the number of bits in b.  Normally, b and k are register
338   variables for speed, and are initialized at the beginning of a
339   routine that uses these macros from a global bit buffer and count.
340
341   In order to not ask for more bits than there are in the compressed
342   stream, the Huffman tables are constructed to only ask for just
343   enough bits to make up the end-of-block code (value 256).  Then no
344   bytes need to be "returned" to the buffer at the end of the last
345   block.  See the huft_build() routine.
346 */
347
348/*
349 * The following 2 were global variables.
350 * They are now fields of the inflate structure.
351 */
352
353#define NEEDBITS(glbl,n) {						\
354		while(k<(n)) {						\
355			int c=(*glbl->gz_input)(glbl->gz_private);	\
356			if(c==GZ_EOF)					\
357				return 1; 				\
358			b|=((ulg)c)<<k;					\
359			k+=8;						\
360		}							\
361	}
362
363#define DUMPBITS(n) {b>>=(n);k-=(n);}
364
365/*
366   Huffman code decoding is performed using a multi-level table lookup.
367   The fastest way to decode is to simply build a lookup table whose
368   size is determined by the longest code.  However, the time it takes
369   to build this table can also be a factor if the data being decoded
370   is not very long.  The most common codes are necessarily the
371   shortest codes, so those codes dominate the decoding time, and hence
372   the speed.  The idea is you can have a shorter table that decodes the
373   shorter, more probable codes, and then point to subsidiary tables for
374   the longer codes.  The time it costs to decode the longer codes is
375   then traded against the time it takes to make longer tables.
376
377   This results of this trade are in the variables lbits and dbits
378   below.  lbits is the number of bits the first level table for literal/
379   length codes can decode in one step, and dbits is the same thing for
380   the distance codes.  Subsequent tables are also less than or equal to
381   those sizes.  These values may be adjusted either when all of the
382   codes are shorter than that, in which case the longest code length in
383   bits is used, or when the shortest code is *longer* than the requested
384   table size, in which case the length of the shortest code in bits is
385   used.
386
387   There are two different values for the two tables, since they code a
388   different number of possibilities each.  The literal/length table
389   codes 286 possible values, or in a flat code, a little over eight
390   bits.  The distance table codes 30 possible values, or a little less
391   than five bits, flat.  The optimum values for speed end up being
392   about one bit more than those, so lbits is 8+1 and dbits is 5+1.
393   The optimum values may differ though from machine to machine, and
394   possibly even between compilers.  Your mileage may vary.
395 */
396
397static const int lbits = 9;	/* bits in base literal/length lookup table */
398static const int dbits = 6;	/* bits in base distance lookup table */
399
400
401/* If BMAX needs to be larger than 16, then h and x[] should be ulg. */
402#define BMAX 16			/* maximum bit length of any code (16 for
403				 * explode) */
404#define N_MAX 288		/* maximum number of codes in any set */
405
406/* Given a list of code lengths and a maximum table size, make a set of
407   tables to decode that set of codes.  Return zero on success, one if
408   the given code set is incomplete (the tables are still built in this
409   case), two if the input is invalid (all zero length codes or an
410   oversubscribed set of lengths), and three if not enough memory.
411   The code with value 256 is special, and the tables are constructed
412   so that no bits beyond that code are fetched when that code is
413   decoded. */
414/*
415 * Arguments:
416 * b	code lengths in bits (all assumed <= BMAX)
417 * n	number of codes (assumed <= N_MAX)
418 * s	number of simple-valued codes (0..s-1)
419 * d	list of base values for non-simple codes
420 * e	list of extra bits for non-simple codes
421 * t	result: starting table
422 * m	maximum lookup bits, returns actual
423 */
424static int
425huft_build(struct inflate *glbl, unsigned *b, unsigned n, unsigned s,
426    const ush *d, const ush *e, struct huft **t, int *m)
427{
428	unsigned        a;	/* counter for codes of length k */
429	unsigned        c[BMAX + 1];	/* bit length count table */
430	unsigned        el;	/* length of EOB code (value 256) */
431	unsigned        f;	/* i repeats in table every f entries */
432	int             g;	/* maximum code length */
433	int             h;	/* table level */
434	unsigned i;		/* counter, current code */
435	unsigned j;		/* counter */
436	int    k;		/* number of bits in current code */
437	int             lx[BMAX + 1];	/* memory for l[-1..BMAX-1] */
438	int            *l = lx + 1;	/* stack of bits per table */
439	unsigned *p;		/* pointer into c[], b[], or v[] */
440	struct huft *q;		/* points to current table */
441	struct huft     r;	/* table entry for structure assignment */
442	struct huft    *u[BMAX];/* table stack */
443	unsigned        v[N_MAX];	/* values in order of bit length */
444	int    w;		/* bits before this table == (l * h) */
445	unsigned        x[BMAX + 1];	/* bit offsets, then code stack */
446	unsigned       *xp;	/* pointer into x */
447	int             y;	/* number of dummy codes added */
448	unsigned        z;	/* number of entries in current table */
449
450	/* Generate counts for each bit length */
451	el = n > 256 ? b[256] : BMAX;	/* set length of EOB code, if any */
452#ifdef _KERNEL
453	memzero((char *) c, sizeof(c));
454#else
455	for (i = 0; i < BMAX+1; i++)
456		c [i] = 0;
457#endif
458	p = b;
459	i = n;
460	do {
461		c[*p]++;
462		p++;		/* assume all entries <= BMAX */
463	} while (--i);
464	if (c[0] == n) {	/* null input--all zero length codes */
465		*t = (struct huft *) NULL;
466		*m = 0;
467		return 0;
468	}
469	/* Find minimum and maximum length, bound *m by those */
470	for (j = 1; j <= BMAX; j++)
471		if (c[j])
472			break;
473	k = j;			/* minimum code length */
474	if ((unsigned) *m < j)
475		*m = j;
476	for (i = BMAX; i; i--)
477		if (c[i])
478			break;
479	g = i;			/* maximum code length */
480	if ((unsigned) *m > i)
481		*m = i;
482
483	/* Adjust last length count to fill out codes, if needed */
484	for (y = 1 << j; j < i; j++, y <<= 1)
485		if ((y -= c[j]) < 0)
486			return 2;	/* bad input: more codes than bits */
487	if ((y -= c[i]) < 0)
488		return 2;
489	c[i] += y;
490
491	/* Generate starting offsets into the value table for each length */
492	x[1] = j = 0;
493	p = c + 1;
494	xp = x + 2;
495	while (--i) {		/* note that i == g from above */
496		*xp++ = (j += *p++);
497	}
498
499	/* Make a table of values in order of bit lengths */
500	p = b;
501	i = 0;
502	do {
503		if ((j = *p++) != 0)
504			v[x[j]++] = i;
505	} while (++i < n);
506
507	/* Generate the Huffman codes and for each, make the table entries */
508	x[0] = i = 0;		/* first Huffman code is zero */
509	p = v;			/* grab values in bit order */
510	h = -1;			/* no tables yet--level -1 */
511	w = l[-1] = 0;		/* no bits decoded yet */
512	u[0] = (struct huft *) NULL;	/* just to keep compilers happy */
513	q = (struct huft *) NULL;	/* ditto */
514	z = 0;			/* ditto */
515
516	/* go through the bit lengths (k already is bits in shortest code) */
517	for (; k <= g; k++) {
518		a = c[k];
519		while (a--) {
520			/*
521			 * here i is the Huffman code of length k bits for
522			 * value *p
523			 */
524			/* make tables up to required level */
525			while (k > w + l[h]) {
526				w += l[h++];	/* add bits already decoded */
527
528				/*
529				 * compute minimum size table less than or
530				 * equal to *m bits
531				 */
532				z = (z = g - w) > (unsigned) *m ? *m : z;	/* upper limit */
533				if ((f = 1 << (j = k - w)) > a + 1) {	/* try a k-w bit table *//* t
534									 * oo few codes for k-w
535									 * bit table */
536					f -= a + 1;	/* deduct codes from
537							 * patterns left */
538					xp = c + k;
539					while (++j < z) {	/* try smaller tables up
540								 * to z bits */
541						if ((f <<= 1) <= *++xp)
542							break;	/* enough codes to use
543								 * up j bits */
544						f -= *xp;	/* else deduct codes
545								 * from patterns */
546					}
547				}
548				if ((unsigned) w + j > el && (unsigned) w < el)
549					j = el - w;	/* make EOB code end at
550							 * table */
551				z = 1 << j;	/* table entries for j-bit
552						 * table */
553				l[h] = j;	/* set table size in stack */
554
555				/* allocate and link in new table */
556				if ((q = (struct huft *) malloc((z + 1) * sizeof(struct huft), M_GZIP, M_WAITOK)) ==
557				    (struct huft *) NULL) {
558					if (h)
559						huft_free(glbl, u[0]);
560					return 3;	/* not enough memory */
561				}
562				glbl->gz_hufts += z + 1;	/* track memory usage */
563				*t = q + 1;	/* link to list for
564						 * huft_free() */
565				*(t = &(q->v.t)) = (struct huft *) NULL;
566				u[h] = ++q;	/* table starts after link */
567
568				/* connect to last table, if there is one */
569				if (h) {
570					x[h] = i;	/* save pattern for
571							 * backing up */
572					r.b = (uch) l[h - 1];	/* bits to dump before
573								 * this table */
574					r.e = (uch) (16 + j);	/* bits in this table */
575					r.v.t = q;	/* pointer to this table */
576					j = (i & ((1 << w) - 1)) >> (w - l[h - 1]);
577					u[h - 1][j] = r;	/* connect to last table */
578				}
579			}
580
581			/* set up table entry in r */
582			r.b = (uch) (k - w);
583			if (p >= v + n)
584				r.e = 99;	/* out of values--invalid
585						 * code */
586			else if (*p < s) {
587				r.e = (uch) (*p < 256 ? 16 : 15);	/* 256 is end-of-block
588									 * code */
589				r.v.n = *p++;	/* simple code is just the
590						 * value */
591			} else {
592				r.e = (uch) e[*p - s];	/* non-simple--look up
593							 * in lists */
594				r.v.n = d[*p++ - s];
595			}
596
597			/* fill code-like entries with r */
598			f = 1 << (k - w);
599			for (j = i >> w; j < z; j += f)
600				q[j] = r;
601
602			/* backwards increment the k-bit code i */
603			for (j = 1 << (k - 1); i & j; j >>= 1)
604				i ^= j;
605			i ^= j;
606
607			/* backup over finished tables */
608			while ((i & ((1 << w) - 1)) != x[h])
609				w -= l[--h];	/* don't need to update q */
610		}
611	}
612
613	/* return actual size of base table */
614	*m = l[0];
615
616	/* Return true (1) if we were given an incomplete table */
617	return y != 0 && g != 1;
618}
619
620/*
621 * Arguments:
622 * t	table to free
623 */
624static int
625huft_free(struct inflate *glbl, struct huft *t)
626/* Free the malloc'ed tables built by huft_build(), which makes a linked
627   list of the tables it made, with the links in a dummy first entry of
628   each table. */
629{
630	struct huft *p, *q;
631
632	/* Go through linked list, freeing from the malloced (t[-1]) address. */
633	p = t;
634	while (p != (struct huft *) NULL) {
635		q = (--p)->v.t;
636		free(p, M_GZIP);
637		p = q;
638	}
639	return 0;
640}
641
642/* inflate (decompress) the codes in a deflated (compressed) block.
643   Return an error code or zero if it all goes ok. */
644/*
645 * Arguments:
646 * tl, td	literal/length and distance decoder tables
647 * bl, bd	number of bits decoded by tl[] and td[]
648 */
649static int
650inflate_codes(struct inflate *glbl, struct huft *tl, struct huft*td, int bl,
651    int bd)
652{
653	unsigned e;		/* table entry flag/number of extra bits */
654	unsigned        n, d;	/* length and index for copy */
655	unsigned        w;	/* current window position */
656	struct huft    *t;	/* pointer to table entry */
657	unsigned        ml, md;	/* masks for bl and bd bits */
658	ulg    b;		/* bit buffer */
659	unsigned k;		/* number of bits in bit buffer */
660
661	/* make local copies of globals */
662	b = glbl->gz_bb;			/* initialize bit buffer */
663	k = glbl->gz_bk;
664	w = glbl->gz_wp;	/* initialize window position */
665
666	/* inflate the coded data */
667	ml = mask[bl];		/* precompute masks for speed */
668	md = mask[bd];
669	while (1) {		/* do until end of block */
670		NEEDBITS(glbl, (unsigned) bl)
671			if ((e = (t = tl + ((unsigned) b & ml))->e) > 16)
672			do {
673				if (e == 99)
674					return 1;
675				DUMPBITS(t->b)
676					e -= 16;
677				NEEDBITS(glbl, e)
678			} while ((e = (t = t->v.t + ((unsigned) b & mask[e]))->e) > 16);
679		DUMPBITS(t->b)
680			if (e == 16) {	/* then it's a literal */
681			glbl->gz_slide[w++] = (uch) t->v.n;
682			if (w == GZ_WSIZE) {
683				FLUSH(glbl, w);
684				w = 0;
685			}
686		} else {	/* it's an EOB or a length */
687			/* exit if end of block */
688			if (e == 15)
689				break;
690
691			/* get length of block to copy */
692			NEEDBITS(glbl, e)
693				n = t->v.n + ((unsigned) b & mask[e]);
694			DUMPBITS(e);
695
696			/* decode distance of block to copy */
697			NEEDBITS(glbl, (unsigned) bd)
698				if ((e = (t = td + ((unsigned) b & md))->e) > 16)
699				do {
700					if (e == 99)
701						return 1;
702					DUMPBITS(t->b)
703						e -= 16;
704					NEEDBITS(glbl, e)
705				} while ((e = (t = t->v.t + ((unsigned) b & mask[e]))->e) > 16);
706			DUMPBITS(t->b)
707				NEEDBITS(glbl, e)
708				d = w - t->v.n - ((unsigned) b & mask[e]);
709			DUMPBITS(e)
710			/* do the copy */
711				do {
712				n -= (e = (e = GZ_WSIZE - ((d &= GZ_WSIZE - 1) > w ? d : w)) > n ? n : e);
713#ifndef NOMEMCPY
714				if (w - d >= e) {	/* (this test assumes
715							 * unsigned comparison) */
716					memcpy(glbl->gz_slide + w, glbl->gz_slide + d, e);
717					w += e;
718					d += e;
719				} else	/* do it slow to avoid memcpy()
720					 * overlap */
721#endif				/* !NOMEMCPY */
722					do {
723						glbl->gz_slide[w++] = glbl->gz_slide[d++];
724					} while (--e);
725				if (w == GZ_WSIZE) {
726					FLUSH(glbl, w);
727					w = 0;
728				}
729			} while (n);
730		}
731	}
732
733	/* restore the globals from the locals */
734	glbl->gz_wp = w;	/* restore global window pointer */
735	glbl->gz_bb = b;			/* restore global bit buffer */
736	glbl->gz_bk = k;
737
738	/* done */
739	return 0;
740}
741
742/* "decompress" an inflated type 0 (stored) block. */
743static int
744inflate_stored(struct inflate *glbl)
745{
746	unsigned        n;	/* number of bytes in block */
747	unsigned        w;	/* current window position */
748	ulg    b;		/* bit buffer */
749	unsigned k;		/* number of bits in bit buffer */
750
751	/* make local copies of globals */
752	b = glbl->gz_bb;			/* initialize bit buffer */
753	k = glbl->gz_bk;
754	w = glbl->gz_wp;	/* initialize window position */
755
756	/* go to byte boundary */
757	n = k & 7;
758	DUMPBITS(n);
759
760	/* get the length and its complement */
761	NEEDBITS(glbl, 16)
762		n = ((unsigned) b & 0xffff);
763	DUMPBITS(16)
764		NEEDBITS(glbl, 16)
765		if (n != (unsigned) ((~b) & 0xffff))
766		return 1;	/* error in compressed data */
767	DUMPBITS(16)
768	/* read and output the compressed data */
769		while (n--) {
770		NEEDBITS(glbl, 8)
771			glbl->gz_slide[w++] = (uch) b;
772		if (w == GZ_WSIZE) {
773			FLUSH(glbl, w);
774			w = 0;
775		}
776		DUMPBITS(8)
777	}
778
779	/* restore the globals from the locals */
780	glbl->gz_wp = w;	/* restore global window pointer */
781	glbl->gz_bb = b;			/* restore global bit buffer */
782	glbl->gz_bk = k;
783	return 0;
784}
785
786/* decompress an inflated type 1 (fixed Huffman codes) block.  We should
787   either replace this with a custom decoder, or at least precompute the
788   Huffman tables. */
789static int
790inflate_fixed(struct inflate *glbl)
791{
792	/* if first time, set up tables for fixed blocks */
793	if (glbl->gz_fixed_tl == (struct huft *) NULL) {
794		int             i;	/* temporary variable */
795		static unsigned l[288];	/* length list for huft_build */
796
797		/* literal table */
798		for (i = 0; i < 144; i++)
799			l[i] = 8;
800		for (; i < 256; i++)
801			l[i] = 9;
802		for (; i < 280; i++)
803			l[i] = 7;
804		for (; i < 288; i++)	/* make a complete, but wrong code
805					 * set */
806			l[i] = 8;
807		glbl->gz_fixed_bl = 7;
808		if ((i = huft_build(glbl, l, 288, 257, cplens, cplext,
809			    &glbl->gz_fixed_tl, &glbl->gz_fixed_bl)) != 0) {
810			glbl->gz_fixed_tl = (struct huft *) NULL;
811			return i;
812		}
813		/* distance table */
814		for (i = 0; i < 30; i++)	/* make an incomplete code
815						 * set */
816			l[i] = 5;
817		glbl->gz_fixed_bd = 5;
818		if ((i = huft_build(glbl, l, 30, 0, cpdist, cpdext,
819			     &glbl->gz_fixed_td, &glbl->gz_fixed_bd)) > 1) {
820			huft_free(glbl, glbl->gz_fixed_tl);
821			glbl->gz_fixed_tl = (struct huft *) NULL;
822			return i;
823		}
824	}
825	/* decompress until an end-of-block code */
826	return inflate_codes(glbl, glbl->gz_fixed_tl, glbl->gz_fixed_td, glbl->gz_fixed_bl, glbl->gz_fixed_bd) != 0;
827}
828
829/* decompress an inflated type 2 (dynamic Huffman codes) block. */
830static int
831inflate_dynamic(struct inflate *glbl)
832{
833	int             i;	/* temporary variables */
834	unsigned        j;
835	unsigned        l;	/* last length */
836	unsigned        m;	/* mask for bit lengths table */
837	unsigned        n;	/* number of lengths to get */
838	struct huft    *tl;	/* literal/length code table */
839	struct huft    *td;	/* distance code table */
840	int             bl;	/* lookup bits for tl */
841	int             bd;	/* lookup bits for td */
842	unsigned        nb;	/* number of bit length codes */
843	unsigned        nl;	/* number of literal/length codes */
844	unsigned        nd;	/* number of distance codes */
845#ifdef PKZIP_BUG_WORKAROUND
846	unsigned        ll[288 + 32];	/* literal/length and distance code
847					 * lengths */
848#else
849	unsigned        ll[286 + 30];	/* literal/length and distance code
850					 * lengths */
851#endif
852	ulg    b;		/* bit buffer */
853	unsigned k;		/* number of bits in bit buffer */
854
855	/* make local bit buffer */
856	b = glbl->gz_bb;
857	k = glbl->gz_bk;
858
859	/* read in table lengths */
860	NEEDBITS(glbl, 5)
861		nl = 257 + ((unsigned) b & 0x1f);	/* number of
862							 * literal/length codes */
863	DUMPBITS(5)
864		NEEDBITS(glbl, 5)
865		nd = 1 + ((unsigned) b & 0x1f);	/* number of distance codes */
866	DUMPBITS(5)
867		NEEDBITS(glbl, 4)
868		nb = 4 + ((unsigned) b & 0xf);	/* number of bit length codes */
869	DUMPBITS(4)
870#ifdef PKZIP_BUG_WORKAROUND
871		if (nl > 288 || nd > 32)
872#else
873		if (nl > 286 || nd > 30)
874#endif
875		return 1;	/* bad lengths */
876	/* read in bit-length-code lengths */
877	for (j = 0; j < nb; j++) {
878		NEEDBITS(glbl, 3)
879			ll[border[j]] = (unsigned) b & 7;
880		DUMPBITS(3)
881	}
882	for (; j < 19; j++)
883		ll[border[j]] = 0;
884
885	/* build decoding table for trees--single level, 7 bit lookup */
886	bl = 7;
887	if ((i = huft_build(glbl, ll, 19, 19, NULL, NULL, &tl, &bl)) != 0) {
888		if (i == 1)
889			huft_free(glbl, tl);
890		return i;	/* incomplete code set */
891	}
892	/* read in literal and distance code lengths */
893	n = nl + nd;
894	m = mask[bl];
895	i = l = 0;
896	while ((unsigned) i < n) {
897		NEEDBITS(glbl, (unsigned) bl)
898			j = (td = tl + ((unsigned) b & m))->b;
899		DUMPBITS(j)
900			j = td->v.n;
901		if (j < 16)	/* length of code in bits (0..15) */
902			ll[i++] = l = j;	/* save last length in l */
903		else if (j == 16) {	/* repeat last length 3 to 6 times */
904			NEEDBITS(glbl, 2)
905				j = 3 + ((unsigned) b & 3);
906			DUMPBITS(2)
907				if ((unsigned) i + j > n)
908				return 1;
909			while (j--)
910				ll[i++] = l;
911		} else if (j == 17) {	/* 3 to 10 zero length codes */
912			NEEDBITS(glbl, 3)
913				j = 3 + ((unsigned) b & 7);
914			DUMPBITS(3)
915				if ((unsigned) i + j > n)
916				return 1;
917			while (j--)
918				ll[i++] = 0;
919			l = 0;
920		} else {	/* j == 18: 11 to 138 zero length codes */
921			NEEDBITS(glbl, 7)
922				j = 11 + ((unsigned) b & 0x7f);
923			DUMPBITS(7)
924				if ((unsigned) i + j > n)
925				return 1;
926			while (j--)
927				ll[i++] = 0;
928			l = 0;
929		}
930	}
931
932	/* free decoding table for trees */
933	huft_free(glbl, tl);
934
935	/* restore the global bit buffer */
936	glbl->gz_bb = b;
937	glbl->gz_bk = k;
938
939	/* build the decoding tables for literal/length and distance codes */
940	bl = lbits;
941	i = huft_build(glbl, ll, nl, 257, cplens, cplext, &tl, &bl);
942	if (i != 0) {
943		if (i == 1 && !qflag) {
944			FPRINTF("(incomplete l-tree)  ");
945			huft_free(glbl, tl);
946		}
947		return i;	/* incomplete code set */
948	}
949	bd = dbits;
950	i = huft_build(glbl, ll + nl, nd, 0, cpdist, cpdext, &td, &bd);
951	if (i != 0) {
952		if (i == 1 && !qflag) {
953			FPRINTF("(incomplete d-tree)  ");
954#ifdef PKZIP_BUG_WORKAROUND
955			i = 0;
956		}
957#else
958			huft_free(glbl, td);
959		}
960		huft_free(glbl, tl);
961		return i;	/* incomplete code set */
962#endif
963	}
964	/* decompress until an end-of-block code */
965	if (inflate_codes(glbl, tl, td, bl, bd))
966		return 1;
967
968	/* free the decoding tables, return */
969	huft_free(glbl, tl);
970	huft_free(glbl, td);
971	return 0;
972}
973
974/* decompress an inflated block */
975/*
976 * Arguments:
977 * e	last block flag
978 */
979static int
980inflate_block(struct inflate *glbl, int *e)
981{
982	unsigned        t;	/* block type */
983	ulg    b;		/* bit buffer */
984	unsigned k;		/* number of bits in bit buffer */
985
986	/* make local bit buffer */
987	b = glbl->gz_bb;
988	k = glbl->gz_bk;
989
990	/* read in last block bit */
991	NEEDBITS(glbl, 1)
992		* e = (int) b & 1;
993	DUMPBITS(1)
994	/* read in block type */
995		NEEDBITS(glbl, 2)
996		t = (unsigned) b & 3;
997	DUMPBITS(2)
998	/* restore the global bit buffer */
999		glbl->gz_bb = b;
1000	glbl->gz_bk = k;
1001
1002	/* inflate that block type */
1003	if (t == 2)
1004		return inflate_dynamic(glbl);
1005	if (t == 0)
1006		return inflate_stored(glbl);
1007	if (t == 1)
1008		return inflate_fixed(glbl);
1009	/* bad block type */
1010	return 2;
1011}
1012
1013
1014
1015/* decompress an inflated entry */
1016static int
1017xinflate(struct inflate *glbl)
1018{
1019	int             e;	/* last block flag */
1020	int             r;	/* result code */
1021	unsigned        h;	/* maximum struct huft's malloc'ed */
1022
1023	glbl->gz_fixed_tl = (struct huft *) NULL;
1024
1025	/* initialize window, bit buffer */
1026	glbl->gz_wp = 0;
1027	glbl->gz_bk = 0;
1028	glbl->gz_bb = 0;
1029
1030	/* decompress until the last block */
1031	h = 0;
1032	do {
1033		glbl->gz_hufts = 0;
1034		if ((r = inflate_block(glbl, &e)) != 0)
1035			return r;
1036		if (glbl->gz_hufts > h)
1037			h = glbl->gz_hufts;
1038	} while (!e);
1039
1040	/* flush out slide */
1041	FLUSH(glbl, glbl->gz_wp);
1042
1043	/* return success */
1044	return 0;
1045}
1046
1047/* Nobody uses this - why not? */
1048int
1049inflate(struct inflate *glbl)
1050{
1051	int             i;
1052#ifdef _KERNEL
1053	u_char		*p = NULL;
1054
1055	if (!glbl->gz_slide)
1056		p = glbl->gz_slide = malloc(GZ_WSIZE, M_GZIP, M_WAITOK);
1057#endif
1058	if (!glbl->gz_slide)
1059#ifdef _KERNEL
1060		return(ENOMEM);
1061#else
1062		return 3; /* kzip expects 3 */
1063#endif
1064	i = xinflate(glbl);
1065
1066	if (glbl->gz_fixed_td != (struct huft *) NULL) {
1067		huft_free(glbl, glbl->gz_fixed_td);
1068		glbl->gz_fixed_td = (struct huft *) NULL;
1069	}
1070	if (glbl->gz_fixed_tl != (struct huft *) NULL) {
1071		huft_free(glbl, glbl->gz_fixed_tl);
1072		glbl->gz_fixed_tl = (struct huft *) NULL;
1073	}
1074#ifdef _KERNEL
1075	if (p == glbl->gz_slide) {
1076		free(glbl->gz_slide, M_GZIP);
1077		glbl->gz_slide = NULL;
1078	}
1079#endif
1080	return i;
1081}
1082/* ----------------------- END INFLATE.C */
1083