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