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