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