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