Coverage Report

Created: 2023-06-13 14:35

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