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