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