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