Don't delete source file when decompressing to stdout
[oweals/busybox.git] / archival / libunarchive / unzip.c
1 /* vi: set sw=4 ts=4: */
2 /*
3  * gunzip implementation for busybox
4  *
5  * Based on GNU gzip v1.2.4 Copyright (C) 1992-1993 Jean-loup Gailly.
6  *
7  * Originally adjusted for busybox by Sven Rudolph <sr1@inf.tu-dresden.de>
8  * based on gzip sources
9  *
10  * Adjusted further by Erik Andersen <andersee@debian.org> to support
11  * files as well as stdin/stdout, and to generally behave itself wrt
12  * command line handling.
13  *
14  * General cleanup to better adhere to the style guide and make use of standard
15  * busybox functions by Glenn McGrath <bug1@optushome.com.au>
16  * 
17  * This program is free software; you can redistribute it and/or modify
18  * it under the terms of the GNU General Public License as published by
19  * the Free Software Foundation; either version 2 of the License, or
20  * (at your option) any later version.
21  *
22  * This program is distributed in the hope that it will be useful,
23  * but WITHOUT ANY WARRANTY; without even the implied warranty of
24  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
25  * General Public License for more details.
26  *
27  * You should have received a copy of the GNU General Public License
28  * along with this program; if not, write to the Free Software
29  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
30  *
31  *
32  * gzip (GNU zip) -- compress files with zip algorithm and 'compress' interface
33  * Copyright (C) 1992-1993 Jean-loup Gailly
34  * The unzip code was written and put in the public domain by Mark Adler.
35  * Portions of the lzw code are derived from the public domain 'compress'
36  * written by Spencer Thomas, Joe Orost, James Woods, Jim McKie, Steve Davies,
37  * Ken Turkowski, Dave Mack and Peter Jannesen.
38  *
39  * See the license_msg below and the file COPYING for the software license.
40  * See the file algorithm.doc for the compression algorithms and file formats.
41  */
42
43 #if 0
44 static char *license_msg[] = {
45         "   Copyright (C) 1992-1993 Jean-loup Gailly",
46         "   This program is free software; you can redistribute it and/or modify",
47         "   it under the terms of the GNU General Public License as published by",
48         "   the Free Software Foundation; either version 2, or (at your option)",
49         "   any later version.",
50         "",
51         "   This program is distributed in the hope that it will be useful,",
52         "   but WITHOUT ANY WARRANTY; without even the implied warranty of",
53         "   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the",
54         "   GNU General Public License for more details.",
55         "",
56         "   You should have received a copy of the GNU General Public License",
57         "   along with this program; if not, write to the Free Software",
58         "   Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.",
59         0
60 };
61 #endif
62
63 #include <sys/types.h>
64 #include <sys/wait.h>
65 #include <signal.h>
66 #include <stdlib.h>
67 #include <string.h>
68 #include "libbb.h"
69
70 static FILE *in_file, *out_file;
71
72 /* these are freed by gz_close */
73 static unsigned char *window;
74 static unsigned long *crc_table;
75
76 static unsigned long crc; /* shift register contents */
77
78 /* Return codes from gzip */
79 static const int ERROR = 1;
80
81 /*
82  * window size--must be a power of two, and
83  *  at least 32K for zip's deflate method
84  */
85 static const int WSIZE = 0x8000;
86
87 /* If BMAX needs to be larger than 16, then h and x[] should be ulg. */
88 static const int BMAX = 16;             /* maximum bit length of any code (16 for explode) */
89 static const int N_MAX = 288;           /* maximum number of codes in any set */
90
91 static long bytes_out;          /* number of output bytes */
92 static unsigned long outcnt;    /* bytes in output buffer */
93
94 static unsigned hufts;          /* track memory usage */
95 static unsigned long bb;                        /* bit buffer */
96 static unsigned bk;             /* bits in bit buffer */
97
98 typedef struct huft_s {
99         unsigned char e;                /* number of extra bits or operation */
100         unsigned char b;                /* number of bits in this code or subcode */
101         union {
102                 unsigned short n;               /* literal, length base, or distance base */
103                 struct huft_s *t;       /* pointer to next level of table */
104         } v;
105 } huft_t;
106
107 static const unsigned short mask_bits[] = {
108         0x0000,
109         0x0001, 0x0003, 0x0007, 0x000f, 0x001f, 0x003f, 0x007f, 0x00ff,
110         0x01ff, 0x03ff, 0x07ff, 0x0fff, 0x1fff, 0x3fff, 0x7fff, 0xffff
111 };
112
113 //static int error_number = 0;
114 /* ========================================================================
115  * Signal and error handler.
116  */
117  
118 static void abort_gzip(void)
119 {
120         error_msg("gzip aborted\n");
121         exit(ERROR);
122 }
123
124 static void make_crc_table(void)
125 {
126         const unsigned long poly = 0xedb88320;      /* polynomial exclusive-or pattern */
127         unsigned short i;                /* counter for all possible eight bit values */
128
129         /* initial shift register value */
130         crc = 0xffffffffL;      
131         crc_table = (unsigned long *) malloc(256 * sizeof(unsigned long));
132
133         /* Compute and print table of CRC's, five per line */
134         for (i = 0; i < 256; i++) {
135                 unsigned long table_entry;      /* crc shift register */
136                 char k; /* byte being shifted into crc apparatus */
137
138                 table_entry = i;
139            /* The idea to initialize the register with the byte instead of
140              * zero was stolen from Haruhiko Okumura's ar002
141              */
142                 for (k = 8; k; k--) {
143                         table_entry = table_entry & 1 ? (table_entry >> 1) ^ poly : table_entry >> 1;
144                 }
145                 crc_table[i]=table_entry;
146         }
147 }
148
149 /* ===========================================================================
150  * Write the output window window[0..outcnt-1] and update crc and bytes_out.
151  * (Used for the decompressed data only.)
152  */
153 static void flush_window(void)
154 {
155         int n;
156
157         if (outcnt == 0)
158                 return;
159
160         for (n = 0; n < outcnt; n++) {
161                 crc = crc_table[((int) crc ^ (window[n])) & 0xff] ^ (crc >> 8);
162         }
163
164         if (fwrite(window, 1, outcnt, out_file) != outcnt) {
165                 error_msg_and_die("Couldnt write");
166         }
167         bytes_out += (unsigned long) outcnt;
168         outcnt = 0;
169 }
170
171 /*
172  * Free the malloc'ed tables built by huft_build(), which makes a linked
173  * list of the tables it made, with the links in a dummy first entry of
174  * each table. 
175  * t: table to free
176  */
177 static int huft_free(huft_t *t)
178 {
179         huft_t *p, *q;
180
181         /* Go through linked list, freeing from the malloced (t[-1]) address. */
182         p = t;
183         while (p != (huft_t *) NULL) {
184                 q = (--p)->v.t;
185                 free((char *) p);
186                 p = q;
187         }
188         return 0;
189 }
190
191 typedef unsigned char extra_bits_t;
192
193 /* Given a list of code lengths and a maximum table size, make a set of
194  * tables to decode that set of codes.  Return zero on success, one if
195  * the given code set is incomplete (the tables are still built in this
196  * case), two if the input is invalid (all zero length codes or an
197  * oversubscribed set of lengths), and three if not enough memory.
198  *
199  * b:   code lengths in bits (all assumed <= BMAX)
200  * n:   number of codes (assumed <= N_MAX)
201  * s:   number of simple-valued codes (0..s-1)
202  * d:   list of base values for non-simple codes
203  * e:   list of extra bits for non-simple codes
204  * t:   result: starting table
205  * m:   maximum lookup bits, returns actual
206  */
207 static int huft_build(unsigned int *b, const unsigned int n, const unsigned int s, 
208         const unsigned short *d, const extra_bits_t *e, huft_t **t, int *m)
209 {
210         unsigned a;             /* counter for codes of length k */
211         unsigned c[BMAX + 1];   /* bit length count table */
212         unsigned f;             /* i repeats in table every f entries */
213         int g;                  /* maximum code length */
214         int h;                  /* table level */
215         register unsigned i;    /* counter, current code */
216         register unsigned j;    /* counter */
217         register int k;         /* number of bits in current code */
218         int l;                  /* bits per table (returned in m) */
219         register unsigned *p;           /* pointer into c[], b[], or v[] */
220         register huft_t *q;     /* points to current table */
221         huft_t r;               /* table entry for structure assignment */
222         huft_t *u[BMAX];        /* table stack */
223         unsigned v[N_MAX];      /* values in order of bit length */
224         register int w;         /* bits before this table == (l * h) */
225         unsigned x[BMAX + 1];   /* bit offsets, then code stack */
226         unsigned *xp;           /* pointer into x */
227         int y;                  /* number of dummy codes added */
228         unsigned z;             /* number of entries in current table */
229
230         /* Generate counts for each bit length */
231         memset ((void *)(c), 0, sizeof(c));
232         p = b;
233         i = n;
234         do {
235                 c[*p]++;        /* assume all entries <= BMAX */
236                 p++;            /* Can't combine with above line (Solaris bug) */
237         } while (--i);
238         if (c[0] == n) {        /* null input--all zero length codes */
239                 *t = (huft_t *) NULL;
240                 *m = 0;
241                 return 0;
242         }
243
244         /* Find minimum and maximum length, bound *m by those */
245         l = *m;
246         for (j = 1; j <= BMAX; j++)
247                 if (c[j])
248                         break;
249         k = j;                          /* minimum code length */
250         if ((unsigned) l < j)
251                 l = j;
252         for (i = BMAX; i; i--)
253                 if (c[i])
254                         break;
255         g = i;                          /* maximum code length */
256         if ((unsigned) l > i)
257                 l = i;
258         *m = l;
259
260         /* Adjust last length count to fill out codes, if needed */
261         for (y = 1 << j; j < i; j++, y <<= 1)
262                 if ((y -= c[j]) < 0)
263                         return 2;       /* bad input: more codes than bits */
264         if ((y -= c[i]) < 0)
265                 return 2;
266         c[i] += y;
267
268         /* Generate starting offsets into the value table for each length */
269         x[1] = j = 0;
270         p = c + 1;
271         xp = x + 2;
272         while (--i) {                   /* note that i == g from above */
273                 *xp++ = (j += *p++);
274         }
275
276         /* Make a table of values in order of bit lengths */
277         p = b;
278         i = 0;
279         do {
280                 if ((j = *p++) != 0)
281                         v[x[j]++] = i;
282         } while (++i < n);
283
284         /* Generate the Huffman codes and for each, make the table entries */
285         x[0] = i = 0;                   /* first Huffman code is zero */
286         p = v;                          /* grab values in bit order */
287         h = -1;                         /* no tables yet--level -1 */
288         w = -l;                         /* bits decoded == (l * h) */
289         u[0] = (huft_t *) NULL; /* just to keep compilers happy */
290         q = (huft_t *) NULL;    /* ditto */
291         z = 0;                          /* ditto */
292
293         /* go through the bit lengths (k already is bits in shortest code) */
294         for (; k <= g; k++) {
295                 a = c[k];
296                 while (a--) {
297                         /* here i is the Huffman code of length k bits for value *p */
298                         /* make tables up to required level */
299                         while (k > w + l) {
300                                 h++;
301                                 w += l;         /* previous table always l bits */
302
303                                 /* compute minimum size table less than or equal to l bits */
304                                 z = (z = g - w) > (unsigned) l ? l : z; /* upper limit on table size */
305                                 if ((f = 1 << (j = k - w)) > a + 1) {   /* try a k-w bit table *//* too few codes for k-w bit table */
306                                         f -= a + 1;     /* deduct codes from patterns left */
307                                         xp = c + k;
308                                         while (++j < z) {       /* try smaller tables up to z bits */
309                                                 if ((f <<= 1) <= *++xp)
310                                                         break;  /* enough codes to use up j bits */
311                                                 f -= *xp;       /* else deduct codes from patterns */
312                                         }
313                                 }
314                                 z = 1 << j;             /* table entries for j-bit table */
315
316                                 /* allocate and link in new table */
317                                 q = (huft_t *) xmalloc((z + 1) * sizeof(huft_t));
318
319                                 hufts += z + 1; /* track memory usage */
320                                 *t = q + 1;             /* link to list for huft_free() */
321                                 *(t = &(q->v.t)) = NULL;
322                                 u[h] = ++q;             /* table starts after link */
323
324                                 /* connect to last table, if there is one */
325                                 if (h) {
326                                         x[h] = i;       /* save pattern for backing up */
327                                         r.b = (unsigned char) l;        /* bits to dump before this table */
328                                         r.e = (unsigned char) (16 + j); /* bits in this table */
329                                         r.v.t = q;      /* pointer to this table */
330                                         j = i >> (w - l);       /* (get around Turbo C bug) */
331                                         u[h - 1][j] = r;        /* connect to last table */
332                                 }
333                         }
334
335                         /* set up table entry in r */
336                         r.b = (unsigned char) (k - w);
337                         if (p >= v + n)
338                                 r.e = 99;               /* out of values--invalid code */
339                         else if (*p < s) {
340                                 r.e = (unsigned char) (*p < 256 ? 16 : 15);     /* 256 is end-of-block code */
341                                 r.v.n = (unsigned short) (*p);  /* simple code is just the value */
342                                 p++;                    /* one compiler does not like *p++ */
343                         } else {
344                                 r.e = (unsigned char) e[*p - s];        /* non-simple--look up in lists */
345                                 r.v.n = d[*p++ - s];
346                         }
347
348                         /* fill code-like entries with r */
349                         f = 1 << (k - w);
350                         for (j = i >> w; j < z; j += f)
351                                 q[j] = r;
352
353                         /* backwards increment the k-bit code i */
354                         for (j = 1 << (k - 1); i & j; j >>= 1)
355                                 i ^= j;
356                         i ^= j;
357
358                         /* backup over finished tables */
359                         while ((i & ((1 << w) - 1)) != x[h]) {
360                                 h--;                    /* don't need to update q */
361                                 w -= l;
362                         }
363                 }
364         }
365         /* Return true (1) if we were given an incomplete table */
366         return y != 0 && g != 1;
367 }
368
369 /*
370  * inflate (decompress) the codes in a deflated (compressed) block.
371  * Return an error code or zero if it all goes ok.
372  *
373  * tl, td: literal/length and distance decoder tables
374  * bl, bd: number of bits decoded by tl[] and td[]
375  */
376 static int inflate_codes(huft_t *tl, huft_t *td, int bl, int bd)
377 {
378         register unsigned long e;               /* table entry flag/number of extra bits */
379         unsigned long n, d;                             /* length and index for copy */
380         unsigned long w;                                /* current window position */
381         huft_t *t;                              /* pointer to table entry */
382         unsigned ml, md;                        /* masks for bl and bd bits */
383         register unsigned long b;                               /* bit buffer */
384         register unsigned k;            /* number of bits in bit buffer */
385
386         /* make local copies of globals */
387         b = bb;                                 /* initialize bit buffer */
388         k = bk;
389         w = outcnt;                             /* initialize window position */
390
391         /* inflate the coded data */
392         ml = mask_bits[bl];                     /* precompute masks for speed */
393         md = mask_bits[bd];
394         for (;;) {                              /* do until end of block */
395                 while (k < (unsigned) bl) {
396                         b |= ((unsigned long)fgetc(in_file)) << k;
397                         k += 8;
398                 }
399                 if ((e = (t = tl + ((unsigned) b & ml))->e) > 16)
400                 do {
401                         if (e == 99) {
402                                 return 1;
403                         }
404                         b >>= t->b;
405                         k -= t->b;
406                         e -= 16;
407                         while (k < e) {
408                                 b |= ((unsigned long)fgetc(in_file)) << k;
409                                 k += 8;
410                         }
411                 } while ((e = (t = t->v.t + ((unsigned) b & mask_bits[e]))->e) > 16);
412                 b >>= t->b;
413                 k -= t->b;
414                 if (e == 16) {          /* then it's a literal */
415                         window[w++] = (unsigned char) t->v.n;
416                         if (w == WSIZE) {
417                                 outcnt=(w),
418                                 flush_window();
419                                 w = 0;
420                         }
421                 } else {                                /* it's an EOB or a length */
422
423                         /* exit if end of block */
424                         if (e == 15) {
425                                 break;
426                         }
427
428                         /* get length of block to copy */
429                         while (k < e) {
430                                 b |= ((unsigned long)fgetc(in_file)) << k;
431                                 k += 8;
432                         }
433                         n = t->v.n + ((unsigned) b & mask_bits[e]);
434                         b >>= e;
435                         k -= e;
436
437                         /* decode distance of block to copy */
438                         while (k < (unsigned) bd) {
439                                 b |= ((unsigned long)fgetc(in_file)) << k;
440                                 k += 8;
441                         }
442
443                         if ((e = (t = td + ((unsigned) b & md))->e) > 16)
444                                 do {
445                                         if (e == 99)
446                                                 return 1;
447                                         b >>= t->b;
448                                         k -= t->b;
449                                         e -= 16;
450                                         while (k < e) {
451                                                 b |= ((unsigned long)fgetc(in_file)) << k;
452                                                 k += 8;
453                                         }
454                                 } while ((e = (t = t->v.t + ((unsigned) b & mask_bits[e]))->e) > 16);
455                         b >>= t->b;
456                         k -= t->b;
457                         while (k < e) {
458                                 b |= ((unsigned long)fgetc(in_file)) << k;
459                                 k += 8;
460                         }
461                         d = w - t->v.n - ((unsigned) b & mask_bits[e]);
462                         b >>= e;
463                         k -= e;
464
465                         /* do the copy */
466                         do {
467                                 n -= (e = (e = WSIZE - ((d &= WSIZE - 1) > w ? d : w)) > n ? n : e);
468 #if !defined(NOMEMCPY) && !defined(DEBUG)
469                                 if (w - d >= e) {       /* (this test assumes unsigned comparison) */
470                                         memcpy(window + w, window + d, e);
471                                         w += e;
472                                         d += e;
473                                 } else                  /* do it slow to avoid memcpy() overlap */
474 #endif                                                  /* !NOMEMCPY */
475                                         do {
476                                                 window[w++] = window[d++];
477                                         } while (--e);
478                                 if (w == WSIZE) {
479                                         outcnt=(w),
480                                         flush_window();
481                                         w = 0;
482                                 }
483                         } while (n);
484                 }
485         }
486
487         /* restore the globals from the locals */
488         outcnt = w;                     /* restore global window pointer */
489         bb = b;                         /* restore global bit buffer */
490         bk = k;
491
492         /* done */
493         return 0;
494 }
495
496 static const unsigned short cplens[] = {     /* Copy lengths for literal codes 257..285 */
497     3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,
498     35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0
499 };
500 /* note: see note #13 above about the 258 in this list. */
501 static const extra_bits_t cplext[] = {  /* Extra bits for literal codes 257..285 */
502     0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2,
503     3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0, 99, 99
504 };                 /* 99==invalid */
505 static const unsigned short cpdist[] = {     /* Copy offsets for distance codes 0..29 */
506     1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,
507     257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,
508     8193, 12289, 16385, 24577
509 };
510 static const extra_bits_t cpdext[] = {  /* Extra bits for distance codes */
511     0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6,
512     7, 7, 8, 8, 9, 9, 10, 10, 11, 11,
513     12, 12, 13, 13
514 };
515 /* Tables for deflate from PKZIP's appnote.txt. */
516 static const extra_bits_t border[] = {  /* Order of the bit length code lengths */
517     16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15
518 };
519
520 /*
521  * decompress an inflated block
522  * e: last block flag
523  *
524  * GLOBAL VARIABLES: bb, kk,
525  */
526 static int inflate_block(int *e)
527 {
528         unsigned t;                     /* block type */
529         register unsigned long b;                       /* bit buffer */
530         register unsigned k;            /* number of bits in bit buffer */
531
532         /* make local bit buffer */
533         b = bb;
534         k = bk;
535
536         /* read in last block bit */
537         while (k < 1) {
538                 b |= ((unsigned long)fgetc(in_file)) << k;
539                 k += 8;
540         }
541         *e = (int) b & 1;
542         b >>= 1;
543         k -= 1;
544
545         /* read in block type */
546         while (k < 2) {
547                 b |= ((unsigned long)fgetc(in_file)) << k;
548                 k += 8;
549         }
550         t = (unsigned) b & 3;
551         b >>= 2;
552         k -= 2;
553
554         /* restore the global bit buffer */
555         bb = b;
556         bk = k;
557
558         /* inflate that block type */
559         switch (t) {
560         case 0: /* Inflate stored */
561                 {
562                         unsigned long n;                        /* number of bytes in block */
563                         unsigned long w;                        /* current window position */
564                         register unsigned long b_stored;                        /* bit buffer */
565                         register unsigned long k_stored;                /* number of bits in bit buffer */
566
567                         /* make local copies of globals */
568                         b_stored = bb;                          /* initialize bit buffer */
569                         k_stored = bk;
570                         w = outcnt;                     /* initialize window position */
571
572                         /* go to byte boundary */
573                         n = k_stored & 7;
574                         b_stored >>= n;
575                         k_stored -= n;
576
577                         /* get the length and its complement */
578                         while (k_stored < 16) {
579                                 b_stored |= ((unsigned long)fgetc(in_file)) << k_stored;
580                                 k_stored += 8;
581                         }
582                         n = ((unsigned) b_stored & 0xffff);
583                         b_stored >>= 16;
584                         k_stored -= 16;
585                         while (k_stored < 16) {
586                                 b_stored |= ((unsigned long)fgetc(in_file)) << k_stored;
587                                 k_stored += 8;
588                         }
589                         if (n != (unsigned) ((~b_stored) & 0xffff)) {
590                                 return 1;               /* error in compressed data */
591                         }
592                         b_stored >>= 16;
593                         k_stored -= 16;
594
595                         /* read and output the compressed data */
596                         while (n--) {
597                                 while (k_stored < 8) {
598                                         b_stored |= ((unsigned long)fgetc(in_file)) << k_stored;
599                                         k_stored += 8;
600                                 }
601                                 window[w++] = (unsigned char) b_stored;
602                                 if (w == (unsigned long)WSIZE) {
603                                         outcnt=(w),
604                                         flush_window();
605                                         w = 0;
606                                 }
607                                 b_stored >>= 8;
608                                 k_stored -= 8;
609                         }
610
611                         /* restore the globals from the locals */
612                         outcnt = w;                     /* restore global window pointer */
613                         bb = b_stored;                          /* restore global bit buffer */
614                         bk = k_stored;
615                         return 0;
616                 }
617         case 1: /* Inflate fixed 
618                          * decompress an inflated type 1 (fixed Huffman codes) block.  We should
619                          * either replace this with a custom decoder, or at least precompute the
620                          * Huffman tables.
621                          */
622                 {
623                         int i;                                  /* temporary variable */
624                         huft_t *tl;                             /* literal/length code table */
625                         huft_t *td;                             /* distance code table */
626                         int bl;                                 /* lookup bits for tl */
627                         int bd;                                 /* lookup bits for td */
628                         unsigned int l[288];    /* length list for huft_build */
629
630                         /* set up literal table */
631                         for (i = 0; i < 144; i++) {
632                                 l[i] = 8;
633                         }
634                         for (; i < 256; i++) {
635                                 l[i] = 9;
636                         }
637                         for (; i < 280; i++) {
638                                 l[i] = 7;
639                         }
640                         for (; i < 288; i++) {  /* make a complete, but wrong code set */
641                                 l[i] = 8;
642                         }
643                         bl = 7;
644                         if ((i = huft_build(l, 288, 257, cplens, cplext, &tl, &bl)) != 0) {
645                                 return i;
646                         }
647
648                         /* set up distance table */
649                         for (i = 0; i < 30; i++) {      /* make an incomplete code set */
650                                 l[i] = 5;
651                         }
652                         bd = 5;
653                         if ((i = huft_build(l, 30, 0, cpdist, cpdext, &td, &bd)) > 1) {
654                                 huft_free(tl);
655                                 return i;
656                         }
657
658                         /* decompress until an end-of-block code */
659                         if (inflate_codes(tl, td, bl, bd))
660                                 return 1;
661
662                         /* free the decoding tables, return */
663                         huft_free(tl);
664                         huft_free(td);
665                         return 0;
666                 }
667         case 2: /* Inflate dynamic */
668                 {
669                         const int dbits = 6;                                    /* bits in base distance lookup table */
670                         const int lbits = 9;                                    /* bits in base literal/length lookup table */
671
672                         int i;                                          /* temporary variables */
673                         unsigned j;
674                         unsigned l;                                     /* last length */
675                         unsigned m;                                     /* mask for bit lengths table */
676                         unsigned n;                                     /* number of lengths to get */
677                         huft_t *tl;                     /* literal/length code table */
678                         huft_t *td;                     /* distance code table */
679                         int bl;                                         /* lookup bits for tl */
680                         int bd;                                         /* lookup bits for td */
681                         unsigned nb;                            /* number of bit length codes */
682                         unsigned nl;                            /* number of literal/length codes */
683                         unsigned nd;                            /* number of distance codes */
684
685                         unsigned ll[286 + 30];          /* literal/length and distance code lengths */
686                         register unsigned long b_dynamic;       /* bit buffer */
687                         register unsigned k_dynamic;            /* number of bits in bit buffer */
688
689                         /* make local bit buffer */
690                         b_dynamic = bb;
691                         k_dynamic = bk;
692
693                         /* read in table lengths */
694                         while (k_dynamic < 5) {
695                                 b_dynamic |= ((unsigned long)fgetc(in_file)) << k_dynamic;
696                                 k_dynamic += 8;
697                         }
698                         nl = 257 + ((unsigned) b_dynamic & 0x1f);       /* number of literal/length codes */
699                         b_dynamic >>= 5;
700                         k_dynamic -= 5;
701                         while (k_dynamic < 5) {
702                                 b_dynamic |= ((unsigned long)fgetc(in_file)) << k_dynamic;
703                                 k_dynamic += 8;
704                         }
705                         nd = 1 + ((unsigned) b_dynamic & 0x1f); /* number of distance codes */
706                         b_dynamic >>= 5;
707                         k_dynamic -= 5;
708                         while (k_dynamic < 4) {
709                                 b_dynamic |= ((unsigned long)fgetc(in_file)) << k_dynamic;
710                                 k_dynamic += 8;
711                         }
712                         nb = 4 + ((unsigned) b_dynamic & 0xf);  /* number of bit length codes */
713                         b_dynamic >>= 4;
714                         k_dynamic -= 4;
715                         if (nl > 286 || nd > 30) {
716                                 return 1;       /* bad lengths */
717                         }
718
719                         /* read in bit-length-code lengths */
720                         for (j = 0; j < nb; j++) {
721                                 while (k_dynamic < 3) {
722                                         b_dynamic |= ((unsigned long)fgetc(in_file)) << k_dynamic;
723                                         k_dynamic += 8;
724                                 }
725                                 ll[border[j]] = (unsigned) b_dynamic & 7;
726                                 b_dynamic >>= 3;
727                                 k_dynamic -= 3;
728                         }
729                         for (; j < 19; j++) {
730                                 ll[border[j]] = 0;
731                         }
732
733                         /* build decoding table for trees--single level, 7 bit lookup */
734                         bl = 7;
735                         if ((i = huft_build(ll, 19, 19, NULL, NULL, &tl, &bl)) != 0) {
736                                 if (i == 1) {
737                                         huft_free(tl);
738                                 }
739                                 return i;                       /* incomplete code set */
740                         }
741
742                         /* read in literal and distance code lengths */
743                         n = nl + nd;
744                         m = mask_bits[bl];
745                         i = l = 0;
746                         while ((unsigned) i < n) {
747                                 while (k_dynamic < (unsigned) bl) {
748                                         b_dynamic |= ((unsigned long)fgetc(in_file)) << k_dynamic;
749                                         k_dynamic += 8;
750                                 }
751                                 j = (td = tl + ((unsigned) b_dynamic & m))->b;
752                                 b_dynamic >>= j;
753                                 k_dynamic -= j;
754                                 j = td->v.n;
755                                 if (j < 16) {                   /* length of code in bits (0..15) */
756                                         ll[i++] = l = j;        /* save last length in l */
757                                 }
758                                 else if (j == 16) {             /* repeat last length 3 to 6 times */
759                                         while (k_dynamic < 2) {
760                                                 b_dynamic |= ((unsigned long)fgetc(in_file)) << k_dynamic;
761                                                 k_dynamic += 8;
762                                         }
763                                         j = 3 + ((unsigned) b_dynamic & 3);
764                                         b_dynamic >>= 2;
765                                         k_dynamic -= 2;
766                                         if ((unsigned) i + j > n) {
767                                                 return 1;
768                                         }
769                                         while (j--) {
770                                                 ll[i++] = l;
771                                         }
772                                 } else if (j == 17) {   /* 3 to 10 zero length codes */
773                                         while (k_dynamic < 3) {
774                                                 b_dynamic |= ((unsigned long)fgetc(in_file)) << k_dynamic;
775                                                 k_dynamic += 8;
776                                         }
777                                         j = 3 + ((unsigned) b_dynamic & 7);
778                                         b_dynamic >>= 3;
779                                         k_dynamic -= 3;
780                                         if ((unsigned) i + j > n) {
781                                                 return 1;
782                                         }
783                                         while (j--) {
784                                                 ll[i++] = 0;
785                                         }
786                                         l = 0;
787                                 } else {                /* j == 18: 11 to 138 zero length codes */
788                                         while (k_dynamic < 7) {
789                                                 b_dynamic |= ((unsigned long)fgetc(in_file)) << k_dynamic;
790                                                 k_dynamic += 8;
791                                         }
792                                         j = 11 + ((unsigned) b_dynamic & 0x7f);
793                                         b_dynamic >>= 7;
794                                         k_dynamic -= 7;
795                                         if ((unsigned) i + j > n) {
796                                                 return 1;
797                                         }
798                                         while (j--) {
799                                                 ll[i++] = 0;
800                                         }
801                                         l = 0;
802                                 }
803                         }
804
805                         /* free decoding table for trees */
806                         huft_free(tl);
807
808                         /* restore the global bit buffer */
809                         bb = b_dynamic;
810                         bk = k_dynamic;
811
812                         /* build the decoding tables for literal/length and distance codes */
813                         bl = lbits;
814                         if ((i = huft_build(ll, nl, 257, cplens, cplext, &tl, &bl)) != 0) {
815                                 if (i == 1) {
816                                         error_msg("Incomplete literal tree");
817                                         huft_free(tl);
818                                 }
819                                 return i;                       /* incomplete code set */
820                         }
821                         bd = dbits;
822                         if ((i = huft_build(ll + nl, nd, 0, cpdist, cpdext, &td, &bd)) != 0) {
823                                 if (i == 1) {
824                                         error_msg("incomplete distance tree");
825                                         huft_free(td);
826                                 }
827                                 huft_free(tl);
828                                 return i;                       /* incomplete code set */
829                         }
830
831                         /* decompress until an end-of-block code */
832                         if (inflate_codes(tl, td, bl, bd))
833                                 return 1;
834
835                         /* free the decoding tables, return */
836                         huft_free(tl);
837                         huft_free(td);
838                         return 0;
839                 }
840         default:
841                 /* bad block type */
842                 return 2;
843         }
844 }
845
846 /*
847  * decompress an inflated entry
848  *
849  * GLOBAL VARIABLES: outcnt, bk, bb, hufts, inptr
850  */
851 extern int inflate(FILE *in, FILE *out)
852 {
853         int e;                          /* last block flag */
854         int r;                          /* result code */
855         unsigned h = 0;         /* maximum struct huft's malloc'ed */
856
857         /* initialize window, bit buffer */
858         outcnt = 0;
859         bk = 0;
860         bb = 0;
861
862         in_file = in;
863         out_file = out;
864
865         /* Allocate all global buffers (for DYN_ALLOC option) */
866         window = xmalloc((size_t)(((2L*WSIZE)+1L)*sizeof(unsigned char)));
867         bytes_out = 0L;
868
869         /* Create the crc table */
870         make_crc_table();
871
872         /* decompress until the last block */
873         do {
874                 hufts = 0;
875                 if ((r = inflate_block(&e)) != 0) {
876                         return r;
877                 }
878                 if (hufts > h) {
879                         h = hufts;
880                 }
881         } while (!e);
882
883         /* Undo too much lookahead. The next read will be byte aligned so we
884          * can discard unused bits in the last meaningful byte.
885          */
886         while (bk >= 8) {
887                 bk -= 8;
888                 ungetc((bb << bk), in_file);
889         }
890
891         /* flush out window */
892         flush_window();
893         free(window);
894         free(crc_table);
895
896         /* return success */
897         return 0;
898 }
899
900 /* ===========================================================================
901  * Unzip in to out.  This routine works on gzip files only.
902  *
903  * IN assertions: the buffer inbuf contains already the beginning of
904  *   the compressed data, from offsets inptr to insize-1 included.
905  *   The magic header has already been checked. The output buffer is cleared.
906  * in, out: input and output file descriptors
907  */
908 extern int unzip(FILE *l_in_file, FILE *l_out_file)
909 {
910         unsigned char buf[8];   /* extended local header */
911         unsigned char flags;    /* compression flags */
912         typedef void (*sig_type) (int);
913         unsigned short i;
914
915         if (signal(SIGINT, SIG_IGN) != SIG_IGN) {
916                 (void) signal(SIGINT, (sig_type) abort_gzip);
917         }
918 #ifdef SIGTERM
919 //      if (signal(SIGTERM, SIG_IGN) != SIG_IGN) {
920 //              (void) signal(SIGTERM, (sig_type) abort_gzip);
921 //      }
922 #endif
923 #ifdef SIGHUP
924         if (signal(SIGHUP, SIG_IGN) != SIG_IGN) {
925                 (void) signal(SIGHUP, (sig_type) abort_gzip);
926         }
927 #endif
928
929         /* Magic header for gzip files, 1F 8B = \037\213 */
930         if ((fgetc(l_in_file) != 0x1F) || (fgetc(l_in_file) != 0x8b)) {
931                 error_msg("Invalid gzip magic");
932                 return EXIT_FAILURE;
933         }
934
935         /* Check the compression method */
936         if (fgetc(l_in_file) != 8) {
937                 error_msg("Unknown compression method");
938                 return(-1);
939         }
940
941         flags = (unsigned char) fgetc(l_in_file);
942
943         /* Ignore time stamp(4), extra flags(1), OS type(1) */
944         for (i = 0; i < 6; i++) {
945                 fgetc(l_in_file);
946         }
947
948         if (flags & 0x04) {
949                 /* bit 2 set: extra field present */
950                 const unsigned short extra = fgetc(l_in_file) + (fgetc(l_in_file) << 8);
951
952                 for (i = 0; i < extra; i++) {
953                         fgetc(l_in_file);
954                 }
955         }
956
957         /* Discard original name if any */
958         if (flags & 0x08) {
959                 /* bit 3 set: original file name present */
960                 while (fgetc(l_in_file) != 0);  /* null */
961         }
962
963         /* Discard file comment if any */
964         if (flags & 0x10) {
965                 /* bit 4 set: file comment present */
966                 while (fgetc(l_in_file) != 0);  /* null */
967         }
968
969         /* Decompress */
970         if (inflate(l_in_file, l_out_file) != 0) {
971                 error_msg("invalid compressed data--format violated");
972         }
973
974         /* Get the crc and original length
975          * crc32  (see algorithm.doc)
976          * uncompressed input size modulo 2^32
977          */
978         fread(buf, 1, 8, l_in_file);
979
980         /* Validate decompression - crc */
981         if ((unsigned int)((buf[0] | (buf[1] << 8)) |((buf[2] | (buf[3] << 8)) << 16)) != (crc ^ 0xffffffffL)) {
982                 error_msg("invalid compressed data--crc error");
983         }
984         /* Validate decompression - size */
985         if (((buf[4] | (buf[5] << 8)) |((buf[6] | (buf[7] << 8)) << 16)) != (unsigned long) bytes_out) {
986                 error_msg("invalid compressed data--length error");
987         }
988
989         return 0;
990 }
991
992 /*
993  * This needs access to global variables window and crc_table, so its not in its own file.
994  */
995 extern void gz_close(int gunzip_pid)
996 {
997         if (kill(gunzip_pid, SIGTERM) == -1) {
998                 error_msg_and_die("***  Couldnt kill old gunzip process *** aborting");
999         }
1000
1001         if (waitpid(gunzip_pid, NULL, 0) == -1) {
1002                 printf("Couldnt wait ?");
1003         }
1004
1005         free(window);
1006         free(crc_table);
1007 }