varnish-cache/lib/libvgz/inflate.c
0
/* inflate.c -- zlib decompression
1
 * Copyright (C) 1995-2022 Mark Adler
2
 * For conditions of distribution and use, see copyright notice in zlib.h
3
 */
4
5
/*
6
 * Change history:
7
 *
8
 * 1.2.beta0    24 Nov 2002
9
 * - First version -- complete rewrite of inflate to simplify code, avoid
10
 *   creation of window when not needed, minimize use of window when it is
11
 *   needed, make inffast.c even faster, implement gzip decoding, and to
12
 *   improve code readability and style over the previous zlib inflate code
13
 *
14
 * 1.2.beta1    25 Nov 2002
15
 * - Use pointers for available input and output checking in inffast.c
16
 * - Remove input and output counters in inffast.c
17
 * - Change inffast.c entry and loop from avail_in >= 7 to >= 6
18
 * - Remove unnecessary second byte pull from length extra in inffast.c
19
 * - Unroll direct copy to three copies per loop in inffast.c
20
 *
21
 * 1.2.beta2    4 Dec 2002
22
 * - Change external routine names to reduce potential conflicts
23
 * - Correct filename to inffixed.h for fixed tables in inflate.c
24
 * - Make hbuf[] unsigned char to match parameter type in inflate.c
25
 * - Change strm->next_out[-state->offset] to *(strm->next_out - state->offset)
26
 *   to avoid negation problem on Alphas (64 bit) in inflate.c
27
 *
28
 * 1.2.beta3    22 Dec 2002
29
 * - Add comments on state->bits assertion in inffast.c
30
 * - Add comments on op field in inftrees.h
31
 * - Fix bug in reuse of allocated window after inflateReset()
32
 * - Remove bit fields--back to byte structure for speed
33
 * - Remove distance extra == 0 check in inflate_fast()--only helps for lengths
34
 * - Change post-increments to pre-increments in inflate_fast(), PPC biased?
35
 * - Add compile time option, POSTINC, to use post-increments instead (Intel?)
36
 * - Make MATCH copy in inflate() much faster for when inflate_fast() not used
37
 * - Use local copies of stream next and avail values, as well as local bit
38
 *   buffer and bit count in inflate()--for speed when inflate_fast() not used
39
 *
40
 * 1.2.beta4    1 Jan 2003
41
 * - Split ptr - 257 statements in inflate_table() to avoid compiler warnings
42
 * - Move a comment on output buffer sizes from inffast.c to inflate.c
43
 * - Add comments in inffast.c to introduce the inflate_fast() routine
44
 * - Rearrange window copies in inflate_fast() for speed and simplification
45
 * - Unroll last copy for window match in inflate_fast()
46
 * - Use local copies of window variables in inflate_fast() for speed
47
 * - Pull out common wnext == 0 case for speed in inflate_fast()
48
 * - Make op and len in inflate_fast() unsigned for consistency
49
 * - Add FAR to lcode and dcode declarations in inflate_fast()
50
 * - Simplified bad distance check in inflate_fast()
51
 * - Added inflateBackInit(), inflateBack(), and inflateBackEnd() in new
52
 *   source file infback.c to provide a call-back interface to inflate for
53
 *   programs like gzip and unzip -- uses window as output buffer to avoid
54
 *   window copying
55
 *
56
 * 1.2.beta5    1 Jan 2003
57
 * - Improved inflateBack() interface to allow the caller to provide initial
58
 *   input in strm.
59
 * - Fixed stored blocks bug in inflateBack()
60
 *
61
 * 1.2.beta6    4 Jan 2003
62
 * - Added comments in inffast.c on effectiveness of POSTINC
63
 * - Typecasting all around to reduce compiler warnings
64
 * - Changed loops from while (1) or do {} while (1) to for (;;), again to
65
 *   make compilers happy
66
 * - Changed type of window in inflateBackInit() to unsigned char *
67
 *
68
 * 1.2.beta7    27 Jan 2003
69
 * - Changed many types to unsigned or unsigned short to avoid warnings
70
 * - Added inflateCopy() function
71
 *
72
 * 1.2.0        9 Mar 2003
73
 * - Changed inflateBack() interface to provide separate opaque descriptors
74
 *   for the in() and out() functions
75
 * - Changed inflateBack() argument and in_func typedef to swap the length
76
 *   and buffer address return values for the input function
77
 * - Check next_in and next_out for Z_NULL on entry to inflate()
78
 *
79
 * The history for versions after 1.2.0 are in ChangeLog in zlib distribution.
80
 */
81
82
#include "zutil.h"
83
#include "inftrees.h"
84
#include "inflate.h"
85
#include "inffast.h"
86
87
#ifdef MAKEFIXED
88
#  ifndef BUILDFIXED
89
#    define BUILDFIXED
90
#  endif
91
#endif
92
93
/* function prototypes */
94
local int inflateStateCheck OF((z_streamp strm));
95
local void fixedtables OF((struct inflate_state FAR *state));
96
local int updatewindow OF((z_streamp strm, const unsigned char FAR *end,
97
                           unsigned copy));
98
#ifdef BUILDFIXED
99
   void makefixed OF((void));
100
#endif
101
#ifdef NOVGZ
102
local unsigned syncsearch OF((unsigned FAR *have, const unsigned char FAR *buf,
103
                              unsigned len));
104
#endif /* NOVGZ */
105
106 7766
local int inflateStateCheck(strm)
107
z_streamp strm;
108
{
109
    struct inflate_state FAR *state;
110 15532
    if (strm == Z_NULL ||
111 7766
        strm->zalloc == (alloc_func)0 || strm->zfree == (free_func)0)
112 0
        return 1;
113 7766
    state = (struct inflate_state FAR *)strm->state;
114 15532
    if (state == Z_NULL || state->strm != strm ||
115 7766
        state->mode < HEAD || state->mode > SYNC)
116 0
        return 1;
117 7766
    return 0;
118 7766
}
119
120 1080
int ZEXPORT inflateResetKeep(strm)
121
z_streamp strm;
122
{
123
    struct inflate_state FAR *state;
124
125 1080
    if (inflateStateCheck(strm)) return Z_STREAM_ERROR;
126 1080
    state = (struct inflate_state FAR *)strm->state;
127 1080
    strm->total_in = strm->total_out = state->total = 0;
128 1080
    strm->start_bit = strm->stop_bit = strm->last_bit = 0;
129 1080
    strm->msg = Z_NULL;
130 1080
    if (state->wrap)        /* to support ill-conceived Java test suite */
131 1080
        strm->adler = state->wrap & 1;
132 1080
    state->mode = HEAD;
133 1080
    state->last = 0;
134 1080
    state->havedict = 0;
135 1080
    state->flags = -1;
136 1080
    state->dmax = 32768U;
137 1080
    state->head = Z_NULL;
138 1080
    state->hold = 0;
139 1080
    state->bits = 0;
140 1080
    state->lencode = state->distcode = state->next = state->codes;
141 1080
    state->sane = 1;
142 1080
    state->back = -1;
143
    Tracev((stderr, "inflate: reset\n"));
144 1080
    return Z_OK;
145 1080
}
146
147 1080
int ZEXPORT inflateReset(strm)
148
z_streamp strm;
149
{
150
    struct inflate_state FAR *state;
151
152 1080
    if (inflateStateCheck(strm)) return Z_STREAM_ERROR;
153 1080
    state = (struct inflate_state FAR *)strm->state;
154 1080
    state->wsize = 0;
155 1080
    state->whave = 0;
156 1080
    state->wnext = 0;
157 1080
    return inflateResetKeep(strm);
158 1080
}
159
160 1080
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 1080
    if (inflateStateCheck(strm)) return Z_STREAM_ERROR;
169 1080
    state = (struct inflate_state FAR *)strm->state;
170
171
    /* extract wrap request from windowBits parameter */
172 1080
    if (windowBits < 0) {
173 0
        wrap = 0;
174 0
        windowBits = -windowBits;
175 0
    }
176
    else {
177 1080
        wrap = (windowBits >> 4) + 5;
178
#ifdef GUNZIP
179 1080
        if (windowBits < 48)
180 1080
            windowBits &= 15;
181
#endif
182
    }
183
184
    /* set number of window bits, free window if different */
185 1080
    if (windowBits && (windowBits < 8 || windowBits > 15))
186 0
        return Z_STREAM_ERROR;
187 1080
    if (state->window != Z_NULL && state->wbits != (unsigned)windowBits) {
188 0
        ZFREE(strm, state->window);
189 0
        state->window = Z_NULL;
190 0
    }
191
192
    /* update state and reset the rest of it */
193 1080
    state->wrap = wrap;
194 1080
    state->wbits = (unsigned)windowBits;
195 1080
    return inflateReset(strm);
196 1080
}
197
198 1080
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 1080
    if (version == Z_NULL || version[0] != ZLIB_VERSION[0] ||
208 1080
        stream_size != (int)(sizeof(z_stream)))
209 0
        return Z_VERSION_ERROR;
210 1080
    if (strm == Z_NULL) return Z_STREAM_ERROR;
211 1080
    strm->msg = Z_NULL;                 /* in case we return an error */
212 1080
    if (strm->zalloc == (alloc_func)0) {
213
#ifdef Z_SOLO
214
        return Z_STREAM_ERROR;
215
#else
216 1080
        strm->zalloc = zcalloc;
217 1080
        strm->opaque = (voidpf)0;
218
#endif
219 1080
    }
220 1080
    if (strm->zfree == (free_func)0)
221
#ifdef Z_SOLO
222
        return Z_STREAM_ERROR;
223
#else
224 1080
        strm->zfree = zcfree;
225
#endif
226 1080
    state = (struct inflate_state FAR *)
227 1080
            ZALLOC(strm, 1, sizeof(struct inflate_state));
228 1080
    if (state == Z_NULL) return Z_MEM_ERROR;
229
    Tracev((stderr, "inflate: allocated\n"));
230 1080
    strm->state = (struct internal_state FAR *)state;
231 1080
    state->strm = strm;
232 1080
    state->window = Z_NULL;
233 1080
    state->mode = HEAD;     /* to pass state test in inflateReset2() */
234 1080
    ret = inflateReset2(strm, windowBits);
235 1080
    if (ret != Z_OK) {
236 0
        ZFREE(strm, state);
237 0
        strm->state = Z_NULL;
238 0
    }
239 1080
    return ret;
240 1080
}
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 /* NOVGZ */
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 1644
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 1644
    state->lencode = lenfix;
323 1644
    state->lenbits = 9;
324 1644
    state->distcode = distfix;
325 1644
    state->distbits = 5;
326 1644
}
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 2486
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 2486
    state = (struct inflate_state FAR *)strm->state;
412
413
    /* if it hasn't been done already, allocate space for the window */
414 2486
    if (state->window == Z_NULL) {
415 264
        state->window = (unsigned char FAR *)
416 264
                        ZALLOC(strm, 1U << state->wbits,
417
                               sizeof(unsigned char));
418 264
        if (state->window == Z_NULL) return 1;
419 264
    }
420
421
    /* if window not in use yet, initialize */
422 2486
    if (state->wsize == 0) {
423 264
        state->wsize = 1U << state->wbits;
424 264
        state->wnext = 0;
425 264
        state->whave = 0;
426 264
    }
427
428
    /* copy state->wsize or less output bytes into the circular window */
429 2486
    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 0
    }
434
    else {
435 2486
        dist = state->wsize - state->wnext;
436 2486
        if (dist > copy) dist = copy;
437 2486
        zmemcpy(state->window + state->wnext, end - copy, dist);
438 2486
        copy -= dist;
439 2486
        if (copy) {
440 0
            zmemcpy(state->window, end - copy, copy);
441 0
            state->wnext = copy;
442 0
            state->whave = state->wsize;
443 0
        }
444
        else {
445 2486
            state->wnext += dist;
446 2486
            if (state->wnext == state->wsize) state->wnext = 0;
447 2486
            if (state->whave < state->wsize) state->whave += dist;
448
        }
449
    }
450 2486
    return 0;
451 2486
}
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(check, buf, len) \
458
    (state->flags ? crc32(check, buf, len) : adler32(check, buf, len))
459
#else
460
#  define UPDATE_CHECK(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 3446
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 3446
    if (inflateStateCheck(strm) || strm->next_out == Z_NULL ||
653 3446
        (strm->next_in == Z_NULL && strm->avail_in != 0))
654 0
        return Z_STREAM_ERROR;
655
656 3446
    state = (struct inflate_state FAR *)strm->state;
657 3446
    if (state->mode == TYPE) state->mode = TYPEDO;      /* skip check */
658 3446
    LOAD();
659 3446
    in = have;
660 3446
    out = left;
661 3446
    ret = Z_OK;
662 24309
    for (;;)
663 24309
        switch (state->mode) {
664
        case HEAD:
665 864
            if (state->wrap == 0) {
666 0
                state->mode = TYPEDO;
667 0
                break;
668
            }
669 2592
            NEEDBITS(16);
670
#ifdef GUNZIP
671 864
            if ((state->wrap & 2) && hold == 0x8b1f) {  /* gzip header */
672 864
                if (state->wbits == 0)
673 0
                    state->wbits = 15;
674 864
                state->check = crc32(0L, Z_NULL, 0);
675 864
                CRC2(state->check, hold);
676 864
                INITBITS();
677 864
                state->mode = FLAGS;
678 864
                break;
679
            }
680 0
            if (state->head != Z_NULL)
681 0
                state->head->done = -1;
682 0
            if (!(state->wrap & 1) ||   /* check if zlib header allowed */
683
#else
684
            if (
685
#endif
686 0
                ((BITS(8) << 8) + (hold >> 8)) % 31) {
687 0
                strm->msg = "incorrect header check";
688 0
                state->mode = BAD;
689 0
                break;
690
            }
691 0
            if (BITS(4) != Z_DEFLATED) {
692 0
                strm->msg = "unknown compression method";
693 0
                state->mode = BAD;
694 0
                break;
695
            }
696 0
            DROPBITS(4);
697 0
            len = BITS(4) + 8;
698 0
            if (state->wbits == 0)
699 0
                state->wbits = len;
700 0
            if (len > 15 || len > state->wbits) {
701 0
                strm->msg = "invalid window size";
702 0
                state->mode = BAD;
703 0
                break;
704
            }
705 0
            state->dmax = 1U << len;
706 0
            state->flags = 0;               /* indicate zlib header */
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 2600
            NEEDBITS(16);
715 864
            state->flags = (int)(hold);
716 864
            if ((state->flags & 0xff) != Z_DEFLATED) {
717 0
                strm->msg = "unknown compression method";
718 0
                state->mode = BAD;
719 0
                break;
720
            }
721 864
            if (state->flags & 0xe000) {
722 0
                strm->msg = "unknown header flags set";
723 0
                state->mode = BAD;
724 0
                break;
725
            }
726 864
            if (state->head != Z_NULL)
727 0
                state->head->text = (int)((hold >> 8) & 1);
728 864
            if ((state->flags & 0x0200) && (state->wrap & 4))
729 8
                CRC2(state->check, hold);
730 864
            INITBITS();
731 864
            state->mode = TIME;
732
                /* fallthrough */
733
        case TIME:
734 4320
            NEEDBITS(32);
735 864
            if (state->head != Z_NULL)
736 0
                state->head->time = hold;
737 864
            if ((state->flags & 0x0200) && (state->wrap & 4))
738 8
                CRC4(state->check, hold);
739 864
            INITBITS();
740 864
            state->mode = OS;
741
                /* fallthrough */
742
        case OS:
743 2592
            NEEDBITS(16);
744 864
            if (state->head != Z_NULL) {
745 0
                state->head->xflags = (int)(hold & 0xff);
746 0
                state->head->os = (int)(hold >> 8);
747 0
            }
748 864
            if ((state->flags & 0x0200) && (state->wrap & 4))
749 8
                CRC2(state->check, hold);
750 864
            INITBITS();
751 864
            state->mode = EXLEN;
752
                /* fallthrough */
753
        case EXLEN:
754 864
            if (state->flags & 0x0400) {
755 24
                NEEDBITS(16);
756 8
                state->length = (unsigned)(hold);
757 8
                if (state->head != Z_NULL)
758 0
                    state->head->extra_len = (unsigned)hold;
759 8
                if ((state->flags & 0x0200) && (state->wrap & 4))
760 8
                    CRC2(state->check, hold);
761 8
                INITBITS();
762 8
            }
763 856
            else if (state->head != Z_NULL)
764 0
                state->head->extra = Z_NULL;
765 864
            state->mode = EXTRA;
766
                /* fallthrough */
767
        case EXTRA:
768 864
            if (state->flags & 0x0400) {
769 8
                copy = state->length;
770 8
                if (copy > have) copy = have;
771 8
                if (copy) {
772 8
                    if (state->head != Z_NULL &&
773 0
                        state->head->extra != Z_NULL &&
774 0
                        (len = state->head->extra_len - state->length) <
775 0
                            state->head->extra_max) {
776 0
                        zmemcpy(state->head->extra + len, next,
777 0
                                len + copy > state->head->extra_max ?
778 0
                                state->head->extra_max - len : copy);
779 0
                    }
780 8
                    if ((state->flags & 0x0200) && (state->wrap & 4))
781 8
                        state->check = crc32(state->check, next, copy);
782 8
                    have -= copy;
783 8
                    next += copy;
784 8
                    state->length -= copy;
785 8
                }
786 8
                if (state->length) goto inf_leave;
787 8
            }
788 864
            state->length = 0;
789 864
            state->mode = NAME;
790
                /* fallthrough */
791
        case NAME:
792 864
            if (state->flags & 0x0800) {
793 28
                if (have == 0) goto inf_leave;
794 28
                copy = 0;
795 28
                do {
796 88
                    len = (unsigned)(next[copy++]);
797 88
                    if (state->head != Z_NULL &&
798 0
                            state->head->name != Z_NULL &&
799 0
                            state->length < state->head->name_max)
800 0
                        state->head->name[state->length++] = (Bytef)len;
801 88
                } while (len && copy < have);
802 28
                if ((state->flags & 0x0200) && (state->wrap & 4))
803 8
                    state->check = crc32(state->check, next, copy);
804 28
                have -= copy;
805 28
                next += copy;
806 28
                if (len) goto inf_leave;
807 28
            }
808 836
            else if (state->head != Z_NULL)
809 0
                state->head->name = Z_NULL;
810 864
            state->length = 0;
811 864
            state->mode = COMMENT;
812
                /* fallthrough */
813
        case COMMENT:
814 864
            if (state->flags & 0x1000) {
815 8
                if (have == 0) goto inf_leave;
816 8
                copy = 0;
817 8
                do {
818 72
                    len = (unsigned)(next[copy++]);
819 72
                    if (state->head != Z_NULL &&
820 0
                            state->head->comment != Z_NULL &&
821 0
                            state->length < state->head->comm_max)
822 0
                        state->head->comment[state->length++] = (Bytef)len;
823 72
                } while (len && copy < have);
824 8
                if ((state->flags & 0x0200) && (state->wrap & 4))
825 8
                    state->check = crc32(state->check, next, copy);
826 8
                have -= copy;
827 8
                next += copy;
828 8
                if (len) goto inf_leave;
829 8
            }
830 856
            else if (state->head != Z_NULL)
831 0
                state->head->comment = Z_NULL;
832 864
            state->mode = HCRC;
833
                /* fallthrough */
834
        case HCRC:
835 864
            if (state->flags & 0x0200) {
836 24
                NEEDBITS(16);
837 8
                if ((state->wrap & 4) && hold != (state->check & 0xffff)) {
838 0
                    strm->msg = "header crc mismatch";
839 0
                    state->mode = BAD;
840 0
                    break;
841
                }
842 8
                INITBITS();
843 8
            }
844 864
            if (state->head != Z_NULL) {
845 0
                state->head->hcrc = (int)((state->flags >> 9) & 1);
846 0
                state->head->done = 1;
847 0
            }
848 864
            strm->adler = state->check = crc32(0L, Z_NULL, 0);
849 864
            state->mode = TYPE;
850 864
            break;
851
#endif
852
        case DICTID:
853 0
            NEEDBITS(32);
854 0
            strm->adler = state->check = ZSWAP32(hold);
855 0
            INITBITS();
856 0
            state->mode = DICT;
857
                /* fallthrough */
858
        case DICT:
859 0
            if (state->havedict == 0) {
860 0
                RESTORE();
861 0
                return Z_NEED_DICT;
862
            }
863 0
            strm->adler = state->check = adler32(0L, Z_NULL, 0);
864 0
            state->mode = TYPE;
865
                /* fallthrough */
866
        case TYPE:
867 4088
            if (flush == Z_BLOCK || flush == Z_TREES) goto inf_leave;
868
                /* fallthrough */
869
        case TYPEDO:
870 4616
            if (strm->start_bit == 0)
871 864
                strm->start_bit = 8 * (strm->total_in + in - have) - bits;
872 4616
            if (state->last) {
873 840
                strm->stop_bit = 8 * (strm->total_in + in - have) - bits;
874 840
                BYTEBITS();
875 840
                state->mode = CHECK;
876 840
                break;
877
            }
878 6089
            NEEDBITS(3);
879 3248
            state->last = BITS(1);
880 3248
            if (state->last)
881 864
                strm->last_bit = 8 * (strm->total_in + in - have) - bits;
882 3248
            DROPBITS(1);
883 3248
            switch (BITS(2)) {
884
            case 0:                             /* stored block */
885
                Tracev((stderr, "inflate:     stored block%s\n",
886
                        state->last ? " (last)" : ""));
887 1572
                state->mode = STORED;
888 1572
                break;
889
            case 1:                             /* fixed block */
890 1644
                fixedtables(state);
891
                Tracev((stderr, "inflate:     fixed codes block%s\n",
892
                        state->last ? " (last)" : ""));
893 1644
                state->mode = LEN_;             /* decode codes */
894 1644
                if (flush == Z_TREES) {
895 0
                    DROPBITS(2);
896 0
                    goto inf_leave;
897
                }
898 1644
                break;
899
            case 2:                             /* dynamic block */
900
                Tracev((stderr, "inflate:     dynamic codes block%s\n",
901
                        state->last ? " (last)" : ""));
902 32
                state->mode = TABLE;
903 32
                break;
904
            case 3:
905 0
                strm->msg = "invalid block type";
906 0
                state->mode = BAD;
907 0
            }
908 3248
            DROPBITS(2);
909 3248
            break;
910
        case STORED:
911 1596
            BYTEBITS();                         /* go to byte boundary */
912 7884
            NEEDBITS(32);
913 1572
            if ((hold & 0xffff) != ((hold >> 16) ^ 0xffff)) {
914 0
                strm->msg = "invalid stored block lengths";
915 0
                state->mode = BAD;
916 0
                break;
917
            }
918 1572
            state->length = (unsigned)hold & 0xffff;
919
            Tracev((stderr, "inflate:       stored length %u\n",
920
                    state->length));
921 1572
            INITBITS();
922 1572
            state->mode = COPY_;
923 1572
            if (flush == Z_TREES) goto inf_leave;
924
                /* fallthrough */
925
        case COPY_:
926 1572
            state->mode = COPY;
927
                /* fallthrough */
928
        case COPY:
929 4872
            copy = state->length;
930 4872
            if (copy) {
931 3300
                if (copy > have) copy = have;
932 3300
                if (copy > left) copy = left;
933 3300
                if (copy == 0) goto inf_leave;
934 1862
                zmemcpy(put, next, copy);
935 1862
                have -= copy;
936 1862
                next += copy;
937 1862
                left -= copy;
938 1862
                put += copy;
939 1862
                state->length -= copy;
940 1862
                break;
941
            }
942
            Tracev((stderr, "inflate:       stored end\n"));
943 1572
            state->mode = TYPE;
944 1572
            break;
945
        case TABLE:
946 96
            NEEDBITS(14);
947 32
            state->nlen = BITS(5) + 257;
948 32
            DROPBITS(5);
949 32
            state->ndist = BITS(5) + 1;
950 32
            DROPBITS(5);
951 32
            state->ncode = BITS(4) + 4;
952 32
            DROPBITS(4);
953
#ifndef PKZIP_BUG_WORKAROUND
954 32
            if (state->nlen > 286 || state->ndist > 30) {
955 0
                strm->msg = "too many length or distance symbols";
956 0
                state->mode = BAD;
957 0
                break;
958
            }
959
#endif
960
            Tracev((stderr, "inflate:       table sizes ok\n"));
961 32
            state->have = 0;
962 32
            state->mode = LENLENS;
963
                /* fallthrough */
964
        case LENLENS:
965 560
            while (state->have < state->ncode) {
966 720
                NEEDBITS(3);
967 528
                state->lens[order[state->have++]] = (unsigned short)BITS(3);
968 528
                DROPBITS(3);
969
            }
970 112
            while (state->have < 19)
971 80
                state->lens[order[state->have++]] = 0;
972 32
            state->next = state->codes;
973 32
            state->lencode = (const code FAR *)(state->next);
974 32
            state->lenbits = 7;
975 64
            ret = inflate_table(CODES, state->lens, 19, &(state->next),
976 32
                                &(state->lenbits), state->work);
977 32
            if (ret) {
978 0
                strm->msg = "invalid code lengths set";
979 0
                state->mode = BAD;
980 0
                break;
981
            }
982
            Tracev((stderr, "inflate:       code lengths ok\n"));
983 32
            state->have = 0;
984 32
            state->mode = CODELENS;
985
                /* fallthrough */
986
        case CODELENS:
987 2408
            while (state->have < state->nlen + state->ndist) {
988 3292
                for (;;) {
989 3292
                    here = state->lencode[BITS(state->lenbits)];
990 3292
                    if ((unsigned)(here.bits) <= bits) break;
991 916
                    PULLBYTE();
992
                }
993 2376
                if (here.val < 16) {
994 2060
                    DROPBITS(here.bits);
995 2060
                    state->lens[state->have++] = here.val;
996 2060
                }
997
                else {
998 316
                    if (here.val == 16) {
999 52
                        NEEDBITS(here.bits + 2);
1000 48
                        DROPBITS(here.bits);
1001 48
                        if (state->have == 0) {
1002 0
                            strm->msg = "invalid bit length repeat";
1003 0
                            state->mode = BAD;
1004 0
                            break;
1005
                        }
1006 48
                        len = state->lens[state->have - 1];
1007 48
                        copy = 3 + BITS(2);
1008 48
                        DROPBITS(2);
1009 48
                    }
1010 268
                    else if (here.val == 17) {
1011 180
                        NEEDBITS(here.bits + 3);
1012 140
                        DROPBITS(here.bits);
1013 140
                        len = 0;
1014 140
                        copy = 3 + BITS(3);
1015 140
                        DROPBITS(3);
1016 140
                    }
1017
                    else {
1018 228
                        NEEDBITS(here.bits + 7);
1019 128
                        DROPBITS(here.bits);
1020 128
                        len = 0;
1021 128
                        copy = 11 + BITS(7);
1022 128
                        DROPBITS(7);
1023
                    }
1024 316
                    if (state->have + copy > state->nlen + state->ndist) {
1025 0
                        strm->msg = "invalid bit length repeat";
1026 0
                        state->mode = BAD;
1027 0
                        break;
1028
                    }
1029 7356
                    while (copy--)
1030 7040
                        state->lens[state->have++] = (unsigned short)len;
1031
                }
1032
            }
1033
1034
            /* handle error breaks in while */
1035 32
            if (state->mode == BAD) break;
1036
1037
            /* check for end-of-block code (better have one) */
1038 32
            if (state->lens[256] == 0) {
1039 0
                strm->msg = "invalid code -- missing end-of-block";
1040 0
                state->mode = BAD;
1041 0
                break;
1042
            }
1043
1044
            /* build code tables -- note: do not change the lenbits or distbits
1045
               values here (9 and 6) without reading the comments in inftrees.h
1046
               concerning the ENOUGH constants, which depend on those values */
1047 32
            state->next = state->codes;
1048 32
            state->lencode = (const code FAR *)(state->next);
1049 32
            state->lenbits = 9;
1050 64
            ret = inflate_table(LENS, state->lens, state->nlen, &(state->next),
1051 32
                                &(state->lenbits), state->work);
1052 32
            if (ret) {
1053 0
                strm->msg = "invalid literal/lengths set";
1054 0
                state->mode = BAD;
1055 0
                break;
1056
            }
1057 32
            state->distcode = (const code FAR *)(state->next);
1058 32
            state->distbits = 6;
1059 64
            ret = inflate_table(DISTS, state->lens + state->nlen, state->ndist,
1060 32
                            &(state->next), &(state->distbits), state->work);
1061 32
            if (ret) {
1062 0
                strm->msg = "invalid distances set";
1063 0
                state->mode = BAD;
1064 0
                break;
1065
            }
1066
            Tracev((stderr, "inflate:       codes ok\n"));
1067 32
            state->mode = LEN_;
1068 32
            if (flush == Z_TREES) goto inf_leave;
1069
                /* fallthrough */
1070
        case LEN_:
1071 1676
            state->mode = LEN;
1072
                /* fallthrough */
1073
        case LEN:
1074 7256
            if (have >= 6 && left >= 258) {
1075 1914
                RESTORE();
1076 1914
                inflate_fast(strm, out);
1077 1914
                LOAD();
1078 1914
                if (state->mode == TYPE)
1079 1036
                    state->back = -1;
1080 1914
                break;
1081
            }
1082 5342
            state->back = 0;
1083 10444
            for (;;) {
1084 10444
                here = state->lencode[BITS(state->lenbits)];
1085 10444
                if ((unsigned)(here.bits) <= bits) break;
1086 5250
                PULLBYTE();
1087
            }
1088 5194
            if (here.op && (here.op & 0xf0) == 0) {
1089 0
                last = here;
1090 0
                for (;;) {
1091 0
                    here = state->lencode[last.val +
1092 0
                            (BITS(last.bits + last.op) >> last.bits)];
1093 0
                    if ((unsigned)(last.bits + here.bits) <= bits) break;
1094 0
                    PULLBYTE();
1095
                }
1096 0
                DROPBITS(last.bits);
1097 0
                state->back += last.bits;
1098 0
            }
1099 5194
            DROPBITS(here.bits);
1100 5194
            state->back += here.bits;
1101 5194
            state->length = (unsigned)here.val;
1102 5194
            if ((int)(here.op) == 0) {
1103
                Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
1104
                        "inflate:         literal '%c'\n" :
1105
                        "inflate:         literal 0x%02x\n", here.val));
1106 4513
                state->mode = LIT;
1107 4513
                break;
1108
            }
1109 681
            if (here.op & 32) {
1110
                Tracevv((stderr, "inflate:         end of block\n"));
1111 616
                state->back = -1;
1112 616
                state->mode = TYPE;
1113 616
                break;
1114
            }
1115 65
            if (here.op & 64) {
1116 0
                strm->msg = "invalid literal/length code";
1117 0
                state->mode = BAD;
1118 0
                break;
1119
            }
1120 65
            state->extra = (unsigned)(here.op) & 15;
1121 65
            state->mode = LENEXT;
1122
                /* fallthrough */
1123
        case LENEXT:
1124 65
            if (state->extra) {
1125 8
                NEEDBITS(state->extra);
1126 8
                state->length += BITS(state->extra);
1127 8
                DROPBITS(state->extra);
1128 8
                state->back += state->extra;
1129 8
            }
1130
            Tracevv((stderr, "inflate:         length %u\n", state->length));
1131 65
            state->was = state->length;
1132 65
            state->mode = DIST;
1133
                /* fallthrough */
1134
        case DIST:
1135 84
            for (;;) {
1136 84
                here = state->distcode[BITS(state->distbits)];
1137 84
                if ((unsigned)(here.bits) <= bits) break;
1138 19
                PULLBYTE();
1139
            }
1140 65
            if ((here.op & 0xf0) == 0) {
1141 0
                last = here;
1142 0
                for (;;) {
1143 0
                    here = state->distcode[last.val +
1144 0
                            (BITS(last.bits + last.op) >> last.bits)];
1145 0
                    if ((unsigned)(last.bits + here.bits) <= bits) break;
1146 0
                    PULLBYTE();
1147
                }
1148 0
                DROPBITS(last.bits);
1149 0
                state->back += last.bits;
1150 0
            }
1151 65
            DROPBITS(here.bits);
1152 65
            state->back += here.bits;
1153 65
            if (here.op & 64) {
1154 0
                strm->msg = "invalid distance code";
1155 0
                state->mode = BAD;
1156 0
                break;
1157
            }
1158 65
            state->offset = (unsigned)here.val;
1159 65
            state->extra = (unsigned)(here.op) & 15;
1160 65
            state->mode = DISTEXT;
1161
                /* fallthrough */
1162
        case DISTEXT:
1163 65
            if (state->extra) {
1164 75
                NEEDBITS(state->extra);
1165 49
                state->offset += BITS(state->extra);
1166 49
                DROPBITS(state->extra);
1167 49
                state->back += state->extra;
1168 49
            }
1169
#ifdef INFLATE_STRICT
1170
            if (state->offset > state->dmax) {
1171
                strm->msg = "invalid distance too far back";
1172
                state->mode = BAD;
1173
                break;
1174
            }
1175
#endif
1176
            Tracevv((stderr, "inflate:         distance %u\n", state->offset));
1177 57
            state->mode = MATCH;
1178
                /* fallthrough */
1179
        case MATCH:
1180 57
            if (left == 0) goto inf_leave;
1181 57
            copy = out - left;
1182 57
            if (state->offset > copy) {         /* copy from window */
1183 6
                copy = state->offset - copy;
1184 6
                if (copy > state->whave) {
1185 0
                    if (state->sane) {
1186 0
                        strm->msg = "invalid distance too far back";
1187 0
                        state->mode = BAD;
1188 0
                        break;
1189
                    }
1190
#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
1191
                    Trace((stderr, "inflate.c too far\n"));
1192
                    copy -= state->whave;
1193
                    if (copy > state->length) copy = state->length;
1194
                    if (copy > left) copy = left;
1195
                    left -= copy;
1196
                    state->length -= copy;
1197
                    do {
1198
                        *put++ = 0;
1199
                    } while (--copy);
1200
                    if (state->length == 0) state->mode = LEN;
1201
                    break;
1202
#endif
1203 0
                }
1204 6
                if (copy > state->wnext) {
1205 0
                    copy -= state->wnext;
1206 0
                    from = state->window + (state->wsize - copy);
1207 0
                }
1208
                else
1209 6
                    from = state->window + (state->wnext - copy);
1210 6
                if (copy > state->length) copy = state->length;
1211 6
            }
1212
            else {                              /* copy from output */
1213 51
                from = put - state->offset;
1214 51
                copy = state->length;
1215
            }
1216 57
            if (copy > left) copy = left;
1217 57
            left -= copy;
1218 57
            state->length -= copy;
1219 57
            do {
1220 299
                *put++ = *from++;
1221 299
            } while (--copy);
1222 57
            if (state->length == 0) state->mode = LEN;
1223 57
            break;
1224
        case LIT:
1225 4529
            if (left == 0) goto inf_leave;
1226 4513
            *put++ = (unsigned char)(state->length);
1227 4513
            left--;
1228 4513
            state->mode = LEN;
1229 4513
            break;
1230
        case CHECK:
1231 968
            if (state->wrap) {
1232 4328
                NEEDBITS(32);
1233 840
                out -= left;
1234 840
                strm->total_out += out;
1235 840
                state->total += out;
1236 840
                if ((state->wrap & 4) && out)
1237 624
                    strm->adler = state->check =
1238 624
                        UPDATE_CHECK(state->check, put - out, out);
1239 840
                out = left;
1240 1680
                if ((state->wrap & 4) && (
1241
#ifdef GUNZIP
1242 840
                     state->flags ? hold :
1243
#endif
1244 840
                     ZSWAP32(hold)) != state->check) {
1245 0
                    strm->msg = "incorrect data check";
1246 0
                    state->mode = BAD;
1247 0
                    break;
1248
                }
1249 840
                INITBITS();
1250
                Tracev((stderr, "inflate:   check matches trailer\n"));
1251 840
            }
1252
#ifdef GUNZIP
1253 840
            state->mode = LENGTH;
1254
                /* fallthrough */
1255
        case LENGTH:
1256 840
            if (state->wrap && state->flags) {
1257 4200
                NEEDBITS(32);
1258 840
                if ((state->wrap & 4) && hold != (state->total & 0xffffffff)) {
1259 0
                    strm->msg = "incorrect length check";
1260 0
                    state->mode = BAD;
1261 0
                    break;
1262
                }
1263 840
                INITBITS();
1264
                Tracev((stderr, "inflate:   length matches trailer\n"));
1265 840
            }
1266
#endif
1267 840
            state->mode = DONE;
1268
                /* fallthrough */
1269
        case DONE:
1270 1140
            ret = Z_STREAM_END;
1271 1140
            goto inf_leave;
1272
        case BAD:
1273 8
            ret = Z_DATA_ERROR;
1274 8
            goto inf_leave;
1275
        case MEM:
1276 0
            return Z_MEM_ERROR;
1277
        case SYNC:
1278
                /* fallthrough */
1279
        default:
1280 0
            return Z_STREAM_ERROR;
1281
        }
1282
1283
    /*
1284
       Return from inflate(), updating the total counts and the check value.
1285
       If there was no progress during the inflate() call, return a buffer
1286
       error.  Call updatewindow() to create and/or update the window state.
1287
       Note: a memory error from inflate() is non-recoverable.
1288
     */
1289
  inf_leave:
1290 3446
    RESTORE();
1291 3574
    if (state->wsize || (out != strm->avail_out && state->mode < BAD &&
1292 264
            (state->mode < CHECK || flush != Z_FINISH)))
1293 2486
        if (updatewindow(strm, strm->next_out, out - strm->avail_out)) {
1294 0
            state->mode = MEM;
1295 0
            return Z_MEM_ERROR;
1296
        }
1297 3446
    in -= strm->avail_in;
1298 3446
    out -= strm->avail_out;
1299 3446
    strm->total_in += in;
1300 3446
    strm->total_out += out;
1301 3446
    state->total += out;
1302 3446
    if ((state->wrap & 4) && out)
1303 1914
        strm->adler = state->check =
1304 1914
            UPDATE_CHECK(state->check, strm->next_out - out, out);
1305 10338
    strm->data_type = (int)state->bits + (state->last ? 64 : 0) +
1306 6892
                      (state->mode == TYPE ? 128 : 0) +
1307 3446
                      (state->mode == LEN_ || state->mode == COPY_ ? 256 : 0);
1308 3446
    if (((in == 0 && out == 0) || flush == Z_FINISH) && ret == Z_OK)
1309 48
        ret = Z_BUF_ERROR;
1310 3446
    return ret;
1311 3446
}
1312
1313 1080
int ZEXPORT inflateEnd(strm)
1314
z_streamp strm;
1315
{
1316
    struct inflate_state FAR *state;
1317 1080
    if (inflateStateCheck(strm))
1318 0
        return Z_STREAM_ERROR;
1319 1080
    state = (struct inflate_state FAR *)strm->state;
1320 1080
    if (state->window != Z_NULL) ZFREE(strm, state->window);
1321 1080
    ZFREE(strm, strm->state);
1322 1080
    strm->state = Z_NULL;
1323
    Tracev((stderr, "inflate: end\n"));
1324 1080
    return Z_OK;
1325 1080
}
1326
1327
#ifdef NOVGZ
1328
1329
int ZEXPORT inflateGetDictionary(strm, dictionary, dictLength)
1330
z_streamp strm;
1331
Bytef *dictionary;
1332
uInt *dictLength;
1333
{
1334
    struct inflate_state FAR *state;
1335
1336
    /* check state */
1337
    if (inflateStateCheck(strm)) return Z_STREAM_ERROR;
1338
    state = (struct inflate_state FAR *)strm->state;
1339
1340
    /* copy dictionary */
1341
    if (state->whave && dictionary != Z_NULL) {
1342
        zmemcpy(dictionary, state->window + state->wnext,
1343
                state->whave - state->wnext);
1344
        zmemcpy(dictionary + state->whave - state->wnext,
1345
                state->window, state->wnext);
1346
    }
1347
    if (dictLength != Z_NULL)
1348
        *dictLength = state->whave;
1349
    return Z_OK;
1350
}
1351
1352
int ZEXPORT inflateSetDictionary(strm, dictionary, dictLength)
1353
z_streamp strm;
1354
const Bytef *dictionary;
1355
uInt dictLength;
1356
{
1357
    struct inflate_state FAR *state;
1358
    unsigned long dictid;
1359
    int ret;
1360
1361
    /* check state */
1362
    if (inflateStateCheck(strm)) return Z_STREAM_ERROR;
1363
    state = (struct inflate_state FAR *)strm->state;
1364
    if (state->wrap != 0 && state->mode != DICT)
1365
        return Z_STREAM_ERROR;
1366
1367
    /* check for correct dictionary identifier */
1368
    if (state->mode == DICT) {
1369
        dictid = adler32(0L, Z_NULL, 0);
1370
        dictid = adler32(dictid, dictionary, dictLength);
1371
        if (dictid != state->check)
1372
            return Z_DATA_ERROR;
1373
    }
1374
1375
    /* copy dictionary to window using updatewindow(), which will amend the
1376
       existing dictionary if appropriate */
1377
    ret = updatewindow(strm, dictionary + dictLength, dictLength);
1378
    if (ret) {
1379
        state->mode = MEM;
1380
        return Z_MEM_ERROR;
1381
    }
1382
    state->havedict = 1;
1383
    Tracev((stderr, "inflate:   dictionary set\n"));
1384
    return Z_OK;
1385
}
1386
1387
int ZEXPORT inflateGetHeader(strm, head)
1388
z_streamp strm;
1389
gz_headerp head;
1390
{
1391
    struct inflate_state FAR *state;
1392
1393
    /* check state */
1394
    if (inflateStateCheck(strm)) return Z_STREAM_ERROR;
1395
    state = (struct inflate_state FAR *)strm->state;
1396
    if ((state->wrap & 2) == 0) return Z_STREAM_ERROR;
1397
1398
    /* save header structure */
1399
    state->head = head;
1400
    head->done = 0;
1401
    return Z_OK;
1402
}
1403
1404
/*
1405
   Search buf[0..len-1] for the pattern: 0, 0, 0xff, 0xff.  Return when found
1406
   or when out of input.  When called, *have is the number of pattern bytes
1407
   found in order so far, in 0..3.  On return *have is updated to the new
1408
   state.  If on return *have equals four, then the pattern was found and the
1409
   return value is how many bytes were read including the last byte of the
1410
   pattern.  If *have is less than four, then the pattern has not been found
1411
   yet and the return value is len.  In the latter case, syncsearch() can be
1412
   called again with more data and the *have state.  *have is initialized to
1413
   zero for the first call.
1414
 */
1415
local unsigned syncsearch(have, buf, len)
1416
unsigned FAR *have;
1417
const unsigned char FAR *buf;
1418
unsigned len;
1419
{
1420
    unsigned got;
1421
    unsigned next;
1422
1423
    got = *have;
1424
    next = 0;
1425
    while (next < len && got < 4) {
1426
        if ((int)(buf[next]) == (got < 2 ? 0 : 0xff))
1427
            got++;
1428
        else if (buf[next])
1429
            got = 0;
1430
        else
1431
            got = 4 - got;
1432
        next++;
1433
    }
1434
    *have = got;
1435
    return next;
1436
}
1437
1438
int ZEXPORT inflateSync(strm)
1439
z_streamp strm;
1440
{
1441
    unsigned len;               /* number of bytes to look at or looked at */
1442
    int flags;                  /* temporary to save header status */
1443
    unsigned long in, out;      /* temporary to save total_in and total_out */
1444
    unsigned char buf[4];       /* to restore bit buffer to byte string */
1445
    struct inflate_state FAR *state;
1446
1447
    /* check parameters */
1448
    if (inflateStateCheck(strm)) return Z_STREAM_ERROR;
1449
    state = (struct inflate_state FAR *)strm->state;
1450
    if (strm->avail_in == 0 && state->bits < 8) return Z_BUF_ERROR;
1451
1452
    /* if first time, start search in bit buffer */
1453
    if (state->mode != SYNC) {
1454
        state->mode = SYNC;
1455
        state->hold <<= state->bits & 7;
1456
        state->bits -= state->bits & 7;
1457
        len = 0;
1458
        while (state->bits >= 8) {
1459
            buf[len++] = (unsigned char)(state->hold);
1460
            state->hold >>= 8;
1461
            state->bits -= 8;
1462
        }
1463
        state->have = 0;
1464
        syncsearch(&(state->have), buf, len);
1465
    }
1466
1467
    /* search available input */
1468
    len = syncsearch(&(state->have), strm->next_in, strm->avail_in);
1469
    strm->avail_in -= len;
1470
    strm->next_in += len;
1471
    strm->total_in += len;
1472
1473
    /* return no joy or set up to restart inflate() on a new block */
1474
    if (state->have != 4) return Z_DATA_ERROR;
1475
    if (state->flags == -1)
1476
        state->wrap = 0;    /* if no header yet, treat as raw */
1477
    else
1478
        state->wrap &= ~4;  /* no point in computing a check value now */
1479
    flags = state->flags;
1480
    in = strm->total_in;  out = strm->total_out;
1481
    inflateReset(strm);
1482
    strm->total_in = in;  strm->total_out = out;
1483
    state->flags = flags;
1484
    state->mode = TYPE;
1485
    return Z_OK;
1486
}
1487
1488
/*
1489
   Returns true if inflate is currently at the end of a block generated by
1490
   Z_SYNC_FLUSH or Z_FULL_FLUSH. This function is used by one PPP
1491
   implementation to provide an additional safety check. PPP uses
1492
   Z_SYNC_FLUSH but removes the length bytes of the resulting empty stored
1493
   block. When decompressing, PPP checks that at the end of input packet,
1494
   inflate is waiting for these length bytes.
1495
 */
1496
int ZEXPORT inflateSyncPoint(strm)
1497
z_streamp strm;
1498
{
1499
    struct inflate_state FAR *state;
1500
1501
    if (inflateStateCheck(strm)) return Z_STREAM_ERROR;
1502
    state = (struct inflate_state FAR *)strm->state;
1503
    return state->mode == STORED && state->bits == 0;
1504
}
1505
1506
int ZEXPORT inflateCopy(dest, source)
1507
z_streamp dest;
1508
z_streamp source;
1509
{
1510
    struct inflate_state FAR *state;
1511
    struct inflate_state FAR *copy;
1512
    unsigned char FAR *window;
1513
    unsigned wsize;
1514
1515
    /* check input */
1516
    if (inflateStateCheck(source) || dest == Z_NULL)
1517
        return Z_STREAM_ERROR;
1518
    state = (struct inflate_state FAR *)source->state;
1519
1520
    /* allocate space */
1521
    copy = (struct inflate_state FAR *)
1522
           ZALLOC(source, 1, sizeof(struct inflate_state));
1523
    if (copy == Z_NULL) return Z_MEM_ERROR;
1524
    window = Z_NULL;
1525
    if (state->window != Z_NULL) {
1526
        window = (unsigned char FAR *)
1527
                 ZALLOC(source, 1U << state->wbits, sizeof(unsigned char));
1528
        if (window == Z_NULL) {
1529
            ZFREE(source, copy);
1530
            return Z_MEM_ERROR;
1531
        }
1532
    }
1533
1534
    /* copy state */
1535
    zmemcpy((voidpf)dest, (voidpf)source, sizeof(z_stream));
1536
    zmemcpy((voidpf)copy, (voidpf)state, sizeof(struct inflate_state));
1537
    copy->strm = dest;
1538
    if (state->lencode >= state->codes &&
1539
        state->lencode <= state->codes + ENOUGH - 1) {
1540
        copy->lencode = copy->codes + (state->lencode - state->codes);
1541
        copy->distcode = copy->codes + (state->distcode - state->codes);
1542
    }
1543
    copy->next = copy->codes + (state->next - state->codes);
1544
    if (window != Z_NULL) {
1545
        wsize = 1U << state->wbits;
1546
        zmemcpy(window, state->window, wsize);
1547
    }
1548
    copy->window = window;
1549
    dest->state = (struct internal_state FAR *)copy;
1550
    return Z_OK;
1551
}
1552
1553
int ZEXPORT inflateUndermine(strm, subvert)
1554
z_streamp strm;
1555
int subvert;
1556
{
1557
    struct inflate_state FAR *state;
1558
1559
    if (inflateStateCheck(strm)) return Z_STREAM_ERROR;
1560
    state = (struct inflate_state FAR *)strm->state;
1561
#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
1562
    state->sane = !subvert;
1563
    return Z_OK;
1564
#else
1565
    (void)subvert;
1566
    state->sane = 1;
1567
    return Z_DATA_ERROR;
1568
#endif
1569
}
1570
1571
int ZEXPORT inflateValidate(strm, check)
1572
z_streamp strm;
1573
int check;
1574
{
1575
    struct inflate_state FAR *state;
1576
1577
    if (inflateStateCheck(strm)) return Z_STREAM_ERROR;
1578
    state = (struct inflate_state FAR *)strm->state;
1579
    if (check && state->wrap)
1580
        state->wrap |= 4;
1581
    else
1582
        state->wrap &= ~4;
1583
    return Z_OK;
1584
}
1585
1586
long ZEXPORT inflateMark(strm)
1587
z_streamp strm;
1588
{
1589
    struct inflate_state FAR *state;
1590
1591
    if (inflateStateCheck(strm))
1592
        return -(1L << 16);
1593
    state = (struct inflate_state FAR *)strm->state;
1594
    return (long)(((unsigned long)((long)state->back)) << 16) +
1595
        (state->mode == COPY ? state->length :
1596
            (state->mode == MATCH ? state->was - state->length : 0));
1597
}
1598
1599
unsigned long ZEXPORT inflateCodesUsed(strm)
1600
z_streamp strm;
1601
{
1602
    struct inflate_state FAR *state;
1603
    if (inflateStateCheck(strm)) return (unsigned long)-1;
1604
    state = (struct inflate_state FAR *)strm->state;
1605
    return (unsigned long)(state->next - state->codes);
1606
}
1607
1608
#endif /* NOVGZ */