inflate.c revision 146081
1131380Stjr/* inflate.c -- zlib decompression
2131380Stjr * Copyright (C) 1995-2003 Mark Adler
3131380Stjr * For conditions of distribution and use, see copyright notice in zlib.h
417651Speter */
517651Speter
6131380Stjr/*
7131380Stjr * Change history:
8131380Stjr *
9131380Stjr * 1.2.beta0    24 Nov 2002
10131380Stjr * - First version -- complete rewrite of inflate to simplify code, avoid
11131380Stjr *   creation of window when not needed, minimize use of window when it is
12131380Stjr *   needed, make inffast.c even faster, implement gzip decoding, and to
13131380Stjr *   improve code readability and style over the previous zlib inflate code
14131380Stjr *
15131380Stjr * 1.2.beta1    25 Nov 2002
16131380Stjr * - Use pointers for available input and output checking in inffast.c
17131380Stjr * - Remove input and output counters in inffast.c
18131380Stjr * - Change inffast.c entry and loop from avail_in >= 7 to >= 6
19131380Stjr * - Remove unnecessary second byte pull from length extra in inffast.c
20131380Stjr * - Unroll direct copy to three copies per loop in inffast.c
21131380Stjr *
22131380Stjr * 1.2.beta2    4 Dec 2002
23131380Stjr * - Change external routine names to reduce potential conflicts
24131380Stjr * - Correct filename to inffixed.h for fixed tables in inflate.c
25131380Stjr * - Make hbuf[] unsigned char to match parameter type in inflate.c
26131380Stjr * - Change strm->next_out[-state->offset] to *(strm->next_out - state->offset)
27131380Stjr *   to avoid negation problem on Alphas (64 bit) in inflate.c
28131380Stjr *
29131380Stjr * 1.2.beta3    22 Dec 2002
30131380Stjr * - Add comments on state->bits assertion in inffast.c
31131380Stjr * - Add comments on op field in inftrees.h
32131380Stjr * - Fix bug in reuse of allocated window after inflateReset()
33131380Stjr * - Remove bit fields--back to byte structure for speed
34131380Stjr * - Remove distance extra == 0 check in inflate_fast()--only helps for lengths
35131380Stjr * - Change post-increments to pre-increments in inflate_fast(), PPC biased?
36131380Stjr * - Add compile time option, POSTINC, to use post-increments instead (Intel?)
37131380Stjr * - Make MATCH copy in inflate() much faster for when inflate_fast() not used
38131380Stjr * - Use local copies of stream next and avail values, as well as local bit
39131380Stjr *   buffer and bit count in inflate()--for speed when inflate_fast() not used
40131380Stjr *
41131380Stjr * 1.2.beta4    1 Jan 2003
42131380Stjr * - Split ptr - 257 statements in inflate_table() to avoid compiler warnings
43131380Stjr * - Move a comment on output buffer sizes from inffast.c to inflate.c
44131380Stjr * - Add comments in inffast.c to introduce the inflate_fast() routine
45131380Stjr * - Rearrange window copies in inflate_fast() for speed and simplification
46131380Stjr * - Unroll last copy for window match in inflate_fast()
47131380Stjr * - Use local copies of window variables in inflate_fast() for speed
48131380Stjr * - Pull out common write == 0 case for speed in inflate_fast()
49131380Stjr * - Make op and len in inflate_fast() unsigned for consistency
50131380Stjr * - Add FAR to lcode and dcode declarations in inflate_fast()
51131380Stjr * - Simplified bad distance check in inflate_fast()
52131380Stjr * - Added inflateBackInit(), inflateBack(), and inflateBackEnd() in new
53131380Stjr *   source file infback.c to provide a call-back interface to inflate for
54131380Stjr *   programs like gzip and unzip -- uses window as output buffer to avoid
55131380Stjr *   window copying
56131380Stjr *
57131380Stjr * 1.2.beta5    1 Jan 2003
58131380Stjr * - Improved inflateBack() interface to allow the caller to provide initial
59131380Stjr *   input in strm.
60131380Stjr * - Fixed stored blocks bug in inflateBack()
61131380Stjr *
62131380Stjr * 1.2.beta6    4 Jan 2003
63131380Stjr * - Added comments in inffast.c on effectiveness of POSTINC
64131380Stjr * - Typecasting all around to reduce compiler warnings
65131380Stjr * - Changed loops from while (1) or do {} while (1) to for (;;), again to
66131380Stjr *   make compilers happy
67131380Stjr * - Changed type of window in inflateBackInit() to unsigned char *
68131380Stjr *
69131380Stjr * 1.2.beta7    27 Jan 2003
70131380Stjr * - Changed many types to unsigned or unsigned short to avoid warnings
71131380Stjr * - Added inflateCopy() function
72131380Stjr *
73131380Stjr * 1.2.0        9 Mar 2003
74131380Stjr * - Changed inflateBack() interface to provide separate opaque descriptors
75131380Stjr *   for the in() and out() functions
76131380Stjr * - Changed inflateBack() argument and in_func typedef to swap the length
77131380Stjr *   and buffer address return values for the input function
78131380Stjr * - Check next_in and next_out for Z_NULL on entry to inflate()
79131380Stjr *
80131380Stjr * The history for versions after 1.2.0 are in ChangeLog in zlib distribution.
81131380Stjr */
82131380Stjr
8317651Speter#include "zutil.h"
84131380Stjr#include "inftrees.h"
85131380Stjr#include "inflate.h"
86131380Stjr#include "inffast.h"
8717651Speter
88131380Stjr#ifdef MAKEFIXED
89131380Stjr#  ifndef BUILDFIXED
90131380Stjr#    define BUILDFIXED
91131380Stjr#  endif
92131380Stjr#endif
9317651Speter
94131380Stjr/* function prototypes */
95131380Stjrlocal void fixedtables OF((struct inflate_state FAR *state));
96131380Stjrlocal int updatewindow OF((z_streamp strm, unsigned out));
97131380Stjr#ifdef BUILDFIXED
98131380Stjr   void makefixed OF((void));
99131380Stjr#endif
100131380Stjrlocal unsigned syncsearch OF((unsigned FAR *have, unsigned char FAR *buf,
101131380Stjr                              unsigned len));
10217651Speter
103131380Stjrint ZEXPORT inflateReset(strm)
104131380Stjrz_streamp strm;
105131380Stjr{
106131380Stjr    struct inflate_state FAR *state;
10733904Ssteve
108131380Stjr    if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
109131380Stjr    state = (struct inflate_state FAR *)strm->state;
110131380Stjr    strm->total_in = strm->total_out = state->total = 0;
111131380Stjr    strm->msg = Z_NULL;
112146081Skientzle    strm->adler = 1;        /* to support ill-conceived Java test suite */
113131380Stjr    state->mode = HEAD;
114131380Stjr    state->last = 0;
115131380Stjr    state->havedict = 0;
116131380Stjr    state->wsize = 0;
117131380Stjr    state->whave = 0;
118131380Stjr    state->hold = 0;
119131380Stjr    state->bits = 0;
120131380Stjr    state->lencode = state->distcode = state->next = state->codes;
121131380Stjr    Tracev((stderr, "inflate: reset\n"));
122131380Stjr    return Z_OK;
123131380Stjr}
12433904Ssteve
125131380Stjrint ZEXPORT inflateInit2_(strm, windowBits, version, stream_size)
126131380Stjrz_streamp strm;
127131380Stjrint windowBits;
128131380Stjrconst char *version;
129131380Stjrint stream_size;
130131380Stjr{
131131380Stjr    struct inflate_state FAR *state;
13217651Speter
133131380Stjr    if (version == Z_NULL || version[0] != ZLIB_VERSION[0] ||
134131380Stjr        stream_size != (int)(sizeof(z_stream)))
135131380Stjr        return Z_VERSION_ERROR;
136131380Stjr    if (strm == Z_NULL) return Z_STREAM_ERROR;
137131380Stjr    strm->msg = Z_NULL;                 /* in case we return an error */
138131380Stjr    if (strm->zalloc == (alloc_func)0) {
139131380Stjr        strm->zalloc = zcalloc;
140131380Stjr        strm->opaque = (voidpf)0;
141131380Stjr    }
142131380Stjr    if (strm->zfree == (free_func)0) strm->zfree = zcfree;
143131380Stjr    state = (struct inflate_state FAR *)
144131380Stjr            ZALLOC(strm, 1, sizeof(struct inflate_state));
145131380Stjr    if (state == Z_NULL) return Z_MEM_ERROR;
146131380Stjr    Tracev((stderr, "inflate: allocated\n"));
147131380Stjr    strm->state = (voidpf)state;
148131380Stjr    if (windowBits < 0) {
149131380Stjr        state->wrap = 0;
150131380Stjr        windowBits = -windowBits;
151131380Stjr    }
152131380Stjr    else {
153131380Stjr        state->wrap = (windowBits >> 4) + 1;
154131380Stjr#ifdef GUNZIP
155131380Stjr        if (windowBits < 48) windowBits &= 15;
156131380Stjr#endif
157131380Stjr    }
158131380Stjr    if (windowBits < 8 || windowBits > 15) {
159131380Stjr        ZFREE(strm, state);
160131380Stjr        strm->state = Z_NULL;
161131380Stjr        return Z_STREAM_ERROR;
162131380Stjr    }
163131380Stjr    state->wbits = (unsigned)windowBits;
164131380Stjr    state->window = Z_NULL;
165131380Stjr    return inflateReset(strm);
166131380Stjr}
16717651Speter
168131380Stjrint ZEXPORT inflateInit_(strm, version, stream_size)
169131380Stjrz_streamp strm;
170131380Stjrconst char *version;
171131380Stjrint stream_size;
17217651Speter{
173131380Stjr    return inflateInit2_(strm, DEF_WBITS, version, stream_size);
17417651Speter}
17517651Speter
176131380Stjr/*
177131380Stjr   Return state with length and distance decoding tables and index sizes set to
178131380Stjr   fixed code decoding.  Normally this returns fixed tables from inffixed.h.
179131380Stjr   If BUILDFIXED is defined, then instead this routine builds the tables the
180131380Stjr   first time it's called, and returns those tables the first time and
181131380Stjr   thereafter.  This reduces the size of the code by about 2K bytes, in
182131380Stjr   exchange for a little execution time.  However, BUILDFIXED should not be
183131380Stjr   used for threaded applications, since the rewriting of the tables and virgin
184131380Stjr   may not be thread-safe.
185131380Stjr */
186131380Stjrlocal void fixedtables(state)
187131380Stjrstruct inflate_state FAR *state;
188131380Stjr{
189131380Stjr#ifdef BUILDFIXED
190131380Stjr    static int virgin = 1;
191131380Stjr    static code *lenfix, *distfix;
192131380Stjr    static code fixed[544];
19317651Speter
194131380Stjr    /* build fixed huffman tables if first call (may not be thread safe) */
195131380Stjr    if (virgin) {
196131380Stjr        unsigned sym, bits;
197131380Stjr        static code *next;
198131380Stjr
199131380Stjr        /* literal/length table */
200131380Stjr        sym = 0;
201131380Stjr        while (sym < 144) state->lens[sym++] = 8;
202131380Stjr        while (sym < 256) state->lens[sym++] = 9;
203131380Stjr        while (sym < 280) state->lens[sym++] = 7;
204131380Stjr        while (sym < 288) state->lens[sym++] = 8;
205131380Stjr        next = fixed;
206131380Stjr        lenfix = next;
207131380Stjr        bits = 9;
208131380Stjr        inflate_table(LENS, state->lens, 288, &(next), &(bits), state->work);
209131380Stjr
210131380Stjr        /* distance table */
211131380Stjr        sym = 0;
212131380Stjr        while (sym < 32) state->lens[sym++] = 5;
213131380Stjr        distfix = next;
214131380Stjr        bits = 5;
215131380Stjr        inflate_table(DISTS, state->lens, 32, &(next), &(bits), state->work);
216131380Stjr
217131380Stjr        /* do this just once */
218131380Stjr        virgin = 0;
219131380Stjr    }
220131380Stjr#else /* !BUILDFIXED */
221131380Stjr#   include "inffixed.h"
222131380Stjr#endif /* BUILDFIXED */
223131380Stjr    state->lencode = lenfix;
224131380Stjr    state->lenbits = 9;
225131380Stjr    state->distcode = distfix;
226131380Stjr    state->distbits = 5;
22717651Speter}
22817651Speter
229131380Stjr#ifdef MAKEFIXED
230131380Stjr#include <stdio.h>
23117651Speter
232131380Stjr/*
233131380Stjr   Write out the inffixed.h that is #include'd above.  Defining MAKEFIXED also
234131380Stjr   defines BUILDFIXED, so the tables are built on the fly.  makefixed() writes
235131380Stjr   those tables to stdout, which would be piped to inffixed.h.  A small program
236131380Stjr   can simply call makefixed to do this:
23717651Speter
238131380Stjr    void makefixed(void);
23917651Speter
240131380Stjr    int main(void)
241131380Stjr    {
242131380Stjr        makefixed();
243131380Stjr        return 0;
244131380Stjr    }
24517651Speter
246131380Stjr   Then that can be linked with zlib built with MAKEFIXED defined and run:
24717651Speter
248131380Stjr    a.out > inffixed.h
249131380Stjr */
250131380Stjrvoid makefixed()
251131380Stjr{
252131380Stjr    unsigned low, size;
253131380Stjr    struct inflate_state state;
25417651Speter
255131380Stjr    fixedtables(&state);
256131380Stjr    puts("    /* inffixed.h -- table for decoding fixed codes");
257131380Stjr    puts("     * Generated automatically by makefixed().");
258131380Stjr    puts("     */");
259131380Stjr    puts("");
260131380Stjr    puts("    /* WARNING: this file should *not* be used by applications.");
261131380Stjr    puts("       It is part of the implementation of this library and is");
262131380Stjr    puts("       subject to change. Applications should only use zlib.h.");
263131380Stjr    puts("     */");
264131380Stjr    puts("");
265131380Stjr    size = 1U << 9;
266131380Stjr    printf("    static const code lenfix[%u] = {", size);
267131380Stjr    low = 0;
268131380Stjr    for (;;) {
269131380Stjr        if ((low % 7) == 0) printf("\n        ");
270131380Stjr        printf("{%u,%u,%d}", state.lencode[low].op, state.lencode[low].bits,
271131380Stjr               state.lencode[low].val);
272131380Stjr        if (++low == size) break;
273131380Stjr        putchar(',');
274131380Stjr    }
275131380Stjr    puts("\n    };");
276131380Stjr    size = 1U << 5;
277131380Stjr    printf("\n    static const code distfix[%u] = {", size);
278131380Stjr    low = 0;
279131380Stjr    for (;;) {
280131380Stjr        if ((low % 6) == 0) printf("\n        ");
281131380Stjr        printf("{%u,%u,%d}", state.distcode[low].op, state.distcode[low].bits,
282131380Stjr               state.distcode[low].val);
283131380Stjr        if (++low == size) break;
284131380Stjr        putchar(',');
285131380Stjr    }
286131380Stjr    puts("\n    };");
28717651Speter}
288131380Stjr#endif /* MAKEFIXED */
28917651Speter
290131380Stjr/*
291131380Stjr   Update the window with the last wsize (normally 32K) bytes written before
292131380Stjr   returning.  If window does not exist yet, create it.  This is only called
293131380Stjr   when a window is already in use, or when output has been written during this
294131380Stjr   inflate call, but the end of the deflate stream has not been reached yet.
295131380Stjr   It is also called to create a window for dictionary data when a dictionary
296131380Stjr   is loaded.
29717651Speter
298131380Stjr   Providing output buffers larger than 32K to inflate() should provide a speed
299131380Stjr   advantage, since only the last 32K of output is copied to the sliding window
300131380Stjr   upon return from inflate(), and since all distances after the first 32K of
301131380Stjr   output will fall in the output data, making match copies simpler and faster.
302131380Stjr   The advantage may be dependent on the size of the processor's data caches.
303131380Stjr */
304131380Stjrlocal int updatewindow(strm, out)
305131380Stjrz_streamp strm;
306131380Stjrunsigned out;
30717651Speter{
308131380Stjr    struct inflate_state FAR *state;
309131380Stjr    unsigned copy, dist;
310131380Stjr
311131380Stjr    state = (struct inflate_state FAR *)strm->state;
312131380Stjr
313131380Stjr    /* if it hasn't been done already, allocate space for the window */
314131380Stjr    if (state->window == Z_NULL) {
315131380Stjr        state->window = (unsigned char FAR *)
316131380Stjr                        ZALLOC(strm, 1U << state->wbits,
317131380Stjr                               sizeof(unsigned char));
318131380Stjr        if (state->window == Z_NULL) return 1;
319131380Stjr    }
320131380Stjr
321131380Stjr    /* if window not in use yet, initialize */
322131380Stjr    if (state->wsize == 0) {
323131380Stjr        state->wsize = 1U << state->wbits;
324131380Stjr        state->write = 0;
325131380Stjr        state->whave = 0;
326131380Stjr    }
327131380Stjr
328131380Stjr    /* copy state->wsize or less output bytes into the circular window */
329131380Stjr    copy = out - strm->avail_out;
330131380Stjr    if (copy >= state->wsize) {
331131380Stjr        zmemcpy(state->window, strm->next_out - state->wsize, state->wsize);
332131380Stjr        state->write = 0;
333131380Stjr        state->whave = state->wsize;
334131380Stjr    }
335131380Stjr    else {
336131380Stjr        dist = state->wsize - state->write;
337131380Stjr        if (dist > copy) dist = copy;
338131380Stjr        zmemcpy(state->window + state->write, strm->next_out - copy, dist);
339131380Stjr        copy -= dist;
340131380Stjr        if (copy) {
341131380Stjr            zmemcpy(state->window, strm->next_out - copy, copy);
342131380Stjr            state->write = copy;
343131380Stjr            state->whave = state->wsize;
344131380Stjr        }
345131380Stjr        else {
346131380Stjr            state->write += dist;
347131380Stjr            if (state->write == state->wsize) state->write = 0;
348131380Stjr            if (state->whave < state->wsize) state->whave += dist;
349131380Stjr        }
350131380Stjr    }
351131380Stjr    return 0;
35217651Speter}
35317651Speter
354131380Stjr/* Macros for inflate(): */
35517651Speter
356131380Stjr/* check function to use adler32() for zlib or crc32() for gzip */
357131380Stjr#ifdef GUNZIP
358131380Stjr#  define UPDATE(check, buf, len) \
359131380Stjr    (state->flags ? crc32(check, buf, len) : adler32(check, buf, len))
360131380Stjr#else
361131380Stjr#  define UPDATE(check, buf, len) adler32(check, buf, len)
362131380Stjr#endif
36317651Speter
364131380Stjr/* check macros for header crc */
365131380Stjr#ifdef GUNZIP
366131380Stjr#  define CRC2(check, word) \
367131380Stjr    do { \
368131380Stjr        hbuf[0] = (unsigned char)(word); \
369131380Stjr        hbuf[1] = (unsigned char)((word) >> 8); \
370131380Stjr        check = crc32(check, hbuf, 2); \
371131380Stjr    } while (0)
37217651Speter
373131380Stjr#  define CRC4(check, word) \
374131380Stjr    do { \
375131380Stjr        hbuf[0] = (unsigned char)(word); \
376131380Stjr        hbuf[1] = (unsigned char)((word) >> 8); \
377131380Stjr        hbuf[2] = (unsigned char)((word) >> 16); \
378131380Stjr        hbuf[3] = (unsigned char)((word) >> 24); \
379131380Stjr        check = crc32(check, hbuf, 4); \
380131380Stjr    } while (0)
381131380Stjr#endif
382131380Stjr
383131380Stjr/* Load registers with state in inflate() for speed */
384131380Stjr#define LOAD() \
385131380Stjr    do { \
386131380Stjr        put = strm->next_out; \
387131380Stjr        left = strm->avail_out; \
388131380Stjr        next = strm->next_in; \
389131380Stjr        have = strm->avail_in; \
390131380Stjr        hold = state->hold; \
391131380Stjr        bits = state->bits; \
392131380Stjr    } while (0)
393131380Stjr
394131380Stjr/* Restore state from registers in inflate() */
395131380Stjr#define RESTORE() \
396131380Stjr    do { \
397131380Stjr        strm->next_out = put; \
398131380Stjr        strm->avail_out = left; \
399131380Stjr        strm->next_in = next; \
400131380Stjr        strm->avail_in = have; \
401131380Stjr        state->hold = hold; \
402131380Stjr        state->bits = bits; \
403131380Stjr    } while (0)
404131380Stjr
405131380Stjr/* Clear the input bit accumulator */
406131380Stjr#define INITBITS() \
407131380Stjr    do { \
408131380Stjr        hold = 0; \
409131380Stjr        bits = 0; \
410131380Stjr    } while (0)
411131380Stjr
412131380Stjr/* Get a byte of input into the bit accumulator, or return from inflate()
413131380Stjr   if there is no input available. */
414131380Stjr#define PULLBYTE() \
415131380Stjr    do { \
416131380Stjr        if (have == 0) goto inf_leave; \
417131380Stjr        have--; \
418131380Stjr        hold += (unsigned long)(*next++) << bits; \
419131380Stjr        bits += 8; \
420131380Stjr    } while (0)
421131380Stjr
422131380Stjr/* Assure that there are at least n bits in the bit accumulator.  If there is
423131380Stjr   not enough available input to do that, then return from inflate(). */
424131380Stjr#define NEEDBITS(n) \
425131380Stjr    do { \
426131380Stjr        while (bits < (unsigned)(n)) \
427131380Stjr            PULLBYTE(); \
428131380Stjr    } while (0)
429131380Stjr
430131380Stjr/* Return the low n bits of the bit accumulator (n < 16) */
431131380Stjr#define BITS(n) \
432131380Stjr    ((unsigned)hold & ((1U << (n)) - 1))
433131380Stjr
434131380Stjr/* Remove n bits from the bit accumulator */
435131380Stjr#define DROPBITS(n) \
436131380Stjr    do { \
437131380Stjr        hold >>= (n); \
438131380Stjr        bits -= (unsigned)(n); \
439131380Stjr    } while (0)
440131380Stjr
441131380Stjr/* Remove zero to seven bits as needed to go to a byte boundary */
442131380Stjr#define BYTEBITS() \
443131380Stjr    do { \
444131380Stjr        hold >>= bits & 7; \
445131380Stjr        bits -= bits & 7; \
446131380Stjr    } while (0)
447131380Stjr
448131380Stjr/* Reverse the bytes in a 32-bit value */
449131380Stjr#define REVERSE(q) \
450131380Stjr    ((((q) >> 24) & 0xff) + (((q) >> 8) & 0xff00) + \
451131380Stjr     (((q) & 0xff00) << 8) + (((q) & 0xff) << 24))
452131380Stjr
453131380Stjr/*
454131380Stjr   inflate() uses a state machine to process as much input data and generate as
455131380Stjr   much output data as possible before returning.  The state machine is
456131380Stjr   structured roughly as follows:
457131380Stjr
458131380Stjr    for (;;) switch (state) {
459131380Stjr    ...
460131380Stjr    case STATEn:
461131380Stjr        if (not enough input data or output space to make progress)
462131380Stjr            return;
463131380Stjr        ... make progress ...
464131380Stjr        state = STATEm;
46517651Speter        break;
466131380Stjr    ...
467131380Stjr    }
46817651Speter
469131380Stjr   so when inflate() is called again, the same case is attempted again, and
470131380Stjr   if the appropriate resources are provided, the machine proceeds to the
471131380Stjr   next state.  The NEEDBITS() macro is usually the way the state evaluates
472131380Stjr   whether it can proceed or should return.  NEEDBITS() does the return if
473131380Stjr   the requested bits are not available.  The typical use of the BITS macros
474131380Stjr   is:
475131380Stjr
476131380Stjr        NEEDBITS(n);
477131380Stjr        ... do something with BITS(n) ...
478131380Stjr        DROPBITS(n);
479131380Stjr
480131380Stjr   where NEEDBITS(n) either returns from inflate() if there isn't enough
481131380Stjr   input left to load n bits into the accumulator, or it continues.  BITS(n)
482131380Stjr   gives the low n bits in the accumulator.  When done, DROPBITS(n) drops
483131380Stjr   the low n bits off the accumulator.  INITBITS() clears the accumulator
484131380Stjr   and sets the number of available bits to zero.  BYTEBITS() discards just
485131380Stjr   enough bits to put the accumulator on a byte boundary.  After BYTEBITS()
486131380Stjr   and a NEEDBITS(8), then BITS(8) would return the next byte in the stream.
487131380Stjr
488131380Stjr   NEEDBITS(n) uses PULLBYTE() to get an available byte of input, or to return
489131380Stjr   if there is no input available.  The decoding of variable length codes uses
490131380Stjr   PULLBYTE() directly in order to pull just enough bytes to decode the next
491131380Stjr   code, and no more.
492131380Stjr
493131380Stjr   Some states loop until they get enough input, making sure that enough
494131380Stjr   state information is maintained to continue the loop where it left off
495131380Stjr   if NEEDBITS() returns in the loop.  For example, want, need, and keep
496131380Stjr   would all have to actually be part of the saved state in case NEEDBITS()
497131380Stjr   returns:
498131380Stjr
499131380Stjr    case STATEw:
500131380Stjr        while (want < need) {
501131380Stjr            NEEDBITS(n);
502131380Stjr            keep[want++] = BITS(n);
503131380Stjr            DROPBITS(n);
504131380Stjr        }
505131380Stjr        state = STATEx;
506131380Stjr    case STATEx:
507131380Stjr
508131380Stjr   As shown above, if the next state is also the next case, then the break
509131380Stjr   is omitted.
510131380Stjr
511131380Stjr   A state may also return if there is not enough output space available to
512131380Stjr   complete that state.  Those states are copying stored data, writing a
513131380Stjr   literal byte, and copying a matching string.
514131380Stjr
515131380Stjr   When returning, a "goto inf_leave" is used to update the total counters,
516131380Stjr   update the check value, and determine whether any progress has been made
517131380Stjr   during that inflate() call in order to return the proper return code.
518131380Stjr   Progress is defined as a change in either strm->avail_in or strm->avail_out.
519131380Stjr   When there is a window, goto inf_leave will update the window with the last
520131380Stjr   output written.  If a goto inf_leave occurs in the middle of decompression
521131380Stjr   and there is no window currently, goto inf_leave will create one and copy
522131380Stjr   output to the window for the next call of inflate().
523131380Stjr
524131380Stjr   In this implementation, the flush parameter of inflate() only affects the
525131380Stjr   return code (per zlib.h).  inflate() always writes as much as possible to
526131380Stjr   strm->next_out, given the space available and the provided input--the effect
527131380Stjr   documented in zlib.h of Z_SYNC_FLUSH.  Furthermore, inflate() always defers
528131380Stjr   the allocation of and copying into a sliding window until necessary, which
529131380Stjr   provides the effect documented in zlib.h for Z_FINISH when the entire input
530131380Stjr   stream available.  So the only thing the flush parameter actually does is:
531131380Stjr   when flush is set to Z_FINISH, inflate() cannot return Z_OK.  Instead it
532131380Stjr   will return Z_BUF_ERROR if it has not reached the end of the stream.
533131380Stjr */
534131380Stjr
535131380Stjrint ZEXPORT inflate(strm, flush)
536131380Stjrz_streamp strm;
537131380Stjrint flush;
538131380Stjr{
539131380Stjr    struct inflate_state FAR *state;
540131380Stjr    unsigned char FAR *next;    /* next input */
541131380Stjr    unsigned char FAR *put;     /* next output */
542131380Stjr    unsigned have, left;        /* available input and output */
543131380Stjr    unsigned long hold;         /* bit buffer */
544131380Stjr    unsigned bits;              /* bits in bit buffer */
545131380Stjr    unsigned in, out;           /* save starting available input and output */
546131380Stjr    unsigned copy;              /* number of stored or match bytes to copy */
547131380Stjr    unsigned char FAR *from;    /* where to copy match bytes from */
548131380Stjr    code this;                  /* current decoding table entry */
549131380Stjr    code last;                  /* parent table entry */
550131380Stjr    unsigned len;               /* length to copy for repeats, bits to drop */
551131380Stjr    int ret;                    /* return code */
552131380Stjr#ifdef GUNZIP
553131380Stjr    unsigned char hbuf[4];      /* buffer for gzip header crc calculation */
55433904Ssteve#endif
555131380Stjr    static const unsigned short order[19] = /* permutation of code lengths */
556131380Stjr        {16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15};
557131380Stjr
558131380Stjr    if (strm == Z_NULL || strm->state == Z_NULL || strm->next_out == Z_NULL ||
559131380Stjr        (strm->next_in == Z_NULL && strm->avail_in != 0))
560131380Stjr        return Z_STREAM_ERROR;
561131380Stjr
562131380Stjr    state = (struct inflate_state FAR *)strm->state;
563131380Stjr    if (state->mode == TYPE) state->mode = TYPEDO;      /* skip check */
564131380Stjr    LOAD();
565131380Stjr    in = have;
566131380Stjr    out = left;
567131380Stjr    ret = Z_OK;
568131380Stjr    for (;;)
569131380Stjr        switch (state->mode) {
570131380Stjr        case HEAD:
571131380Stjr            if (state->wrap == 0) {
572131380Stjr                state->mode = TYPEDO;
573131380Stjr                break;
574131380Stjr            }
575131380Stjr            NEEDBITS(16);
576131380Stjr#ifdef GUNZIP
577131380Stjr            if ((state->wrap & 2) && hold == 0x8b1f) {  /* gzip header */
578131380Stjr                state->check = crc32(0L, Z_NULL, 0);
579131380Stjr                CRC2(state->check, hold);
580131380Stjr                INITBITS();
581131380Stjr                state->mode = FLAGS;
582131380Stjr                break;
583131380Stjr            }
584131380Stjr            state->flags = 0;           /* expect zlib header */
585131380Stjr            if (!(state->wrap & 1) ||   /* check if zlib header allowed */
586131380Stjr#else
587131380Stjr            if (
588131380Stjr#endif
589131380Stjr                ((BITS(8) << 8) + (hold >> 8)) % 31) {
590131380Stjr                strm->msg = (char *)"incorrect header check";
591131380Stjr                state->mode = BAD;
592131380Stjr                break;
593131380Stjr            }
594131380Stjr            if (BITS(4) != Z_DEFLATED) {
595131380Stjr                strm->msg = (char *)"unknown compression method";
596131380Stjr                state->mode = BAD;
597131380Stjr                break;
598131380Stjr            }
599131380Stjr            DROPBITS(4);
600131380Stjr            if (BITS(4) + 8 > state->wbits) {
601131380Stjr                strm->msg = (char *)"invalid window size";
602131380Stjr                state->mode = BAD;
603131380Stjr                break;
604131380Stjr            }
605131380Stjr            Tracev((stderr, "inflate:   zlib header ok\n"));
606131380Stjr            strm->adler = state->check = adler32(0L, Z_NULL, 0);
607131380Stjr            state->mode = hold & 0x200 ? DICTID : TYPE;
608131380Stjr            INITBITS();
609131380Stjr            break;
610131380Stjr#ifdef GUNZIP
611131380Stjr        case FLAGS:
612131380Stjr            NEEDBITS(16);
613131380Stjr            state->flags = (int)(hold);
614131380Stjr            if ((state->flags & 0xff) != Z_DEFLATED) {
615131380Stjr                strm->msg = (char *)"unknown compression method";
616131380Stjr                state->mode = BAD;
617131380Stjr                break;
618131380Stjr            }
619131380Stjr            if (state->flags & 0xe000) {
620131380Stjr                strm->msg = (char *)"unknown header flags set";
621131380Stjr                state->mode = BAD;
622131380Stjr                break;
623131380Stjr            }
624131380Stjr            if (state->flags & 0x0200) CRC2(state->check, hold);
625131380Stjr            INITBITS();
626131380Stjr            state->mode = TIME;
627131380Stjr        case TIME:
628131380Stjr            NEEDBITS(32);
629131380Stjr            if (state->flags & 0x0200) CRC4(state->check, hold);
630131380Stjr            INITBITS();
631131380Stjr            state->mode = OS;
632131380Stjr        case OS:
633131380Stjr            NEEDBITS(16);
634131380Stjr            if (state->flags & 0x0200) CRC2(state->check, hold);
635131380Stjr            INITBITS();
636131380Stjr            state->mode = EXLEN;
637131380Stjr        case EXLEN:
638131380Stjr            if (state->flags & 0x0400) {
639131380Stjr                NEEDBITS(16);
640131380Stjr                state->length = (unsigned)(hold);
641131380Stjr                if (state->flags & 0x0200) CRC2(state->check, hold);
642131380Stjr                INITBITS();
643131380Stjr            }
644131380Stjr            state->mode = EXTRA;
645131380Stjr        case EXTRA:
646131380Stjr            if (state->flags & 0x0400) {
647131380Stjr                copy = state->length;
648131380Stjr                if (copy > have) copy = have;
649131380Stjr                if (copy) {
650131380Stjr                    if (state->flags & 0x0200)
651131380Stjr                        state->check = crc32(state->check, next, copy);
652131380Stjr                    have -= copy;
653131380Stjr                    next += copy;
654131380Stjr                    state->length -= copy;
655131380Stjr                }
656131380Stjr                if (state->length) goto inf_leave;
657131380Stjr            }
658131380Stjr            state->mode = NAME;
659131380Stjr        case NAME:
660131380Stjr            if (state->flags & 0x0800) {
661131380Stjr                if (have == 0) goto inf_leave;
662131380Stjr                copy = 0;
663131380Stjr                do {
664131380Stjr                    len = (unsigned)(next[copy++]);
665131380Stjr                } while (len && copy < have);
666131380Stjr                if (state->flags & 0x02000)
667131380Stjr                    state->check = crc32(state->check, next, copy);
668131380Stjr                have -= copy;
669131380Stjr                next += copy;
670131380Stjr                if (len) goto inf_leave;
671131380Stjr            }
672131380Stjr            state->mode = COMMENT;
673131380Stjr        case COMMENT:
674131380Stjr            if (state->flags & 0x1000) {
675131380Stjr                if (have == 0) goto inf_leave;
676131380Stjr                copy = 0;
677131380Stjr                do {
678131380Stjr                    len = (unsigned)(next[copy++]);
679131380Stjr                } while (len && copy < have);
680131380Stjr                if (state->flags & 0x02000)
681131380Stjr                    state->check = crc32(state->check, next, copy);
682131380Stjr                have -= copy;
683131380Stjr                next += copy;
684131380Stjr                if (len) goto inf_leave;
685131380Stjr            }
686131380Stjr            state->mode = HCRC;
687131380Stjr        case HCRC:
688131380Stjr            if (state->flags & 0x0200) {
689131380Stjr                NEEDBITS(16);
690131380Stjr                if (hold != (state->check & 0xffff)) {
691131380Stjr                    strm->msg = (char *)"header crc mismatch";
692131380Stjr                    state->mode = BAD;
693131380Stjr                    break;
694131380Stjr                }
695131380Stjr                INITBITS();
696131380Stjr            }
697131380Stjr            strm->adler = state->check = crc32(0L, Z_NULL, 0);
698131380Stjr            state->mode = TYPE;
699131380Stjr            break;
700131380Stjr#endif
701131380Stjr        case DICTID:
702131380Stjr            NEEDBITS(32);
703131380Stjr            strm->adler = state->check = REVERSE(hold);
704131380Stjr            INITBITS();
705131380Stjr            state->mode = DICT;
706131380Stjr        case DICT:
707131380Stjr            if (state->havedict == 0) {
708131380Stjr                RESTORE();
709131380Stjr                return Z_NEED_DICT;
710131380Stjr            }
711131380Stjr            strm->adler = state->check = adler32(0L, Z_NULL, 0);
712131380Stjr            state->mode = TYPE;
713131380Stjr        case TYPE:
714131380Stjr            if (flush == Z_BLOCK) goto inf_leave;
715131380Stjr        case TYPEDO:
716131380Stjr            if (state->last) {
717131380Stjr                BYTEBITS();
718131380Stjr                state->mode = CHECK;
719131380Stjr                break;
720131380Stjr            }
721131380Stjr            NEEDBITS(3);
722131380Stjr            state->last = BITS(1);
723131380Stjr            DROPBITS(1);
724131380Stjr            switch (BITS(2)) {
725131380Stjr            case 0:                             /* stored block */
726131380Stjr                Tracev((stderr, "inflate:     stored block%s\n",
727131380Stjr                        state->last ? " (last)" : ""));
728131380Stjr                state->mode = STORED;
729131380Stjr                break;
730131380Stjr            case 1:                             /* fixed block */
731131380Stjr                fixedtables(state);
732131380Stjr                Tracev((stderr, "inflate:     fixed codes block%s\n",
733131380Stjr                        state->last ? " (last)" : ""));
734131380Stjr                state->mode = LEN;              /* decode codes */
735131380Stjr                break;
736131380Stjr            case 2:                             /* dynamic block */
737131380Stjr                Tracev((stderr, "inflate:     dynamic codes block%s\n",
738131380Stjr                        state->last ? " (last)" : ""));
739131380Stjr                state->mode = TABLE;
740131380Stjr                break;
741131380Stjr            case 3:
742131380Stjr                strm->msg = (char *)"invalid block type";
743131380Stjr                state->mode = BAD;
744131380Stjr            }
745131380Stjr            DROPBITS(2);
746131380Stjr            break;
747131380Stjr        case STORED:
748131380Stjr            BYTEBITS();                         /* go to byte boundary */
749131380Stjr            NEEDBITS(32);
750131380Stjr            if ((hold & 0xffff) != ((hold >> 16) ^ 0xffff)) {
751131380Stjr                strm->msg = (char *)"invalid stored block lengths";
752131380Stjr                state->mode = BAD;
753131380Stjr                break;
754131380Stjr            }
755131380Stjr            state->length = (unsigned)hold & 0xffff;
756131380Stjr            Tracev((stderr, "inflate:       stored length %u\n",
757131380Stjr                    state->length));
758131380Stjr            INITBITS();
759131380Stjr            state->mode = COPY;
760131380Stjr        case COPY:
761131380Stjr            copy = state->length;
762131380Stjr            if (copy) {
763131380Stjr                if (copy > have) copy = have;
764131380Stjr                if (copy > left) copy = left;
765131380Stjr                if (copy == 0) goto inf_leave;
766131380Stjr                zmemcpy(put, next, copy);
767131380Stjr                have -= copy;
768131380Stjr                next += copy;
769131380Stjr                left -= copy;
770131380Stjr                put += copy;
771131380Stjr                state->length -= copy;
772131380Stjr                break;
773131380Stjr            }
774131380Stjr            Tracev((stderr, "inflate:       stored end\n"));
775131380Stjr            state->mode = TYPE;
776131380Stjr            break;
777131380Stjr        case TABLE:
778131380Stjr            NEEDBITS(14);
779131380Stjr            state->nlen = BITS(5) + 257;
780131380Stjr            DROPBITS(5);
781131380Stjr            state->ndist = BITS(5) + 1;
782131380Stjr            DROPBITS(5);
783131380Stjr            state->ncode = BITS(4) + 4;
784131380Stjr            DROPBITS(4);
785131380Stjr#ifndef PKZIP_BUG_WORKAROUND
786131380Stjr            if (state->nlen > 286 || state->ndist > 30) {
787131380Stjr                strm->msg = (char *)"too many length or distance symbols";
788131380Stjr                state->mode = BAD;
789131380Stjr                break;
790131380Stjr            }
791131380Stjr#endif
792131380Stjr            Tracev((stderr, "inflate:       table sizes ok\n"));
793131380Stjr            state->have = 0;
794131380Stjr            state->mode = LENLENS;
795131380Stjr        case LENLENS:
796131380Stjr            while (state->have < state->ncode) {
797131380Stjr                NEEDBITS(3);
798131380Stjr                state->lens[order[state->have++]] = (unsigned short)BITS(3);
799131380Stjr                DROPBITS(3);
800131380Stjr            }
801131380Stjr            while (state->have < 19)
802131380Stjr                state->lens[order[state->have++]] = 0;
803131380Stjr            state->next = state->codes;
804131380Stjr            state->lencode = (code const FAR *)(state->next);
805131380Stjr            state->lenbits = 7;
806131380Stjr            ret = inflate_table(CODES, state->lens, 19, &(state->next),
807131380Stjr                                &(state->lenbits), state->work);
808131380Stjr            if (ret) {
809131380Stjr                strm->msg = (char *)"invalid code lengths set";
810131380Stjr                state->mode = BAD;
811131380Stjr                break;
812131380Stjr            }
813131380Stjr            Tracev((stderr, "inflate:       code lengths ok\n"));
814131380Stjr            state->have = 0;
815131380Stjr            state->mode = CODELENS;
816131380Stjr        case CODELENS:
817131380Stjr            while (state->have < state->nlen + state->ndist) {
818131380Stjr                for (;;) {
819131380Stjr                    this = state->lencode[BITS(state->lenbits)];
820131380Stjr                    if ((unsigned)(this.bits) <= bits) break;
821131380Stjr                    PULLBYTE();
822131380Stjr                }
823131380Stjr                if (this.val < 16) {
824131380Stjr                    NEEDBITS(this.bits);
825131380Stjr                    DROPBITS(this.bits);
826131380Stjr                    state->lens[state->have++] = this.val;
827131380Stjr                }
828131380Stjr                else {
829131380Stjr                    if (this.val == 16) {
830131380Stjr                        NEEDBITS(this.bits + 2);
831131380Stjr                        DROPBITS(this.bits);
832131380Stjr                        if (state->have == 0) {
833131380Stjr                            strm->msg = (char *)"invalid bit length repeat";
834131380Stjr                            state->mode = BAD;
835131380Stjr                            break;
836131380Stjr                        }
837131380Stjr                        len = state->lens[state->have - 1];
838131380Stjr                        copy = 3 + BITS(2);
839131380Stjr                        DROPBITS(2);
840131380Stjr                    }
841131380Stjr                    else if (this.val == 17) {
842131380Stjr                        NEEDBITS(this.bits + 3);
843131380Stjr                        DROPBITS(this.bits);
844131380Stjr                        len = 0;
845131380Stjr                        copy = 3 + BITS(3);
846131380Stjr                        DROPBITS(3);
847131380Stjr                    }
848131380Stjr                    else {
849131380Stjr                        NEEDBITS(this.bits + 7);
850131380Stjr                        DROPBITS(this.bits);
851131380Stjr                        len = 0;
852131380Stjr                        copy = 11 + BITS(7);
853131380Stjr                        DROPBITS(7);
854131380Stjr                    }
855131380Stjr                    if (state->have + copy > state->nlen + state->ndist) {
856131380Stjr                        strm->msg = (char *)"invalid bit length repeat";
857131380Stjr                        state->mode = BAD;
858131380Stjr                        break;
859131380Stjr                    }
860131380Stjr                    while (copy--)
861131380Stjr                        state->lens[state->have++] = (unsigned short)len;
862131380Stjr                }
863131380Stjr            }
864131380Stjr
865146081Skientzle            /* handle error breaks in while */
866146081Skientzle            if (state->mode == BAD) break;
867134354Snectar
868131380Stjr            /* build code tables */
869131380Stjr            state->next = state->codes;
870131380Stjr            state->lencode = (code const FAR *)(state->next);
871131380Stjr            state->lenbits = 9;
872131380Stjr            ret = inflate_table(LENS, state->lens, state->nlen, &(state->next),
873131380Stjr                                &(state->lenbits), state->work);
874131380Stjr            if (ret) {
875131380Stjr                strm->msg = (char *)"invalid literal/lengths set";
876131380Stjr                state->mode = BAD;
877131380Stjr                break;
878131380Stjr            }
879131380Stjr            state->distcode = (code const FAR *)(state->next);
880131380Stjr            state->distbits = 6;
881131380Stjr            ret = inflate_table(DISTS, state->lens + state->nlen, state->ndist,
882131380Stjr                            &(state->next), &(state->distbits), state->work);
883131380Stjr            if (ret) {
884131380Stjr                strm->msg = (char *)"invalid distances set";
885131380Stjr                state->mode = BAD;
886131380Stjr                break;
887131380Stjr            }
888131380Stjr            Tracev((stderr, "inflate:       codes ok\n"));
889131380Stjr            state->mode = LEN;
890131380Stjr        case LEN:
891131380Stjr            if (have >= 6 && left >= 258) {
892131380Stjr                RESTORE();
893131380Stjr                inflate_fast(strm, out);
894131380Stjr                LOAD();
895131380Stjr                break;
896131380Stjr            }
897131380Stjr            for (;;) {
898131380Stjr                this = state->lencode[BITS(state->lenbits)];
899131380Stjr                if ((unsigned)(this.bits) <= bits) break;
900131380Stjr                PULLBYTE();
901131380Stjr            }
902131380Stjr            if (this.op && (this.op & 0xf0) == 0) {
903131380Stjr                last = this;
904131380Stjr                for (;;) {
905131380Stjr                    this = state->lencode[last.val +
906131380Stjr                            (BITS(last.bits + last.op) >> last.bits)];
907131380Stjr                    if ((unsigned)(last.bits + this.bits) <= bits) break;
908131380Stjr                    PULLBYTE();
909131380Stjr                }
910131380Stjr                DROPBITS(last.bits);
911131380Stjr            }
912131380Stjr            DROPBITS(this.bits);
913131380Stjr            state->length = (unsigned)this.val;
914131380Stjr            if ((int)(this.op) == 0) {
915131380Stjr                Tracevv((stderr, this.val >= 0x20 && this.val < 0x7f ?
916131380Stjr                        "inflate:         literal '%c'\n" :
917131380Stjr                        "inflate:         literal 0x%02x\n", this.val));
918131380Stjr                state->mode = LIT;
919131380Stjr                break;
920131380Stjr            }
921131380Stjr            if (this.op & 32) {
922131380Stjr                Tracevv((stderr, "inflate:         end of block\n"));
923131380Stjr                state->mode = TYPE;
924131380Stjr                break;
925131380Stjr            }
926131380Stjr            if (this.op & 64) {
927131380Stjr                strm->msg = (char *)"invalid literal/length code";
928131380Stjr                state->mode = BAD;
929131380Stjr                break;
930131380Stjr            }
931131380Stjr            state->extra = (unsigned)(this.op) & 15;
932131380Stjr            state->mode = LENEXT;
933131380Stjr        case LENEXT:
934131380Stjr            if (state->extra) {
935131380Stjr                NEEDBITS(state->extra);
936131380Stjr                state->length += BITS(state->extra);
937131380Stjr                DROPBITS(state->extra);
938131380Stjr            }
939131380Stjr            Tracevv((stderr, "inflate:         length %u\n", state->length));
940131380Stjr            state->mode = DIST;
941131380Stjr        case DIST:
942131380Stjr            for (;;) {
943131380Stjr                this = state->distcode[BITS(state->distbits)];
944131380Stjr                if ((unsigned)(this.bits) <= bits) break;
945131380Stjr                PULLBYTE();
946131380Stjr            }
947131380Stjr            if ((this.op & 0xf0) == 0) {
948131380Stjr                last = this;
949131380Stjr                for (;;) {
950131380Stjr                    this = state->distcode[last.val +
951131380Stjr                            (BITS(last.bits + last.op) >> last.bits)];
952131380Stjr                    if ((unsigned)(last.bits + this.bits) <= bits) break;
953131380Stjr                    PULLBYTE();
954131380Stjr                }
955131380Stjr                DROPBITS(last.bits);
956131380Stjr            }
957131380Stjr            DROPBITS(this.bits);
958131380Stjr            if (this.op & 64) {
959131380Stjr                strm->msg = (char *)"invalid distance code";
960131380Stjr                state->mode = BAD;
961131380Stjr                break;
962131380Stjr            }
963131380Stjr            state->offset = (unsigned)this.val;
964131380Stjr            state->extra = (unsigned)(this.op) & 15;
965131380Stjr            state->mode = DISTEXT;
966131380Stjr        case DISTEXT:
967131380Stjr            if (state->extra) {
968131380Stjr                NEEDBITS(state->extra);
969131380Stjr                state->offset += BITS(state->extra);
970131380Stjr                DROPBITS(state->extra);
971131380Stjr            }
972131380Stjr            if (state->offset > state->whave + out - left) {
973131380Stjr                strm->msg = (char *)"invalid distance too far back";
974131380Stjr                state->mode = BAD;
975131380Stjr                break;
976131380Stjr            }
977131380Stjr            Tracevv((stderr, "inflate:         distance %u\n", state->offset));
978131380Stjr            state->mode = MATCH;
979131380Stjr        case MATCH:
980131380Stjr            if (left == 0) goto inf_leave;
981131380Stjr            copy = out - left;
982131380Stjr            if (state->offset > copy) {         /* copy from window */
983131380Stjr                copy = state->offset - copy;
984131380Stjr                if (copy > state->write) {
985131380Stjr                    copy -= state->write;
986131380Stjr                    from = state->window + (state->wsize - copy);
987131380Stjr                }
988131380Stjr                else
989131380Stjr                    from = state->window + (state->write - copy);
990131380Stjr                if (copy > state->length) copy = state->length;
991131380Stjr            }
992131380Stjr            else {                              /* copy from output */
993131380Stjr                from = put - state->offset;
994131380Stjr                copy = state->length;
995131380Stjr            }
996131380Stjr            if (copy > left) copy = left;
997131380Stjr            left -= copy;
998131380Stjr            state->length -= copy;
999131380Stjr            do {
1000131380Stjr                *put++ = *from++;
1001131380Stjr            } while (--copy);
1002131380Stjr            if (state->length == 0) state->mode = LEN;
1003131380Stjr            break;
1004131380Stjr        case LIT:
1005131380Stjr            if (left == 0) goto inf_leave;
1006131380Stjr            *put++ = (unsigned char)(state->length);
1007131380Stjr            left--;
1008131380Stjr            state->mode = LEN;
1009131380Stjr            break;
1010131380Stjr        case CHECK:
1011131380Stjr            if (state->wrap) {
1012131380Stjr                NEEDBITS(32);
1013131380Stjr                out -= left;
1014131380Stjr                strm->total_out += out;
1015131380Stjr                state->total += out;
1016131380Stjr                if (out)
1017131380Stjr                    strm->adler = state->check =
1018131380Stjr                        UPDATE(state->check, put - out, out);
1019131380Stjr                out = left;
1020131380Stjr                if ((
1021131380Stjr#ifdef GUNZIP
1022131380Stjr                     state->flags ? hold :
1023131380Stjr#endif
1024131380Stjr                     REVERSE(hold)) != state->check) {
1025131380Stjr                    strm->msg = (char *)"incorrect data check";
1026131380Stjr                    state->mode = BAD;
1027131380Stjr                    break;
1028131380Stjr                }
1029131380Stjr                INITBITS();
1030131380Stjr                Tracev((stderr, "inflate:   check matches trailer\n"));
1031131380Stjr            }
1032131380Stjr#ifdef GUNZIP
1033131380Stjr            state->mode = LENGTH;
1034131380Stjr        case LENGTH:
1035131380Stjr            if (state->wrap && state->flags) {
1036131380Stjr                NEEDBITS(32);
1037131380Stjr                if (hold != (state->total & 0xffffffffUL)) {
1038131380Stjr                    strm->msg = (char *)"incorrect length check";
1039131380Stjr                    state->mode = BAD;
1040131380Stjr                    break;
1041131380Stjr                }
1042131380Stjr                INITBITS();
1043131380Stjr                Tracev((stderr, "inflate:   length matches trailer\n"));
1044131380Stjr            }
1045131380Stjr#endif
1046131380Stjr            state->mode = DONE;
1047131380Stjr        case DONE:
1048131380Stjr            ret = Z_STREAM_END;
1049131380Stjr            goto inf_leave;
1050131380Stjr        case BAD:
1051131380Stjr            ret = Z_DATA_ERROR;
1052131380Stjr            goto inf_leave;
1053131380Stjr        case MEM:
1054131380Stjr            return Z_MEM_ERROR;
1055131380Stjr        case SYNC:
1056131380Stjr        default:
1057131380Stjr            return Z_STREAM_ERROR;
1058131380Stjr        }
1059131380Stjr
1060131380Stjr    /*
1061131380Stjr       Return from inflate(), updating the total counts and the check value.
1062131380Stjr       If there was no progress during the inflate() call, return a buffer
1063131380Stjr       error.  Call updatewindow() to create and/or update the window state.
1064131380Stjr       Note: a memory error from inflate() is non-recoverable.
1065131380Stjr     */
1066131380Stjr  inf_leave:
1067131380Stjr    RESTORE();
1068131380Stjr    if (state->wsize || (state->mode < CHECK && out != strm->avail_out))
1069131380Stjr        if (updatewindow(strm, out)) {
1070131380Stjr            state->mode = MEM;
1071131380Stjr            return Z_MEM_ERROR;
1072131380Stjr        }
1073131380Stjr    in -= strm->avail_in;
1074131380Stjr    out -= strm->avail_out;
1075131380Stjr    strm->total_in += in;
1076131380Stjr    strm->total_out += out;
1077131380Stjr    state->total += out;
1078131380Stjr    if (state->wrap && out)
1079131380Stjr        strm->adler = state->check =
1080131380Stjr            UPDATE(state->check, strm->next_out - out, out);
1081131380Stjr    strm->data_type = state->bits + (state->last ? 64 : 0) +
1082131380Stjr                      (state->mode == TYPE ? 128 : 0);
1083131380Stjr    if (((in == 0 && out == 0) || flush == Z_FINISH) && ret == Z_OK)
1084131380Stjr        ret = Z_BUF_ERROR;
1085131380Stjr    return ret;
108617651Speter}
108717651Speter
1088131380Stjrint ZEXPORT inflateEnd(strm)
1089131380Stjrz_streamp strm;
1090131380Stjr{
1091131380Stjr    struct inflate_state FAR *state;
1092131380Stjr    if (strm == Z_NULL || strm->state == Z_NULL || strm->zfree == (free_func)0)
1093131380Stjr        return Z_STREAM_ERROR;
1094131380Stjr    state = (struct inflate_state FAR *)strm->state;
1095131380Stjr    if (state->window != Z_NULL) ZFREE(strm, state->window);
1096131380Stjr    ZFREE(strm, strm->state);
1097131380Stjr    strm->state = Z_NULL;
1098131380Stjr    Tracev((stderr, "inflate: end\n"));
1099131380Stjr    return Z_OK;
1100131380Stjr}
110117651Speter
1102131380Stjrint ZEXPORT inflateSetDictionary(strm, dictionary, dictLength)
1103131380Stjrz_streamp strm;
110417651Speterconst Bytef *dictionary;
1105131380StjruInt dictLength;
110617651Speter{
1107131380Stjr    struct inflate_state FAR *state;
1108131380Stjr    unsigned long id;
110917651Speter
1110131380Stjr    /* check state */
1111131380Stjr    if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
1112131380Stjr    state = (struct inflate_state FAR *)strm->state;
1113131380Stjr    if (state->mode != DICT) return Z_STREAM_ERROR;
111417651Speter
1115131380Stjr    /* check for correct dictionary id */
1116131380Stjr    id = adler32(0L, Z_NULL, 0);
1117131380Stjr    id = adler32(id, dictionary, dictLength);
1118131380Stjr    if (id != state->check) return Z_DATA_ERROR;
111917651Speter
1120131380Stjr    /* copy dictionary to window */
1121131380Stjr    if (updatewindow(strm, strm->avail_out)) {
1122131380Stjr        state->mode = MEM;
1123131380Stjr        return Z_MEM_ERROR;
1124131380Stjr    }
1125131380Stjr    if (dictLength > state->wsize) {
1126131380Stjr        zmemcpy(state->window, dictionary + dictLength - state->wsize,
1127131380Stjr                state->wsize);
1128131380Stjr        state->whave = state->wsize;
1129131380Stjr    }
1130131380Stjr    else {
1131131380Stjr        zmemcpy(state->window + state->wsize - dictLength, dictionary,
1132131380Stjr                dictLength);
1133131380Stjr        state->whave = dictLength;
1134131380Stjr    }
1135131380Stjr    state->havedict = 1;
1136131380Stjr    Tracev((stderr, "inflate:   dictionary set\n"));
1137131380Stjr    return Z_OK;
113817651Speter}
113917651Speter
1140131380Stjr/*
1141131380Stjr   Search buf[0..len-1] for the pattern: 0, 0, 0xff, 0xff.  Return when found
1142131380Stjr   or when out of input.  When called, *have is the number of pattern bytes
1143131380Stjr   found in order so far, in 0..3.  On return *have is updated to the new
1144131380Stjr   state.  If on return *have equals four, then the pattern was found and the
1145131380Stjr   return value is how many bytes were read including the last byte of the
1146131380Stjr   pattern.  If *have is less than four, then the pattern has not been found
1147131380Stjr   yet and the return value is len.  In the latter case, syncsearch() can be
1148131380Stjr   called again with more data and the *have state.  *have is initialized to
1149131380Stjr   zero for the first call.
1150131380Stjr */
1151131380Stjrlocal unsigned syncsearch(have, buf, len)
1152131380Stjrunsigned FAR *have;
1153131380Stjrunsigned char FAR *buf;
1154131380Stjrunsigned len;
1155131380Stjr{
1156131380Stjr    unsigned got;
1157131380Stjr    unsigned next;
115817651Speter
1159131380Stjr    got = *have;
1160131380Stjr    next = 0;
1161131380Stjr    while (next < len && got < 4) {
1162131380Stjr        if ((int)(buf[next]) == (got < 2 ? 0 : 0xff))
1163131380Stjr            got++;
1164131380Stjr        else if (buf[next])
1165131380Stjr            got = 0;
1166131380Stjr        else
1167131380Stjr            got = 4 - got;
1168131380Stjr        next++;
1169131380Stjr    }
1170131380Stjr    *have = got;
1171131380Stjr    return next;
1172131380Stjr}
1173131380Stjr
1174131380Stjrint ZEXPORT inflateSync(strm)
1175131380Stjrz_streamp strm;
117617651Speter{
1177131380Stjr    unsigned len;               /* number of bytes to look at or looked at */
1178131380Stjr    unsigned long in, out;      /* temporary to save total_in and total_out */
1179131380Stjr    unsigned char buf[4];       /* to restore bit buffer to byte string */
1180131380Stjr    struct inflate_state FAR *state;
118117651Speter
1182131380Stjr    /* check parameters */
1183131380Stjr    if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
1184131380Stjr    state = (struct inflate_state FAR *)strm->state;
1185131380Stjr    if (strm->avail_in == 0 && state->bits < 8) return Z_BUF_ERROR;
118617651Speter
1187131380Stjr    /* if first time, start search in bit buffer */
1188131380Stjr    if (state->mode != SYNC) {
1189131380Stjr        state->mode = SYNC;
1190131380Stjr        state->hold <<= state->bits & 7;
1191131380Stjr        state->bits -= state->bits & 7;
1192131380Stjr        len = 0;
1193131380Stjr        while (state->bits >= 8) {
1194131380Stjr            buf[len++] = (unsigned char)(state->hold);
1195131380Stjr            state->hold >>= 8;
1196131380Stjr            state->bits -= 8;
1197131380Stjr        }
1198131380Stjr        state->have = 0;
1199131380Stjr        syncsearch(&(state->have), buf, len);
1200131380Stjr    }
120117651Speter
1202131380Stjr    /* search available input */
1203131380Stjr    len = syncsearch(&(state->have), strm->next_in, strm->avail_in);
1204131380Stjr    strm->avail_in -= len;
1205131380Stjr    strm->next_in += len;
1206131380Stjr    strm->total_in += len;
120717651Speter
1208131380Stjr    /* return no joy or set up to restart inflate() on a new block */
1209131380Stjr    if (state->have != 4) return Z_DATA_ERROR;
1210131380Stjr    in = strm->total_in;  out = strm->total_out;
1211131380Stjr    inflateReset(strm);
1212131380Stjr    strm->total_in = in;  strm->total_out = out;
1213131380Stjr    state->mode = TYPE;
1214131380Stjr    return Z_OK;
121517651Speter}
121633904Ssteve
1217131380Stjr/*
1218131380Stjr   Returns true if inflate is currently at the end of a block generated by
1219131380Stjr   Z_SYNC_FLUSH or Z_FULL_FLUSH. This function is used by one PPP
1220131380Stjr   implementation to provide an additional safety check. PPP uses
1221131380Stjr   Z_SYNC_FLUSH but removes the length bytes of the resulting empty stored
1222131380Stjr   block. When decompressing, PPP checks that at the end of input packet,
1223131380Stjr   inflate is waiting for these length bytes.
122433904Ssteve */
1225131380Stjrint ZEXPORT inflateSyncPoint(strm)
1226131380Stjrz_streamp strm;
122733904Ssteve{
1228131380Stjr    struct inflate_state FAR *state;
1229131380Stjr
1230131380Stjr    if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
1231131380Stjr    state = (struct inflate_state FAR *)strm->state;
1232131380Stjr    return state->mode == STORED && state->bits == 0;
123333904Ssteve}
1234131380Stjr
1235131380Stjrint ZEXPORT inflateCopy(dest, source)
1236131380Stjrz_streamp dest;
1237131380Stjrz_streamp source;
1238131380Stjr{
1239131380Stjr    struct inflate_state FAR *state;
1240131380Stjr    struct inflate_state FAR *copy;
1241131380Stjr    unsigned char FAR *window;
1242131380Stjr
1243131380Stjr    /* check input */
1244131380Stjr    if (dest == Z_NULL || source == Z_NULL || source->state == Z_NULL ||
1245131380Stjr        source->zalloc == (alloc_func)0 || source->zfree == (free_func)0)
1246131380Stjr        return Z_STREAM_ERROR;
1247131380Stjr    state = (struct inflate_state FAR *)source->state;
1248131380Stjr
1249131380Stjr    /* allocate space */
1250131380Stjr    copy = (struct inflate_state FAR *)
1251131380Stjr           ZALLOC(source, 1, sizeof(struct inflate_state));
1252131380Stjr    if (copy == Z_NULL) return Z_MEM_ERROR;
1253131380Stjr    window = Z_NULL;
1254131380Stjr    if (state->window != Z_NULL) {
1255131380Stjr        window = (unsigned char FAR *)
1256131380Stjr                 ZALLOC(source, 1U << state->wbits, sizeof(unsigned char));
1257131380Stjr        if (window == Z_NULL) {
1258131380Stjr            ZFREE(source, copy);
1259131380Stjr            return Z_MEM_ERROR;
1260131380Stjr        }
1261131380Stjr    }
1262131380Stjr
1263131380Stjr    /* copy state */
1264131380Stjr    *dest = *source;
1265131380Stjr    *copy = *state;
1266131380Stjr    copy->lencode = copy->codes + (state->lencode - state->codes);
1267131380Stjr    copy->distcode = copy->codes + (state->distcode - state->codes);
1268131380Stjr    copy->next = copy->codes + (state->next - state->codes);
1269131380Stjr    if (window != Z_NULL)
1270131380Stjr        zmemcpy(window, state->window, 1U << state->wbits);
1271131380Stjr    copy->window = window;
1272131380Stjr    dest->state = (voidpf)copy;
1273131380Stjr    return Z_OK;
1274131380Stjr}
1275