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