Coverage Report

Created: 2025-07-14 06:15

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