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