xref: /netbsd-src/common/dist/zlib/inflate.c (revision 4b169a6ba595ae283ca507b26b15fdff40495b1c)
1 /*	$NetBSD: inflate.c,v 1.7 2022/10/15 19:49:32 christos Exp $	*/
2 
3 /* inflate.c -- zlib decompression
4  * Copyright (C) 1995-2022 Mark Adler
5  * For conditions of distribution and use, see copyright notice in zlib.h
6  */
7 
8 /*
9  * Change history:
10  *
11  * 1.2.beta0    24 Nov 2002
12  * - First version -- complete rewrite of inflate to simplify code, avoid
13  *   creation of window when not needed, minimize use of window when it is
14  *   needed, make inffast.c even faster, implement gzip decoding, and to
15  *   improve code readability and style over the previous zlib inflate code
16  *
17  * 1.2.beta1    25 Nov 2002
18  * - Use pointers for available input and output checking in inffast.c
19  * - Remove input and output counters in inffast.c
20  * - Change inffast.c entry and loop from avail_in >= 7 to >= 6
21  * - Remove unnecessary second byte pull from length extra in inffast.c
22  * - Unroll direct copy to three copies per loop in inffast.c
23  *
24  * 1.2.beta2    4 Dec 2002
25  * - Change external routine names to reduce potential conflicts
26  * - Correct filename to inffixed.h for fixed tables in inflate.c
27  * - Make hbuf[] unsigned char to match parameter type in inflate.c
28  * - Change strm->next_out[-state->offset] to *(strm->next_out - state->offset)
29  *   to avoid negation problem on Alphas (64 bit) in inflate.c
30  *
31  * 1.2.beta3    22 Dec 2002
32  * - Add comments on state->bits assertion in inffast.c
33  * - Add comments on op field in inftrees.h
34  * - Fix bug in reuse of allocated window after inflateReset()
35  * - Remove bit fields--back to byte structure for speed
36  * - Remove distance extra == 0 check in inflate_fast()--only helps for lengths
37  * - Change post-increments to pre-increments in inflate_fast(), PPC biased?
38  * - Add compile time option, POSTINC, to use post-increments instead (Intel?)
39  * - Make MATCH copy in inflate() much faster for when inflate_fast() not used
40  * - Use local copies of stream next and avail values, as well as local bit
41  *   buffer and bit count in inflate()--for speed when inflate_fast() not used
42  *
43  * 1.2.beta4    1 Jan 2003
44  * - Split ptr - 257 statements in inflate_table() to avoid compiler warnings
45  * - Move a comment on output buffer sizes from inffast.c to inflate.c
46  * - Add comments in inffast.c to introduce the inflate_fast() routine
47  * - Rearrange window copies in inflate_fast() for speed and simplification
48  * - Unroll last copy for window match in inflate_fast()
49  * - Use local copies of window variables in inflate_fast() for speed
50  * - Pull out common wnext == 0 case for speed in inflate_fast()
51  * - Make op and len in inflate_fast() unsigned for consistency
52  * - Add FAR to lcode and dcode declarations in inflate_fast()
53  * - Simplified bad distance check in inflate_fast()
54  * - Added inflateBackInit(), inflateBack(), and inflateBackEnd() in new
55  *   source file infback.c to provide a call-back interface to inflate for
56  *   programs like gzip and unzip -- uses window as output buffer to avoid
57  *   window copying
58  *
59  * 1.2.beta5    1 Jan 2003
60  * - Improved inflateBack() interface to allow the caller to provide initial
61  *   input in strm.
62  * - Fixed stored blocks bug in inflateBack()
63  *
64  * 1.2.beta6    4 Jan 2003
65  * - Added comments in inffast.c on effectiveness of POSTINC
66  * - Typecasting all around to reduce compiler warnings
67  * - Changed loops from while (1) or do {} while (1) to for (;;), again to
68  *   make compilers happy
69  * - Changed type of window in inflateBackInit() to unsigned char *
70  *
71  * 1.2.beta7    27 Jan 2003
72  * - Changed many types to unsigned or unsigned short to avoid warnings
73  * - Added inflateCopy() function
74  *
75  * 1.2.0        9 Mar 2003
76  * - Changed inflateBack() interface to provide separate opaque descriptors
77  *   for the in() and out() functions
78  * - Changed inflateBack() argument and in_func typedef to swap the length
79  *   and buffer address return values for the input function
80  * - Check next_in and next_out for Z_NULL on entry to inflate()
81  *
82  * The history for versions after 1.2.0 are in ChangeLog in zlib distribution.
83  */
84 
85 #include "zutil.h"
86 #include "inftrees.h"
87 #include "inflate.h"
88 #include "inffast.h"
89 
90 #ifdef MAKEFIXED
91 #  ifndef BUILDFIXED
92 #    define BUILDFIXED
93 #  endif
94 #endif
95 
96 /* function prototypes */
97 local int inflateStateCheck OF((z_streamp strm));
98 local void fixedtables OF((struct inflate_state FAR *state));
99 local int updatewindow OF((z_streamp strm, const unsigned char FAR *end,
100                            unsigned copy));
101 #ifdef BUILDFIXED
102    void makefixed OF((void));
103 #endif
104 local unsigned syncsearch OF((unsigned FAR *have, const unsigned char FAR *buf,
105                               unsigned len));
106 
107 local int inflateStateCheck(strm)
108 z_streamp strm;
109 {
110     struct inflate_state FAR *state;
111     if (strm == Z_NULL ||
112         strm->zalloc == (alloc_func)0 || strm->zfree == (free_func)0)
113         return 1;
114     state = (struct inflate_state FAR *)strm->state;
115     if (state == Z_NULL || state->strm != strm ||
116         state->mode < HEAD || state->mode > SYNC)
117         return 1;
118     return 0;
119 }
120 
121 int ZEXPORT inflateResetKeep(strm)
122 z_streamp strm;
123 {
124     struct inflate_state FAR *state;
125 
126     if (inflateStateCheck(strm)) return Z_STREAM_ERROR;
127     state = (struct inflate_state FAR *)strm->state;
128     strm->total_in = strm->total_out = state->total = 0;
129     strm->msg = Z_NULL;
130     if (state->wrap)        /* to support ill-conceived Java test suite */
131         strm->adler = state->wrap & 1;
132     state->mode = HEAD;
133     state->last = 0;
134     state->havedict = 0;
135     state->flags = -1;
136     state->dmax = 32768U;
137     state->head = Z_NULL;
138     state->hold = 0;
139     state->bits = 0;
140     state->lencode = state->distcode = state->next = state->codes;
141     state->sane = 1;
142     state->back = -1;
143     Tracev((stderr, "inflate: reset\n"));
144     return Z_OK;
145 }
146 
147 int ZEXPORT inflateReset(strm)
148 z_streamp strm;
149 {
150     struct inflate_state FAR *state;
151 
152     if (inflateStateCheck(strm)) return Z_STREAM_ERROR;
153     state = (struct inflate_state FAR *)strm->state;
154     state->wsize = 0;
155     state->whave = 0;
156     state->wnext = 0;
157     return inflateResetKeep(strm);
158 }
159 
160 int ZEXPORT inflateReset2(strm, windowBits)
161 z_streamp strm;
162 int windowBits;
163 {
164     int wrap;
165     struct inflate_state FAR *state;
166 
167     /* get the state */
168     if (inflateStateCheck(strm)) return Z_STREAM_ERROR;
169     state = (struct inflate_state FAR *)strm->state;
170 
171     /* extract wrap request from windowBits parameter */
172     if (windowBits < 0) {
173         if (windowBits < -15)
174             return Z_STREAM_ERROR;
175         wrap = 0;
176         windowBits = -windowBits;
177     }
178     else {
179         wrap = (windowBits >> 4) + 5;
180 #ifdef GUNZIP
181         if (windowBits < 48)
182             windowBits &= 15;
183 #endif
184     }
185 
186     /* set number of window bits, free window if different */
187     if (windowBits && (windowBits < 8 || windowBits > 15))
188         return Z_STREAM_ERROR;
189     if (state->window != Z_NULL && state->wbits != (unsigned)windowBits) {
190         ZFREE(strm, state->window);
191         state->window = Z_NULL;
192     }
193 
194     /* update state and reset the rest of it */
195     state->wrap = wrap;
196     state->wbits = (unsigned)windowBits;
197     return inflateReset(strm);
198 }
199 
200 int ZEXPORT inflateInit2_(strm, windowBits, version, stream_size)
201 z_streamp strm;
202 int windowBits;
203 const char *version;
204 int stream_size;
205 {
206     int ret;
207     struct inflate_state FAR *state;
208 
209     if (version == Z_NULL || version[0] != ZLIB_VERSION[0] ||
210         stream_size != (int)(sizeof(z_stream)))
211         return Z_VERSION_ERROR;
212     if (strm == Z_NULL) return Z_STREAM_ERROR;
213     strm->msg = Z_NULL;                 /* in case we return an error */
214     if (strm->zalloc == (alloc_func)0) {
215 #ifdef Z_SOLO
216         return Z_STREAM_ERROR;
217 #else
218         strm->zalloc = zcalloc;
219         strm->opaque = (voidpf)0;
220 #endif
221     }
222     if (strm->zfree == (free_func)0)
223 #ifdef Z_SOLO
224         return Z_STREAM_ERROR;
225 #else
226         strm->zfree = zcfree;
227 #endif
228     state = (struct inflate_state FAR *)
229             ZALLOC(strm, 1, sizeof(struct inflate_state));
230     if (state == Z_NULL) return Z_MEM_ERROR;
231     Tracev((stderr, "inflate: allocated\n"));
232     strm->state = (struct internal_state FAR *)state;
233     state->strm = strm;
234     state->window = Z_NULL;
235     state->mode = HEAD;     /* to pass state test in inflateReset2() */
236     ret = inflateReset2(strm, windowBits);
237     if (ret != Z_OK) {
238         ZFREE(strm, state);
239         strm->state = Z_NULL;
240     }
241     return ret;
242 }
243 
244 int ZEXPORT inflateInit_(strm, version, stream_size)
245 z_streamp strm;
246 const char *version;
247 int stream_size;
248 {
249     return inflateInit2_(strm, DEF_WBITS, version, stream_size);
250 }
251 
252 int ZEXPORT inflatePrime(strm, bits, value)
253 z_streamp strm;
254 int bits;
255 int value;
256 {
257     struct inflate_state FAR *state;
258 
259     if (inflateStateCheck(strm)) return Z_STREAM_ERROR;
260     state = (struct inflate_state FAR *)strm->state;
261     if (bits < 0) {
262         state->hold = 0;
263         state->bits = 0;
264         return Z_OK;
265     }
266     if (bits > 16 || state->bits + (uInt)bits > 32) return Z_STREAM_ERROR;
267     value &= (1L << bits) - 1;
268     state->hold += (unsigned)value << state->bits;
269     state->bits += (uInt)bits;
270     return Z_OK;
271 }
272 
273 /*
274    Return state with length and distance decoding tables and index sizes set to
275    fixed code decoding.  Normally this returns fixed tables from inffixed.h.
276    If BUILDFIXED is defined, then instead this routine builds the tables the
277    first time it's called, and returns those tables the first time and
278    thereafter.  This reduces the size of the code by about 2K bytes, in
279    exchange for a little execution time.  However, BUILDFIXED should not be
280    used for threaded applications, since the rewriting of the tables and virgin
281    may not be thread-safe.
282  */
283 local void fixedtables(state)
284 struct inflate_state FAR *state;
285 {
286 #ifdef BUILDFIXED
287     static int virgin = 1;
288     static code *lenfix, *distfix;
289     static code fixed[544];
290 
291     /* build fixed huffman tables if first call (may not be thread safe) */
292     if (virgin) {
293         unsigned sym, bits;
294         static code *next;
295 
296         /* literal/length table */
297         sym = 0;
298         while (sym < 144) state->lens[sym++] = 8;
299         while (sym < 256) state->lens[sym++] = 9;
300         while (sym < 280) state->lens[sym++] = 7;
301         while (sym < 288) state->lens[sym++] = 8;
302         next = fixed;
303         lenfix = next;
304         bits = 9;
305         inflate_table(LENS, state->lens, 288, &(next), &(bits), state->work);
306 
307         /* distance table */
308         sym = 0;
309         while (sym < 32) state->lens[sym++] = 5;
310         distfix = next;
311         bits = 5;
312         inflate_table(DISTS, state->lens, 32, &(next), &(bits), state->work);
313 
314         /* do this just once */
315         virgin = 0;
316     }
317 #else /* !BUILDFIXED */
318 #   include "inffixed.h"
319 #endif /* BUILDFIXED */
320     state->lencode = lenfix;
321     state->lenbits = 9;
322     state->distcode = distfix;
323     state->distbits = 5;
324 }
325 
326 #ifdef MAKEFIXED
327 #include <stdio.h>
328 
329 /*
330    Write out the inffixed.h that is #include'd above.  Defining MAKEFIXED also
331    defines BUILDFIXED, so the tables are built on the fly.  makefixed() writes
332    those tables to stdout, which would be piped to inffixed.h.  A small program
333    can simply call makefixed to do this:
334 
335     void makefixed(void);
336 
337     int main(void)
338     {
339         makefixed();
340         return 0;
341     }
342 
343    Then that can be linked with zlib built with MAKEFIXED defined and run:
344 
345     a.out > inffixed.h
346  */
347 void makefixed()
348 {
349     unsigned low, size;
350     struct inflate_state state;
351 
352     fixedtables(&state);
353     puts("    /* inffixed.h -- table for decoding fixed codes");
354     puts("     * Generated automatically by makefixed().");
355     puts("     */");
356     puts("");
357     puts("    /* WARNING: this file should *not* be used by applications.");
358     puts("       It is part of the implementation of this library and is");
359     puts("       subject to change. Applications should only use zlib.h.");
360     puts("     */");
361     puts("");
362     size = 1U << 9;
363     printf("    static const code lenfix[%u] = {", size);
364     low = 0;
365     for (;;) {
366         if ((low % 7) == 0) printf("\n        ");
367         printf("{%u,%u,%d}", (low & 127) == 99 ? 64 : state.lencode[low].op,
368                state.lencode[low].bits, state.lencode[low].val);
369         if (++low == size) break;
370         putchar(',');
371     }
372     puts("\n    };");
373     size = 1U << 5;
374     printf("\n    static const code distfix[%u] = {", size);
375     low = 0;
376     for (;;) {
377         if ((low % 6) == 0) printf("\n        ");
378         printf("{%u,%u,%d}", state.distcode[low].op, state.distcode[low].bits,
379                state.distcode[low].val);
380         if (++low == size) break;
381         putchar(',');
382     }
383     puts("\n    };");
384 }
385 #endif /* MAKEFIXED */
386 
387 /*
388    Update the window with the last wsize (normally 32K) bytes written before
389    returning.  If window does not exist yet, create it.  This is only called
390    when a window is already in use, or when output has been written during this
391    inflate call, but the end of the deflate stream has not been reached yet.
392    It is also called to create a window for dictionary data when a dictionary
393    is loaded.
394 
395    Providing output buffers larger than 32K to inflate() should provide a speed
396    advantage, since only the last 32K of output is copied to the sliding window
397    upon return from inflate(), and since all distances after the first 32K of
398    output will fall in the output data, making match copies simpler and faster.
399    The advantage may be dependent on the size of the processor's data caches.
400  */
401 local int updatewindow(strm, end, copy)
402 z_streamp strm;
403 const Bytef *end;
404 unsigned copy;
405 {
406     struct inflate_state FAR *state;
407     unsigned dist;
408 
409     state = (struct inflate_state FAR *)strm->state;
410 
411     /* if it hasn't been done already, allocate space for the window */
412     if (state->window == Z_NULL) {
413         state->window = (unsigned char FAR *)
414                         ZALLOC(strm, 1U << state->wbits,
415                                sizeof(unsigned char));
416         if (state->window == Z_NULL) return 1;
417     }
418 
419     /* if window not in use yet, initialize */
420     if (state->wsize == 0) {
421         state->wsize = 1U << state->wbits;
422         state->wnext = 0;
423         state->whave = 0;
424     }
425 
426     /* copy state->wsize or less output bytes into the circular window */
427     if (copy >= state->wsize) {
428         zmemcpy(state->window, end - state->wsize, state->wsize);
429         state->wnext = 0;
430         state->whave = state->wsize;
431     }
432     else {
433         dist = state->wsize - state->wnext;
434         if (dist > copy) dist = copy;
435         zmemcpy(state->window + state->wnext, end - copy, dist);
436         copy -= dist;
437         if (copy) {
438             zmemcpy(state->window, end - copy, copy);
439             state->wnext = copy;
440             state->whave = state->wsize;
441         }
442         else {
443             state->wnext += dist;
444             if (state->wnext == state->wsize) state->wnext = 0;
445             if (state->whave < state->wsize) state->whave += dist;
446         }
447     }
448     return 0;
449 }
450 
451 /* Macros for inflate(): */
452 
453 /* check function to use adler32() for zlib or crc32() for gzip */
454 #ifdef GUNZIP
455 #  define UPDATE_CHECK(check, buf, len) \
456     (state->flags ? crc32(check, buf, len) : adler32(check, buf, len))
457 #else
458 #  define UPDATE_CHECK(check, buf, len) adler32(check, buf, len)
459 #endif
460 
461 /* check macros for header crc */
462 #ifdef GUNZIP
463 #  define CRC2(check, word) \
464     do { \
465         hbuf[0] = (unsigned char)(word); \
466         hbuf[1] = (unsigned char)((word) >> 8); \
467         check = crc32(check, hbuf, 2); \
468     } while (0)
469 
470 #  define CRC4(check, word) \
471     do { \
472         hbuf[0] = (unsigned char)(word); \
473         hbuf[1] = (unsigned char)((word) >> 8); \
474         hbuf[2] = (unsigned char)((word) >> 16); \
475         hbuf[3] = (unsigned char)((word) >> 24); \
476         check = crc32(check, hbuf, 4); \
477     } while (0)
478 #endif
479 
480 /* Load registers with state in inflate() for speed */
481 #define LOAD() \
482     do { \
483         put = strm->next_out; \
484         left = strm->avail_out; \
485         next = strm->next_in; \
486         have = strm->avail_in; \
487         hold = state->hold; \
488         bits = state->bits; \
489     } while (0)
490 
491 /* Restore state from registers in inflate() */
492 #define RESTORE() \
493     do { \
494         strm->next_out = put; \
495         strm->avail_out = left; \
496         strm->next_in = next; \
497         strm->avail_in = have; \
498         state->hold = hold; \
499         state->bits = bits; \
500     } while (0)
501 
502 /* Clear the input bit accumulator */
503 #define INITBITS() \
504     do { \
505         hold = 0; \
506         bits = 0; \
507     } while (0)
508 
509 /* Get a byte of input into the bit accumulator, or return from inflate()
510    if there is no input available. */
511 #define PULLBYTE() \
512     do { \
513         if (have == 0) goto inf_leave; \
514         have--; \
515         hold += (unsigned long)(*next++) << bits; \
516         bits += 8; \
517     } while (0)
518 
519 /* Assure that there are at least n bits in the bit accumulator.  If there is
520    not enough available input to do that, then return from inflate(). */
521 #define NEEDBITS(n) \
522     do { \
523         while (bits < (unsigned)(n)) \
524             PULLBYTE(); \
525     } while (0)
526 
527 /* Return the low n bits of the bit accumulator (n < 16) */
528 #define BITS(n) \
529     ((unsigned)hold & ((1U << (n)) - 1))
530 
531 /* Remove n bits from the bit accumulator */
532 #define DROPBITS(n) \
533     do { \
534         hold >>= (n); \
535         bits -= (unsigned)(n); \
536     } while (0)
537 
538 /* Remove zero to seven bits as needed to go to a byte boundary */
539 #define BYTEBITS() \
540     do { \
541         hold >>= bits & 7; \
542         bits -= bits & 7; \
543     } while (0)
544 
545 /*
546    inflate() uses a state machine to process as much input data and generate as
547    much output data as possible before returning.  The state machine is
548    structured roughly as follows:
549 
550     for (;;) switch (state) {
551     ...
552     case STATEn:
553         if (not enough input data or output space to make progress)
554             return;
555         ... make progress ...
556         state = STATEm;
557         break;
558     ...
559     }
560 
561    so when inflate() is called again, the same case is attempted again, and
562    if the appropriate resources are provided, the machine proceeds to the
563    next state.  The NEEDBITS() macro is usually the way the state evaluates
564    whether it can proceed or should return.  NEEDBITS() does the return if
565    the requested bits are not available.  The typical use of the BITS macros
566    is:
567 
568         NEEDBITS(n);
569         ... do something with BITS(n) ...
570         DROPBITS(n);
571 
572    where NEEDBITS(n) either returns from inflate() if there isn't enough
573    input left to load n bits into the accumulator, or it continues.  BITS(n)
574    gives the low n bits in the accumulator.  When done, DROPBITS(n) drops
575    the low n bits off the accumulator.  INITBITS() clears the accumulator
576    and sets the number of available bits to zero.  BYTEBITS() discards just
577    enough bits to put the accumulator on a byte boundary.  After BYTEBITS()
578    and a NEEDBITS(8), then BITS(8) would return the next byte in the stream.
579 
580    NEEDBITS(n) uses PULLBYTE() to get an available byte of input, or to return
581    if there is no input available.  The decoding of variable length codes uses
582    PULLBYTE() directly in order to pull just enough bytes to decode the next
583    code, and no more.
584 
585    Some states loop until they get enough input, making sure that enough
586    state information is maintained to continue the loop where it left off
587    if NEEDBITS() returns in the loop.  For example, want, need, and keep
588    would all have to actually be part of the saved state in case NEEDBITS()
589    returns:
590 
591     case STATEw:
592         while (want < need) {
593             NEEDBITS(n);
594             keep[want++] = BITS(n);
595             DROPBITS(n);
596         }
597         state = STATEx;
598     case STATEx:
599 
600    As shown above, if the next state is also the next case, then the break
601    is omitted.
602 
603    A state may also return if there is not enough output space available to
604    complete that state.  Those states are copying stored data, writing a
605    literal byte, and copying a matching string.
606 
607    When returning, a "goto inf_leave" is used to update the total counters,
608    update the check value, and determine whether any progress has been made
609    during that inflate() call in order to return the proper return code.
610    Progress is defined as a change in either strm->avail_in or strm->avail_out.
611    When there is a window, goto inf_leave will update the window with the last
612    output written.  If a goto inf_leave occurs in the middle of decompression
613    and there is no window currently, goto inf_leave will create one and copy
614    output to the window for the next call of inflate().
615 
616    In this implementation, the flush parameter of inflate() only affects the
617    return code (per zlib.h).  inflate() always writes as much as possible to
618    strm->next_out, given the space available and the provided input--the effect
619    documented in zlib.h of Z_SYNC_FLUSH.  Furthermore, inflate() always defers
620    the allocation of and copying into a sliding window until necessary, which
621    provides the effect documented in zlib.h for Z_FINISH when the entire input
622    stream available.  So the only thing the flush parameter actually does is:
623    when flush is set to Z_FINISH, inflate() cannot return Z_OK.  Instead it
624    will return Z_BUF_ERROR if it has not reached the end of the stream.
625  */
626 
627 int ZEXPORT inflate(strm, flush)
628 z_streamp strm;
629 int flush;
630 {
631     struct inflate_state FAR *state;
632     z_const unsigned char FAR *next;    /* next input */
633     unsigned char FAR *put;     /* next output */
634     unsigned have, left;        /* available input and output */
635     unsigned long hold;         /* bit buffer */
636     unsigned bits;              /* bits in bit buffer */
637     unsigned in, out;           /* save starting available input and output */
638     unsigned copy;              /* number of stored or match bytes to copy */
639     unsigned char FAR *from;    /* where to copy match bytes from */
640     code here;                  /* current decoding table entry */
641     code last;                  /* parent table entry */
642     unsigned len;               /* length to copy for repeats, bits to drop */
643     int ret;                    /* return code */
644 #ifdef GUNZIP
645     unsigned char hbuf[4];      /* buffer for gzip header crc calculation */
646 #endif
647     static const unsigned short order[19] = /* permutation of code lengths */
648         {16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15};
649 
650 #if defined(__NetBSD__) && defined(_STANDALONE)
651     /* Some kernels are loaded at address 0x0 so strm->next_out could be NULL */
652     if (inflateStateCheck(strm) ||
653         (strm->next_in == Z_NULL && strm->avail_in != 0))
654         return Z_STREAM_ERROR;
655 #else
656     if (inflateStateCheck(strm) || strm->next_out == Z_NULL ||
657         (strm->next_in == Z_NULL && strm->avail_in != 0))
658         return Z_STREAM_ERROR;
659 #endif
660 
661     state = (struct inflate_state FAR *)strm->state;
662     if (state->mode == TYPE) state->mode = TYPEDO;      /* skip check */
663     LOAD();
664     in = have;
665     out = left;
666     ret = Z_OK;
667     for (;;)
668         switch (state->mode) {
669         case HEAD:
670             if (state->wrap == 0) {
671                 state->mode = TYPEDO;
672                 break;
673             }
674             NEEDBITS(16);
675 #ifdef GUNZIP
676             if ((state->wrap & 2) && hold == 0x8b1f) {  /* gzip header */
677                 if (state->wbits == 0)
678                     state->wbits = 15;
679                 state->check = crc32(0L, Z_NULL, 0);
680                 CRC2(state->check, hold);
681                 INITBITS();
682                 state->mode = FLAGS;
683                 break;
684             }
685             if (state->head != Z_NULL)
686                 state->head->done = -1;
687             if (!(state->wrap & 1) ||   /* check if zlib header allowed */
688 #else
689             if (
690 #endif
691                 ((BITS(8) << 8) + (hold >> 8)) % 31) {
692                 strm->msg = __UNCONST("incorrect header check");
693                 state->mode = BAD;
694                 break;
695             }
696             if (BITS(4) != Z_DEFLATED) {
697                 strm->msg = __UNCONST("unknown compression method");
698                 state->mode = BAD;
699                 break;
700             }
701             DROPBITS(4);
702             len = BITS(4) + 8;
703             if (state->wbits == 0)
704                 state->wbits = len;
705             if (len > 15 || len > state->wbits) {
706                 strm->msg = __UNCONST("invalid window size");
707                 state->mode = BAD;
708                 break;
709             }
710             state->dmax = 1U << len;
711             state->flags = 0;               /* indicate zlib header */
712             Tracev((stderr, "inflate:   zlib header ok\n"));
713             strm->adler = state->check = adler32(0L, Z_NULL, 0);
714             state->mode = hold & 0x200 ? DICTID : TYPE;
715             INITBITS();
716             break;
717 #ifdef GUNZIP
718         case FLAGS:
719             NEEDBITS(16);
720             state->flags = (int)(hold);
721             if ((state->flags & 0xff) != Z_DEFLATED) {
722                 strm->msg = __UNCONST("unknown compression method");
723                 state->mode = BAD;
724                 break;
725             }
726             if (state->flags & 0xe000) {
727                 strm->msg = __UNCONST("unknown header flags set");
728                 state->mode = BAD;
729                 break;
730             }
731             if (state->head != Z_NULL)
732                 state->head->text = (int)((hold >> 8) & 1);
733             if ((state->flags & 0x0200) && (state->wrap & 4))
734                 CRC2(state->check, hold);
735             INITBITS();
736             state->mode = TIME;
737                 /* fallthrough */
738         case TIME:
739             NEEDBITS(32);
740             if (state->head != Z_NULL)
741                 state->head->time = hold;
742             if ((state->flags & 0x0200) && (state->wrap & 4))
743                 CRC4(state->check, hold);
744             INITBITS();
745             state->mode = OS;
746                 /* fallthrough */
747         case OS:
748             NEEDBITS(16);
749             if (state->head != Z_NULL) {
750                 state->head->xflags = (int)(hold & 0xff);
751                 state->head->os = (int)(hold >> 8);
752             }
753             if ((state->flags & 0x0200) && (state->wrap & 4))
754                 CRC2(state->check, hold);
755             INITBITS();
756             state->mode = EXLEN;
757                 /* fallthrough */
758         case EXLEN:
759             if (state->flags & 0x0400) {
760                 NEEDBITS(16);
761                 state->length = (unsigned)(hold);
762                 if (state->head != Z_NULL)
763                     state->head->extra_len = (unsigned)hold;
764                 if ((state->flags & 0x0200) && (state->wrap & 4))
765                     CRC2(state->check, hold);
766                 INITBITS();
767             }
768             else if (state->head != Z_NULL)
769                 state->head->extra = Z_NULL;
770             state->mode = EXTRA;
771                 /* fallthrough */
772         case EXTRA:
773             if (state->flags & 0x0400) {
774                 copy = state->length;
775                 if (copy > have) copy = have;
776                 if (copy) {
777                     if (state->head != Z_NULL &&
778                         state->head->extra != Z_NULL &&
779                         (len = state->head->extra_len - state->length) <
780                             state->head->extra_max) {
781                         zmemcpy(state->head->extra + len, next,
782                                 len + copy > state->head->extra_max ?
783                                 state->head->extra_max - len : copy);
784                     }
785                     if ((state->flags & 0x0200) && (state->wrap & 4))
786                         state->check = crc32(state->check, next, copy);
787                     have -= copy;
788                     next += copy;
789                     state->length -= copy;
790                 }
791                 if (state->length) goto inf_leave;
792             }
793             state->length = 0;
794             state->mode = NAME;
795                 /* fallthrough */
796         case NAME:
797             if (state->flags & 0x0800) {
798                 if (have == 0) goto inf_leave;
799                 copy = 0;
800                 do {
801                     len = (unsigned)(next[copy++]);
802                     if (state->head != Z_NULL &&
803                             state->head->name != Z_NULL &&
804                             state->length < state->head->name_max)
805                         state->head->name[state->length++] = (Bytef)len;
806                 } while (len && copy < have);
807                 if ((state->flags & 0x0200) && (state->wrap & 4))
808                     state->check = crc32(state->check, next, copy);
809                 have -= copy;
810                 next += copy;
811                 if (len) goto inf_leave;
812             }
813             else if (state->head != Z_NULL)
814                 state->head->name = Z_NULL;
815             state->length = 0;
816             state->mode = COMMENT;
817                 /* fallthrough */
818         case COMMENT:
819             if (state->flags & 0x1000) {
820                 if (have == 0) goto inf_leave;
821                 copy = 0;
822                 do {
823                     len = (unsigned)(next[copy++]);
824                     if (state->head != Z_NULL &&
825                             state->head->comment != Z_NULL &&
826                             state->length < state->head->comm_max)
827                         state->head->comment[state->length++] = (Bytef)len;
828                 } while (len && copy < have);
829                 if ((state->flags & 0x0200) && (state->wrap & 4))
830                     state->check = crc32(state->check, next, copy);
831                 have -= copy;
832                 next += copy;
833                 if (len) goto inf_leave;
834             }
835             else if (state->head != Z_NULL)
836                 state->head->comment = Z_NULL;
837             state->mode = HCRC;
838                 /* fallthrough */
839         case HCRC:
840             if (state->flags & 0x0200) {
841                 NEEDBITS(16);
842                 if ((state->wrap & 4) && hold != (state->check & 0xffff)) {
843                     strm->msg = __UNCONST("header crc mismatch");
844                     state->mode = BAD;
845                     break;
846                 }
847                 INITBITS();
848             }
849             if (state->head != Z_NULL) {
850                 state->head->hcrc = (int)((state->flags >> 9) & 1);
851                 state->head->done = 1;
852             }
853             strm->adler = state->check = crc32(0L, Z_NULL, 0);
854             state->mode = TYPE;
855             break;
856 #endif
857         case DICTID:
858             NEEDBITS(32);
859             strm->adler = state->check = ZSWAP32(hold);
860             INITBITS();
861             state->mode = DICT;
862                 /* fallthrough */
863         case DICT:
864             if (state->havedict == 0) {
865                 RESTORE();
866                 return Z_NEED_DICT;
867             }
868             strm->adler = state->check = adler32(0L, Z_NULL, 0);
869             state->mode = TYPE;
870                 /* fallthrough */
871         case TYPE:
872             if (flush == Z_BLOCK || flush == Z_TREES) goto inf_leave;
873                 /* fallthrough */
874         case TYPEDO:
875             if (state->last) {
876                 BYTEBITS();
877                 state->mode = CHECK;
878                 break;
879             }
880             NEEDBITS(3);
881             state->last = BITS(1);
882             DROPBITS(1);
883             switch (BITS(2)) {
884             case 0:                             /* stored block */
885                 Tracev((stderr, "inflate:     stored block%s\n",
886                         state->last ? " (last)" : ""));
887                 state->mode = STORED;
888                 break;
889             case 1:                             /* fixed block */
890                 fixedtables(state);
891                 Tracev((stderr, "inflate:     fixed codes block%s\n",
892                         state->last ? " (last)" : ""));
893                 state->mode = LEN_;             /* decode codes */
894                 if (flush == Z_TREES) {
895                     DROPBITS(2);
896                     goto inf_leave;
897                 }
898                 break;
899             case 2:                             /* dynamic block */
900                 Tracev((stderr, "inflate:     dynamic codes block%s\n",
901                         state->last ? " (last)" : ""));
902                 state->mode = TABLE;
903                 break;
904             case 3:
905                 strm->msg = __UNCONST("invalid block type");
906                 state->mode = BAD;
907             }
908             DROPBITS(2);
909             break;
910         case STORED:
911             BYTEBITS();                         /* go to byte boundary */
912             NEEDBITS(32);
913             if ((hold & 0xffff) != ((hold >> 16) ^ 0xffff)) {
914                 strm->msg = __UNCONST("invalid stored block lengths");
915                 state->mode = BAD;
916                 break;
917             }
918             state->length = (unsigned)hold & 0xffff;
919             Tracev((stderr, "inflate:       stored length %u\n",
920                     state->length));
921             INITBITS();
922             state->mode = COPY_;
923             if (flush == Z_TREES) goto inf_leave;
924                 /* fallthrough */
925         case COPY_:
926             state->mode = COPY;
927                 /* fallthrough */
928         case COPY:
929             copy = state->length;
930             if (copy) {
931                 if (copy > have) copy = have;
932                 if (copy > left) copy = left;
933                 if (copy == 0) goto inf_leave;
934                 zmemcpy(put, next, copy);
935                 have -= copy;
936                 next += copy;
937                 left -= copy;
938                 put += copy;
939                 state->length -= copy;
940                 break;
941             }
942             Tracev((stderr, "inflate:       stored end\n"));
943             state->mode = TYPE;
944             break;
945         case TABLE:
946             NEEDBITS(14);
947             state->nlen = BITS(5) + 257;
948             DROPBITS(5);
949             state->ndist = BITS(5) + 1;
950             DROPBITS(5);
951             state->ncode = BITS(4) + 4;
952             DROPBITS(4);
953 #ifndef PKZIP_BUG_WORKAROUND
954             if (state->nlen > 286 || state->ndist > 30) {
955                 strm->msg = __UNCONST("too many length or distance symbols");
956                 state->mode = BAD;
957                 break;
958             }
959 #endif
960             Tracev((stderr, "inflate:       table sizes ok\n"));
961             state->have = 0;
962             state->mode = LENLENS;
963                 /* fallthrough */
964         case LENLENS:
965             while (state->have < state->ncode) {
966                 NEEDBITS(3);
967                 state->lens[order[state->have++]] = (unsigned short)BITS(3);
968                 DROPBITS(3);
969             }
970             while (state->have < 19)
971                 state->lens[order[state->have++]] = 0;
972             state->next = state->codes;
973             state->lencode = (const code FAR *)(state->next);
974             state->lenbits = 7;
975             ret = inflate_table(CODES, state->lens, 19, &(state->next),
976                                 &(state->lenbits), state->work);
977             if (ret) {
978                 strm->msg = __UNCONST("invalid code lengths set");
979                 state->mode = BAD;
980                 break;
981             }
982             Tracev((stderr, "inflate:       code lengths ok\n"));
983             state->have = 0;
984             state->mode = CODELENS;
985                 /* fallthrough */
986         case CODELENS:
987             while (state->have < state->nlen + state->ndist) {
988                 for (;;) {
989                     here = state->lencode[BITS(state->lenbits)];
990                     if ((unsigned)(here.bits) <= bits) break;
991                     PULLBYTE();
992                 }
993                 if (here.val < 16) {
994                     DROPBITS(here.bits);
995                     state->lens[state->have++] = here.val;
996                 }
997                 else {
998                     if (here.val == 16) {
999                         NEEDBITS(here.bits + 2);
1000                         DROPBITS(here.bits);
1001                         if (state->have == 0) {
1002                             strm->msg = __UNCONST("invalid bit length repeat");
1003                             state->mode = BAD;
1004                             break;
1005                         }
1006                         len = state->lens[state->have - 1];
1007                         copy = 3 + BITS(2);
1008                         DROPBITS(2);
1009                     }
1010                     else if (here.val == 17) {
1011                         NEEDBITS(here.bits + 3);
1012                         DROPBITS(here.bits);
1013                         len = 0;
1014                         copy = 3 + BITS(3);
1015                         DROPBITS(3);
1016                     }
1017                     else {
1018                         NEEDBITS(here.bits + 7);
1019                         DROPBITS(here.bits);
1020                         len = 0;
1021                         copy = 11 + BITS(7);
1022                         DROPBITS(7);
1023                     }
1024                     if (state->have + copy > state->nlen + state->ndist) {
1025                         strm->msg = __UNCONST("invalid bit length repeat");
1026                         state->mode = BAD;
1027                         break;
1028                     }
1029                     while (copy--)
1030                         state->lens[state->have++] = (unsigned short)len;
1031                 }
1032             }
1033 
1034             /* handle error breaks in while */
1035             if (state->mode == BAD) break;
1036 
1037             /* check for end-of-block code (better have one) */
1038             if (state->lens[256] == 0) {
1039                 strm->msg = __UNCONST("invalid code -- missing end-of-block");
1040                 state->mode = BAD;
1041                 break;
1042             }
1043 
1044             /* build code tables -- note: do not change the lenbits or distbits
1045                values here (9 and 6) without reading the comments in inftrees.h
1046                concerning the ENOUGH constants, which depend on those values */
1047             state->next = state->codes;
1048             state->lencode = (const code FAR *)(state->next);
1049             state->lenbits = 9;
1050             ret = inflate_table(LENS, state->lens, state->nlen, &(state->next),
1051                                 &(state->lenbits), state->work);
1052             if (ret) {
1053                 strm->msg = __UNCONST("invalid literal/lengths set");
1054                 state->mode = BAD;
1055                 break;
1056             }
1057             state->distcode = (const code FAR *)(state->next);
1058             state->distbits = 6;
1059             ret = inflate_table(DISTS, state->lens + state->nlen, state->ndist,
1060                             &(state->next), &(state->distbits), state->work);
1061             if (ret) {
1062                 strm->msg = __UNCONST("invalid distances set");
1063                 state->mode = BAD;
1064                 break;
1065             }
1066             Tracev((stderr, "inflate:       codes ok\n"));
1067             state->mode = LEN_;
1068             if (flush == Z_TREES) goto inf_leave;
1069                 /* fallthrough */
1070         case LEN_:
1071             state->mode = LEN;
1072                 /* fallthrough */
1073         case LEN:
1074             if (have >= 6 && left >= 258) {
1075                 RESTORE();
1076                 inflate_fast(strm, out);
1077                 LOAD();
1078                 if (state->mode == TYPE)
1079                     state->back = -1;
1080                 break;
1081             }
1082             state->back = 0;
1083             for (;;) {
1084                 here = state->lencode[BITS(state->lenbits)];
1085                 if ((unsigned)(here.bits) <= bits) break;
1086                 PULLBYTE();
1087             }
1088             if (here.op && (here.op & 0xf0) == 0) {
1089                 last = here;
1090                 for (;;) {
1091                     here = state->lencode[last.val +
1092                             (BITS(last.bits + last.op) >> last.bits)];
1093                     if ((unsigned)(last.bits + here.bits) <= bits) break;
1094                     PULLBYTE();
1095                 }
1096                 DROPBITS(last.bits);
1097                 state->back += last.bits;
1098             }
1099             DROPBITS(here.bits);
1100             state->back += here.bits;
1101             state->length = (unsigned)here.val;
1102             if ((int)(here.op) == 0) {
1103                 Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
1104                         "inflate:         literal '%c'\n" :
1105                         "inflate:         literal 0x%02x\n", here.val));
1106                 state->mode = LIT;
1107                 break;
1108             }
1109             if (here.op & 32) {
1110                 Tracevv((stderr, "inflate:         end of block\n"));
1111                 state->back = -1;
1112                 state->mode = TYPE;
1113                 break;
1114             }
1115             if (here.op & 64) {
1116                 strm->msg = __UNCONST("invalid literal/length code");
1117                 state->mode = BAD;
1118                 break;
1119             }
1120             state->extra = (unsigned)(here.op) & 15;
1121             state->mode = LENEXT;
1122                 /* fallthrough */
1123         case LENEXT:
1124             if (state->extra) {
1125                 NEEDBITS(state->extra);
1126                 state->length += BITS(state->extra);
1127                 DROPBITS(state->extra);
1128                 state->back += state->extra;
1129             }
1130             Tracevv((stderr, "inflate:         length %u\n", state->length));
1131             state->was = state->length;
1132             state->mode = DIST;
1133                 /* fallthrough */
1134         case DIST:
1135             for (;;) {
1136                 here = state->distcode[BITS(state->distbits)];
1137                 if ((unsigned)(here.bits) <= bits) break;
1138                 PULLBYTE();
1139             }
1140             if ((here.op & 0xf0) == 0) {
1141                 last = here;
1142                 for (;;) {
1143                     here = state->distcode[last.val +
1144                             (BITS(last.bits + last.op) >> last.bits)];
1145                     if ((unsigned)(last.bits + here.bits) <= bits) break;
1146                     PULLBYTE();
1147                 }
1148                 DROPBITS(last.bits);
1149                 state->back += last.bits;
1150             }
1151             DROPBITS(here.bits);
1152             state->back += here.bits;
1153             if (here.op & 64) {
1154                 strm->msg = __UNCONST("invalid distance code");
1155                 state->mode = BAD;
1156                 break;
1157             }
1158             state->offset = (unsigned)here.val;
1159             state->extra = (unsigned)(here.op) & 15;
1160             state->mode = DISTEXT;
1161                 /* fallthrough */
1162         case DISTEXT:
1163             if (state->extra) {
1164                 NEEDBITS(state->extra);
1165                 state->offset += BITS(state->extra);
1166                 DROPBITS(state->extra);
1167                 state->back += state->extra;
1168             }
1169 #ifdef INFLATE_STRICT
1170             if (state->offset > state->dmax) {
1171                 strm->msg = __UNCONST("invalid distance too far back");
1172                 state->mode = BAD;
1173                 break;
1174             }
1175 #endif
1176             Tracevv((stderr, "inflate:         distance %u\n", state->offset));
1177             state->mode = MATCH;
1178                 /* fallthrough */
1179         case MATCH:
1180             if (left == 0) goto inf_leave;
1181             copy = out - left;
1182             if (state->offset > copy) {         /* copy from window */
1183                 copy = state->offset - copy;
1184                 if (copy > state->whave) {
1185                     if (state->sane) {
1186                         strm->msg = __UNCONST("invalid distance too far back");
1187                         state->mode = BAD;
1188                         break;
1189                     }
1190 #ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
1191                     Trace((stderr, "inflate.c too far\n"));
1192                     copy -= state->whave;
1193                     if (copy > state->length) copy = state->length;
1194                     if (copy > left) copy = left;
1195                     left -= copy;
1196                     state->length -= copy;
1197                     do {
1198                         *put++ = 0;
1199                     } while (--copy);
1200                     if (state->length == 0) state->mode = LEN;
1201                     break;
1202 #endif
1203                 }
1204                 if (copy > state->wnext) {
1205                     copy -= state->wnext;
1206                     from = state->window + (state->wsize - copy);
1207                 }
1208                 else
1209                     from = state->window + (state->wnext - copy);
1210                 if (copy > state->length) copy = state->length;
1211             }
1212             else {                              /* copy from output */
1213                 from = put - state->offset;
1214                 copy = state->length;
1215             }
1216             if (copy > left) copy = left;
1217             left -= copy;
1218             state->length -= copy;
1219             do {
1220                 *put++ = *from++;
1221             } while (--copy);
1222             if (state->length == 0) state->mode = LEN;
1223             break;
1224         case LIT:
1225             if (left == 0) goto inf_leave;
1226             *put++ = (unsigned char)(state->length);
1227             left--;
1228             state->mode = LEN;
1229             break;
1230         case CHECK:
1231             if (state->wrap) {
1232                 NEEDBITS(32);
1233                 out -= left;
1234                 strm->total_out += out;
1235                 state->total += out;
1236                 if ((state->wrap & 4) && out)
1237                     strm->adler = state->check =
1238                         UPDATE_CHECK(state->check, put - out, out);
1239                 out = left;
1240                 if ((state->wrap & 4) && (
1241 #ifdef GUNZIP
1242                      state->flags ? hold :
1243 #endif
1244                      ZSWAP32(hold)) != state->check) {
1245                     strm->msg = __UNCONST("incorrect data check");
1246                     state->mode = BAD;
1247                     break;
1248                 }
1249                 INITBITS();
1250                 Tracev((stderr, "inflate:   check matches trailer\n"));
1251             }
1252 #ifdef GUNZIP
1253             state->mode = LENGTH;
1254                 /* fallthrough */
1255         case LENGTH:
1256             if (state->wrap && state->flags) {
1257                 NEEDBITS(32);
1258                 if ((state->wrap & 4) && hold != (state->total & 0xffffffff)) {
1259                     strm->msg = __UNCONST("incorrect length check");
1260                     state->mode = BAD;
1261                     break;
1262                 }
1263                 INITBITS();
1264                 Tracev((stderr, "inflate:   length matches trailer\n"));
1265             }
1266 #endif
1267             state->mode = DONE;
1268                 /* fallthrough */
1269         case DONE:
1270             ret = Z_STREAM_END;
1271             goto inf_leave;
1272         case BAD:
1273             ret = Z_DATA_ERROR;
1274             goto inf_leave;
1275         case MEM:
1276             return Z_MEM_ERROR;
1277         case SYNC:
1278                 /* fallthrough */
1279         default:
1280             return Z_STREAM_ERROR;
1281         }
1282 
1283     /*
1284        Return from inflate(), updating the total counts and the check value.
1285        If there was no progress during the inflate() call, return a buffer
1286        error.  Call updatewindow() to create and/or update the window state.
1287        Note: a memory error from inflate() is non-recoverable.
1288      */
1289   inf_leave:
1290     RESTORE();
1291     if (state->wsize || (out != strm->avail_out && state->mode < BAD &&
1292             (state->mode < CHECK || flush != Z_FINISH)))
1293         if (updatewindow(strm, strm->next_out, out - strm->avail_out)) {
1294             state->mode = MEM;
1295             return Z_MEM_ERROR;
1296         }
1297     in -= strm->avail_in;
1298     out -= strm->avail_out;
1299     strm->total_in += in;
1300     strm->total_out += out;
1301     state->total += out;
1302     if ((state->wrap & 4) && out)
1303         strm->adler = state->check =
1304             UPDATE_CHECK(state->check, strm->next_out - out, out);
1305     strm->data_type = (int)state->bits + (state->last ? 64 : 0) +
1306                       (state->mode == TYPE ? 128 : 0) +
1307                       (state->mode == LEN_ || state->mode == COPY_ ? 256 : 0);
1308     if (((in == 0 && out == 0) || flush == Z_FINISH) && ret == Z_OK)
1309         ret = Z_BUF_ERROR;
1310     return ret;
1311 }
1312 
1313 int ZEXPORT inflateEnd(strm)
1314 z_streamp strm;
1315 {
1316     struct inflate_state FAR *state;
1317     if (inflateStateCheck(strm))
1318         return Z_STREAM_ERROR;
1319     state = (struct inflate_state FAR *)strm->state;
1320     if (state->window != Z_NULL) ZFREE(strm, state->window);
1321     ZFREE(strm, strm->state);
1322     strm->state = Z_NULL;
1323     Tracev((stderr, "inflate: end\n"));
1324     return Z_OK;
1325 }
1326 
1327 int ZEXPORT inflateGetDictionary(strm, dictionary, dictLength)
1328 z_streamp strm;
1329 Bytef *dictionary;
1330 uInt *dictLength;
1331 {
1332     struct inflate_state FAR *state;
1333 
1334     /* check state */
1335     if (inflateStateCheck(strm)) return Z_STREAM_ERROR;
1336     state = (struct inflate_state FAR *)strm->state;
1337 
1338     /* copy dictionary */
1339     if (state->whave && dictionary != Z_NULL) {
1340         zmemcpy(dictionary, state->window + state->wnext,
1341                 state->whave - state->wnext);
1342         zmemcpy(dictionary + state->whave - state->wnext,
1343                 state->window, state->wnext);
1344     }
1345     if (dictLength != Z_NULL)
1346         *dictLength = state->whave;
1347     return Z_OK;
1348 }
1349 
1350 int ZEXPORT inflateSetDictionary(strm, dictionary, dictLength)
1351 z_streamp strm;
1352 const Bytef *dictionary;
1353 uInt dictLength;
1354 {
1355     struct inflate_state FAR *state;
1356     unsigned long dictid;
1357     int ret;
1358 
1359     /* check state */
1360     if (inflateStateCheck(strm)) return Z_STREAM_ERROR;
1361     state = (struct inflate_state FAR *)strm->state;
1362     if (state->wrap != 0 && state->mode != DICT)
1363         return Z_STREAM_ERROR;
1364 
1365     /* check for correct dictionary identifier */
1366     if (state->mode == DICT) {
1367         dictid = adler32(0L, Z_NULL, 0);
1368         dictid = adler32(dictid, dictionary, dictLength);
1369         if (dictid != state->check)
1370             return Z_DATA_ERROR;
1371     }
1372 
1373     /* copy dictionary to window using updatewindow(), which will amend the
1374        existing dictionary if appropriate */
1375     ret = updatewindow(strm, dictionary + dictLength, dictLength);
1376     if (ret) {
1377         state->mode = MEM;
1378         return Z_MEM_ERROR;
1379     }
1380     state->havedict = 1;
1381     Tracev((stderr, "inflate:   dictionary set\n"));
1382     return Z_OK;
1383 }
1384 
1385 int ZEXPORT inflateGetHeader(strm, head)
1386 z_streamp strm;
1387 gz_headerp head;
1388 {
1389     struct inflate_state FAR *state;
1390 
1391     /* check state */
1392     if (inflateStateCheck(strm)) return Z_STREAM_ERROR;
1393     state = (struct inflate_state FAR *)strm->state;
1394     if ((state->wrap & 2) == 0) return Z_STREAM_ERROR;
1395 
1396     /* save header structure */
1397     state->head = head;
1398     head->done = 0;
1399     return Z_OK;
1400 }
1401 
1402 /*
1403    Search buf[0..len-1] for the pattern: 0, 0, 0xff, 0xff.  Return when found
1404    or when out of input.  When called, *have is the number of pattern bytes
1405    found in order so far, in 0..3.  On return *have is updated to the new
1406    state.  If on return *have equals four, then the pattern was found and the
1407    return value is how many bytes were read including the last byte of the
1408    pattern.  If *have is less than four, then the pattern has not been found
1409    yet and the return value is len.  In the latter case, syncsearch() can be
1410    called again with more data and the *have state.  *have is initialized to
1411    zero for the first call.
1412  */
1413 local unsigned syncsearch(have, buf, len)
1414 unsigned FAR *have;
1415 const unsigned char FAR *buf;
1416 unsigned len;
1417 {
1418     unsigned got;
1419     unsigned next;
1420 
1421     got = *have;
1422     next = 0;
1423     while (next < len && got < 4) {
1424         if ((int)(buf[next]) == (got < 2 ? 0 : 0xff))
1425             got++;
1426         else if (buf[next])
1427             got = 0;
1428         else
1429             got = 4 - got;
1430         next++;
1431     }
1432     *have = got;
1433     return next;
1434 }
1435 
1436 int ZEXPORT inflateSync(strm)
1437 z_streamp strm;
1438 {
1439     unsigned len;               /* number of bytes to look at or looked at */
1440     int flags;                  /* temporary to save header status */
1441     unsigned long in, out;      /* temporary to save total_in and total_out */
1442     unsigned char buf[4];       /* to restore bit buffer to byte string */
1443     struct inflate_state FAR *state;
1444 
1445     /* check parameters */
1446     if (inflateStateCheck(strm)) return Z_STREAM_ERROR;
1447     state = (struct inflate_state FAR *)strm->state;
1448     if (strm->avail_in == 0 && state->bits < 8) return Z_BUF_ERROR;
1449 
1450     /* if first time, start search in bit buffer */
1451     if (state->mode != SYNC) {
1452         state->mode = SYNC;
1453         state->hold <<= state->bits & 7;
1454         state->bits -= state->bits & 7;
1455         len = 0;
1456         while (state->bits >= 8) {
1457             buf[len++] = (unsigned char)(state->hold);
1458             state->hold >>= 8;
1459             state->bits -= 8;
1460         }
1461         state->have = 0;
1462         syncsearch(&(state->have), buf, len);
1463     }
1464 
1465     /* search available input */
1466     len = syncsearch(&(state->have), strm->next_in, strm->avail_in);
1467     strm->avail_in -= len;
1468     strm->next_in += len;
1469     strm->total_in += len;
1470 
1471     /* return no joy or set up to restart inflate() on a new block */
1472     if (state->have != 4) return Z_DATA_ERROR;
1473     if (state->flags == -1)
1474         state->wrap = 0;    /* if no header yet, treat as raw */
1475     else
1476         state->wrap &= ~4;  /* no point in computing a check value now */
1477     flags = state->flags;
1478     in = strm->total_in;  out = strm->total_out;
1479     inflateReset(strm);
1480     strm->total_in = in;  strm->total_out = out;
1481     state->flags = flags;
1482     state->mode = TYPE;
1483     return Z_OK;
1484 }
1485 
1486 /*
1487    Returns true if inflate is currently at the end of a block generated by
1488    Z_SYNC_FLUSH or Z_FULL_FLUSH. This function is used by one PPP
1489    implementation to provide an additional safety check. PPP uses
1490    Z_SYNC_FLUSH but removes the length bytes of the resulting empty stored
1491    block. When decompressing, PPP checks that at the end of input packet,
1492    inflate is waiting for these length bytes.
1493  */
1494 int ZEXPORT inflateSyncPoint(strm)
1495 z_streamp strm;
1496 {
1497     struct inflate_state FAR *state;
1498 
1499     if (inflateStateCheck(strm)) return Z_STREAM_ERROR;
1500     state = (struct inflate_state FAR *)strm->state;
1501     return state->mode == STORED && state->bits == 0;
1502 }
1503 
1504 int ZEXPORT inflateCopy(dest, source)
1505 z_streamp dest;
1506 z_streamp source;
1507 {
1508     struct inflate_state FAR *state;
1509     struct inflate_state FAR *copy;
1510     unsigned char FAR *window;
1511     unsigned wsize;
1512 
1513     /* check input */
1514     if (inflateStateCheck(source) || dest == Z_NULL)
1515         return Z_STREAM_ERROR;
1516     state = (struct inflate_state FAR *)source->state;
1517 
1518     /* allocate space */
1519     copy = (struct inflate_state FAR *)
1520            ZALLOC(source, 1, sizeof(struct inflate_state));
1521     if (copy == Z_NULL) return Z_MEM_ERROR;
1522     window = Z_NULL;
1523     if (state->window != Z_NULL) {
1524         window = (unsigned char FAR *)
1525                  ZALLOC(source, 1U << state->wbits, sizeof(unsigned char));
1526         if (window == Z_NULL) {
1527             ZFREE(source, copy);
1528             return Z_MEM_ERROR;
1529         }
1530     }
1531 
1532     /* copy state */
1533     zmemcpy((voidpf)dest, (voidpf)source, sizeof(z_stream));
1534     zmemcpy((voidpf)copy, (voidpf)state, sizeof(struct inflate_state));
1535     copy->strm = dest;
1536     if (state->lencode >= state->codes &&
1537         state->lencode <= state->codes + ENOUGH - 1) {
1538         copy->lencode = copy->codes + (state->lencode - state->codes);
1539         copy->distcode = copy->codes + (state->distcode - state->codes);
1540     }
1541     copy->next = copy->codes + (state->next - state->codes);
1542     if (window != Z_NULL) {
1543         wsize = 1U << state->wbits;
1544         zmemcpy(window, state->window, wsize);
1545     }
1546     copy->window = window;
1547     dest->state = (struct internal_state FAR *)copy;
1548     return Z_OK;
1549 }
1550 
1551 int ZEXPORT inflateUndermine(strm, subvert)
1552 z_streamp strm;
1553 int subvert;
1554 {
1555     struct inflate_state FAR *state;
1556 
1557     if (inflateStateCheck(strm)) return Z_STREAM_ERROR;
1558     state = (struct inflate_state FAR *)strm->state;
1559 #ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
1560     state->sane = !subvert;
1561     return Z_OK;
1562 #else
1563     (void)subvert;
1564     state->sane = 1;
1565     return Z_DATA_ERROR;
1566 #endif
1567 }
1568 
1569 int ZEXPORT inflateValidate(strm, check)
1570 z_streamp strm;
1571 int check;
1572 {
1573     struct inflate_state FAR *state;
1574 
1575     if (inflateStateCheck(strm)) return Z_STREAM_ERROR;
1576     state = (struct inflate_state FAR *)strm->state;
1577     if (check && state->wrap)
1578         state->wrap |= 4;
1579     else
1580         state->wrap &= ~4;
1581     return Z_OK;
1582 }
1583 
1584 long ZEXPORT inflateMark(strm)
1585 z_streamp strm;
1586 {
1587     struct inflate_state FAR *state;
1588 
1589     if (inflateStateCheck(strm))
1590         return -(1L << 16);
1591     state = (struct inflate_state FAR *)strm->state;
1592     return (long)(((unsigned long)((long)state->back)) << 16) +
1593         (state->mode == COPY ? state->length :
1594             (state->mode == MATCH ? state->was - state->length : 0));
1595 }
1596 
1597 unsigned long ZEXPORT inflateCodesUsed(strm)
1598 z_streamp strm;
1599 {
1600     struct inflate_state FAR *state;
1601     if (inflateStateCheck(strm)) return (unsigned long)-1;
1602     state = (struct inflate_state FAR *)strm->state;
1603     return (unsigned long)(state->next - state->codes);
1604 }
1605