xref: /illumos-gate/usr/src/contrib/zlib/inflate.c (revision 2e401bab)
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 
inflateStateCheck(z_streamp strm)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 
inflateResetKeep(z_streamp strm)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 
inflateReset(z_streamp strm)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 
inflateReset2(z_streamp strm,int windowBits)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 
inflateInit2_(z_streamp strm,int windowBits,const char * version,int stream_size)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 
inflateInit_(z_streamp strm,const char * version,int stream_size)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 
inflatePrime(z_streamp strm,int bits,int value)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  */
fixedtables(struct inflate_state FAR * state)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  */
makefixed(void)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  */
updatewindow(z_streamp strm,const Bytef * end,unsigned copy)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 
inflate(z_streamp strm,int flush)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                             state->head->extra_max) {
750                         zmemcpy(state->head->extra + len, next,
751                                 len + copy > state->head->extra_max ?
752                                 state->head->extra_max - len : copy);
753                     }
754                     if ((state->flags & 0x0200) && (state->wrap & 4))
755                         state->check = crc32(state->check, next, copy);
756                     have -= copy;
757                     next += copy;
758                     state->length -= copy;
759                 }
760                 if (state->length) goto inf_leave;
761             }
762             state->length = 0;
763             state->mode = NAME;
764 	    /* FALLTHROUGH */
765         case NAME:
766             if (state->flags & 0x0800) {
767                 if (have == 0) goto inf_leave;
768                 copy = 0;
769                 do {
770                     len = (unsigned)(next[copy++]);
771                     if (state->head != Z_NULL &&
772                             state->head->name != Z_NULL &&
773                             state->length < state->head->name_max)
774                         state->head->name[state->length++] = (Bytef)len;
775                 } while (len && copy < have);
776                 if ((state->flags & 0x0200) && (state->wrap & 4))
777                     state->check = crc32(state->check, next, copy);
778                 have -= copy;
779                 next += copy;
780                 if (len) goto inf_leave;
781             }
782             else if (state->head != Z_NULL)
783                 state->head->name = Z_NULL;
784             state->length = 0;
785             state->mode = COMMENT;
786 	    /* FALLTHROUGH */
787         case COMMENT:
788             if (state->flags & 0x1000) {
789                 if (have == 0) goto inf_leave;
790                 copy = 0;
791                 do {
792                     len = (unsigned)(next[copy++]);
793                     if (state->head != Z_NULL &&
794                             state->head->comment != Z_NULL &&
795                             state->length < state->head->comm_max)
796                         state->head->comment[state->length++] = (Bytef)len;
797                 } while (len && copy < have);
798                 if ((state->flags & 0x0200) && (state->wrap & 4))
799                     state->check = crc32(state->check, next, copy);
800                 have -= copy;
801                 next += copy;
802                 if (len) goto inf_leave;
803             }
804             else if (state->head != Z_NULL)
805                 state->head->comment = Z_NULL;
806             state->mode = HCRC;
807 	    /* FALLTHROUGH */
808         case HCRC:
809             if (state->flags & 0x0200) {
810                 NEEDBITS(16);
811                 if ((state->wrap & 4) && hold != (state->check & 0xffff)) {
812                     strm->msg = (char *)"header crc mismatch";
813                     state->mode = BAD;
814                     break;
815                 }
816                 INITBITS();
817             }
818             if (state->head != Z_NULL) {
819                 state->head->hcrc = (int)((state->flags >> 9) & 1);
820                 state->head->done = 1;
821             }
822             strm->adler = state->check = crc32(0L, Z_NULL, 0);
823             state->mode = TYPE;
824             break;
825 #endif
826         case DICTID:
827             NEEDBITS(32);
828             strm->adler = state->check = ZSWAP32(hold);
829             INITBITS();
830             state->mode = DICT;
831 	    /* FALLTHROUGH */
832         case DICT:
833             if (state->havedict == 0) {
834                 RESTORE();
835                 return Z_NEED_DICT;
836             }
837             strm->adler = state->check = adler32(0L, Z_NULL, 0);
838             state->mode = TYPE;
839 	    /* FALLTHROUGH */
840         case TYPE:
841             if (flush == Z_BLOCK || flush == Z_TREES) goto inf_leave;
842 	    /* FALLTHROUGH */
843         case TYPEDO:
844             if (state->last) {
845                 BYTEBITS();
846                 state->mode = CHECK;
847                 break;
848             }
849             NEEDBITS(3);
850             state->last = BITS(1);
851             DROPBITS(1);
852             switch (BITS(2)) {
853             case 0:                             /* stored block */
854                 Tracev((stderr, "inflate:     stored block%s\n",
855                         state->last ? " (last)" : ""));
856                 state->mode = STORED;
857                 break;
858             case 1:                             /* fixed block */
859                 fixedtables(state);
860                 Tracev((stderr, "inflate:     fixed codes block%s\n",
861                         state->last ? " (last)" : ""));
862                 state->mode = LEN_;             /* decode codes */
863                 if (flush == Z_TREES) {
864                     DROPBITS(2);
865                     goto inf_leave;
866                 }
867                 break;
868             case 2:                             /* dynamic block */
869                 Tracev((stderr, "inflate:     dynamic codes block%s\n",
870                         state->last ? " (last)" : ""));
871                 state->mode = TABLE;
872                 break;
873             case 3:
874                 strm->msg = (char *)"invalid block type";
875                 state->mode = BAD;
876             }
877             DROPBITS(2);
878             break;
879         case STORED:
880             BYTEBITS();                         /* go to byte boundary */
881             NEEDBITS(32);
882             if ((hold & 0xffff) != ((hold >> 16) ^ 0xffff)) {
883                 strm->msg = (char *)"invalid stored block lengths";
884                 state->mode = BAD;
885                 break;
886             }
887             state->length = (unsigned)hold & 0xffff;
888             Tracev((stderr, "inflate:       stored length %u\n",
889                     state->length));
890             INITBITS();
891             state->mode = COPY_;
892             if (flush == Z_TREES) goto inf_leave;
893 	    /* FALLTHROUGH */
894         case COPY_:
895             state->mode = COPY;
896 	    /* FALLTHROUGH */
897         case COPY:
898             copy = state->length;
899             if (copy) {
900                 if (copy > have) copy = have;
901                 if (copy > left) copy = left;
902                 if (copy == 0) goto inf_leave;
903                 zmemcpy(put, next, copy);
904                 have -= copy;
905                 next += copy;
906                 left -= copy;
907                 put += copy;
908                 state->length -= copy;
909                 break;
910             }
911             Tracev((stderr, "inflate:       stored end\n"));
912             state->mode = TYPE;
913             break;
914         case TABLE:
915             NEEDBITS(14);
916             state->nlen = BITS(5) + 257;
917             DROPBITS(5);
918             state->ndist = BITS(5) + 1;
919             DROPBITS(5);
920             state->ncode = BITS(4) + 4;
921             DROPBITS(4);
922 #ifndef PKZIP_BUG_WORKAROUND
923             if (state->nlen > 286 || state->ndist > 30) {
924                 strm->msg = (char *)"too many length or distance symbols";
925                 state->mode = BAD;
926                 break;
927             }
928 #endif
929             Tracev((stderr, "inflate:       table sizes ok\n"));
930             state->have = 0;
931             state->mode = LENLENS;
932                 /* fallthrough */
933         case LENLENS:
934             while (state->have < state->ncode) {
935                 NEEDBITS(3);
936                 state->lens[order[state->have++]] = (unsigned short)BITS(3);
937                 DROPBITS(3);
938             }
939             while (state->have < 19)
940                 state->lens[order[state->have++]] = 0;
941             state->next = state->codes;
942             state->lencode = (const code FAR *)(state->next);
943             state->lenbits = 7;
944             ret = inflate_table(CODES, state->lens, 19, &(state->next),
945                                 &(state->lenbits), state->work);
946             if (ret) {
947                 strm->msg = (char *)"invalid code lengths set";
948                 state->mode = BAD;
949                 break;
950             }
951             Tracev((stderr, "inflate:       code lengths ok\n"));
952             state->have = 0;
953             state->mode = CODELENS;
954                 /* fallthrough */
955         case CODELENS:
956             while (state->have < state->nlen + state->ndist) {
957                 for (;;) {
958                     here = state->lencode[BITS(state->lenbits)];
959                     if ((unsigned)(here.bits) <= bits) break;
960                     PULLBYTE();
961                 }
962                 if (here.val < 16) {
963                     DROPBITS(here.bits);
964                     state->lens[state->have++] = here.val;
965                 }
966                 else {
967                     if (here.val == 16) {
968                         NEEDBITS(here.bits + 2);
969                         DROPBITS(here.bits);
970                         if (state->have == 0) {
971                             strm->msg = (char *)"invalid bit length repeat";
972                             state->mode = BAD;
973                             break;
974                         }
975                         len = state->lens[state->have - 1];
976                         copy = 3 + BITS(2);
977                         DROPBITS(2);
978                     }
979                     else if (here.val == 17) {
980                         NEEDBITS(here.bits + 3);
981                         DROPBITS(here.bits);
982                         len = 0;
983                         copy = 3 + BITS(3);
984                         DROPBITS(3);
985                     }
986                     else {
987                         NEEDBITS(here.bits + 7);
988                         DROPBITS(here.bits);
989                         len = 0;
990                         copy = 11 + BITS(7);
991                         DROPBITS(7);
992                     }
993                     if (state->have + copy > state->nlen + state->ndist) {
994                         strm->msg = (char *)"invalid bit length repeat";
995                         state->mode = BAD;
996                         break;
997                     }
998                     while (copy--)
999                         state->lens[state->have++] = (unsigned short)len;
1000                 }
1001             }
1002 
1003             /* handle error breaks in while */
1004             if (state->mode == BAD) break;
1005 
1006             /* check for end-of-block code (better have one) */
1007             if (state->lens[256] == 0) {
1008                 strm->msg = (char *)"invalid code -- missing end-of-block";
1009                 state->mode = BAD;
1010                 break;
1011             }
1012 
1013             /* build code tables -- note: do not change the lenbits or distbits
1014                values here (9 and 6) without reading the comments in inftrees.h
1015                concerning the ENOUGH constants, which depend on those values */
1016             state->next = state->codes;
1017             state->lencode = (const code FAR *)(state->next);
1018             state->lenbits = 9;
1019             ret = inflate_table(LENS, state->lens, state->nlen, &(state->next),
1020                                 &(state->lenbits), state->work);
1021             if (ret) {
1022                 strm->msg = (char *)"invalid literal/lengths set";
1023                 state->mode = BAD;
1024                 break;
1025             }
1026             state->distcode = (const code FAR *)(state->next);
1027             state->distbits = 6;
1028             ret = inflate_table(DISTS, state->lens + state->nlen, state->ndist,
1029                             &(state->next), &(state->distbits), state->work);
1030             if (ret) {
1031                 strm->msg = (char *)"invalid distances set";
1032                 state->mode = BAD;
1033                 break;
1034             }
1035             Tracev((stderr, "inflate:       codes ok\n"));
1036             state->mode = LEN_;
1037             if (flush == Z_TREES) goto inf_leave;
1038 	    /* FALLTHROUGH */
1039         case LEN_:
1040             state->mode = LEN;
1041 	    /* FALLTHROUGH */
1042         case LEN:
1043             if (have >= 6 && left >= 258) {
1044                 RESTORE();
1045                 inflate_fast(strm, out);
1046                 LOAD();
1047                 if (state->mode == TYPE)
1048                     state->back = -1;
1049                 break;
1050             }
1051             state->back = 0;
1052             for (;;) {
1053                 here = state->lencode[BITS(state->lenbits)];
1054                 if ((unsigned)(here.bits) <= bits) break;
1055                 PULLBYTE();
1056             }
1057             if (here.op && (here.op & 0xf0) == 0) {
1058                 last = here;
1059                 for (;;) {
1060                     here = state->lencode[last.val +
1061                             (BITS(last.bits + last.op) >> last.bits)];
1062                     if ((unsigned)(last.bits + here.bits) <= bits) break;
1063                     PULLBYTE();
1064                 }
1065                 DROPBITS(last.bits);
1066                 state->back += last.bits;
1067             }
1068             DROPBITS(here.bits);
1069             state->back += here.bits;
1070             state->length = (unsigned)here.val;
1071             if ((int)(here.op) == 0) {
1072                 Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
1073                         "inflate:         literal '%c'\n" :
1074                         "inflate:         literal 0x%02x\n", here.val));
1075                 state->mode = LIT;
1076                 break;
1077             }
1078             if (here.op & 32) {
1079                 Tracevv((stderr, "inflate:         end of block\n"));
1080                 state->back = -1;
1081                 state->mode = TYPE;
1082                 break;
1083             }
1084             if (here.op & 64) {
1085                 strm->msg = (char *)"invalid literal/length code";
1086                 state->mode = BAD;
1087                 break;
1088             }
1089             state->extra = (unsigned)(here.op) & 15;
1090             state->mode = LENEXT;
1091 	    /* FALLTHROUGH */
1092         case LENEXT:
1093             if (state->extra) {
1094                 NEEDBITS(state->extra);
1095                 state->length += BITS(state->extra);
1096                 DROPBITS(state->extra);
1097                 state->back += state->extra;
1098             }
1099             Tracevv((stderr, "inflate:         length %u\n", state->length));
1100             state->was = state->length;
1101             state->mode = DIST;
1102 	    /* FALLTHROUGH */
1103         case DIST:
1104             for (;;) {
1105                 here = state->distcode[BITS(state->distbits)];
1106                 if ((unsigned)(here.bits) <= bits) break;
1107                 PULLBYTE();
1108             }
1109             if ((here.op & 0xf0) == 0) {
1110                 last = here;
1111                 for (;;) {
1112                     here = state->distcode[last.val +
1113                             (BITS(last.bits + last.op) >> last.bits)];
1114                     if ((unsigned)(last.bits + here.bits) <= bits) break;
1115                     PULLBYTE();
1116                 }
1117                 DROPBITS(last.bits);
1118                 state->back += last.bits;
1119             }
1120             DROPBITS(here.bits);
1121             state->back += here.bits;
1122             if (here.op & 64) {
1123                 strm->msg = (char *)"invalid distance code";
1124                 state->mode = BAD;
1125                 break;
1126             }
1127             state->offset = (unsigned)here.val;
1128             state->extra = (unsigned)(here.op) & 15;
1129             state->mode = DISTEXT;
1130 	    /* FALLTHROUGH */
1131         case DISTEXT:
1132             if (state->extra) {
1133                 NEEDBITS(state->extra);
1134                 state->offset += BITS(state->extra);
1135                 DROPBITS(state->extra);
1136                 state->back += state->extra;
1137             }
1138 #ifdef INFLATE_STRICT
1139             if (state->offset > state->dmax) {
1140                 strm->msg = (char *)"invalid distance too far back";
1141                 state->mode = BAD;
1142                 break;
1143             }
1144 #endif
1145             Tracevv((stderr, "inflate:         distance %u\n", state->offset));
1146             state->mode = MATCH;
1147 	    /* FALLTHROUGH */
1148         case MATCH:
1149             if (left == 0) goto inf_leave;
1150             copy = out - left;
1151             if (state->offset > copy) {         /* copy from window */
1152                 copy = state->offset - copy;
1153                 if (copy > state->whave) {
1154                     if (state->sane) {
1155                         strm->msg = (char *)"invalid distance too far back";
1156                         state->mode = BAD;
1157                         break;
1158                     }
1159 #ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
1160                     Trace((stderr, "inflate.c too far\n"));
1161                     copy -= state->whave;
1162                     if (copy > state->length) copy = state->length;
1163                     if (copy > left) copy = left;
1164                     left -= copy;
1165                     state->length -= copy;
1166                     do {
1167                         *put++ = 0;
1168                     } while (--copy);
1169                     if (state->length == 0) state->mode = LEN;
1170                     break;
1171 #endif
1172                 }
1173                 if (copy > state->wnext) {
1174                     copy -= state->wnext;
1175                     from = state->window + (state->wsize - copy);
1176                 }
1177                 else
1178                     from = state->window + (state->wnext - copy);
1179                 if (copy > state->length) copy = state->length;
1180             }
1181             else {                              /* copy from output */
1182                 from = put - state->offset;
1183                 copy = state->length;
1184             }
1185             if (copy > left) copy = left;
1186             left -= copy;
1187             state->length -= copy;
1188             do {
1189                 *put++ = *from++;
1190             } while (--copy);
1191             if (state->length == 0) state->mode = LEN;
1192             break;
1193         case LIT:
1194             if (left == 0) goto inf_leave;
1195             *put++ = (unsigned char)(state->length);
1196             left--;
1197             state->mode = LEN;
1198             break;
1199         case CHECK:
1200             if (state->wrap) {
1201                 NEEDBITS(32);
1202                 out -= left;
1203                 strm->total_out += out;
1204                 state->total += out;
1205                 if ((state->wrap & 4) && out)
1206                     strm->adler = state->check =
1207                         UPDATE_CHECK(state->check, put - out, out);
1208                 out = left;
1209                 if ((state->wrap & 4) && (
1210 #ifdef GUNZIP
1211                      state->flags ? hold :
1212 #endif
1213                      ZSWAP32(hold)) != state->check) {
1214                     strm->msg = (char *)"incorrect data check";
1215                     state->mode = BAD;
1216                     break;
1217                 }
1218                 INITBITS();
1219                 Tracev((stderr, "inflate:   check matches trailer\n"));
1220             }
1221 #ifdef GUNZIP
1222             state->mode = LENGTH;
1223 	    /* FALLTHROUGH */
1224         case LENGTH:
1225             if (state->wrap && state->flags) {
1226                 NEEDBITS(32);
1227                 if ((state->wrap & 4) && hold != (state->total & 0xffffffff)) {
1228                     strm->msg = (char *)"incorrect length check";
1229                     state->mode = BAD;
1230                     break;
1231                 }
1232                 INITBITS();
1233                 Tracev((stderr, "inflate:   length matches trailer\n"));
1234             }
1235 #endif
1236             state->mode = DONE;
1237 	    /* FALLTHROUGH */
1238         case DONE:
1239             ret = Z_STREAM_END;
1240             goto inf_leave;
1241         case BAD:
1242             ret = Z_DATA_ERROR;
1243             goto inf_leave;
1244         case MEM:
1245             return Z_MEM_ERROR;
1246         case SYNC:
1247                 /* fallthrough */
1248         default:
1249             return Z_STREAM_ERROR;
1250         }
1251 
1252     /*
1253        Return from inflate(), updating the total counts and the check value.
1254        If there was no progress during the inflate() call, return a buffer
1255        error.  Call updatewindow() to create and/or update the window state.
1256        Note: a memory error from inflate() is non-recoverable.
1257      */
1258   inf_leave:
1259     RESTORE();
1260     if (state->wsize || (out != strm->avail_out && state->mode < BAD &&
1261             (state->mode < CHECK || flush != Z_FINISH)))
1262         if (updatewindow(strm, strm->next_out, out - strm->avail_out)) {
1263             state->mode = MEM;
1264             return Z_MEM_ERROR;
1265         }
1266     in -= strm->avail_in;
1267     out -= strm->avail_out;
1268     strm->total_in += in;
1269     strm->total_out += out;
1270     state->total += out;
1271     if ((state->wrap & 4) && out)
1272         strm->adler = state->check =
1273             UPDATE_CHECK(state->check, strm->next_out - out, out);
1274     strm->data_type = (int)state->bits + (state->last ? 64 : 0) +
1275                       (state->mode == TYPE ? 128 : 0) +
1276                       (state->mode == LEN_ || state->mode == COPY_ ? 256 : 0);
1277     if (((in == 0 && out == 0) || flush == Z_FINISH) && ret == Z_OK)
1278         ret = Z_BUF_ERROR;
1279     return ret;
1280 }
1281 
inflateEnd(z_streamp strm)1282 int ZEXPORT inflateEnd(z_streamp strm)
1283 {
1284     struct inflate_state FAR *state;
1285     if (inflateStateCheck(strm))
1286         return Z_STREAM_ERROR;
1287     state = (struct inflate_state FAR *)strm->state;
1288     if (state->window != Z_NULL) ZFREE(strm, state->window);
1289     ZFREE(strm, strm->state);
1290     strm->state = Z_NULL;
1291     Tracev((stderr, "inflate: end\n"));
1292     return Z_OK;
1293 }
1294 
inflateGetDictionary(z_streamp strm,Bytef * dictionary,uInt * dictLength)1295 int ZEXPORT inflateGetDictionary(z_streamp strm, Bytef *dictionary,
1296     uInt *dictLength)
1297 {
1298     struct inflate_state FAR *state;
1299 
1300     /* check state */
1301     if (inflateStateCheck(strm)) return Z_STREAM_ERROR;
1302     state = (struct inflate_state FAR *)strm->state;
1303 
1304     /* copy dictionary */
1305     if (state->whave && dictionary != Z_NULL) {
1306         zmemcpy(dictionary, state->window + state->wnext,
1307                 state->whave - state->wnext);
1308         zmemcpy(dictionary + state->whave - state->wnext,
1309                 state->window, state->wnext);
1310     }
1311     if (dictLength != Z_NULL)
1312         *dictLength = state->whave;
1313     return Z_OK;
1314 }
1315 
inflateSetDictionary(z_streamp strm,const Bytef * dictionary,uInt dictLength)1316 int ZEXPORT inflateSetDictionary(z_streamp strm, const Bytef *dictionary,
1317     uInt dictLength)
1318 {
1319     struct inflate_state FAR *state;
1320     unsigned long dictid;
1321     int ret;
1322 
1323     /* check state */
1324     if (inflateStateCheck(strm)) return Z_STREAM_ERROR;
1325     state = (struct inflate_state FAR *)strm->state;
1326     if (state->wrap != 0 && state->mode != DICT)
1327         return Z_STREAM_ERROR;
1328 
1329     /* check for correct dictionary identifier */
1330     if (state->mode == DICT) {
1331         dictid = adler32(0L, Z_NULL, 0);
1332         dictid = adler32(dictid, dictionary, dictLength);
1333         if (dictid != state->check)
1334             return Z_DATA_ERROR;
1335     }
1336 
1337     /* copy dictionary to window using updatewindow(), which will amend the
1338        existing dictionary if appropriate */
1339     ret = updatewindow(strm, dictionary + dictLength, dictLength);
1340     if (ret) {
1341         state->mode = MEM;
1342         return Z_MEM_ERROR;
1343     }
1344     state->havedict = 1;
1345     Tracev((stderr, "inflate:   dictionary set\n"));
1346     return Z_OK;
1347 }
1348 
inflateGetHeader(z_streamp strm,gz_headerp head)1349 int ZEXPORT inflateGetHeader(z_streamp strm, gz_headerp head)
1350 {
1351     struct inflate_state FAR *state;
1352 
1353     /* check state */
1354     if (inflateStateCheck(strm)) return Z_STREAM_ERROR;
1355     state = (struct inflate_state FAR *)strm->state;
1356     if ((state->wrap & 2) == 0) return Z_STREAM_ERROR;
1357 
1358     /* save header structure */
1359     state->head = head;
1360     head->done = 0;
1361     return Z_OK;
1362 }
1363 
1364 /*
1365    Search buf[0..len-1] for the pattern: 0, 0, 0xff, 0xff.  Return when found
1366    or when out of input.  When called, *have is the number of pattern bytes
1367    found in order so far, in 0..3.  On return *have is updated to the new
1368    state.  If on return *have equals four, then the pattern was found and the
1369    return value is how many bytes were read including the last byte of the
1370    pattern.  If *have is less than four, then the pattern has not been found
1371    yet and the return value is len.  In the latter case, syncsearch() can be
1372    called again with more data and the *have state.  *have is initialized to
1373    zero for the first call.
1374  */
syncsearch(unsigned FAR * have,const unsigned char FAR * buf,unsigned len)1375 local unsigned syncsearch(unsigned FAR *have, const unsigned char FAR *buf,
1376     unsigned len)
1377 {
1378     unsigned got;
1379     unsigned next;
1380 
1381     got = *have;
1382     next = 0;
1383     while (next < len && got < 4) {
1384         if ((int)(buf[next]) == (got < 2 ? 0 : 0xff))
1385             got++;
1386         else if (buf[next])
1387             got = 0;
1388         else
1389             got = 4 - got;
1390         next++;
1391     }
1392     *have = got;
1393     return next;
1394 }
1395 
inflateSync(z_streamp strm)1396 int ZEXPORT inflateSync(z_streamp strm)
1397 {
1398     unsigned len;               /* number of bytes to look at or looked at */
1399     int flags;                  /* temporary to save header status */
1400     unsigned long in, out;      /* temporary to save total_in and total_out */
1401     unsigned char buf[4];       /* to restore bit buffer to byte string */
1402     struct inflate_state FAR *state;
1403 
1404     /* check parameters */
1405     if (inflateStateCheck(strm)) return Z_STREAM_ERROR;
1406     state = (struct inflate_state FAR *)strm->state;
1407     if (strm->avail_in == 0 && state->bits < 8) return Z_BUF_ERROR;
1408 
1409     /* if first time, start search in bit buffer */
1410     if (state->mode != SYNC) {
1411         state->mode = SYNC;
1412         state->hold <<= state->bits & 7;
1413         state->bits -= state->bits & 7;
1414         len = 0;
1415         while (state->bits >= 8) {
1416             buf[len++] = (unsigned char)(state->hold);
1417             state->hold >>= 8;
1418             state->bits -= 8;
1419         }
1420         state->have = 0;
1421         syncsearch(&(state->have), buf, len);
1422     }
1423 
1424     /* search available input */
1425     len = syncsearch(&(state->have), strm->next_in, strm->avail_in);
1426     strm->avail_in -= len;
1427     strm->next_in += len;
1428     strm->total_in += len;
1429 
1430     /* return no joy or set up to restart inflate() on a new block */
1431     if (state->have != 4) return Z_DATA_ERROR;
1432     if (state->flags == -1)
1433         state->wrap = 0;    /* if no header yet, treat as raw */
1434     else
1435         state->wrap &= ~4;  /* no point in computing a check value now */
1436     flags = state->flags;
1437     in = strm->total_in;  out = strm->total_out;
1438     inflateReset(strm);
1439     strm->total_in = in;  strm->total_out = out;
1440     state->flags = flags;
1441     state->mode = TYPE;
1442     return Z_OK;
1443 }
1444 
1445 /*
1446    Returns true if inflate is currently at the end of a block generated by
1447    Z_SYNC_FLUSH or Z_FULL_FLUSH. This function is used by one PPP
1448    implementation to provide an additional safety check. PPP uses
1449    Z_SYNC_FLUSH but removes the length bytes of the resulting empty stored
1450    block. When decompressing, PPP checks that at the end of input packet,
1451    inflate is waiting for these length bytes.
1452  */
inflateSyncPoint(z_streamp strm)1453 int ZEXPORT inflateSyncPoint(z_streamp strm)
1454 {
1455     struct inflate_state FAR *state;
1456 
1457     if (inflateStateCheck(strm)) return Z_STREAM_ERROR;
1458     state = (struct inflate_state FAR *)strm->state;
1459     return state->mode == STORED && state->bits == 0;
1460 }
1461 
inflateCopy(z_streamp dest,z_streamp source)1462 int ZEXPORT inflateCopy(z_streamp dest, z_streamp source)
1463 {
1464     struct inflate_state FAR *state;
1465     struct inflate_state FAR *copy;
1466     unsigned char FAR *window;
1467     unsigned wsize;
1468 
1469     /* check input */
1470     if (inflateStateCheck(source) || dest == Z_NULL)
1471         return Z_STREAM_ERROR;
1472     state = (struct inflate_state FAR *)source->state;
1473 
1474     /* allocate space */
1475     copy = (struct inflate_state FAR *)
1476            ZALLOC(source, 1, sizeof(struct inflate_state));
1477     if (copy == Z_NULL) return Z_MEM_ERROR;
1478     window = Z_NULL;
1479     if (state->window != Z_NULL) {
1480         window = (unsigned char FAR *)
1481                  ZALLOC(source, 1U << state->wbits, sizeof(unsigned char));
1482         if (window == Z_NULL) {
1483             ZFREE(source, copy);
1484             return Z_MEM_ERROR;
1485         }
1486     }
1487 
1488     /* copy state */
1489     zmemcpy((voidpf)dest, (voidpf)source, sizeof(z_stream));
1490     zmemcpy((voidpf)copy, (voidpf)state, sizeof(struct inflate_state));
1491     copy->strm = dest;
1492     if (state->lencode >= state->codes &&
1493         state->lencode <= state->codes + ENOUGH - 1) {
1494         copy->lencode = copy->codes + (state->lencode - state->codes);
1495         copy->distcode = copy->codes + (state->distcode - state->codes);
1496     }
1497     copy->next = copy->codes + (state->next - state->codes);
1498     if (window != Z_NULL) {
1499         wsize = 1U << state->wbits;
1500         zmemcpy(window, state->window, wsize);
1501     }
1502     copy->window = window;
1503     dest->state = (struct internal_state FAR *)copy;
1504     return Z_OK;
1505 }
1506 
inflateUndermine(z_streamp strm,int subvert)1507 int ZEXPORT inflateUndermine(z_streamp strm, int subvert)
1508 {
1509     struct inflate_state FAR *state;
1510 
1511     if (inflateStateCheck(strm)) return Z_STREAM_ERROR;
1512     state = (struct inflate_state FAR *)strm->state;
1513 #ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
1514     state->sane = !subvert;
1515     return Z_OK;
1516 #else
1517     (void)subvert;
1518     state->sane = 1;
1519     return Z_DATA_ERROR;
1520 #endif
1521 }
1522 
inflateValidate(z_streamp strm,int check)1523 int ZEXPORT inflateValidate(z_streamp strm, int check)
1524 {
1525     struct inflate_state FAR *state;
1526 
1527     if (inflateStateCheck(strm)) return Z_STREAM_ERROR;
1528     state = (struct inflate_state FAR *)strm->state;
1529     if (check && state->wrap)
1530         state->wrap |= 4;
1531     else
1532         state->wrap &= ~4;
1533     return Z_OK;
1534 }
1535 
inflateMark(z_streamp strm)1536 long ZEXPORT inflateMark(z_streamp strm)
1537 {
1538     struct inflate_state FAR *state;
1539 
1540     if (inflateStateCheck(strm))
1541         return -(1L << 16);
1542     state = (struct inflate_state FAR *)strm->state;
1543     return (long)(((unsigned long)((long)state->back)) << 16) +
1544         (state->mode == COPY ? state->length :
1545             (state->mode == MATCH ? state->was - state->length : 0));
1546 }
1547 
inflateCodesUsed(z_streamp strm)1548 unsigned long ZEXPORT inflateCodesUsed(z_streamp strm)
1549 {
1550     struct inflate_state FAR *state;
1551     if (inflateStateCheck(strm)) return (unsigned long)-1;
1552     state = (struct inflate_state FAR *)strm->state;
1553     return (unsigned long)(state->next - state->codes);
1554 }
1555