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