1/* inflate.c -- zlib decompression
2 * Copyright (C) 1995-2005 Mark Adler
3 * For conditions of distribution and use, see copyright notice in zlib.h
4 */
5local void fixedtables OF((struct inflate_state FAR *state));
6local int updatewindow OF((z_streamp strm, unsigned out));
7
8int ZEXPORT inflateReset(z_streamp strm)
9{
10    struct inflate_state FAR *state;
11
12    if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
13    state = (struct inflate_state FAR *)strm->state;
14    strm->total_in = strm->total_out = state->total = 0;
15    strm->msg = Z_NULL;
16    strm->adler = 1;        /* to support ill-conceived Java test suite */
17    state->mode = HEAD;
18    state->last = 0;
19    state->havedict = 0;
20    state->dmax = 32768U;
21    state->head = Z_NULL;
22    state->wsize = 0;
23    state->whave = 0;
24    state->wnext = 0;
25    state->hold = 0;
26    state->bits = 0;
27    state->lencode = state->distcode = state->next = state->codes;
28    schedule();
29    Tracev((stderr, "inflate: reset\n"));
30    return Z_OK;
31}
32
33int ZEXPORT inflateInit2_(z_streamp strm, int windowBits,
34			  int stream_size)
35{
36    struct inflate_state FAR *state;
37
38    if (strm == Z_NULL) return Z_STREAM_ERROR;
39    strm->msg = Z_NULL;                 /* in case we return an error */
40    if (strm->zalloc == (alloc_func)0) {
41        strm->zalloc = zcalloc;
42        strm->opaque = (voidpf)0;
43    }
44    if (strm->zfree == (free_func)0) strm->zfree = zcfree;
45    state = (struct inflate_state FAR *)
46            ZALLOC(strm, 1, sizeof(struct inflate_state));
47    if (state == Z_NULL) return Z_MEM_ERROR;
48    Tracev((stderr, "inflate: allocated\n"));
49    strm->state = (struct internal_state FAR *)state;
50    if (windowBits < 0) {
51        state->wrap = 0;
52        windowBits = -windowBits;
53    }
54    else {
55        state->wrap = (windowBits >> 4) + 1;
56#ifdef GUNZIP
57        if (windowBits < 48) windowBits &= 15;
58#endif
59    }
60    if (windowBits < 8 || windowBits > 15) {
61        ZFREE(strm, state);
62        strm->state = Z_NULL;
63        return Z_STREAM_ERROR;
64    }
65    state->wbits = (unsigned)windowBits;
66    state->window = Z_NULL;
67    return inflateReset(strm);
68}
69
70int ZEXPORT inflateInit_(z_streamp strm, int stream_size)
71{
72    return inflateInit2_(strm, DEF_WBITS, stream_size);
73}
74
75local void fixedtables(struct inflate_state FAR *state)
76{
77    state->lencode = lenfix;
78    state->lenbits = 9;
79    state->distcode = distfix;
80    state->distbits = 5;
81}
82
83/*
84   Update the window with the last wsize (normally 32K) bytes written before
85   returning.  If window does not exist yet, create it.  This is only called
86   when a window is already in use, or when output has been written during this
87   inflate call, but the end of the deflate stream has not been reached yet.
88   It is also called to create a window for dictionary data when a dictionary
89   is loaded.
90
91   Providing output buffers larger than 32K to inflate() should provide a speed
92   advantage, since only the last 32K of output is copied to the sliding window
93   upon return from inflate(), and since all distances after the first 32K of
94   output will fall in the output data, making match copies simpler and faster.
95   The advantage may be dependent on the size of the processor's data caches.
96 */
97local int updatewindow(z_streamp strm, unsigned out)
98{
99    struct inflate_state FAR *state;
100    unsigned copy, dist;
101
102    state = (struct inflate_state FAR *)strm->state;
103
104    /* if it hasn't been done already, allocate space for the window */
105    if (state->window == Z_NULL) {
106        state->window = (unsigned char FAR *)
107                        ZALLOC(strm, 1U << state->wbits,
108                               sizeof(unsigned char));
109        if (state->window == Z_NULL) return 1;
110    }
111
112    /* if window not in use yet, initialize */
113    if (state->wsize == 0) {
114        state->wsize = 1U << state->wbits;
115        state->wnext = 0;
116        state->whave = 0;
117    }
118
119    /* copy state->wsize or less output bytes into the circular window */
120    copy = out - strm->avail_out;
121    if (copy >= state->wsize) {
122        zmemcpy(state->window, strm->next_out - state->wsize, state->wsize);
123        state->wnext = 0;
124        state->whave = state->wsize;
125    }
126    else {
127        dist = state->wsize - state->wnext;
128        if (dist > copy) dist = copy;
129        zmemcpy(state->window + state->wnext, strm->next_out - copy, dist);
130        copy -= dist;
131        if (copy) {
132            zmemcpy(state->window, strm->next_out - copy, copy);
133            state->wnext = copy;
134            state->whave = state->wsize;
135        }
136        else {
137            state->wnext += dist;
138            if (state->wnext == state->wsize) state->wnext = 0;
139            if (state->whave < state->wsize) state->whave += dist;
140        }
141    }
142    return 0;
143}
144
145/* Macros for inflate(): */
146
147/* check function to use adler32() for zlib or crc32() for gzip */
148#ifdef GUNZIP
149#  define UPDATE(check, buf, len) \
150    (state->flags ? crc32(check, buf, len) : adler32(check, buf, len))
151#else
152#  define UPDATE(check, buf, len) adler32(check, buf, len)
153#endif
154
155/* check macros for header crc */
156#ifdef GUNZIP
157#  define CRC2(check, word) \
158    do { \
159        hbuf[0] = (unsigned char)(word); \
160        hbuf[1] = (unsigned char)((word) >> 8); \
161        check = crc32(check, hbuf, 2); \
162    } while (0)
163
164#  define CRC4(check, word) \
165    do { \
166        hbuf[0] = (unsigned char)(word); \
167        hbuf[1] = (unsigned char)((word) >> 8); \
168        hbuf[2] = (unsigned char)((word) >> 16); \
169        hbuf[3] = (unsigned char)((word) >> 24); \
170        check = crc32(check, hbuf, 4); \
171    } while (0)
172#endif
173
174/* Load registers with state in inflate() for speed */
175#define LOAD() \
176    do { \
177        put = strm->next_out; \
178        left = strm->avail_out; \
179        next = strm->next_in; \
180        have = strm->avail_in; \
181        hold = state->hold; \
182        bits = state->bits; \
183    } while (0)
184
185/* Restore state from registers in inflate() */
186#define RESTORE() \
187    do { \
188        strm->next_out = put; \
189        strm->avail_out = left; \
190        strm->next_in = next; \
191        strm->avail_in = have; \
192        state->hold = hold; \
193        state->bits = bits; \
194    } while (0)
195
196/* Clear the input bit accumulator */
197#define INITBITS() \
198    do { \
199        hold = 0; \
200        bits = 0; \
201    } while (0)
202
203/* Get a byte of input into the bit accumulator, or return from inflate()
204   if there is no input available. */
205#define PULLBYTE() \
206    do { \
207        if (have == 0) goto inf_leave; \
208        have--; \
209        hold += (unsigned long)(*next++) << bits; \
210        bits += 8; \
211    } while (0)
212
213/* Assure that there are at least n bits in the bit accumulator.  If there is
214   not enough available input to do that, then return from inflate(). */
215#define NEEDBITS(n) \
216    do { \
217        while (bits < (unsigned)(n)) \
218            PULLBYTE(); \
219    } while (0)
220
221/* Return the low n bits of the bit accumulator (n < 16) */
222#define BITS(n) \
223    ((unsigned)hold & ((1U << (n)) - 1))
224
225/* Remove n bits from the bit accumulator */
226#define DROPBITS(n) \
227    do { \
228        hold >>= (n); \
229        bits -= (unsigned)(n); \
230    } while (0)
231
232/* Remove zero to seven bits as needed to go to a byte boundary */
233#define BYTEBITS() \
234    do { \
235        hold >>= bits & 7; \
236        bits -= bits & 7; \
237    } while (0)
238
239/* Reverse the bytes in a 32-bit value */
240#define REVERSE(q) \
241    ((((q) >> 24) & 0xff) + (((q) >> 8) & 0xff00) + \
242     (((q) & 0xff00) << 8) + (((q) & 0xff) << 24))
243
244/*
245   inflate() uses a state machine to process as much input data and generate as
246   much output data as possible before returning.  The state machine is
247   structured roughly as follows:
248
249    for (;;) switch (state) {
250    ...
251    case STATEn:
252        if (not enough input data or output space to make progress)
253            return;
254        ... make progress ...
255        state = STATEm;
256        break;
257    ...
258    }
259
260   so when inflate() is called again, the same case is attempted again, and
261   if the appropriate resources are provided, the machine proceeds to the
262   next state.  The NEEDBITS() macro is usually the way the state evaluates
263   whether it can proceed or should return.  NEEDBITS() does the return if
264   the requested bits are not available.  The typical use of the BITS macros
265   is:
266
267        NEEDBITS(n);
268        ... do something with BITS(n) ...
269        DROPBITS(n);
270
271   where NEEDBITS(n) either returns from inflate() if there isn't enough
272   input left to load n bits into the accumulator, or it continues.  BITS(n)
273   gives the low n bits in the accumulator.  When done, DROPBITS(n) drops
274   the low n bits off the accumulator.  INITBITS() clears the accumulator
275   and sets the number of available bits to zero.  BYTEBITS() discards just
276   enough bits to put the accumulator on a byte boundary.  After BYTEBITS()
277   and a NEEDBITS(8), then BITS(8) would return the next byte in the stream.
278
279   NEEDBITS(n) uses PULLBYTE() to get an available byte of input, or to return
280   if there is no input available.  The decoding of variable length codes uses
281   PULLBYTE() directly in order to pull just enough bytes to decode the next
282   code, and no more.
283
284   Some states loop until they get enough input, making sure that enough
285   state information is maintained to continue the loop where it left off
286   if NEEDBITS() returns in the loop.  For example, want, need, and keep
287   would all have to actually be part of the saved state in case NEEDBITS()
288   returns:
289
290    case STATEw:
291        while (want < need) {
292            NEEDBITS(n);
293            keep[want++] = BITS(n);
294            DROPBITS(n);
295        }
296        state = STATEx;
297    case STATEx:
298
299   As shown above, if the next state is also the next case, then the break
300   is omitted.
301
302   A state may also return if there is not enough output space available to
303   complete that state.  Those states are copying stored data, writing a
304   literal byte, and copying a matching string.
305
306   When returning, a "goto inf_leave" is used to update the total counters,
307   update the check value, and determine whether any progress has been made
308   during that inflate() call in order to return the proper return code.
309   Progress is defined as a change in either strm->avail_in or strm->avail_out.
310   When there is a window, goto inf_leave will update the window with the last
311   output written.  If a goto inf_leave occurs in the middle of decompression
312   and there is no window currently, goto inf_leave will create one and copy
313   output to the window for the next call of inflate().
314
315   In this implementation, the flush parameter of inflate() only affects the
316   return code (per zlib.h).  inflate() always writes as much as possible to
317   strm->next_out, given the space available and the provided input--the effect
318   documented in zlib.h of Z_SYNC_FLUSH.  Furthermore, inflate() always defers
319   the allocation of and copying into a sliding window until necessary, which
320   provides the effect documented in zlib.h for Z_FINISH when the entire input
321   stream available.  So the only thing the flush parameter actually does is:
322   when flush is set to Z_FINISH, inflate() cannot return Z_OK.  Instead it
323   will return Z_BUF_ERROR if it has not reached the end of the stream.
324 */
325int ZEXPORT inflate(z_streamp strm, int flush)
326{
327    struct inflate_state FAR *state;
328    unsigned char FAR *next;    /* next input */
329    unsigned char FAR *put;     /* next output */
330    unsigned have, left;        /* available input and output */
331    unsigned long hold;         /* bit buffer */
332    unsigned bits;              /* bits in bit buffer */
333    unsigned in, out;           /* save starting available input and output */
334    unsigned copy;              /* number of stored or match bytes to copy */
335    unsigned char FAR *from;    /* where to copy match bytes from */
336    code this;                  /* current decoding table entry */
337    code last;                  /* parent table entry */
338    unsigned len;               /* length to copy for repeats, bits to drop */
339    int ret;                    /* return code */
340#ifdef GUNZIP
341    unsigned char hbuf[4];      /* buffer for gzip header crc calculation */
342#endif
343    static const unsigned short order[19] = /* permutation of code lengths */
344        {16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15};
345
346    if (strm == Z_NULL || strm->state == Z_NULL ||
347        (strm->next_in == Z_NULL && strm->avail_in != 0))
348        return Z_STREAM_ERROR;
349
350    state = (struct inflate_state FAR *)strm->state;
351    if (state->mode == TYPE) state->mode = TYPEDO;      /* skip check */
352    LOAD();
353    in = have;
354    out = left;
355    ret = Z_OK;
356    for (;;)
357        switch (state->mode) {
358        case HEAD:
359            if (state->wrap == 0) {
360                state->mode = TYPEDO;
361                break;
362            }
363            NEEDBITS(16);
364#ifdef GUNZIP
365            if ((state->wrap & 2) && hold == 0x8b1f) {  /* gzip header */
366                state->check = crc32(0L, Z_NULL, 0);
367                CRC2(state->check, hold);
368                INITBITS();
369                state->mode = FLAGS;
370                break;
371            }
372            state->flags = 0;           /* expect zlib header */
373            if (state->head != Z_NULL)
374                state->head->done = -1;
375            if (!(state->wrap & 1) ||   /* check if zlib header allowed */
376#else
377            if (
378#endif
379                ((BITS(8) << 8) + (hold >> 8)) % 31) {
380                strm->msg = (char *)"incorrect header check";
381                state->mode = BAD;
382                break;
383            }
384            if (BITS(4) != Z_DEFLATED) {
385                strm->msg = (char *)"unknown compression method";
386                state->mode = BAD;
387                break;
388            }
389            DROPBITS(4);
390            len = BITS(4) + 8;
391            if (len > state->wbits) {
392                strm->msg = (char *)"invalid window size";
393                state->mode = BAD;
394                break;
395            }
396            state->dmax = 1U << len;
397            Tracev((stderr, "inflate:   zlib header ok\n"));
398            strm->adler = state->check = adler32(0L, Z_NULL, 0);
399            state->mode = hold & 0x200 ? DICTID : TYPE;
400            INITBITS();
401            break;
402#ifdef GUNZIP
403        case FLAGS:
404            NEEDBITS(16);
405            state->flags = (int)(hold);
406            if ((state->flags & 0xff) != Z_DEFLATED) {
407                strm->msg = (char *)"unknown compression method";
408                state->mode = BAD;
409                break;
410            }
411            if (state->flags & 0xe000) {
412                strm->msg = (char *)"unknown header flags set";
413                state->mode = BAD;
414                break;
415            }
416            if (state->head != Z_NULL)
417                state->head->text = (int)((hold >> 8) & 1);
418            if (state->flags & 0x0200) CRC2(state->check, hold);
419            INITBITS();
420            state->mode = TIME;
421        case TIME:
422            NEEDBITS(32);
423            if (state->head != Z_NULL)
424                state->head->time = hold;
425            if (state->flags & 0x0200) CRC4(state->check, hold);
426            INITBITS();
427            state->mode = OS;
428        case OS:
429            NEEDBITS(16);
430            if (state->head != Z_NULL) {
431                state->head->xflags = (int)(hold & 0xff);
432                state->head->os = (int)(hold >> 8);
433            }
434            if (state->flags & 0x0200) CRC2(state->check, hold);
435            INITBITS();
436            state->mode = EXLEN;
437        case EXLEN:
438            if (state->flags & 0x0400) {
439                NEEDBITS(16);
440                state->length = (unsigned)(hold);
441                if (state->head != Z_NULL)
442                    state->head->extra_len = (unsigned)hold;
443                if (state->flags & 0x0200) CRC2(state->check, hold);
444                INITBITS();
445            }
446            else if (state->head != Z_NULL)
447                state->head->extra = Z_NULL;
448            state->mode = EXTRA;
449        case EXTRA:
450            if (state->flags & 0x0400) {
451                copy = state->length;
452                if (copy > have) copy = have;
453                if (copy) {
454                    if (state->head != Z_NULL &&
455                        state->head->extra != Z_NULL &&
456                        (len = state->head->extra_len - state->length) <
457                            state->head->extra_max) {
458                        zmemcpy(state->head->extra + len, next,
459                                len + copy > state->head->extra_max ?
460                                state->head->extra_max - len : copy);
461                    }
462                    if (state->flags & 0x0200)
463                        state->check = crc32(state->check, next, copy);
464                    have -= copy;
465                    next += copy;
466                    state->length -= copy;
467                }
468                if (state->length) goto inf_leave;
469            }
470            state->length = 0;
471            state->mode = NAME;
472        case NAME:
473            if (state->flags & 0x0800) {
474                if (have == 0) goto inf_leave;
475                copy = 0;
476                do {
477                    len = (unsigned)(next[copy++]);
478                    if (state->head != Z_NULL &&
479                            state->head->name != Z_NULL &&
480                            state->length < state->head->name_max)
481                        state->head->name[state->length++] = len;
482                } while (len && copy < have);
483                if (state->flags & 0x0200)
484                    state->check = crc32(state->check, next, copy);
485                have -= copy;
486                next += copy;
487                if (len) goto inf_leave;
488            }
489            else if (state->head != Z_NULL)
490                state->head->name = Z_NULL;
491            state->length = 0;
492            state->mode = COMMENT;
493        case COMMENT:
494            if (state->flags & 0x1000) {
495                if (have == 0) goto inf_leave;
496                copy = 0;
497                do {
498                    len = (unsigned)(next[copy++]);
499                    if (state->head != Z_NULL &&
500                            state->head->comment != Z_NULL &&
501                            state->length < state->head->comm_max)
502                        state->head->comment[state->length++] = len;
503                } while (len && copy < have);
504                if (state->flags & 0x0200)
505                    state->check = crc32(state->check, next, copy);
506                have -= copy;
507                next += copy;
508                if (len) goto inf_leave;
509            }
510            else if (state->head != Z_NULL)
511                state->head->comment = Z_NULL;
512            state->mode = HCRC;
513        case HCRC:
514            if (state->flags & 0x0200) {
515                NEEDBITS(16);
516                if (hold != (state->check & 0xffff)) {
517                    strm->msg = (char *)"header crc mismatch";
518                    state->mode = BAD;
519                    break;
520                }
521                INITBITS();
522            }
523            if (state->head != Z_NULL) {
524                state->head->hcrc = (int)((state->flags >> 9) & 1);
525                state->head->done = 1;
526            }
527            strm->adler = state->check = crc32(0L, Z_NULL, 0);
528            state->mode = TYPE;
529            break;
530#endif
531        case DICTID:
532            NEEDBITS(32);
533            strm->adler = state->check = REVERSE(hold);
534            INITBITS();
535            state->mode = DICT;
536        case DICT:
537            if (state->havedict == 0) {
538                RESTORE();
539                return Z_NEED_DICT;
540            }
541            strm->adler = state->check = adler32(0L, Z_NULL, 0);
542            state->mode = TYPE;
543        case TYPE:
544	    schedule();
545            if (flush == Z_BLOCK) goto inf_leave;
546        case TYPEDO:
547            if (state->last) {
548                BYTEBITS();
549                state->mode = CHECK;
550                break;
551            }
552            NEEDBITS(3);
553            state->last = BITS(1);
554            DROPBITS(1);
555            switch (BITS(2)) {
556            case 0:                             /* stored block */
557                Tracev((stderr, "inflate:     stored block%s\n",
558                        state->last ? " (last)" : ""));
559                state->mode = STORED;
560                break;
561            case 1:                             /* fixed block */
562                fixedtables(state);
563                Tracev((stderr, "inflate:     fixed codes block%s\n",
564                        state->last ? " (last)" : ""));
565                state->mode = LEN;              /* decode codes */
566                break;
567            case 2:                             /* dynamic block */
568                Tracev((stderr, "inflate:     dynamic codes block%s\n",
569                        state->last ? " (last)" : ""));
570                state->mode = TABLE;
571                break;
572            case 3:
573                strm->msg = (char *)"invalid block type";
574                state->mode = BAD;
575            }
576            DROPBITS(2);
577            break;
578        case STORED:
579            BYTEBITS();                         /* go to byte boundary */
580            NEEDBITS(32);
581            if ((hold & 0xffff) != ((hold >> 16) ^ 0xffff)) {
582                strm->msg = (char *)"invalid stored block lengths";
583                state->mode = BAD;
584                break;
585            }
586            state->length = (unsigned)hold & 0xffff;
587            Tracev((stderr, "inflate:       stored length %u\n",
588                    state->length));
589            INITBITS();
590            state->mode = COPY;
591        case COPY:
592            copy = state->length;
593            if (copy) {
594                if (copy > have) copy = have;
595                if (copy > left) copy = left;
596                if (copy == 0) goto inf_leave;
597                zmemcpy(put, next, copy);
598                have -= copy;
599                next += copy;
600                left -= copy;
601                put += copy;
602                state->length -= copy;
603                break;
604            }
605            Tracev((stderr, "inflate:       stored end\n"));
606            state->mode = TYPE;
607            break;
608        case TABLE:
609            NEEDBITS(14);
610            state->nlen = BITS(5) + 257;
611            DROPBITS(5);
612            state->ndist = BITS(5) + 1;
613            DROPBITS(5);
614            state->ncode = BITS(4) + 4;
615            DROPBITS(4);
616#ifndef PKZIP_BUG_WORKAROUND
617            if (state->nlen > 286 || state->ndist > 30) {
618                strm->msg = (char *)"too many length or distance symbols";
619                state->mode = BAD;
620                break;
621            }
622#endif
623            Tracev((stderr, "inflate:       table sizes ok\n"));
624            state->have = 0;
625            state->mode = LENLENS;
626        case LENLENS:
627            while (state->have < state->ncode) {
628                NEEDBITS(3);
629                state->lens[order[state->have++]] = (unsigned short)BITS(3);
630                DROPBITS(3);
631            }
632            while (state->have < 19)
633                state->lens[order[state->have++]] = 0;
634            state->next = state->codes;
635            state->lencode = (code const FAR *)(state->next);
636            state->lenbits = 7;
637            ret = inflate_table(CODES, state->lens, 19, &(state->next),
638                                &(state->lenbits), state->work);
639            if (ret) {
640                strm->msg = (char *)"invalid code lengths set";
641                state->mode = BAD;
642                break;
643            }
644            Tracev((stderr, "inflate:       code lengths ok\n"));
645            state->have = 0;
646            state->mode = CODELENS;
647        case CODELENS:
648            while (state->have < state->nlen + state->ndist) {
649                for (;;) {
650                    this = state->lencode[BITS(state->lenbits)];
651                    if ((unsigned)(this.bits) <= bits) break;
652                    PULLBYTE();
653                }
654                if (this.val < 16) {
655                    NEEDBITS(this.bits);
656                    DROPBITS(this.bits);
657                    state->lens[state->have++] = this.val;
658                }
659                else {
660                    if (this.val == 16) {
661                        NEEDBITS(this.bits + 2);
662                        DROPBITS(this.bits);
663                        if (state->have == 0) {
664                            strm->msg = (char *)"invalid bit length repeat";
665                            state->mode = BAD;
666                            break;
667                        }
668                        len = state->lens[state->have - 1];
669                        copy = 3 + BITS(2);
670                        DROPBITS(2);
671                    }
672                    else if (this.val == 17) {
673                        NEEDBITS(this.bits + 3);
674                        DROPBITS(this.bits);
675                        len = 0;
676                        copy = 3 + BITS(3);
677                        DROPBITS(3);
678                    }
679                    else {
680                        NEEDBITS(this.bits + 7);
681                        DROPBITS(this.bits);
682                        len = 0;
683                        copy = 11 + BITS(7);
684                        DROPBITS(7);
685                    }
686                    if (state->have + copy > state->nlen + state->ndist) {
687                        strm->msg = (char *)"invalid bit length repeat";
688                        state->mode = BAD;
689                        break;
690                    }
691                    while (copy--)
692                        state->lens[state->have++] = (unsigned short)len;
693                }
694            }
695
696            /* handle error breaks in while */
697            if (state->mode == BAD) break;
698
699            /* build code tables */
700            state->next = state->codes;
701            state->lencode = (code const FAR *)(state->next);
702            state->lenbits = 9;
703            ret = inflate_table(LENS, state->lens, state->nlen, &(state->next),
704                                &(state->lenbits), state->work);
705            if (ret) {
706                strm->msg = (char *)"invalid literal/lengths set";
707                state->mode = BAD;
708                break;
709            }
710            state->distcode = (code const FAR *)(state->next);
711            state->distbits = 6;
712            ret = inflate_table(DISTS, state->lens + state->nlen, state->ndist,
713                            &(state->next), &(state->distbits), state->work);
714            if (ret) {
715                strm->msg = (char *)"invalid distances set";
716                state->mode = BAD;
717                break;
718            }
719            Tracev((stderr, "inflate:       codes ok\n"));
720            state->mode = LEN;
721        case LEN:
722	    schedule();
723            if (have >= 6 && left >= 258) {
724                RESTORE();
725                inflate_fast(strm, out);
726                LOAD();
727                break;
728            }
729            for (;;) {
730                this = state->lencode[BITS(state->lenbits)];
731                if ((unsigned)(this.bits) <= bits) break;
732                PULLBYTE();
733            }
734            if (this.op && (this.op & 0xf0) == 0) {
735                last = this;
736                for (;;) {
737                    this = state->lencode[last.val +
738                            (BITS(last.bits + last.op) >> last.bits)];
739                    if ((unsigned)(last.bits + this.bits) <= bits) break;
740                    PULLBYTE();
741                }
742                DROPBITS(last.bits);
743            }
744            DROPBITS(this.bits);
745            state->length = (unsigned)this.val;
746            if ((int)(this.op) == 0) {
747                Tracevv((stderr, this.val >= 0x20 && this.val < 0x7f ?
748                        "inflate:         literal '%c'\n" :
749                        "inflate:         literal 0x%02x\n", this.val));
750                state->mode = LIT;
751                break;
752            }
753            if (this.op & 32) {
754                Tracevv((stderr, "inflate:         end of block\n"));
755                state->mode = TYPE;
756                break;
757            }
758            if (this.op & 64) {
759                strm->msg = (char *)"invalid literal/length code";
760                state->mode = BAD;
761                break;
762            }
763            state->extra = (unsigned)(this.op) & 15;
764            state->mode = LENEXT;
765        case LENEXT:
766            if (state->extra) {
767                NEEDBITS(state->extra);
768                state->length += BITS(state->extra);
769                DROPBITS(state->extra);
770            }
771            Tracevv((stderr, "inflate:         length %u\n", state->length));
772            state->mode = DIST;
773        case DIST:
774            for (;;) {
775                this = state->distcode[BITS(state->distbits)];
776                if ((unsigned)(this.bits) <= bits) break;
777                PULLBYTE();
778            }
779            if ((this.op & 0xf0) == 0) {
780                last = this;
781                for (;;) {
782                    this = state->distcode[last.val +
783                            (BITS(last.bits + last.op) >> last.bits)];
784                    if ((unsigned)(last.bits + this.bits) <= bits) break;
785                    PULLBYTE();
786                }
787                DROPBITS(last.bits);
788            }
789            DROPBITS(this.bits);
790            if (this.op & 64) {
791                strm->msg = (char *)"invalid distance code";
792                state->mode = BAD;
793                break;
794            }
795            state->offset = (unsigned)this.val;
796            state->extra = (unsigned)(this.op) & 15;
797            state->mode = DISTEXT;
798        case DISTEXT:
799            if (state->extra) {
800                NEEDBITS(state->extra);
801                state->offset += BITS(state->extra);
802                DROPBITS(state->extra);
803            }
804#ifdef INFLATE_STRICT
805            if (state->offset > state->dmax) {
806                strm->msg = (char *)"invalid distance too far back";
807                state->mode = BAD;
808                break;
809            }
810#endif
811            if (state->offset > state->whave + out - left) {
812                strm->msg = (char *)"invalid distance too far back";
813                state->mode = BAD;
814                break;
815            }
816            Tracevv((stderr, "inflate:         distance %u\n", state->offset));
817            state->mode = MATCH;
818        case MATCH:
819            if (left == 0) goto inf_leave;
820            copy = out - left;
821            if (state->offset > copy) {         /* copy from window */
822                copy = state->offset - copy;
823                if (copy > state->wnext) {
824                    copy -= state->wnext;
825                    from = state->window + (state->wsize - copy);
826                }
827                else
828                    from = state->window + (state->wnext - copy);
829                if (copy > state->length) copy = state->length;
830            }
831            else {                              /* copy from output */
832                from = put - state->offset;
833                copy = state->length;
834            }
835            if (copy > left) copy = left;
836            left -= copy;
837            state->length -= copy;
838            do {
839                *put++ = *from++;
840            } while (--copy);
841            if (state->length == 0) state->mode = LEN;
842            break;
843        case LIT:
844            if (left == 0) goto inf_leave;
845            *put++ = (unsigned char)(state->length);
846            left--;
847            state->mode = LEN;
848            break;
849        case CHECK:
850            if (state->wrap) {
851                NEEDBITS(32);
852                out -= left;
853                strm->total_out += out;
854                state->total += out;
855                if (out)
856                    strm->adler = state->check =
857                        UPDATE(state->check, put - out, out);
858                out = left;
859                if ((
860#ifdef GUNZIP
861                     state->flags ? hold :
862#endif
863                     REVERSE(hold)) != state->check) {
864                    strm->msg = (char *)"incorrect data check";
865                    state->mode = BAD;
866                    break;
867                }
868                INITBITS();
869                Tracev((stderr, "inflate:   check matches trailer\n"));
870            }
871#ifdef GUNZIP
872            state->mode = LENGTH;
873        case LENGTH:
874            if (state->wrap && state->flags) {
875                NEEDBITS(32);
876                if (hold != (state->total & 0xffffffffUL)) {
877                    strm->msg = (char *)"incorrect length check";
878                    state->mode = BAD;
879                    break;
880                }
881                INITBITS();
882                Tracev((stderr, "inflate:   length matches trailer\n"));
883            }
884#endif
885            state->mode = DONE;
886        case DONE:
887            ret = Z_STREAM_END;
888            goto inf_leave;
889        case BAD:
890            ret = Z_DATA_ERROR;
891            goto inf_leave;
892        case MEM:
893            return Z_MEM_ERROR;
894        case SYNC:
895        default:
896            return Z_STREAM_ERROR;
897        }
898
899    /*
900       Return from inflate(), updating the total counts and the check value.
901       If there was no progress during the inflate() call, return a buffer
902       error.  Call updatewindow() to create and/or update the window state.
903       Note: a memory error from inflate() is non-recoverable.
904     */
905  inf_leave:
906    RESTORE();
907    if (state->wsize || (state->mode < CHECK && out != strm->avail_out))
908        if (updatewindow(strm, out)) {
909            state->mode = MEM;
910            return Z_MEM_ERROR;
911        }
912    in -= strm->avail_in;
913    out -= strm->avail_out;
914    strm->total_in += in;
915    strm->total_out += out;
916    state->total += out;
917    if (state->wrap && out)
918        strm->adler = state->check =
919            UPDATE(state->check, strm->next_out - out, out);
920    strm->data_type = state->bits + (state->last ? 64 : 0) +
921                      (state->mode == TYPE ? 128 : 0);
922    if (((in == 0 && out == 0) || flush == Z_FINISH) && ret == Z_OK)
923        ret = Z_BUF_ERROR;
924    return ret;
925}
926
927int ZEXPORT inflateEnd(z_streamp strm)
928{
929    struct inflate_state FAR *state;
930    if (strm == Z_NULL || strm->state == Z_NULL || strm->zfree == (free_func)0)
931        return Z_STREAM_ERROR;
932    state = (struct inflate_state FAR *)strm->state;
933    if (state->window != Z_NULL) {
934	schedule();
935	ZFREE(strm, state->window);
936    }
937    ZFREE(strm, strm->state);
938    strm->state = Z_NULL;
939    Tracev((stderr, "inflate: end\n"));
940    return Z_OK;
941}
942