1 /* vi: set sw=4 ts=4: */
3 * Gzip implementation for busybox
5 * Based on GNU gzip v1.2.4 Copyright (C) 1992-1993 Jean-loup Gailly.
7 * Originally adjusted for busybox by Sven Rudolph <sr1@inf.tu-dresden.de>
8 * based on gzip sources
10 * Adjusted further by Erik Andersen <andersen@lineo.com>, <andersee@debian.org>
11 * to support files as well as stdin/stdout, and to generally behave itself wrt
12 * command line handling.
14 * This program is free software; you can redistribute it and/or modify
15 * it under the terms of the GNU General Public License as published by
16 * the Free Software Foundation; either version 2 of the License, or
17 * (at your option) any later version.
19 * This program is distributed in the hope that it will be useful,
20 * but WITHOUT ANY WARRANTY; without even the implied warranty of
21 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
22 * General Public License for more details.
24 * You should have received a copy of the GNU General Public License
25 * along with this program; if not, write to the Free Software
26 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
29 * gzip (GNU zip) -- compress files with zip algorithm and 'compress' interface
30 * Copyright (C) 1992-1993 Jean-loup Gailly
31 * The unzip code was written and put in the public domain by Mark Adler.
32 * Portions of the lzw code are derived from the public domain 'compress'
33 * written by Spencer Thomas, Joe Orost, James Woods, Jim McKie, Steve Davies,
34 * Ken Turkowski, Dave Mack and Peter Jannesen.
36 * See the license_msg below and the file COPYING for the software license.
37 * See the file algorithm.doc for the compression algorithms and file formats.
41 static char *license_msg[] = {
42 " Copyright (C) 1992-1993 Jean-loup Gailly",
43 " This program is free software; you can redistribute it and/or modify",
44 " it under the terms of the GNU General Public License as published by",
45 " the Free Software Foundation; either version 2, or (at your option)",
46 " any later version.",
48 " This program is distributed in the hope that it will be useful,",
49 " but WITHOUT ANY WARRANTY; without even the implied warranty of",
50 " MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the",
51 " GNU General Public License for more details.",
53 " You should have received a copy of the GNU General Public License",
54 " along with this program; if not, write to the Free Software",
55 " Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.",
63 #include <sys/types.h>
74 #define BB_DECLARE_EXTERN
75 #define bb_need_memory_exhausted
76 #define bb_need_name_too_long
81 /* Return codes from gzip */
87 #define INBUFSIZ 0x2000 /* input buffer size */
88 #define INBUF_EXTRA 64 /* required by unlzw() */
89 #define OUTBUFSIZ 8192 /* output buffer size */
90 #define OUTBUF_EXTRA 2048 /* required by unlzw() */
91 #define DIST_BUFSIZE 0x2000 /* buffer for distances, see trees.c */
93 #define GZIP_MAGIC "\037\213" /* Magic header for gzip files, 1F 8B */
96 #define EXTRA_FIELD 0x04 /* bit 2 set: extra field present */
97 #define ORIG_NAME 0x08 /* bit 3 set: original file name present */
98 #define COMMENT 0x10 /* bit 4 set: file comment present */
99 #define WSIZE 0x8000 /* window size--must be a power of two, and */
100 /* at least 32K for zip's deflate method */
102 /* If BMAX needs to be larger than 16, then h and x[] should be ulg. */
103 #define BMAX 16 /* maximum bit length of any code (16 for explode) */
104 #define N_MAX 288 /* maximum number of codes in any set */
106 /* PKZIP header definitions */
107 #define LOCSIG 0x04034b50L /* four-byte lead-in (lsb first) */
108 #define LOCCRC 14 /* offset of crc */
109 #define LOCLEN 22 /* offset of uncompressed length */
110 #define EXTHDR 16 /* size of extended local header, inc sig */
114 /* Diagnostic functions */
116 # define Assert(cond,msg) {if(!(cond)) errorMsg(msg);}
117 # define Trace(x) fprintf x
118 # define Tracev(x) {if (verbose) fprintf x ;}
119 # define Tracevv(x) {if (verbose>1) fprintf x ;}
120 # define Tracec(c,x) {if (verbose && (c)) fprintf x ;}
121 # define Tracecv(c,x) {if (verbose>1 && (c)) fprintf x ;}
123 # define Assert(cond,msg)
128 # define Tracecv(c,x)
131 #ifndef MAX_PATH_LEN /* max pathname length */
133 # define MAX_PATH_LEN BUFSIZ
135 # define MAX_PATH_LEN 1024
139 #define NEXTBYTE() (uch)get_byte()
140 #define NEEDBITS(n) {while(k<(n)){b|=((ulg)NEXTBYTE())<<k;k+=8;}}
141 #define DUMPBITS(n) {b>>=(n);k-=(n);}
143 #define get_byte() (inptr < insize ? inbuf[inptr++] : fill_inbuf(0))
145 /* Macros for getting two-byte and four-byte header values */
146 #define SH(p) ((ush)(uch)((p)[0]) | ((ush)(uch)((p)[1]) << 8))
147 #define LG(p) ((ulg)(SH(p)) | ((ulg)(SH((p)+2)) << 16))
150 void abort_gzip (void);
151 typedef void (*sig_type) (int);
153 typedef unsigned char uch;
154 typedef unsigned short ush;
155 typedef unsigned long ulg;
156 typedef int file_t; /* Do not use stdio */
165 /* local variables */
166 int test_mode = 0; /* check file integrity option */
167 int foreground; /* set if program run in foreground */
168 int maxbits = BITS; /* max bits per code for LZW */
169 int method = DEFLATED; /* compression method */
170 int exit_code = OK; /* program exit code */
171 int last_member; /* set for .zip and .Z files */
172 int part_nb; /* number of parts in .gz file */
173 long ifile_size; /* input file size, -1 for devices (debug only) */
174 long bytes_in; /* number of input bytes */
175 long bytes_out; /* number of output bytes */
176 long total_in = 0; /* input bytes for all files */
177 long total_out = 0; /* output bytes for all files */
178 struct stat istat; /* status for input file */
179 int ifd; /* input file descriptor */
180 int ofd; /* output file descriptor */
181 unsigned insize; /* valid bytes in inbuf */
182 unsigned inptr; /* index of next byte to be processed in inbuf */
183 unsigned outcnt; /* bytes in output buffer */
185 unsigned hufts; /* track memory usage */
186 ulg bb; /* bit buffer */
187 unsigned bk; /* bits in bit buffer */
188 int crc_table_empty = 1;
191 uch e; /* number of extra bits or operation */
192 uch b; /* number of bits in this code or subcode */
194 ush n; /* literal, length base, or distance base */
195 struct huft *t; /* pointer to next level of table */
199 /* Tables for deflate from PKZIP's appnote.txt. */
200 static unsigned border[] = { /* Order of the bit length code lengths */
201 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15
203 static ush cplens[] = { /* Copy lengths for literal codes 257..285 */
204 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,
205 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0
208 /* note: see note #13 above about the 258 in this list. */
209 static ush cplext[] = { /* Extra bits for literal codes 257..285 */
210 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2,
211 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0, 99, 99
214 static ush cpdist[] = { /* Copy offsets for distance codes 0..29 */
215 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,
216 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,
217 8193, 12289, 16385, 24577
220 static ush cpdext[] = { /* Extra bits for distance codes */
221 0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6,
222 7, 7, 8, 8, 9, 9, 10, 10, 11, 11,
228 0x0001, 0x0003, 0x0007, 0x000f, 0x001f, 0x003f, 0x007f, 0x00ff,
229 0x01ff, 0x03ff, 0x07ff, 0x0fff, 0x1fff, 0x3fff, 0x7fff, 0xffff
232 /* ========================================================================
235 void read_error_msg()
237 fprintf(stderr, "\n");
241 fprintf(stderr, "unexpected end of file\n");
246 /* ===========================================================================
247 * Fill the input buffer. This is called only when the buffer is empty.
249 int fill_inbuf(eof_ok)
250 int eof_ok; /* set if EOF acceptable as a result */
254 /* Read as much as possible */
258 len = read(ifd, (char *) inbuf + insize, INBUFSIZ - insize);
259 if (len == 0 || len == EOF)
262 } while (insize < INBUFSIZ);
269 bytes_in += (ulg) insize;
275 /* ========================================================================
276 * Check the magic number of the input file and update ofname if an
277 * original name was given and tostdout is not set.
278 * Return the compression method, -1 for error, -2 for warning.
279 * Set inptr to the offset of the next byte to be processed.
280 * Updates time_stamp if there is one and --no-time is not used.
281 * This function may be called repeatedly for an input file consisting
282 * of several contiguous gzip'ed members.
283 * IN assertions: there is at least one remaining compressed member.
284 * If the member is a zip file, it must be the only one.
286 static int get_method(in)
287 int in; /* input file descriptor */
289 uch flags; /* compression flags */
290 char magic[2]; /* magic header */
291 long header_bytes = 0; /* number of bytes in gzip header */
293 magic[0] = (char) get_byte();
294 magic[1] = (char) get_byte();
295 method = -1; /* unknown yet */
296 part_nb++; /* number of parts in gzip file */
297 last_member = RECORD_IO;
298 /* assume multiple members in gzip file except for record oriented I/O */
300 if (memcmp(magic, GZIP_MAGIC, 2) == 0) {
302 method = (int) get_byte();
303 if (method != DEFLATED) {
304 errorMsg("unknown method %d -- get newer version of gzip\n", method);
308 flags = (uch) get_byte();
310 (ulg) get_byte(); /* Ignore time stamp */
315 (void) get_byte(); /* Ignore extra flags for the moment */
316 (void) get_byte(); /* Ignore OS type for the moment */
318 if ((flags & EXTRA_FIELD) != 0) {
319 unsigned len = (unsigned) get_byte();
320 len |= ((unsigned) get_byte()) << 8;
325 /* Discard original name if any */
326 if ((flags & ORIG_NAME) != 0) {
327 while (get_byte() != 0); /* null */
330 /* Discard file comment if any */
331 if ((flags & COMMENT) != 0) {
332 while (get_byte() != 0) /* null */
336 header_bytes = inptr + 2 * sizeof(long); /* include crc and size */
345 fprintf(stderr, "\nnot in gzip format\n");
349 fprintf(stderr, "\ndecompression OK, trailing garbage ignored\n");
356 /* ========================================================================
357 * Signal and error handler.
364 /* ===========================================================================
365 * Run a set of bytes through the crc shift register. If s is a NULL
366 * pointer, then initialize the crc shift register contents instead.
367 * Return the current crc in either case.
370 uch *s; /* pointer to bytes to pump through */
371 unsigned n; /* number of bytes in s[] */
373 static ulg crc = (ulg) 0xffffffffL; /* shift register contents */
374 register ulg c; /* temporary variable */
375 static unsigned long crc_32_tab[256];
376 if (crc_table_empty) {
377 unsigned long c; /* crc shift register */
378 unsigned long e; /* polynomial exclusive-or pattern */
379 int i; /* counter for all possible eight bit values */
380 int k; /* byte being shifted into crc apparatus */
382 /* terms of polynomial defining this crc (except x^32): */
383 static int p[] = {0,1,2,4,5,7,8,10,11,12,16,22,23,26};
385 /* Make exclusive-or pattern from polynomial (0xedb88320) */
387 for (i = 0; i < sizeof(p)/sizeof(int); i++)
388 e |= 1L << (31 - p[i]);
390 /* Compute and print table of CRC's, five per line */
391 crc_32_tab[0] = 0x00000000L;
392 for (i = 1; i < 256; i++) {
394 /* The idea to initialize the register with the byte instead of
395 * zero was stolen from Haruhiko Okumura's ar002
398 c = c & 1 ? (c >> 1) ^ e : c >> 1;
409 c = crc_32_tab[((int) c ^ (*s++)) & 0xff] ^ (c >> 8);
413 return c ^ 0xffffffffL; /* (instead of ~c for 64-bit machines) */
416 void write_error_msg()
418 fprintf(stderr, "\n");
423 /* ===========================================================================
424 * Does the same as write(), but also handles partial pipe writes and checks
427 void write_buf(fd, buf, cnt)
434 while ((n = write(fd, buf, cnt)) != cnt) {
435 if (n == (unsigned) (-1)) {
439 buf = (void *) ((char *) buf + n);
443 /* ===========================================================================
444 * Write the output window window[0..outcnt-1] and update crc and bytes_out.
445 * (Used for the decompressed data only.)
451 updcrc(window, outcnt);
454 write_buf(ofd, (char *) window, outcnt);
455 bytes_out += (ulg) outcnt;
460 /* "decompress" an inflated type 0 (stored) block. */
462 unsigned n; /* number of bytes in block */
463 unsigned w; /* current window position */
464 register ulg b; /* bit buffer */
465 register unsigned k; /* number of bits in bit buffer */
467 /* make local copies of globals */
468 b = bb; /* initialize bit buffer */
470 w = outcnt; /* initialize window position */
472 /* go to byte boundary */
476 /* get the length and its complement */
478 n = ((unsigned) b & 0xffff);
481 if (n != (unsigned) ((~b) & 0xffff))
482 return 1; /* error in compressed data */
485 /* read and output the compressed data */
488 window[w++] = (uch) b;
498 /* restore the globals from the locals */
499 outcnt = w; /* restore global window pointer */
500 bb = b; /* restore global bit buffer */
506 struct huft *t; /* table to free */
508 /* Free the malloc'ed tables built by huft_build(), which makes a linked
509 list of the tables it made, with the links in a dummy first entry of
512 register struct huft *p, *q;
514 /* Go through linked list, freeing from the malloced (t[-1]) address. */
516 while (p != (struct huft *) NULL) {
525 int huft_build(b, n, s, d, e, t, m)
526 unsigned *b; /* code lengths in bits (all assumed <= BMAX) */
527 unsigned n; /* number of codes (assumed <= N_MAX) */
528 unsigned s; /* number of simple-valued codes (0..s-1) */
529 ush *d; /* list of base values for non-simple codes */
530 ush *e; /* list of extra bits for non-simple codes */
531 struct huft **t; /* result: starting table */
532 int *m; /* maximum lookup bits, returns actual */
534 /* Given a list of code lengths and a maximum table size, make a set of
535 tables to decode that set of codes. Return zero on success, one if
536 the given code set is incomplete (the tables are still built in this
537 case), two if the input is invalid (all zero length codes or an
538 oversubscribed set of lengths), and three if not enough memory. */
540 unsigned a; /* counter for codes of length k */
541 unsigned c[BMAX + 1]; /* bit length count table */
542 unsigned f; /* i repeats in table every f entries */
543 int g; /* maximum code length */
544 int h; /* table level */
545 register unsigned i; /* counter, current code */
546 register unsigned j; /* counter */
547 register int k; /* number of bits in current code */
548 int l; /* bits per table (returned in m) */
549 register unsigned *p; /* pointer into c[], b[], or v[] */
550 register struct huft *q; /* points to current table */
551 struct huft r; /* table entry for structure assignment */
552 struct huft *u[BMAX]; /* table stack */
553 unsigned v[N_MAX]; /* values in order of bit length */
554 register int w; /* bits before this table == (l * h) */
555 unsigned x[BMAX + 1]; /* bit offsets, then code stack */
556 unsigned *xp; /* pointer into x */
557 int y; /* number of dummy codes added */
558 unsigned z; /* number of entries in current table */
560 /* Generate counts for each bit length */
561 memset ((void *)(c), 0, sizeof(c));
565 Tracecv(*p,
\e(stderr, (n - i >= ' ' && n - i <= '~' ? "%c %d\n" : "0x%x %d\n"), n - i, *p));
566 c[*p]++; /* assume all entries <= BMAX */
567 p++; /* Can't combine with above line (Solaris bug) */
569 if (c[0] == n) { /* null input--all zero length codes */
570 *t = (struct huft *) NULL;
575 /* Find minimum and maximum length, bound *m by those */
577 for (j = 1; j <= BMAX; j++)
580 k = j; /* minimum code length */
581 if ((unsigned) l < j)
583 for (i = BMAX; i; i--)
586 g = i; /* maximum code length */
587 if ((unsigned) l > i)
591 /* Adjust last length count to fill out codes, if needed */
592 for (y = 1 << j; j < i; j++, y <<= 1)
594 return 2; /* bad input: more codes than bits */
599 /* Generate starting offsets into the value table for each length */
603 while (--i) { /* note that i == g from above */
607 /* Make a table of values in order of bit lengths */
615 /* Generate the Huffman codes and for each, make the table entries */
616 x[0] = i = 0; /* first Huffman code is zero */
617 p = v; /* grab values in bit order */
618 h = -1; /* no tables yet--level -1 */
619 w = -l; /* bits decoded == (l * h) */
620 u[0] = (struct huft *) NULL; /* just to keep compilers happy */
621 q = (struct huft *) NULL; /* ditto */
624 /* go through the bit lengths (k already is bits in shortest code) */
625 for (; k <= g; k++) {
628 /* here i is the Huffman code of length k bits for value *p */
629 /* make tables up to required level */
632 w += l; /* previous table always l bits */
634 /* compute minimum size table less than or equal to l bits */
635 z = (z = g - w) > (unsigned) l ? l : z; /* upper limit on table size */
636 if ((f = 1 << (j = k - w)) > a + 1) { /* try a k-w bit table *//* too few codes for k-w bit table */
637 f -= a + 1; /* deduct codes from patterns left */
639 while (++j < z) { /* try smaller tables up to z bits */
640 if ((f <<= 1) <= *++xp)
641 break; /* enough codes to use up j bits */
642 f -= *xp; /* else deduct codes from patterns */
645 z = 1 << j; /* table entries for j-bit table */
647 /* allocate and link in new table */
650 (struct huft *) malloc((z + 1) *
651 sizeof(struct huft))) ==
652 (struct huft *) NULL) {
655 return 3; /* not enough memory */
657 hufts += z + 1; /* track memory usage */
658 *t = q + 1; /* link to list for huft_free() */
659 *(t = &(q->v.t)) = (struct huft *) NULL;
660 u[h] = ++q; /* table starts after link */
662 /* connect to last table, if there is one */
664 x[h] = i; /* save pattern for backing up */
665 r.b = (uch) l; /* bits to dump before this table */
666 r.e = (uch) (16 + j); /* bits in this table */
667 r.v.t = q; /* pointer to this table */
668 j = i >> (w - l); /* (get around Turbo C bug) */
669 u[h - 1][j] = r; /* connect to last table */
673 /* set up table entry in r */
676 r.e = 99; /* out of values--invalid code */
678 r.e = (uch) (*p < 256 ? 16 : 15); /* 256 is end-of-block code */
679 r.v.n = (ush) (*p); /* simple code is just the value */
680 p++; /* one compiler does not like *p++ */
682 r.e = (uch) e[*p - s]; /* non-simple--look up in lists */
686 /* fill code-like entries with r */
688 for (j = i >> w; j < z; j += f)
691 /* backwards increment the k-bit code i */
692 for (j = 1 << (k - 1); i & j; j >>= 1)
696 /* backup over finished tables */
697 while ((i & ((1 << w) - 1)) != x[h]) {
698 h--; /* don't need to update q */
703 /* Return true (1) if we were given an incomplete table */
704 return y != 0 && g != 1;
708 int inflate_codes(tl, td, bl, bd)
709 struct huft *tl, *td; /* literal/length and distance decoder tables */
710 int bl, bd; /* number of bits decoded by tl[] and td[] */
712 /* inflate (decompress) the codes in a deflated (compressed) block.
713 Return an error code or zero if it all goes ok. */
715 register unsigned e; /* table entry flag/number of extra bits */
716 unsigned n, d; /* length and index for copy */
717 unsigned w; /* current window position */
718 struct huft *t; /* pointer to table entry */
719 unsigned ml, md; /* masks for bl and bd bits */
720 register ulg b; /* bit buffer */
721 register unsigned k; /* number of bits in bit buffer */
723 /* make local copies of globals */
724 b = bb; /* initialize bit buffer */
726 w = outcnt; /* initialize window position */
728 /* inflate the coded data */
729 ml = mask_bits[bl]; /* precompute masks for speed */
731 for (;;) { /* do until end of block */
732 NEEDBITS((unsigned) bl)
733 if ((e = (t = tl + ((unsigned) b & ml))->e) > 16)
740 } while ((e = (t = t->v.t + ((unsigned) b & mask_bits[e]))->e)
743 if (e == 16) { /* then it's a literal */
744 window[w++] = (uch) t->v.n;
745 Tracevv((stderr, "%c", window[w - 1]));
752 } else { /* it's an EOB or a length */
754 /* exit if end of block */
758 /* get length of block to copy */
760 n = t->v.n + ((unsigned) b & mask_bits[e]);
763 /* decode distance of block to copy */
764 NEEDBITS((unsigned) bd)
765 if ((e = (t = td + ((unsigned) b & md))->e) > 16)
776 t->v.t + ((unsigned) b & mask_bits[e]))->e) >
780 d = w - t->v.n - ((unsigned) b & mask_bits[e]);
782 Tracevv((stderr, "\\[%d,%d]", w - d, n));
788 WSIZE - ((d &= WSIZE - 1) > w ? d : w)) >
790 #if !defined(NOMEMCPY) && !defined(DEBUG)
791 if (w - d >= e) { /* (this test assumes unsigned comparison) */
792 memcpy(window + w, window + d, e);
795 } else /* do it slow to avoid memcpy() overlap */
796 #endif /* !NOMEMCPY */
798 window[w++] = window[d++];
799 Tracevv((stderr, "%c", window[w - 1]));
811 /* restore the globals from the locals */
812 outcnt = w; /* restore global window pointer */
813 bb = b; /* restore global bit buffer */
821 /* decompress an inflated type 1 (fixed Huffman codes) block. We should
822 either replace this with a custom decoder, or at least precompute the
825 int i; /* temporary variable */
826 struct huft *tl; /* literal/length code table */
827 struct huft *td; /* distance code table */
828 int bl; /* lookup bits for tl */
829 int bd; /* lookup bits for td */
830 unsigned l[288]; /* length list for huft_build */
832 /* set up literal table */
833 for (i = 0; i < 144; i++)
839 for (; i < 288; i++) /* make a complete, but wrong code set */
842 if ((i = huft_build(l, 288, 257, cplens, cplext, &tl, &bl)) != 0)
845 /* set up distance table */
846 for (i = 0; i < 30; i++) /* make an incomplete code set */
849 if ((i = huft_build(l, 30, 0, cpdist, cpdext, &td, &bd)) > 1) {
854 /* decompress until an end-of-block code */
855 if (inflate_codes(tl, td, bl, bd))
858 /* free the decoding tables, return */
864 int inflate_dynamic()
865 /* decompress an inflated type 2 (dynamic Huffman codes) block. */
867 int dbits = 6; /* bits in base distance lookup table */
868 int lbits = 9; /* bits in base literal/length lookup table */
870 int i; /* temporary variables */
872 unsigned l; /* last length */
873 unsigned m; /* mask for bit lengths table */
874 unsigned n; /* number of lengths to get */
875 struct huft *tl; /* literal/length code table */
876 struct huft *td; /* distance code table */
877 int bl; /* lookup bits for tl */
878 int bd; /* lookup bits for td */
879 unsigned nb; /* number of bit length codes */
880 unsigned nl; /* number of literal/length codes */
881 unsigned nd; /* number of distance codes */
883 #ifdef PKZIP_BUG_WORKAROUND
884 unsigned ll[288 + 32]; /* literal/length and distance code lengths */
886 unsigned ll[286 + 30]; /* literal/length and distance code lengths */
888 register ulg b; /* bit buffer */
889 register unsigned k; /* number of bits in bit buffer */
891 /* make local bit buffer */
895 /* read in table lengths */
897 nl = 257 + ((unsigned) b & 0x1f); /* number of literal/length codes */
900 nd = 1 + ((unsigned) b & 0x1f); /* number of distance codes */
903 nb = 4 + ((unsigned) b & 0xf); /* number of bit length codes */
905 #ifdef PKZIP_BUG_WORKAROUND
906 if (nl > 288 || nd > 32)
908 if (nl > 286 || nd > 30)
910 return 1; /* bad lengths */
912 /* read in bit-length-code lengths */
913 for (j = 0; j < nb; j++) {
915 ll[border[j]] = (unsigned) b & 7;
921 /* build decoding table for trees--single level, 7 bit lookup */
923 if ((i = huft_build(ll, 19, 19, NULL, NULL, &tl, &bl)) != 0) {
926 return i; /* incomplete code set */
929 /* read in literal and distance code lengths */
933 while ((unsigned) i < n) {
934 NEEDBITS((unsigned) bl)
935 j = (td = tl + ((unsigned) b & m))->b;
938 if (j < 16) /* length of code in bits (0..15) */
939 ll[i++] = l = j; /* save last length in l */
940 else if (j == 16) { /* repeat last length 3 to 6 times */
942 j = 3 + ((unsigned) b & 3);
944 if ((unsigned) i + j > n)
948 } else if (j == 17) { /* 3 to 10 zero length codes */
950 j = 3 + ((unsigned) b & 7);
952 if ((unsigned) i + j > n)
957 } else { /* j == 18: 11 to 138 zero length codes */
960 j = 11 + ((unsigned) b & 0x7f);
962 if ((unsigned) i + j > n)
970 /* free decoding table for trees */
973 /* restore the global bit buffer */
977 /* build the decoding tables for literal/length and distance codes */
979 if ((i = huft_build(ll, nl, 257, cplens, cplext, &tl, &bl)) != 0) {
981 fprintf(stderr, " incomplete literal tree\n");
984 return i; /* incomplete code set */
987 if ((i = huft_build(ll + nl, nd, 0, cpdist, cpdext, &td, &bd)) != 0) {
989 fprintf(stderr, " incomplete distance tree\n");
993 return i; /* incomplete code set */
996 /* decompress until an end-of-block code */
997 if (inflate_codes(tl, td, bl, bd))
1000 /* free the decoding tables, return */
1006 /* decompress an inflated block */
1007 int inflate_block(e)
1008 int *e; /* last block flag */
1010 unsigned t; /* block type */
1011 register ulg b; /* bit buffer */
1012 register unsigned k; /* number of bits in bit buffer */
1014 /* make local bit buffer */
1018 /* read in last block bit */
1023 /* read in block type */
1025 t = (unsigned) b & 3;
1028 /* restore the global bit buffer */
1032 /* inflate that block type */
1034 return inflate_dynamic();
1036 return inflate_stored();
1038 return inflate_fixed();
1040 /* bad block type */
1045 /* decompress an inflated entry */
1047 int e; /* last block flag */
1048 int r; /* result code */
1049 unsigned h; /* maximum struct huft's malloc'ed */
1051 /* initialize window, bit buffer */
1056 /* decompress until the last block */
1060 if ((r = inflate_block(&e)) != 0)
1066 /* Undo too much lookahead. The next read will be byte aligned so we
1067 * can discard unused bits in the last meaningful byte.
1074 /* flush out window */
1077 /* return success */
1079 fprintf(stderr, "<%u> ", h);
1084 /* ===========================================================================
1085 * Unzip in to out. This routine works on both gzip and pkzip files.
1087 * IN assertions: the buffer inbuf contains already the beginning of
1088 * the compressed data, from offsets inptr to insize-1 included.
1089 * The magic header has already been checked. The output buffer is cleared.
1092 int in, out; /* input and output file descriptors */
1094 int ext_header = 0; /* set if extended local header */
1095 int pkzip = 0; /* set for a pkzip file */
1096 ulg orig_crc = 0; /* original crc */
1097 ulg orig_len = 0; /* original uncompressed length */
1099 uch buf[EXTHDR]; /* extended local header */
1103 method = get_method(ifd);
1105 exit(exit_code); /* error message already emitted */
1108 updcrc(NULL, 0); /* initialize crc */
1110 if (pkzip && !ext_header) { /* crc and length at the end otherwise */
1111 orig_crc = LG(inbuf + LOCCRC);
1112 orig_len = LG(inbuf + LOCLEN);
1116 if (method == DEFLATED) {
1118 int res = inflate();
1121 errorMsg(memory_exhausted);
1122 } else if (res != 0) {
1123 errorMsg("invalid compressed data--format violated");
1127 errorMsg("internal error, invalid method");
1130 /* Get the crc and original length */
1132 /* crc32 (see algorithm.doc)
1133 * uncompressed input size modulo 2^32
1135 for (n = 0; n < 8; n++) {
1136 buf[n] = (uch) get_byte(); /* may cause an error if EOF */
1139 orig_len = LG(buf + 4);
1141 } else if (ext_header) { /* If extended header, check it */
1142 /* signature - 4bytes: 0x50 0x4b 0x07 0x08
1144 * compressed size 4-bytes
1145 * uncompressed size 4-bytes
1147 for (n = 0; n < EXTHDR; n++) {
1148 buf[n] = (uch) get_byte(); /* may cause an error if EOF */
1150 orig_crc = LG(buf + 4);
1151 orig_len = LG(buf + 12);
1154 /* Validate decompression */
1155 if (orig_crc != updcrc(outbuf, 0)) {
1156 errorMsg("invalid compressed data--crc error");
1158 if (orig_len != (ulg) bytes_out) {
1159 errorMsg("invalid compressed data--length error");
1162 /* Check if there are more entries in a pkzip file */
1163 if (pkzip && inptr + 4 < insize && LG(inbuf + inptr) == LOCSIG) {
1164 fprintf(stderr, "has more than one entry--rest ignored\n");
1165 if (exit_code == OK)
1166 exit_code = WARNING;
1168 ext_header = pkzip = 0; /* for next file */
1173 /* ===========================================================================
1174 * Clear input and output buffers
1176 void clear_bufs(void)
1180 bytes_in = bytes_out = 0L;
1183 /* ===========================================================================
1184 * Write the output buffer outbuf[0..outcnt-1] and update bytes_out.
1185 * (used for the compressed data only)
1193 write_buf(ofd, (char *) outbuf, outcnt);
1194 bytes_out += (ulg) outcnt;
1198 /* ======================================================================== */
1199 int gunzip_main(int argc, char **argv)
1201 int file_count; /* number of files to precess */
1207 int delInputFile = 0;
1209 struct stat statBuf;
1211 char ifname[MAX_PATH_LEN + 1]; /* input file name */
1212 char ofname[MAX_PATH_LEN + 1]; /* output file name */
1214 if (strcmp(applet_name, "zcat") == 0) {
1219 /* Parse any options */
1220 while (--argc > 0 && **(++argv) == '-') {
1221 if (*((*argv) + 1) == '\0') {
1224 while (*(++(*argv))) {
1236 usage(gunzip_usage);
1246 if (isatty(fileno(stdin)) && fromstdin==1 && force==0)
1247 fatalError( "data not read from terminal. Use -f to force it.\n");
1248 if (isatty(fileno(stdout)) && tostdout==1 && force==0)
1249 fatalError( "data not written to terminal. Use -f to force it.\n");
1252 foreground = signal(SIGINT, SIG_IGN) != SIG_IGN;
1254 (void) signal(SIGINT, (sig_type) abort_gzip);
1257 if (signal(SIGTERM, SIG_IGN) != SIG_IGN) {
1258 (void) signal(SIGTERM, (sig_type) abort_gzip);
1262 if (signal(SIGHUP, SIG_IGN) != SIG_IGN) {
1263 (void) signal(SIGHUP, (sig_type) abort_gzip);
1267 file_count = argc - optind;
1269 /* Allocate all global buffers (for DYN_ALLOC option) */
1270 inbuf = xmalloc((size_t)((INBUFSIZ+INBUF_EXTRA+1L)*sizeof(uch)));
1271 outbuf = xmalloc((size_t)((OUTBUFSIZ+OUTBUF_EXTRA+1L)*sizeof(uch)));
1272 d_buf = xmalloc((size_t)((DIST_BUFSIZE+1L)*sizeof(ush)));
1273 window = xmalloc((size_t)(((2L*WSIZE)+1L)*sizeof(uch)));
1274 tab_prefix0 = xmalloc((size_t)(((1L<<(BITS-1))+1L)*sizeof(ush)));
1275 tab_prefix1 = xmalloc((size_t)(((1L<<(BITS-1))+1L)*sizeof(ush)));
1277 if (fromstdin == 1) {
1278 strcpy(ofname, "stdin");
1280 inFileNum = fileno(stdin);
1281 ifile_size = -1L; /* convention for unknown size */
1283 /* Open up the input file */
1285 usage(gunzip_usage);
1286 if (strlen(*argv) > MAX_PATH_LEN) {
1287 errorMsg(name_too_long);
1290 strcpy(ifname, *argv);
1292 /* Open input fille */
1293 inFileNum = open(ifname, O_RDONLY);
1294 if (inFileNum < 0) {
1298 /* Get the time stamp on the input file. */
1299 result = stat(ifname, &statBuf);
1304 ifile_size = statBuf.st_size;
1307 if (tostdout == 1) {
1308 /* And get to work */
1309 strcpy(ofname, "stdout");
1310 outFileNum = fileno(stdout);
1312 clear_bufs(); /* clear input and output buffers */
1315 /* Actually do the compression/decompression. */
1316 unzip(inFileNum, outFileNum);
1318 } else if (test_mode) {
1319 /* Actually do the compression/decompression. */
1320 unzip(inFileNum, 2);
1324 /* And get to work */
1325 if (strlen(ifname) > MAX_PATH_LEN - 4) {
1326 errorMsg(name_too_long);
1329 strcpy(ofname, ifname);
1330 pos = strstr(ofname, ".gz");
1335 pos = strstr(ofname, ".tgz");
1338 strcat(pos, ".tar");
1343 /* Open output fille */
1344 #if (__GLIBC__ >= 2) && (__GLIBC_MINOR__ >= 1)
1345 outFileNum = open(ofname, O_RDWR | O_CREAT | O_EXCL | O_NOFOLLOW);
1347 outFileNum = open(ofname, O_RDWR | O_CREAT | O_EXCL);
1349 if (outFileNum < 0) {
1353 /* Set permissions on the file */
1354 fchmod(outFileNum, statBuf.st_mode);
1356 clear_bufs(); /* clear input and output buffers */
1359 /* Actually do the compression/decompression. */
1360 result = unzip(inFileNum, outFileNum);
1364 /* Delete the original file */
1366 delFileName = ifname;
1368 delFileName = ofname;
1370 if (delInputFile == 1 && unlink(delFileName) < 0) {
1371 perror(delFileName);