inflate.c 48.8 KB
Newer Older
M
Mark Adler 已提交
1
/* inflate.c -- zlib decompression
M
Mark Adler 已提交
2
 * Copyright (C) 1995-2006 Mark Adler
M
Mark Adler 已提交
3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72
 * For conditions of distribution and use, see copyright notice in zlib.h
 */

/*
 * Change history:
 *
 * 1.2.beta0    24 Nov 2002
 * - First version -- complete rewrite of inflate to simplify code, avoid
 *   creation of window when not needed, minimize use of window when it is
 *   needed, make inffast.c even faster, implement gzip decoding, and to
 *   improve code readability and style over the previous zlib inflate code
 *
 * 1.2.beta1    25 Nov 2002
 * - Use pointers for available input and output checking in inffast.c
 * - Remove input and output counters in inffast.c
 * - Change inffast.c entry and loop from avail_in >= 7 to >= 6
 * - Remove unnecessary second byte pull from length extra in inffast.c
 * - Unroll direct copy to three copies per loop in inffast.c
 *
 * 1.2.beta2    4 Dec 2002
 * - Change external routine names to reduce potential conflicts
 * - Correct filename to inffixed.h for fixed tables in inflate.c
 * - Make hbuf[] unsigned char to match parameter type in inflate.c
 * - Change strm->next_out[-state->offset] to *(strm->next_out - state->offset)
 *   to avoid negation problem on Alphas (64 bit) in inflate.c
 *
 * 1.2.beta3    22 Dec 2002
 * - Add comments on state->bits assertion in inffast.c
 * - Add comments on op field in inftrees.h
 * - Fix bug in reuse of allocated window after inflateReset()
 * - Remove bit fields--back to byte structure for speed
 * - Remove distance extra == 0 check in inflate_fast()--only helps for lengths
 * - Change post-increments to pre-increments in inflate_fast(), PPC biased?
 * - Add compile time option, POSTINC, to use post-increments instead (Intel?)
 * - Make MATCH copy in inflate() much faster for when inflate_fast() not used
 * - Use local copies of stream next and avail values, as well as local bit
 *   buffer and bit count in inflate()--for speed when inflate_fast() not used
 *
 * 1.2.beta4    1 Jan 2003
 * - Split ptr - 257 statements in inflate_table() to avoid compiler warnings
 * - Move a comment on output buffer sizes from inffast.c to inflate.c
 * - Add comments in inffast.c to introduce the inflate_fast() routine
 * - Rearrange window copies in inflate_fast() for speed and simplification
 * - Unroll last copy for window match in inflate_fast()
 * - Use local copies of window variables in inflate_fast() for speed
 * - Pull out common write == 0 case for speed in inflate_fast()
 * - Make op and len in inflate_fast() unsigned for consistency
 * - Add FAR to lcode and dcode declarations in inflate_fast()
 * - Simplified bad distance check in inflate_fast()
 * - Added inflateBackInit(), inflateBack(), and inflateBackEnd() in new
 *   source file infback.c to provide a call-back interface to inflate for
 *   programs like gzip and unzip -- uses window as output buffer to avoid
 *   window copying
 *
 * 1.2.beta5    1 Jan 2003
 * - Improved inflateBack() interface to allow the caller to provide initial
 *   input in strm.
 * - Fixed stored blocks bug in inflateBack()
 *
 * 1.2.beta6    4 Jan 2003
 * - Added comments in inffast.c on effectiveness of POSTINC
 * - Typecasting all around to reduce compiler warnings
 * - Changed loops from while (1) or do {} while (1) to for (;;), again to
 *   make compilers happy
 * - Changed type of window in inflateBackInit() to unsigned char *
 *
 * 1.2.beta7    27 Jan 2003
 * - Changed many types to unsigned or unsigned short to avoid warnings
 * - Added inflateCopy() function
 *
M
Mark Adler 已提交
73
 * 1.2.0        9 Mar 2003
M
Mark Adler 已提交
74 75 76 77 78 79
 * - Changed inflateBack() interface to provide separate opaque descriptors
 *   for the in() and out() functions
 * - Changed inflateBack() argument and in_func typedef to swap the length
 *   and buffer address return values for the input function
 * - Check next_in and next_out for Z_NULL on entry to inflate()
 *
M
Mark Adler 已提交
80
 * The history for versions after 1.2.0 are in ChangeLog in zlib distribution.
M
Mark Adler 已提交
81 82 83
 */

#include "zutil.h"
M
Mark Adler 已提交
84 85 86
#include "inftrees.h"
#include "inflate.h"
#include "inffast.h"
M
Mark Adler 已提交
87

M
Mark Adler 已提交
88 89 90 91 92 93 94 95 96 97 98 99
#ifdef MAKEFIXED
#  ifndef BUILDFIXED
#    define BUILDFIXED
#  endif
#endif

/* function prototypes */
local void fixedtables OF((struct inflate_state FAR *state));
local int updatewindow OF((z_streamp strm, unsigned out));
#ifdef BUILDFIXED
   void makefixed OF((void));
#endif
M
Mark Adler 已提交
100
local unsigned syncsearch OF((unsigned FAR *have, unsigned char FAR *buf,
M
Mark Adler 已提交
101
                              unsigned len));
M
Mark Adler 已提交
102

M
Mark Adler 已提交
103 104
int ZEXPORT inflateReset(strm)
z_streamp strm;
M
Mark Adler 已提交
105
{
M
Mark Adler 已提交
106
    struct inflate_state FAR *state;
M
Mark Adler 已提交
107

M
Mark Adler 已提交
108 109 110 111
    if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
    state = (struct inflate_state FAR *)strm->state;
    strm->total_in = strm->total_out = state->total = 0;
    strm->msg = Z_NULL;
M
Mark Adler 已提交
112
    strm->adler = 1;        /* to support ill-conceived Java test suite */
M
Mark Adler 已提交
113 114 115
    state->mode = HEAD;
    state->last = 0;
    state->havedict = 0;
M
Mark Adler 已提交
116
    state->dmax = 32768U;
M
Mark Adler 已提交
117
    state->head = Z_NULL;
M
Mark Adler 已提交
118
    state->wsize = 0;
M
Mark Adler 已提交
119
    state->whave = 0;
M
Mark Adler 已提交
120
    state->write = 0;
M
Mark Adler 已提交
121 122 123
    state->hold = 0;
    state->bits = 0;
    state->lencode = state->distcode = state->next = state->codes;
M
Mark Adler 已提交
124
    state->sane = 1;
M
Mark Adler 已提交
125 126 127
    Tracev((stderr, "inflate: reset\n"));
    return Z_OK;
}
M
Mark Adler 已提交
128

M
Mark Adler 已提交
129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144
int ZEXPORT inflatePrime(strm, bits, value)
z_streamp strm;
int bits;
int value;
{
    struct inflate_state FAR *state;

    if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
    state = (struct inflate_state FAR *)strm->state;
    if (bits > 16 || state->bits + bits > 32) return Z_STREAM_ERROR;
    value &= (1L << bits) - 1;
    state->hold += value << state->bits;
    state->bits += bits;
    return Z_OK;
}

M
Mark Adler 已提交
145 146 147
int ZEXPORT inflateInit2_(strm, windowBits, version, stream_size)
z_streamp strm;
int windowBits;
M
Mark Adler 已提交
148 149
const char *version;
int stream_size;
M
Mark Adler 已提交
150
{
M
Mark Adler 已提交
151
    struct inflate_state FAR *state;
M
Mark Adler 已提交
152

M
Mark Adler 已提交
153 154 155 156 157
    if (version == Z_NULL || version[0] != ZLIB_VERSION[0] ||
        stream_size != (int)(sizeof(z_stream)))
        return Z_VERSION_ERROR;
    if (strm == Z_NULL) return Z_STREAM_ERROR;
    strm->msg = Z_NULL;                 /* in case we return an error */
M
Mark Adler 已提交
158
    if (strm->zalloc == (alloc_func)0) {
M
Mark Adler 已提交
159 160 161
        strm->zalloc = zcalloc;
        strm->opaque = (voidpf)0;
    }
M
Mark Adler 已提交
162
    if (strm->zfree == (free_func)0) strm->zfree = zcfree;
M
Mark Adler 已提交
163 164 165 166
    state = (struct inflate_state FAR *)
            ZALLOC(strm, 1, sizeof(struct inflate_state));
    if (state == Z_NULL) return Z_MEM_ERROR;
    Tracev((stderr, "inflate: allocated\n"));
M
Mark Adler 已提交
167
    strm->state = (struct internal_state FAR *)state;
M
Mark Adler 已提交
168 169 170 171
    if (windowBits < 0) {
        state->wrap = 0;
        windowBits = -windowBits;
    }
M
Mark Adler 已提交
172 173 174
    else {
        state->wrap = (windowBits >> 4) + 1;
#ifdef GUNZIP
M
Mark Adler 已提交
175
        if (windowBits < 48) windowBits &= 15;
M
Mark Adler 已提交
176 177
#endif
    }
M
Mark Adler 已提交
178 179 180 181 182 183 184 185 186
    if (windowBits < 8 || windowBits > 15) {
        ZFREE(strm, state);
        strm->state = Z_NULL;
        return Z_STREAM_ERROR;
    }
    state->wbits = (unsigned)windowBits;
    state->window = Z_NULL;
    return inflateReset(strm);
}
M
Mark Adler 已提交
187

M
Mark Adler 已提交
188 189
int ZEXPORT inflateInit_(strm, version, stream_size)
z_streamp strm;
M
Mark Adler 已提交
190 191
const char *version;
int stream_size;
M
Mark Adler 已提交
192
{
M
Mark Adler 已提交
193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246
    return inflateInit2_(strm, DEF_WBITS, version, stream_size);
}

/*
   Return state with length and distance decoding tables and index sizes set to
   fixed code decoding.  Normally this returns fixed tables from inffixed.h.
   If BUILDFIXED is defined, then instead this routine builds the tables the
   first time it's called, and returns those tables the first time and
   thereafter.  This reduces the size of the code by about 2K bytes, in
   exchange for a little execution time.  However, BUILDFIXED should not be
   used for threaded applications, since the rewriting of the tables and virgin
   may not be thread-safe.
 */
local void fixedtables(state)
struct inflate_state FAR *state;
{
#ifdef BUILDFIXED
    static int virgin = 1;
    static code *lenfix, *distfix;
    static code fixed[544];

    /* build fixed huffman tables if first call (may not be thread safe) */
    if (virgin) {
        unsigned sym, bits;
        static code *next;

        /* literal/length table */
        sym = 0;
        while (sym < 144) state->lens[sym++] = 8;
        while (sym < 256) state->lens[sym++] = 9;
        while (sym < 280) state->lens[sym++] = 7;
        while (sym < 288) state->lens[sym++] = 8;
        next = fixed;
        lenfix = next;
        bits = 9;
        inflate_table(LENS, state->lens, 288, &(next), &(bits), state->work);

        /* distance table */
        sym = 0;
        while (sym < 32) state->lens[sym++] = 5;
        distfix = next;
        bits = 5;
        inflate_table(DISTS, state->lens, 32, &(next), &(bits), state->work);

        /* do this just once */
        virgin = 0;
    }
#else /* !BUILDFIXED */
#   include "inffixed.h"
#endif /* BUILDFIXED */
    state->lencode = lenfix;
    state->lenbits = 9;
    state->distcode = distfix;
    state->distbits = 5;
M
Mark Adler 已提交
247 248
}

M
Mark Adler 已提交
249 250
#ifdef MAKEFIXED
#include <stdio.h>
M
Mark Adler 已提交
251

M
Mark Adler 已提交
252 253 254 255 256
/*
   Write out the inffixed.h that is #include'd above.  Defining MAKEFIXED also
   defines BUILDFIXED, so the tables are built on the fly.  makefixed() writes
   those tables to stdout, which would be piped to inffixed.h.  A small program
   can simply call makefixed to do this:
M
Mark Adler 已提交
257

M
Mark Adler 已提交
258 259 260 261 262 263 264 265 266 267 268 269 270
    void makefixed(void);

    int main(void)
    {
        makefixed();
        return 0;
    }

   Then that can be linked with zlib built with MAKEFIXED defined and run:

    a.out > inffixed.h
 */
void makefixed()
M
Mark Adler 已提交
271
{
M
Mark Adler 已提交
272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344
    unsigned low, size;
    struct inflate_state state;

    fixedtables(&state);
    puts("    /* inffixed.h -- table for decoding fixed codes");
    puts("     * Generated automatically by makefixed().");
    puts("     */");
    puts("");
    puts("    /* WARNING: this file should *not* be used by applications.");
    puts("       It is part of the implementation of this library and is");
    puts("       subject to change. Applications should only use zlib.h.");
    puts("     */");
    puts("");
    size = 1U << 9;
    printf("    static const code lenfix[%u] = {", size);
    low = 0;
    for (;;) {
        if ((low % 7) == 0) printf("\n        ");
        printf("{%u,%u,%d}", state.lencode[low].op, state.lencode[low].bits,
               state.lencode[low].val);
        if (++low == size) break;
        putchar(',');
    }
    puts("\n    };");
    size = 1U << 5;
    printf("\n    static const code distfix[%u] = {", size);
    low = 0;
    for (;;) {
        if ((low % 6) == 0) printf("\n        ");
        printf("{%u,%u,%d}", state.distcode[low].op, state.distcode[low].bits,
               state.distcode[low].val);
        if (++low == size) break;
        putchar(',');
    }
    puts("\n    };");
}
#endif /* MAKEFIXED */

/*
   Update the window with the last wsize (normally 32K) bytes written before
   returning.  If window does not exist yet, create it.  This is only called
   when a window is already in use, or when output has been written during this
   inflate call, but the end of the deflate stream has not been reached yet.
   It is also called to create a window for dictionary data when a dictionary
   is loaded.

   Providing output buffers larger than 32K to inflate() should provide a speed
   advantage, since only the last 32K of output is copied to the sliding window
   upon return from inflate(), and since all distances after the first 32K of
   output will fall in the output data, making match copies simpler and faster.
   The advantage may be dependent on the size of the processor's data caches.
 */
local int updatewindow(strm, out)
z_streamp strm;
unsigned out;
{
    struct inflate_state FAR *state;
    unsigned copy, dist;

    state = (struct inflate_state FAR *)strm->state;

    /* if it hasn't been done already, allocate space for the window */
    if (state->window == Z_NULL) {
        state->window = (unsigned char FAR *)
                        ZALLOC(strm, 1U << state->wbits,
                               sizeof(unsigned char));
        if (state->window == Z_NULL) return 1;
    }

    /* if window not in use yet, initialize */
    if (state->wsize == 0) {
        state->wsize = 1U << state->wbits;
        state->write = 0;
M
Mark Adler 已提交
345
        state->whave = 0;
M
Mark Adler 已提交
346 347 348 349 350 351 352
    }

    /* copy state->wsize or less output bytes into the circular window */
    copy = out - strm->avail_out;
    if (copy >= state->wsize) {
        zmemcpy(state->window, strm->next_out - state->wsize, state->wsize);
        state->write = 0;
M
Mark Adler 已提交
353
        state->whave = state->wsize;
M
Mark Adler 已提交
354 355 356 357 358 359 360 361 362
    }
    else {
        dist = state->wsize - state->write;
        if (dist > copy) dist = copy;
        zmemcpy(state->window + state->write, strm->next_out - copy, dist);
        copy -= dist;
        if (copy) {
            zmemcpy(state->window, strm->next_out - copy, copy);
            state->write = copy;
M
Mark Adler 已提交
363
            state->whave = state->wsize;
M
Mark Adler 已提交
364 365 366 367
        }
        else {
            state->write += dist;
            if (state->write == state->wsize) state->write = 0;
M
Mark Adler 已提交
368
            if (state->whave < state->wsize) state->whave += dist;
M
Mark Adler 已提交
369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435
        }
    }
    return 0;
}

/* Macros for inflate(): */

/* check function to use adler32() for zlib or crc32() for gzip */
#ifdef GUNZIP
#  define UPDATE(check, buf, len) \
    (state->flags ? crc32(check, buf, len) : adler32(check, buf, len))
#else
#  define UPDATE(check, buf, len) adler32(check, buf, len)
#endif

/* check macros for header crc */
#ifdef GUNZIP
#  define CRC2(check, word) \
    do { \
        hbuf[0] = (unsigned char)(word); \
        hbuf[1] = (unsigned char)((word) >> 8); \
        check = crc32(check, hbuf, 2); \
    } while (0)

#  define CRC4(check, word) \
    do { \
        hbuf[0] = (unsigned char)(word); \
        hbuf[1] = (unsigned char)((word) >> 8); \
        hbuf[2] = (unsigned char)((word) >> 16); \
        hbuf[3] = (unsigned char)((word) >> 24); \
        check = crc32(check, hbuf, 4); \
    } while (0)
#endif

/* Load registers with state in inflate() for speed */
#define LOAD() \
    do { \
        put = strm->next_out; \
        left = strm->avail_out; \
        next = strm->next_in; \
        have = strm->avail_in; \
        hold = state->hold; \
        bits = state->bits; \
    } while (0)

/* Restore state from registers in inflate() */
#define RESTORE() \
    do { \
        strm->next_out = put; \
        strm->avail_out = left; \
        strm->next_in = next; \
        strm->avail_in = have; \
        state->hold = hold; \
        state->bits = bits; \
    } while (0)

/* Clear the input bit accumulator */
#define INITBITS() \
    do { \
        hold = 0; \
        bits = 0; \
    } while (0)

/* Get a byte of input into the bit accumulator, or return from inflate()
   if there is no input available. */
#define PULLBYTE() \
    do { \
M
Mark Adler 已提交
436
        if (have == 0) goto inf_leave; \
M
Mark Adler 已提交
437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484
        have--; \
        hold += (unsigned long)(*next++) << bits; \
        bits += 8; \
    } while (0)

/* Assure that there are at least n bits in the bit accumulator.  If there is
   not enough available input to do that, then return from inflate(). */
#define NEEDBITS(n) \
    do { \
        while (bits < (unsigned)(n)) \
            PULLBYTE(); \
    } while (0)

/* Return the low n bits of the bit accumulator (n < 16) */
#define BITS(n) \
    ((unsigned)hold & ((1U << (n)) - 1))

/* Remove n bits from the bit accumulator */
#define DROPBITS(n) \
    do { \
        hold >>= (n); \
        bits -= (unsigned)(n); \
    } while (0)

/* Remove zero to seven bits as needed to go to a byte boundary */
#define BYTEBITS() \
    do { \
        hold >>= bits & 7; \
        bits -= bits & 7; \
    } while (0)

/* Reverse the bytes in a 32-bit value */
#define REVERSE(q) \
    ((((q) >> 24) & 0xff) + (((q) >> 8) & 0xff00) + \
     (((q) & 0xff00) << 8) + (((q) & 0xff) << 24))

/*
   inflate() uses a state machine to process as much input data and generate as
   much output data as possible before returning.  The state machine is
   structured roughly as follows:

    for (;;) switch (state) {
    ...
    case STATEn:
        if (not enough input data or output space to make progress)
            return;
        ... make progress ...
        state = STATEm;
M
Mark Adler 已提交
485
        break;
M
Mark Adler 已提交
486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534
    ...
    }

   so when inflate() is called again, the same case is attempted again, and
   if the appropriate resources are provided, the machine proceeds to the
   next state.  The NEEDBITS() macro is usually the way the state evaluates
   whether it can proceed or should return.  NEEDBITS() does the return if
   the requested bits are not available.  The typical use of the BITS macros
   is:

        NEEDBITS(n);
        ... do something with BITS(n) ...
        DROPBITS(n);

   where NEEDBITS(n) either returns from inflate() if there isn't enough
   input left to load n bits into the accumulator, or it continues.  BITS(n)
   gives the low n bits in the accumulator.  When done, DROPBITS(n) drops
   the low n bits off the accumulator.  INITBITS() clears the accumulator
   and sets the number of available bits to zero.  BYTEBITS() discards just
   enough bits to put the accumulator on a byte boundary.  After BYTEBITS()
   and a NEEDBITS(8), then BITS(8) would return the next byte in the stream.

   NEEDBITS(n) uses PULLBYTE() to get an available byte of input, or to return
   if there is no input available.  The decoding of variable length codes uses
   PULLBYTE() directly in order to pull just enough bytes to decode the next
   code, and no more.

   Some states loop until they get enough input, making sure that enough
   state information is maintained to continue the loop where it left off
   if NEEDBITS() returns in the loop.  For example, want, need, and keep
   would all have to actually be part of the saved state in case NEEDBITS()
   returns:

    case STATEw:
        while (want < need) {
            NEEDBITS(n);
            keep[want++] = BITS(n);
            DROPBITS(n);
        }
        state = STATEx;
    case STATEx:

   As shown above, if the next state is also the next case, then the break
   is omitted.

   A state may also return if there is not enough output space available to
   complete that state.  Those states are copying stored data, writing a
   literal byte, and copying a matching string.

M
Mark Adler 已提交
535 536 537 538 539 540 541 542
   When returning, a "goto inf_leave" is used to update the total counters,
   update the check value, and determine whether any progress has been made
   during that inflate() call in order to return the proper return code.
   Progress is defined as a change in either strm->avail_in or strm->avail_out.
   When there is a window, goto inf_leave will update the window with the last
   output written.  If a goto inf_leave occurs in the middle of decompression
   and there is no window currently, goto inf_leave will create one and copy
   output to the window for the next call of inflate().
M
Mark Adler 已提交
543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559

   In this implementation, the flush parameter of inflate() only affects the
   return code (per zlib.h).  inflate() always writes as much as possible to
   strm->next_out, given the space available and the provided input--the effect
   documented in zlib.h of Z_SYNC_FLUSH.  Furthermore, inflate() always defers
   the allocation of and copying into a sliding window until necessary, which
   provides the effect documented in zlib.h for Z_FINISH when the entire input
   stream available.  So the only thing the flush parameter actually does is:
   when flush is set to Z_FINISH, inflate() cannot return Z_OK.  Instead it
   will return Z_BUF_ERROR if it has not reached the end of the stream.
 */

int ZEXPORT inflate(strm, flush)
z_streamp strm;
int flush;
{
    struct inflate_state FAR *state;
M
Mark Adler 已提交
560 561
    unsigned char FAR *next;    /* next input */
    unsigned char FAR *put;     /* next output */
M
Mark Adler 已提交
562 563 564 565 566
    unsigned have, left;        /* available input and output */
    unsigned long hold;         /* bit buffer */
    unsigned bits;              /* bits in bit buffer */
    unsigned in, out;           /* save starting available input and output */
    unsigned copy;              /* number of stored or match bytes to copy */
M
Mark Adler 已提交
567
    unsigned char FAR *from;    /* where to copy match bytes from */
M
Mark Adler 已提交
568
    code here;                  /* current decoding table entry */
M
Mark Adler 已提交
569 570 571 572 573 574 575 576 577 578 579 580 581 582
    code last;                  /* parent table entry */
    unsigned len;               /* length to copy for repeats, bits to drop */
    int ret;                    /* return code */
#ifdef GUNZIP
    unsigned char hbuf[4];      /* buffer for gzip header crc calculation */
#endif
    static const unsigned short order[19] = /* permutation of code lengths */
        {16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15};

    if (strm == Z_NULL || strm->state == Z_NULL || strm->next_out == Z_NULL ||
        (strm->next_in == Z_NULL && strm->avail_in != 0))
        return Z_STREAM_ERROR;

    state = (struct inflate_state FAR *)strm->state;
M
Mark Adler 已提交
583
    if (state->mode == TYPE) state->mode = TYPEDO;      /* skip check */
M
Mark Adler 已提交
584 585 586 587 588 589 590 591
    LOAD();
    in = have;
    out = left;
    ret = Z_OK;
    for (;;)
        switch (state->mode) {
        case HEAD:
            if (state->wrap == 0) {
M
Mark Adler 已提交
592
                state->mode = TYPEDO;
M
Mark Adler 已提交
593 594 595 596
                break;
            }
            NEEDBITS(16);
#ifdef GUNZIP
M
Mark Adler 已提交
597
            if ((state->wrap & 2) && hold == 0x8b1f) {  /* gzip header */
M
Mark Adler 已提交
598 599 600 601 602 603
                state->check = crc32(0L, Z_NULL, 0);
                CRC2(state->check, hold);
                INITBITS();
                state->mode = FLAGS;
                break;
            }
M
Mark Adler 已提交
604
            state->flags = 0;           /* expect zlib header */
M
Mark Adler 已提交
605 606
            if (state->head != Z_NULL)
                state->head->done = -1;
M
Mark Adler 已提交
607 608 609
            if (!(state->wrap & 1) ||   /* check if zlib header allowed */
#else
            if (
M
Mark Adler 已提交
610
#endif
M
Mark Adler 已提交
611
                ((BITS(8) << 8) + (hold >> 8)) % 31) {
M
Mark Adler 已提交
612 613 614 615 616 617 618 619 620 621
                strm->msg = (char *)"incorrect header check";
                state->mode = BAD;
                break;
            }
            if (BITS(4) != Z_DEFLATED) {
                strm->msg = (char *)"unknown compression method";
                state->mode = BAD;
                break;
            }
            DROPBITS(4);
M
Mark Adler 已提交
622 623
            len = BITS(4) + 8;
            if (len > state->wbits) {
M
Mark Adler 已提交
624 625 626 627
                strm->msg = (char *)"invalid window size";
                state->mode = BAD;
                break;
            }
M
Mark Adler 已提交
628
            state->dmax = 1U << len;
M
Mark Adler 已提交
629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647
            Tracev((stderr, "inflate:   zlib header ok\n"));
            strm->adler = state->check = adler32(0L, Z_NULL, 0);
            state->mode = hold & 0x200 ? DICTID : TYPE;
            INITBITS();
            break;
#ifdef GUNZIP
        case FLAGS:
            NEEDBITS(16);
            state->flags = (int)(hold);
            if ((state->flags & 0xff) != Z_DEFLATED) {
                strm->msg = (char *)"unknown compression method";
                state->mode = BAD;
                break;
            }
            if (state->flags & 0xe000) {
                strm->msg = (char *)"unknown header flags set";
                state->mode = BAD;
                break;
            }
M
Mark Adler 已提交
648 649
            if (state->head != Z_NULL)
                state->head->text = (int)((hold >> 8) & 1);
M
Mark Adler 已提交
650 651 652 653 654
            if (state->flags & 0x0200) CRC2(state->check, hold);
            INITBITS();
            state->mode = TIME;
        case TIME:
            NEEDBITS(32);
M
Mark Adler 已提交
655 656
            if (state->head != Z_NULL)
                state->head->time = hold;
M
Mark Adler 已提交
657 658 659 660 661
            if (state->flags & 0x0200) CRC4(state->check, hold);
            INITBITS();
            state->mode = OS;
        case OS:
            NEEDBITS(16);
M
Mark Adler 已提交
662 663 664 665
            if (state->head != Z_NULL) {
                state->head->xflags = (int)(hold & 0xff);
                state->head->os = (int)(hold >> 8);
            }
M
Mark Adler 已提交
666 667 668 669 670 671 672
            if (state->flags & 0x0200) CRC2(state->check, hold);
            INITBITS();
            state->mode = EXLEN;
        case EXLEN:
            if (state->flags & 0x0400) {
                NEEDBITS(16);
                state->length = (unsigned)(hold);
M
Mark Adler 已提交
673 674
                if (state->head != Z_NULL)
                    state->head->extra_len = (unsigned)hold;
M
Mark Adler 已提交
675 676 677
                if (state->flags & 0x0200) CRC2(state->check, hold);
                INITBITS();
            }
M
Mark Adler 已提交
678 679
            else if (state->head != Z_NULL)
                state->head->extra = Z_NULL;
M
Mark Adler 已提交
680 681 682 683 684 685
            state->mode = EXTRA;
        case EXTRA:
            if (state->flags & 0x0400) {
                copy = state->length;
                if (copy > have) copy = have;
                if (copy) {
M
Mark Adler 已提交
686 687 688 689 690 691 692
                    if (state->head != Z_NULL &&
                        state->head->extra != Z_NULL) {
                        len = state->head->extra_len - state->length;
                        zmemcpy(state->head->extra + len, next,
                                len + copy > state->head->extra_max ?
                                state->head->extra_max - len : copy);
                    }
M
Mark Adler 已提交
693 694 695 696 697 698
                    if (state->flags & 0x0200)
                        state->check = crc32(state->check, next, copy);
                    have -= copy;
                    next += copy;
                    state->length -= copy;
                }
M
Mark Adler 已提交
699
                if (state->length) goto inf_leave;
M
Mark Adler 已提交
700
            }
M
Mark Adler 已提交
701
            state->length = 0;
M
Mark Adler 已提交
702 703 704
            state->mode = NAME;
        case NAME:
            if (state->flags & 0x0800) {
M
Mark Adler 已提交
705
                if (have == 0) goto inf_leave;
M
Mark Adler 已提交
706 707 708
                copy = 0;
                do {
                    len = (unsigned)(next[copy++]);
M
Mark Adler 已提交
709 710 711 712
                    if (state->head != Z_NULL &&
                            state->head->name != Z_NULL &&
                            state->length < state->head->name_max)
                        state->head->name[state->length++] = len;
M
Mark Adler 已提交
713
                } while (len && copy < have);
M
Mark Adler 已提交
714
                if (state->flags & 0x0200)
M
Mark Adler 已提交
715 716 717
                    state->check = crc32(state->check, next, copy);
                have -= copy;
                next += copy;
M
Mark Adler 已提交
718
                if (len) goto inf_leave;
M
Mark Adler 已提交
719
            }
M
Mark Adler 已提交
720 721 722
            else if (state->head != Z_NULL)
                state->head->name = Z_NULL;
            state->length = 0;
M
Mark Adler 已提交
723 724 725
            state->mode = COMMENT;
        case COMMENT:
            if (state->flags & 0x1000) {
M
Mark Adler 已提交
726
                if (have == 0) goto inf_leave;
M
Mark Adler 已提交
727 728 729
                copy = 0;
                do {
                    len = (unsigned)(next[copy++]);
M
Mark Adler 已提交
730 731 732 733
                    if (state->head != Z_NULL &&
                            state->head->comment != Z_NULL &&
                            state->length < state->head->comm_max)
                        state->head->comment[state->length++] = len;
M
Mark Adler 已提交
734
                } while (len && copy < have);
M
Mark Adler 已提交
735
                if (state->flags & 0x0200)
M
Mark Adler 已提交
736 737 738
                    state->check = crc32(state->check, next, copy);
                have -= copy;
                next += copy;
M
Mark Adler 已提交
739
                if (len) goto inf_leave;
M
Mark Adler 已提交
740
            }
M
Mark Adler 已提交
741 742
            else if (state->head != Z_NULL)
                state->head->comment = Z_NULL;
M
Mark Adler 已提交
743 744 745 746 747 748 749 750 751 752 753
            state->mode = HCRC;
        case HCRC:
            if (state->flags & 0x0200) {
                NEEDBITS(16);
                if (hold != (state->check & 0xffff)) {
                    strm->msg = (char *)"header crc mismatch";
                    state->mode = BAD;
                    break;
                }
                INITBITS();
            }
M
Mark Adler 已提交
754 755 756 757
            if (state->head != Z_NULL) {
                state->head->hcrc = (int)((state->flags >> 9) & 1);
                state->head->done = 1;
            }
M
Mark Adler 已提交
758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774
            strm->adler = state->check = crc32(0L, Z_NULL, 0);
            state->mode = TYPE;
            break;
#endif
        case DICTID:
            NEEDBITS(32);
            strm->adler = state->check = REVERSE(hold);
            INITBITS();
            state->mode = DICT;
        case DICT:
            if (state->havedict == 0) {
                RESTORE();
                return Z_NEED_DICT;
            }
            strm->adler = state->check = adler32(0L, Z_NULL, 0);
            state->mode = TYPE;
        case TYPE:
M
Mark Adler 已提交
775 776
            if (flush == Z_BLOCK) goto inf_leave;
        case TYPEDO:
M
Mark Adler 已提交
777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825
            if (state->last) {
                BYTEBITS();
                state->mode = CHECK;
                break;
            }
            NEEDBITS(3);
            state->last = BITS(1);
            DROPBITS(1);
            switch (BITS(2)) {
            case 0:                             /* stored block */
                Tracev((stderr, "inflate:     stored block%s\n",
                        state->last ? " (last)" : ""));
                state->mode = STORED;
                break;
            case 1:                             /* fixed block */
                fixedtables(state);
                Tracev((stderr, "inflate:     fixed codes block%s\n",
                        state->last ? " (last)" : ""));
                state->mode = LEN;              /* decode codes */
                break;
            case 2:                             /* dynamic block */
                Tracev((stderr, "inflate:     dynamic codes block%s\n",
                        state->last ? " (last)" : ""));
                state->mode = TABLE;
                break;
            case 3:
                strm->msg = (char *)"invalid block type";
                state->mode = BAD;
            }
            DROPBITS(2);
            break;
        case STORED:
            BYTEBITS();                         /* go to byte boundary */
            NEEDBITS(32);
            if ((hold & 0xffff) != ((hold >> 16) ^ 0xffff)) {
                strm->msg = (char *)"invalid stored block lengths";
                state->mode = BAD;
                break;
            }
            state->length = (unsigned)hold & 0xffff;
            Tracev((stderr, "inflate:       stored length %u\n",
                    state->length));
            INITBITS();
            state->mode = COPY;
        case COPY:
            copy = state->length;
            if (copy) {
                if (copy > have) copy = have;
                if (copy > left) copy = left;
M
Mark Adler 已提交
826
                if (copy == 0) goto inf_leave;
M
Mark Adler 已提交
827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879
                zmemcpy(put, next, copy);
                have -= copy;
                next += copy;
                left -= copy;
                put += copy;
                state->length -= copy;
                break;
            }
            Tracev((stderr, "inflate:       stored end\n"));
            state->mode = TYPE;
            break;
        case TABLE:
            NEEDBITS(14);
            state->nlen = BITS(5) + 257;
            DROPBITS(5);
            state->ndist = BITS(5) + 1;
            DROPBITS(5);
            state->ncode = BITS(4) + 4;
            DROPBITS(4);
#ifndef PKZIP_BUG_WORKAROUND
            if (state->nlen > 286 || state->ndist > 30) {
                strm->msg = (char *)"too many length or distance symbols";
                state->mode = BAD;
                break;
            }
#endif
            Tracev((stderr, "inflate:       table sizes ok\n"));
            state->have = 0;
            state->mode = LENLENS;
        case LENLENS:
            while (state->have < state->ncode) {
                NEEDBITS(3);
                state->lens[order[state->have++]] = (unsigned short)BITS(3);
                DROPBITS(3);
            }
            while (state->have < 19)
                state->lens[order[state->have++]] = 0;
            state->next = state->codes;
            state->lencode = (code const FAR *)(state->next);
            state->lenbits = 7;
            ret = inflate_table(CODES, state->lens, 19, &(state->next),
                                &(state->lenbits), state->work);
            if (ret) {
                strm->msg = (char *)"invalid code lengths set";
                state->mode = BAD;
                break;
            }
            Tracev((stderr, "inflate:       code lengths ok\n"));
            state->have = 0;
            state->mode = CODELENS;
        case CODELENS:
            while (state->have < state->nlen + state->ndist) {
                for (;;) {
M
Mark Adler 已提交
880 881
                    here = state->lencode[BITS(state->lenbits)];
                    if ((unsigned)(here.bits) <= bits) break;
M
Mark Adler 已提交
882 883
                    PULLBYTE();
                }
M
Mark Adler 已提交
884 885 886 887
                if (here.val < 16) {
                    NEEDBITS(here.bits);
                    DROPBITS(here.bits);
                    state->lens[state->have++] = here.val;
M
Mark Adler 已提交
888 889
                }
                else {
M
Mark Adler 已提交
890 891 892
                    if (here.val == 16) {
                        NEEDBITS(here.bits + 2);
                        DROPBITS(here.bits);
M
Mark Adler 已提交
893 894 895 896 897 898 899 900 901
                        if (state->have == 0) {
                            strm->msg = (char *)"invalid bit length repeat";
                            state->mode = BAD;
                            break;
                        }
                        len = state->lens[state->have - 1];
                        copy = 3 + BITS(2);
                        DROPBITS(2);
                    }
M
Mark Adler 已提交
902 903 904
                    else if (here.val == 17) {
                        NEEDBITS(here.bits + 3);
                        DROPBITS(here.bits);
M
Mark Adler 已提交
905 906 907 908 909
                        len = 0;
                        copy = 3 + BITS(3);
                        DROPBITS(3);
                    }
                    else {
M
Mark Adler 已提交
910 911
                        NEEDBITS(here.bits + 7);
                        DROPBITS(here.bits);
M
Mark Adler 已提交
912 913 914 915 916 917 918 919 920 921 922 923 924 925
                        len = 0;
                        copy = 11 + BITS(7);
                        DROPBITS(7);
                    }
                    if (state->have + copy > state->nlen + state->ndist) {
                        strm->msg = (char *)"invalid bit length repeat";
                        state->mode = BAD;
                        break;
                    }
                    while (copy--)
                        state->lens[state->have++] = (unsigned short)len;
                }
            }

M
Mark Adler 已提交
926 927
            /* handle error breaks in while */
            if (state->mode == BAD) break;
M
Mark Adler 已提交
928

M
Mark Adler 已提交
929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958
            /* build code tables */
            state->next = state->codes;
            state->lencode = (code const FAR *)(state->next);
            state->lenbits = 9;
            ret = inflate_table(LENS, state->lens, state->nlen, &(state->next),
                                &(state->lenbits), state->work);
            if (ret) {
                strm->msg = (char *)"invalid literal/lengths set";
                state->mode = BAD;
                break;
            }
            state->distcode = (code const FAR *)(state->next);
            state->distbits = 6;
            ret = inflate_table(DISTS, state->lens + state->nlen, state->ndist,
                            &(state->next), &(state->distbits), state->work);
            if (ret) {
                strm->msg = (char *)"invalid distances set";
                state->mode = BAD;
                break;
            }
            Tracev((stderr, "inflate:       codes ok\n"));
            state->mode = LEN;
        case LEN:
            if (have >= 6 && left >= 258) {
                RESTORE();
                inflate_fast(strm, out);
                LOAD();
                break;
            }
            for (;;) {
M
Mark Adler 已提交
959 960
                here = state->lencode[BITS(state->lenbits)];
                if ((unsigned)(here.bits) <= bits) break;
M
Mark Adler 已提交
961 962
                PULLBYTE();
            }
M
Mark Adler 已提交
963 964
            if (here.op && (here.op & 0xf0) == 0) {
                last = here;
M
Mark Adler 已提交
965
                for (;;) {
M
Mark Adler 已提交
966
                    here = state->lencode[last.val +
M
Mark Adler 已提交
967
                            (BITS(last.bits + last.op) >> last.bits)];
M
Mark Adler 已提交
968
                    if ((unsigned)(last.bits + here.bits) <= bits) break;
M
Mark Adler 已提交
969 970 971 972
                    PULLBYTE();
                }
                DROPBITS(last.bits);
            }
M
Mark Adler 已提交
973 974 975 976
            DROPBITS(here.bits);
            state->length = (unsigned)here.val;
            if ((int)(here.op) == 0) {
                Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
M
Mark Adler 已提交
977
                        "inflate:         literal '%c'\n" :
M
Mark Adler 已提交
978
                        "inflate:         literal 0x%02x\n", here.val));
M
Mark Adler 已提交
979 980 981
                state->mode = LIT;
                break;
            }
M
Mark Adler 已提交
982
            if (here.op & 32) {
M
Mark Adler 已提交
983 984 985 986
                Tracevv((stderr, "inflate:         end of block\n"));
                state->mode = TYPE;
                break;
            }
M
Mark Adler 已提交
987
            if (here.op & 64) {
M
Mark Adler 已提交
988 989 990 991
                strm->msg = (char *)"invalid literal/length code";
                state->mode = BAD;
                break;
            }
M
Mark Adler 已提交
992
            state->extra = (unsigned)(here.op) & 15;
M
Mark Adler 已提交
993 994 995 996 997 998 999 1000 1001 1002 1003
            state->mode = LENEXT;
        case LENEXT:
            if (state->extra) {
                NEEDBITS(state->extra);
                state->length += BITS(state->extra);
                DROPBITS(state->extra);
            }
            Tracevv((stderr, "inflate:         length %u\n", state->length));
            state->mode = DIST;
        case DIST:
            for (;;) {
M
Mark Adler 已提交
1004 1005
                here = state->distcode[BITS(state->distbits)];
                if ((unsigned)(here.bits) <= bits) break;
M
Mark Adler 已提交
1006 1007
                PULLBYTE();
            }
M
Mark Adler 已提交
1008 1009
            if ((here.op & 0xf0) == 0) {
                last = here;
M
Mark Adler 已提交
1010
                for (;;) {
M
Mark Adler 已提交
1011
                    here = state->distcode[last.val +
M
Mark Adler 已提交
1012
                            (BITS(last.bits + last.op) >> last.bits)];
M
Mark Adler 已提交
1013
                    if ((unsigned)(last.bits + here.bits) <= bits) break;
M
Mark Adler 已提交
1014 1015 1016 1017
                    PULLBYTE();
                }
                DROPBITS(last.bits);
            }
M
Mark Adler 已提交
1018 1019
            DROPBITS(here.bits);
            if (here.op & 64) {
M
Mark Adler 已提交
1020 1021 1022 1023
                strm->msg = (char *)"invalid distance code";
                state->mode = BAD;
                break;
            }
M
Mark Adler 已提交
1024 1025
            state->offset = (unsigned)here.val;
            state->extra = (unsigned)(here.op) & 15;
M
Mark Adler 已提交
1026 1027 1028 1029 1030 1031 1032
            state->mode = DISTEXT;
        case DISTEXT:
            if (state->extra) {
                NEEDBITS(state->extra);
                state->offset += BITS(state->extra);
                DROPBITS(state->extra);
            }
M
Mark Adler 已提交
1033 1034 1035 1036 1037 1038 1039
#ifdef INFLATE_STRICT
            if (state->offset > state->dmax) {
                strm->msg = (char *)"invalid distance too far back";
                state->mode = BAD;
                break;
            }
#endif
M
Mark Adler 已提交
1040 1041 1042
            Tracevv((stderr, "inflate:         distance %u\n", state->offset));
            state->mode = MATCH;
        case MATCH:
M
Mark Adler 已提交
1043
            if (left == 0) goto inf_leave;
M
Mark Adler 已提交
1044 1045 1046
            copy = out - left;
            if (state->offset > copy) {         /* copy from window */
                copy = state->offset - copy;
M
Mark Adler 已提交
1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066
                if (copy > state->whave) {
                    if (state->sane) {
                        strm->msg = (char *)"invalid distance too far back";
                        state->mode = BAD;
                        break;
                    }
#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
                    Trace((stderr, "inflate.c too far\n"));
                    copy -= state->whave;
                    if (copy > state->length) copy = state->length;
                    if (copy > left) copy = left;
                    left -= copy;
                    state->length -= copy;
                    do {
                        *put++ = 0;
                    } while (--copy);
                    if (state->length == 0) state->mode = LEN;
                    break;
#endif
                }
M
Mark Adler 已提交
1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087
                if (copy > state->write) {
                    copy -= state->write;
                    from = state->window + (state->wsize - copy);
                }
                else
                    from = state->window + (state->write - copy);
                if (copy > state->length) copy = state->length;
            }
            else {                              /* copy from output */
                from = put - state->offset;
                copy = state->length;
            }
            if (copy > left) copy = left;
            left -= copy;
            state->length -= copy;
            do {
                *put++ = *from++;
            } while (--copy);
            if (state->length == 0) state->mode = LEN;
            break;
        case LIT:
M
Mark Adler 已提交
1088
            if (left == 0) goto inf_leave;
M
Mark Adler 已提交
1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105
            *put++ = (unsigned char)(state->length);
            left--;
            state->mode = LEN;
            break;
        case CHECK:
            if (state->wrap) {
                NEEDBITS(32);
                out -= left;
                strm->total_out += out;
                state->total += out;
                if (out)
                    strm->adler = state->check =
                        UPDATE(state->check, put - out, out);
                out = left;
                if ((
#ifdef GUNZIP
                     state->flags ? hold :
M
Mark Adler 已提交
1106
#endif
M
Mark Adler 已提交
1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119
                     REVERSE(hold)) != state->check) {
                    strm->msg = (char *)"incorrect data check";
                    state->mode = BAD;
                    break;
                }
                INITBITS();
                Tracev((stderr, "inflate:   check matches trailer\n"));
            }
#ifdef GUNZIP
            state->mode = LENGTH;
        case LENGTH:
            if (state->wrap && state->flags) {
                NEEDBITS(32);
M
Mark Adler 已提交
1120
                if (hold != (state->total & 0xffffffffUL)) {
M
Mark Adler 已提交
1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131
                    strm->msg = (char *)"incorrect length check";
                    state->mode = BAD;
                    break;
                }
                INITBITS();
                Tracev((stderr, "inflate:   length matches trailer\n"));
            }
#endif
            state->mode = DONE;
        case DONE:
            ret = Z_STREAM_END;
M
Mark Adler 已提交
1132
            goto inf_leave;
M
Mark Adler 已提交
1133 1134
        case BAD:
            ret = Z_DATA_ERROR;
M
Mark Adler 已提交
1135
            goto inf_leave;
M
Mark Adler 已提交
1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148
        case MEM:
            return Z_MEM_ERROR;
        case SYNC:
        default:
            return Z_STREAM_ERROR;
        }

    /*
       Return from inflate(), updating the total counts and the check value.
       If there was no progress during the inflate() call, return a buffer
       error.  Call updatewindow() to create and/or update the window state.
       Note: a memory error from inflate() is non-recoverable.
     */
M
Mark Adler 已提交
1149
  inf_leave:
M
Mark Adler 已提交
1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163
    RESTORE();
    if (state->wsize || (state->mode < CHECK && out != strm->avail_out))
        if (updatewindow(strm, out)) {
            state->mode = MEM;
            return Z_MEM_ERROR;
        }
    in -= strm->avail_in;
    out -= strm->avail_out;
    strm->total_in += in;
    strm->total_out += out;
    state->total += out;
    if (state->wrap && out)
        strm->adler = state->check =
            UPDATE(state->check, strm->next_out - out, out);
M
Mark Adler 已提交
1164 1165
    strm->data_type = state->bits + (state->last ? 64 : 0) +
                      (state->mode == TYPE ? 128 : 0);
M
Mark Adler 已提交
1166 1167 1168
    if (((in == 0 && out == 0) || flush == Z_FINISH) && ret == Z_OK)
        ret = Z_BUF_ERROR;
    return ret;
M
Mark Adler 已提交
1169 1170
}

M
Mark Adler 已提交
1171 1172 1173 1174
int ZEXPORT inflateEnd(strm)
z_streamp strm;
{
    struct inflate_state FAR *state;
M
Mark Adler 已提交
1175
    if (strm == Z_NULL || strm->state == Z_NULL || strm->zfree == (free_func)0)
M
Mark Adler 已提交
1176 1177 1178 1179 1180 1181 1182 1183
        return Z_STREAM_ERROR;
    state = (struct inflate_state FAR *)strm->state;
    if (state->window != Z_NULL) ZFREE(strm, state->window);
    ZFREE(strm, strm->state);
    strm->state = Z_NULL;
    Tracev((stderr, "inflate: end\n"));
    return Z_OK;
}
M
Mark Adler 已提交
1184

M
Mark Adler 已提交
1185 1186
int ZEXPORT inflateSetDictionary(strm, dictionary, dictLength)
z_streamp strm;
M
Mark Adler 已提交
1187
const Bytef *dictionary;
M
Mark Adler 已提交
1188
uInt dictLength;
M
Mark Adler 已提交
1189
{
M
Mark Adler 已提交
1190 1191
    struct inflate_state FAR *state;
    unsigned long id;
M
Mark Adler 已提交
1192

M
Mark Adler 已提交
1193 1194 1195
    /* check state */
    if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
    state = (struct inflate_state FAR *)strm->state;
M
Mark Adler 已提交
1196 1197
    if (state->wrap != 0 && state->mode != DICT)
        return Z_STREAM_ERROR;
M
Mark Adler 已提交
1198

M
Mark Adler 已提交
1199
    /* check for correct dictionary id */
M
Mark Adler 已提交
1200 1201 1202 1203 1204 1205
    if (state->mode == DICT) {
        id = adler32(0L, Z_NULL, 0);
        id = adler32(id, dictionary, dictLength);
        if (id != state->check)
            return Z_DATA_ERROR;
    }
M
Mark Adler 已提交
1206 1207 1208 1209 1210 1211

    /* copy dictionary to window */
    if (updatewindow(strm, strm->avail_out)) {
        state->mode = MEM;
        return Z_MEM_ERROR;
    }
M
Mark Adler 已提交
1212
    if (dictLength > state->wsize) {
M
Mark Adler 已提交
1213 1214
        zmemcpy(state->window, dictionary + dictLength - state->wsize,
                state->wsize);
M
Mark Adler 已提交
1215 1216 1217
        state->whave = state->wsize;
    }
    else {
M
Mark Adler 已提交
1218 1219
        zmemcpy(state->window + state->wsize - dictLength, dictionary,
                dictLength);
M
Mark Adler 已提交
1220 1221
        state->whave = dictLength;
    }
M
Mark Adler 已提交
1222 1223 1224
    state->havedict = 1;
    Tracev((stderr, "inflate:   dictionary set\n"));
    return Z_OK;
M
Mark Adler 已提交
1225
}
M
Mark Adler 已提交
1226

M
Mark Adler 已提交
1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243
int ZEXPORT inflateGetHeader(strm, head)
z_streamp strm;
gz_headerp head;
{
    struct inflate_state FAR *state;

    /* check state */
    if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
    state = (struct inflate_state FAR *)strm->state;
    if ((state->wrap & 2) == 0) return Z_STREAM_ERROR;

    /* save header structure */
    state->head = head;
    head->done = 0;
    return Z_OK;
}

M
Mark Adler 已提交
1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255
/*
   Search buf[0..len-1] for the pattern: 0, 0, 0xff, 0xff.  Return when found
   or when out of input.  When called, *have is the number of pattern bytes
   found in order so far, in 0..3.  On return *have is updated to the new
   state.  If on return *have equals four, then the pattern was found and the
   return value is how many bytes were read including the last byte of the
   pattern.  If *have is less than four, then the pattern has not been found
   yet and the return value is len.  In the latter case, syncsearch() can be
   called again with more data and the *have state.  *have is initialized to
   zero for the first call.
 */
local unsigned syncsearch(have, buf, len)
M
Mark Adler 已提交
1256
unsigned FAR *have;
M
Mark Adler 已提交
1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284
unsigned char FAR *buf;
unsigned len;
{
    unsigned got;
    unsigned next;

    got = *have;
    next = 0;
    while (next < len && got < 4) {
        if ((int)(buf[next]) == (got < 2 ? 0 : 0xff))
            got++;
        else if (buf[next])
            got = 0;
        else
            got = 4 - got;
        next++;
    }
    *have = got;
    return next;
}

int ZEXPORT inflateSync(strm)
z_streamp strm;
{
    unsigned len;               /* number of bytes to look at or looked at */
    unsigned long in, out;      /* temporary to save total_in and total_out */
    unsigned char buf[4];       /* to restore bit buffer to byte string */
    struct inflate_state FAR *state;
M
Mark Adler 已提交
1285

M
Mark Adler 已提交
1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327
    /* check parameters */
    if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
    state = (struct inflate_state FAR *)strm->state;
    if (strm->avail_in == 0 && state->bits < 8) return Z_BUF_ERROR;

    /* if first time, start search in bit buffer */
    if (state->mode != SYNC) {
        state->mode = SYNC;
        state->hold <<= state->bits & 7;
        state->bits -= state->bits & 7;
        len = 0;
        while (state->bits >= 8) {
            buf[len++] = (unsigned char)(state->hold);
            state->hold >>= 8;
            state->bits -= 8;
        }
        state->have = 0;
        syncsearch(&(state->have), buf, len);
    }

    /* search available input */
    len = syncsearch(&(state->have), strm->next_in, strm->avail_in);
    strm->avail_in -= len;
    strm->next_in += len;
    strm->total_in += len;

    /* return no joy or set up to restart inflate() on a new block */
    if (state->have != 4) return Z_DATA_ERROR;
    in = strm->total_in;  out = strm->total_out;
    inflateReset(strm);
    strm->total_in = in;  strm->total_out = out;
    state->mode = TYPE;
    return Z_OK;
}

/*
   Returns true if inflate is currently at the end of a block generated by
   Z_SYNC_FLUSH or Z_FULL_FLUSH. This function is used by one PPP
   implementation to provide an additional safety check. PPP uses
   Z_SYNC_FLUSH but removes the length bytes of the resulting empty stored
   block. When decompressing, PPP checks that at the end of input packet,
   inflate is waiting for these length bytes.
M
Mark Adler 已提交
1328
 */
M
Mark Adler 已提交
1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341
int ZEXPORT inflateSyncPoint(strm)
z_streamp strm;
{
    struct inflate_state FAR *state;

    if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
    state = (struct inflate_state FAR *)strm->state;
    return state->mode == STORED && state->bits == 0;
}

int ZEXPORT inflateCopy(dest, source)
z_streamp dest;
z_streamp source;
M
Mark Adler 已提交
1342
{
M
Mark Adler 已提交
1343 1344 1345
    struct inflate_state FAR *state;
    struct inflate_state FAR *copy;
    unsigned char FAR *window;
M
Mark Adler 已提交
1346
    unsigned wsize;
M
Mark Adler 已提交
1347 1348 1349

    /* check input */
    if (dest == Z_NULL || source == Z_NULL || source->state == Z_NULL ||
M
Mark Adler 已提交
1350
        source->zalloc == (alloc_func)0 || source->zfree == (free_func)0)
M
Mark Adler 已提交
1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368
        return Z_STREAM_ERROR;
    state = (struct inflate_state FAR *)source->state;

    /* allocate space */
    copy = (struct inflate_state FAR *)
           ZALLOC(source, 1, sizeof(struct inflate_state));
    if (copy == Z_NULL) return Z_MEM_ERROR;
    window = Z_NULL;
    if (state->window != Z_NULL) {
        window = (unsigned char FAR *)
                 ZALLOC(source, 1U << state->wbits, sizeof(unsigned char));
        if (window == Z_NULL) {
            ZFREE(source, copy);
            return Z_MEM_ERROR;
        }
    }

    /* copy state */
M
Mark Adler 已提交
1369 1370
    zmemcpy(dest, source, sizeof(z_stream));
    zmemcpy(copy, state, sizeof(struct inflate_state));
M
Mark Adler 已提交
1371
    if (state->lencode >= state->codes &&
M
Mark Adler 已提交
1372
        state->lencode <= state->codes + ENOUGH - 1) {
M
Mark Adler 已提交
1373 1374 1375
        copy->lencode = copy->codes + (state->lencode - state->codes);
        copy->distcode = copy->codes + (state->distcode - state->codes);
    }
M
Mark Adler 已提交
1376
    copy->next = copy->codes + (state->next - state->codes);
M
Mark Adler 已提交
1377 1378 1379 1380
    if (window != Z_NULL) {
        wsize = 1U << state->wbits;
        zmemcpy(window, state->window, wsize);
    }
M
Mark Adler 已提交
1381
    copy->window = window;
M
Mark Adler 已提交
1382
    dest->state = (struct internal_state FAR *)copy;
M
Mark Adler 已提交
1383
    return Z_OK;
M
Mark Adler 已提交
1384
}
M
Mark Adler 已提交
1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401

int ZEXPORT inflateUndermine(strm, subvert)
z_streamp strm;
int subvert;
{
    struct inflate_state FAR *state;

    if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
    state = (struct inflate_state FAR *)strm->state;
#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
    state->sane = !subvert;
    return Z_OK;
#else
    state->sane = 1;
    return Z_DATA_ERROR;
#endif
}