0c9d406708630541ad813b0b0914c6a456c02166
[oweals/busybox.git] / gunzip.c
1 /* vi: set sw=4 ts=4: */
2 /*
3  * Gzip 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 <andersen@lineo.com>, <andersee@debian.org>
11  * to support files as well as stdin/stdout, and to generally behave itself wrt
12  * command line handling.
13  *
14  * This program is free software; you can redistribute it and/or modify
15  * it under the terms of the GNU General Public License as published by
16  * the Free Software Foundation; either version 2 of the License, or
17  * (at your option) any later version.
18  *
19  * This program is distributed in the hope that it will be useful,
20  * but WITHOUT ANY WARRANTY; without even the implied warranty of
21  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
22  * General Public License for more details.
23  *
24  * You should have received a copy of the GNU General Public License
25  * along with this program; if not, write to the Free Software
26  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
27  *
28  *
29  * gzip (GNU zip) -- compress files with zip algorithm and 'compress' interface
30  * Copyright (C) 1992-1993 Jean-loup Gailly
31  * The unzip code was written and put in the public domain by Mark Adler.
32  * Portions of the lzw code are derived from the public domain 'compress'
33  * written by Spencer Thomas, Joe Orost, James Woods, Jim McKie, Steve Davies,
34  * Ken Turkowski, Dave Mack and Peter Jannesen.
35  *
36  * See the license_msg below and the file COPYING for the software license.
37  * See the file algorithm.doc for the compression algorithms and file formats.
38  */
39
40 #if 0
41 static char *license_msg[] = {
42         "   Copyright (C) 1992-1993 Jean-loup Gailly",
43         "   This program is free software; you can redistribute it and/or modify",
44         "   it under the terms of the GNU General Public License as published by",
45         "   the Free Software Foundation; either version 2, or (at your option)",
46         "   any later version.",
47         "",
48         "   This program is distributed in the hope that it will be useful,",
49         "   but WITHOUT ANY WARRANTY; without even the implied warranty of",
50         "   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the",
51         "   GNU General Public License for more details.",
52         "",
53         "   You should have received a copy of the GNU General Public License",
54         "   along with this program; if not, write to the Free Software",
55         "   Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.",
56         0
57 };
58 #endif
59
60 #include "busybox.h"
61 #include <getopt.h>
62 #include <ctype.h>
63 #include <sys/types.h>
64 #include <signal.h>
65 #include <errno.h>
66 #include <stdio.h>
67 #include <string.h>
68 #include <memory.h>
69 #include <unistd.h>
70 #include <fcntl.h>
71 #include <stdlib.h>
72 #include <time.h>
73 #include <dirent.h>
74 #define BB_DECLARE_EXTERN
75 #define bb_need_memory_exhausted
76 #define bb_need_name_too_long
77 #include "messages.c"
78
79 #define RECORD_IO 0
80
81 /* Return codes from gzip */
82 #define OK      0
83 #define ERROR   1
84 #define WARNING 2
85
86 #define DEFLATED     8
87 #define INBUFSIZ     0x2000     /* input buffer size */
88 #define INBUF_EXTRA  64         /* required by unlzw() */
89 #define OUTBUFSIZ    8192       /* output buffer size */
90 #define OUTBUF_EXTRA 2048       /* required by unlzw() */
91 #define DIST_BUFSIZE 0x2000     /* buffer for distances, see trees.c */
92
93 #define GZIP_MAGIC  "\037\213"  /* Magic header for gzip files, 1F 8B */
94
95 /* gzip flag byte */
96 #define EXTRA_FIELD  0x04       /* bit 2 set: extra field present */
97 #define ORIG_NAME    0x08       /* bit 3 set: original file name present */
98 #define COMMENT      0x10       /* bit 4 set: file comment present */
99 #define WSIZE 0x8000            /* window size--must be a power of two, and */
100                                 /*  at least 32K for zip's deflate method */
101
102 /* If BMAX needs to be larger than 16, then h and x[] should be ulg. */
103 #define BMAX 16         /* maximum bit length of any code (16 for explode) */
104 #define N_MAX 288               /* maximum number of codes in any set */
105
106 /* PKZIP header definitions */
107 #define LOCSIG 0x04034b50L      /* four-byte lead-in (lsb first) */
108 #define LOCCRC 14               /* offset of crc */
109 #define LOCLEN 22               /* offset of uncompressed length */
110 #define EXTHDR 16               /* size of extended local header, inc sig */
111
112 #define BITS 16
113
114 /* Diagnostic functions */
115 #ifdef DEBUG
116 #  define Assert(cond,msg) {if(!(cond)) errorMsg(msg);}
117 #  define Trace(x) fprintf x
118 #  define Tracev(x) {if (verbose) fprintf x ;}
119 #  define Tracevv(x) {if (verbose>1) fprintf x ;}
120 #  define Tracec(c,x) {if (verbose && (c)) fprintf x ;}
121 #  define Tracecv(c,x) {if (verbose>1 && (c)) fprintf x ;}
122 #else
123 #  define Assert(cond,msg)
124 #  define Trace(x)
125 #  define Tracev(x)
126 #  define Tracevv(x)
127 #  define Tracec(c,x)
128 #  define Tracecv(c,x)
129 #endif
130
131 #ifndef MAX_PATH_LEN                    /* max pathname length */
132 #  ifdef BUFSIZ
133 #    define MAX_PATH_LEN   BUFSIZ
134 #  else
135 #    define MAX_PATH_LEN   1024
136 #  endif
137 #endif
138
139 #define NEXTBYTE()  (uch)get_byte()
140 #define NEEDBITS(n) {while(k<(n)){b|=((ulg)NEXTBYTE())<<k;k+=8;}}
141 #define DUMPBITS(n) {b>>=(n);k-=(n);}
142
143 #define get_byte()  (inptr < insize ? inbuf[inptr++] : fill_inbuf(0))
144
145 /* Macros for getting two-byte and four-byte header values */
146 #define SH(p) ((ush)(uch)((p)[0]) | ((ush)(uch)((p)[1]) << 8))
147 #define LG(p) ((ulg)(SH(p)) | ((ulg)(SH((p)+2)) << 16))
148
149         /* in gzip.c */
150 void abort_gzip (void);
151 typedef void (*sig_type) (int);
152
153 typedef unsigned char uch;
154 typedef unsigned short ush;
155 typedef unsigned long ulg;
156 typedef int file_t;                             /* Do not use stdio */
157
158 uch *inbuf;
159 uch *outbuf;
160 ush *d_buf;
161 uch *window;
162 ush *tab_prefix0;
163 ush *tab_prefix1;
164
165 /* local variables */
166 int test_mode = 0;      /* check file integrity option */
167 int foreground;         /* set if program run in foreground */
168 int maxbits = BITS;     /* max bits per code for LZW */
169 int method = DEFLATED;  /* compression method */
170 int exit_code = OK;     /* program exit code */
171 int last_member;        /* set for .zip and .Z files */
172 int part_nb;            /* number of parts in .gz file */
173 long ifile_size;        /* input file size, -1 for devices (debug only) */
174 long bytes_in;          /* number of input bytes */
175 long bytes_out;         /* number of output bytes */
176 long total_in = 0;      /* input bytes for all files */
177 long total_out = 0;     /* output bytes for all files */
178 struct stat istat;      /* status for input file */
179 int ifd;                /* input file descriptor */
180 int ofd;                /* output file descriptor */
181 unsigned insize;        /* valid bytes in inbuf */
182 unsigned inptr;         /* index of next byte to be processed in inbuf */
183 unsigned outcnt;        /* bytes in output buffer */
184
185 unsigned hufts;         /* track memory usage */
186 ulg bb;                 /* bit buffer */
187 unsigned bk;            /* bits in bit buffer */
188 int crc_table_empty = 1;
189
190 struct huft {
191         uch e;          /* number of extra bits or operation */
192         uch b;          /* number of bits in this code or subcode */
193         union {
194                 ush n;          /* literal, length base, or distance base */
195                 struct huft *t; /* pointer to next level of table */
196         } v;
197 };
198
199 /* Tables for deflate from PKZIP's appnote.txt. */
200 static unsigned border[] = {    /* Order of the bit length code lengths */
201         16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15
202 };
203 static ush cplens[] = {         /* Copy lengths for literal codes 257..285 */
204         3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,
205         35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0
206 };
207
208 /* note: see note #13 above about the 258 in this list. */
209 static ush cplext[] = {         /* Extra bits for literal codes 257..285 */
210         0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2,
211         3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0, 99, 99
212 };                              /* 99==invalid */
213
214 static ush cpdist[] = {         /* Copy offsets for distance codes 0..29 */
215         1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,
216         257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,
217         8193, 12289, 16385, 24577
218 };
219
220 static ush cpdext[] = {         /* Extra bits for distance codes */
221         0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6,
222         7, 7, 8, 8, 9, 9, 10, 10, 11, 11,
223         12, 12, 13, 13
224 };
225
226 ush mask_bits[] = {
227         0x0000,
228         0x0001, 0x0003, 0x0007, 0x000f, 0x001f, 0x003f, 0x007f, 0x00ff,
229         0x01ff, 0x03ff, 0x07ff, 0x0fff, 0x1fff, 0x3fff, 0x7fff, 0xffff
230 };
231
232 /* ========================================================================
233  * Error handlers.
234  */
235 void read_error_msg()
236 {
237         fprintf(stderr, "\n");
238         if (errno != 0) {
239                 perror("");
240         } else {
241                 fprintf(stderr, "unexpected end of file\n");
242         }
243         abort_gzip();
244 }
245
246 /* ===========================================================================
247  * Fill the input buffer. This is called only when the buffer is empty.
248  */
249 int fill_inbuf(eof_ok)
250 int eof_ok;             /* set if EOF acceptable as a result */
251 {
252         int len;
253
254         /* Read as much as possible */
255         insize = 0;
256         errno = 0;
257         do {
258                 len = read(ifd, (char *) inbuf + insize, INBUFSIZ - insize);
259                 if (len == 0 || len == EOF)
260                         break;
261                 insize += len;
262         } while (insize < INBUFSIZ);
263
264         if (insize == 0) {
265                 if (eof_ok)
266                         return EOF;
267                 read_error_msg();
268         }
269         bytes_in += (ulg) insize;
270         inptr = 1;
271         return inbuf[0];
272 }
273
274
275 /* ========================================================================
276  * Check the magic number of the input file and update ofname if an
277  * original name was given and tostdout is not set.
278  * Return the compression method, -1 for error, -2 for warning.
279  * Set inptr to the offset of the next byte to be processed.
280  * Updates time_stamp if there is one and --no-time is not used.
281  * This function may be called repeatedly for an input file consisting
282  * of several contiguous gzip'ed members.
283  * IN assertions: there is at least one remaining compressed member.
284  *   If the member is a zip file, it must be the only one.
285  */
286 static int get_method(in)
287 int in;                                 /* input file descriptor */
288 {
289         uch flags;                      /* compression flags */
290         char magic[2];                  /* magic header */
291         long header_bytes = 0;          /* number of bytes in gzip header */
292
293         magic[0] = (char) get_byte();
294         magic[1] = (char) get_byte();
295         method = -1;                    /* unknown yet */
296         part_nb++;                      /* number of parts in gzip file */
297         last_member = RECORD_IO;
298         /* assume multiple members in gzip file except for record oriented I/O */
299
300         if (memcmp(magic, GZIP_MAGIC, 2) == 0) {
301
302                 method = (int) get_byte();
303                 if (method != DEFLATED) {
304                         errorMsg("unknown method %d -- get newer version of gzip\n", method);
305                         exit_code = ERROR;
306                         return -1;
307                 }
308                 flags = (uch) get_byte();
309
310                 (ulg) get_byte();               /* Ignore time stamp */
311                 (ulg) get_byte();
312                 (ulg) get_byte();
313                 (ulg) get_byte();
314
315                 (void) get_byte();              /* Ignore extra flags for the moment */
316                 (void) get_byte();              /* Ignore OS type for the moment */
317
318                 if ((flags & EXTRA_FIELD) != 0) {
319                         unsigned len = (unsigned) get_byte();
320                         len |= ((unsigned) get_byte()) << 8;
321                         while (len--)
322                                 (void) get_byte();
323                 }
324
325                 /* Discard original name if any */
326                 if ((flags & ORIG_NAME) != 0) {
327                         while (get_byte() != 0);        /* null */
328                 }
329
330                 /* Discard file comment if any */
331                 if ((flags & COMMENT) != 0) {
332                         while (get_byte() != 0) /* null */
333                                 ;
334                 }
335                 if (part_nb == 1) {
336                         header_bytes = inptr + 2 * sizeof(long);        /* include crc and size */
337                 }
338
339         }
340
341         if (method >= 0)
342                 return method;
343
344         if (part_nb == 1) {
345                 fprintf(stderr, "\nnot in gzip format\n");
346                 exit_code = ERROR;
347                 return -1;
348         } else {
349                 fprintf(stderr, "\ndecompression OK, trailing garbage ignored\n");
350                 if (exit_code == OK)
351                         exit_code = WARNING;
352                 return -2;
353         }
354 }
355
356 /* ========================================================================
357  * Signal and error handler.
358  */
359 void abort_gzip()
360 {
361         exit(ERROR);
362 }
363
364 /* ===========================================================================
365  * Run a set of bytes through the crc shift register.  If s is a NULL
366  * pointer, then initialize the crc shift register contents instead.
367  * Return the current crc in either case.
368  */
369 ulg updcrc(s, n)
370 uch *s;                                 /* pointer to bytes to pump through */
371 unsigned n;                             /* number of bytes in s[] */
372 {
373         static ulg crc = (ulg) 0xffffffffL;     /* shift register contents */
374         register ulg c;                         /* temporary variable */
375         static unsigned long crc_32_tab[256];
376         if (crc_table_empty) {
377                 unsigned long c;      /* crc shift register */
378                 unsigned long e;      /* polynomial exclusive-or pattern */
379                 int i;                /* counter for all possible eight bit values */
380                 int k;                /* byte being shifted into crc apparatus */
381
382                 /* terms of polynomial defining this crc (except x^32): */
383                 static int p[] = {0,1,2,4,5,7,8,10,11,12,16,22,23,26};
384
385                 /* Make exclusive-or pattern from polynomial (0xedb88320) */
386                 e = 0;
387                 for (i = 0; i < sizeof(p)/sizeof(int); i++)
388                         e |= 1L << (31 - p[i]);
389
390                 /* Compute and print table of CRC's, five per line */
391                 crc_32_tab[0] = 0x00000000L;
392                 for (i = 1; i < 256; i++) {
393                         c = i;
394                    /* The idea to initialize the register with the byte instead of
395                      * zero was stolen from Haruhiko Okumura's ar002
396                      */
397                         for (k = 8; k; k--)
398                                 c = c & 1 ? (c >> 1) ^ e : c >> 1;
399                         crc_32_tab[i]=c;
400                 }
401         }
402
403         if (s == NULL) {
404                 c = 0xffffffffL;
405         } else {
406                 c = crc;
407                 if (n)
408                         do {
409                                 c = crc_32_tab[((int) c ^ (*s++)) & 0xff] ^ (c >> 8);
410                         } while (--n);
411         }
412         crc = c;
413         return c ^ 0xffffffffL;         /* (instead of ~c for 64-bit machines) */
414 }
415
416 void write_error_msg()
417 {
418         fprintf(stderr, "\n");
419         perror("");
420         abort_gzip();
421 }
422
423 /* ===========================================================================
424  * Does the same as write(), but also handles partial pipe writes and checks
425  * for error return.
426  */
427 void write_buf(fd, buf, cnt)
428 int fd;
429 void * buf;
430 unsigned cnt;
431 {
432         unsigned n;
433
434         while ((n = write(fd, buf, cnt)) != cnt) {
435                 if (n == (unsigned) (-1)) {
436                         write_error_msg();
437                 }
438                 cnt -= n;
439                 buf = (void *) ((char *) buf + n);
440         }
441 }
442
443 /* ===========================================================================
444  * Write the output window window[0..outcnt-1] and update crc and bytes_out.
445  * (Used for the decompressed data only.)
446  */
447 void flush_window()
448 {
449         if (outcnt == 0)
450                 return;
451         updcrc(window, outcnt);
452
453         if (!test_mode)
454                 write_buf(ofd, (char *) window, outcnt);
455         bytes_out += (ulg) outcnt;
456         outcnt = 0;
457 }
458
459 int inflate_stored()
460 /* "decompress" an inflated type 0 (stored) block. */
461 {
462         unsigned n;                     /* number of bytes in block */
463         unsigned w;                     /* current window position */
464         register ulg b;                 /* bit buffer */
465         register unsigned k;            /* number of bits in bit buffer */
466
467         /* make local copies of globals */
468         b = bb;                         /* initialize bit buffer */
469         k = bk;
470         w = outcnt;                     /* initialize window position */
471
472         /* go to byte boundary */
473         n = k & 7;
474         DUMPBITS(n);
475
476         /* get the length and its complement */
477         NEEDBITS(16)
478                 n = ((unsigned) b & 0xffff);
479         DUMPBITS(16)
480                 NEEDBITS(16)
481                 if (n != (unsigned) ((~b) & 0xffff))
482                 return 1;               /* error in compressed data */
483         DUMPBITS(16)
484
485                 /* read and output the compressed data */
486                 while (n--) {
487                 NEEDBITS(8)
488                         window[w++] = (uch) b;
489                 if (w == WSIZE) {
490 //                      flush_output(w);
491                                 outcnt=(w),
492                                 flush_window();
493                         w = 0;
494                 }
495                 DUMPBITS(8)
496         }
497
498         /* restore the globals from the locals */
499         outcnt = w;                     /* restore global window pointer */
500         bb = b;                         /* restore global bit buffer */
501         bk = k;
502         return 0;
503 }
504
505 int huft_free(t)
506 struct huft *t;                         /* table to free */
507
508 /* Free the malloc'ed tables built by huft_build(), which makes a linked
509    list of the tables it made, with the links in a dummy first entry of
510    each table. */
511 {
512         register struct huft *p, *q;
513
514         /* Go through linked list, freeing from the malloced (t[-1]) address. */
515         p = t;
516         while (p != (struct huft *) NULL) {
517                 q = (--p)->v.t;
518                 free((char *) p);
519                 p = q;
520         }
521         return 0;
522 }
523
524
525 int huft_build(b, n, s, d, e, t, m)
526 unsigned *b;                    /* code lengths in bits (all assumed <= BMAX) */
527 unsigned n;                     /* number of codes (assumed <= N_MAX) */
528 unsigned s;                     /* number of simple-valued codes (0..s-1) */
529 ush *d;                         /* list of base values for non-simple codes */
530 ush *e;                         /* list of extra bits for non-simple codes */
531 struct huft **t;                /* result: starting table */
532 int *m;                         /* maximum lookup bits, returns actual */
533
534 /* Given a list of code lengths and a maximum table size, make a set of
535    tables to decode that set of codes.  Return zero on success, one if
536    the given code set is incomplete (the tables are still built in this
537    case), two if the input is invalid (all zero length codes or an
538    oversubscribed set of lengths), and three if not enough memory. */
539 {
540         unsigned a;             /* counter for codes of length k */
541         unsigned c[BMAX + 1];   /* bit length count table */
542         unsigned f;             /* i repeats in table every f entries */
543         int g;                  /* maximum code length */
544         int h;                  /* table level */
545         register unsigned i;    /* counter, current code */
546         register unsigned j;    /* counter */
547         register int k;         /* number of bits in current code */
548         int l;                  /* bits per table (returned in m) */
549         register unsigned *p;           /* pointer into c[], b[], or v[] */
550         register struct huft *q;        /* points to current table */
551         struct huft r;          /* table entry for structure assignment */
552         struct huft *u[BMAX];   /* table stack */
553         unsigned v[N_MAX];      /* values in order of bit length */
554         register int w;         /* bits before this table == (l * h) */
555         unsigned x[BMAX + 1];   /* bit offsets, then code stack */
556         unsigned *xp;           /* pointer into x */
557         int y;                  /* number of dummy codes added */
558         unsigned z;             /* number of entries in current table */
559
560         /* Generate counts for each bit length */
561         memset ((void *)(c), 0, sizeof(c));
562         p = b;
563         i = n;
564         do {
565                 Tracecv(*p,\e(stderr, (n - i >= ' ' && n - i <= '~' ? "%c %d\n" : "0x%x %d\n"), n - i, *p));
566                 c[*p]++;        /* assume all entries <= BMAX */
567                 p++;            /* Can't combine with above line (Solaris bug) */
568         } while (--i);
569         if (c[0] == n) {        /* null input--all zero length codes */
570                 *t = (struct huft *) NULL;
571                 *m = 0;
572                 return 0;
573         }
574
575         /* Find minimum and maximum length, bound *m by those */
576         l = *m;
577         for (j = 1; j <= BMAX; j++)
578                 if (c[j])
579                         break;
580         k = j;                          /* minimum code length */
581         if ((unsigned) l < j)
582                 l = j;
583         for (i = BMAX; i; i--)
584                 if (c[i])
585                         break;
586         g = i;                          /* maximum code length */
587         if ((unsigned) l > i)
588                 l = i;
589         *m = l;
590
591         /* Adjust last length count to fill out codes, if needed */
592         for (y = 1 << j; j < i; j++, y <<= 1)
593                 if ((y -= c[j]) < 0)
594                         return 2;       /* bad input: more codes than bits */
595         if ((y -= c[i]) < 0)
596                 return 2;
597         c[i] += y;
598
599         /* Generate starting offsets into the value table for each length */
600         x[1] = j = 0;
601         p = c + 1;
602         xp = x + 2;
603         while (--i) {                   /* note that i == g from above */
604                 *xp++ = (j += *p++);
605         }
606
607         /* Make a table of values in order of bit lengths */
608         p = b;
609         i = 0;
610         do {
611                 if ((j = *p++) != 0)
612                         v[x[j]++] = i;
613         } while (++i < n);
614
615         /* Generate the Huffman codes and for each, make the table entries */
616         x[0] = i = 0;                   /* first Huffman code is zero */
617         p = v;                          /* grab values in bit order */
618         h = -1;                         /* no tables yet--level -1 */
619         w = -l;                         /* bits decoded == (l * h) */
620         u[0] = (struct huft *) NULL;    /* just to keep compilers happy */
621         q = (struct huft *) NULL;       /* ditto */
622         z = 0;                          /* ditto */
623
624         /* go through the bit lengths (k already is bits in shortest code) */
625         for (; k <= g; k++) {
626                 a = c[k];
627                 while (a--) {
628                         /* here i is the Huffman code of length k bits for value *p */
629                         /* make tables up to required level */
630                         while (k > w + l) {
631                                 h++;
632                                 w += l;         /* previous table always l bits */
633
634                                 /* compute minimum size table less than or equal to l bits */
635                                 z = (z = g - w) > (unsigned) l ? l : z; /* upper limit on table size */
636                                 if ((f = 1 << (j = k - w)) > a + 1) {   /* try a k-w bit table *//* too few codes for k-w bit table */
637                                         f -= a + 1;     /* deduct codes from patterns left */
638                                         xp = c + k;
639                                         while (++j < z) {       /* try smaller tables up to z bits */
640                                                 if ((f <<= 1) <= *++xp)
641                                                         break;  /* enough codes to use up j bits */
642                                                 f -= *xp;       /* else deduct codes from patterns */
643                                         }
644                                 }
645                                 z = 1 << j;             /* table entries for j-bit table */
646
647                                 /* allocate and link in new table */
648                                 if (
649                                         (q =
650                                          (struct huft *) malloc((z + 1) *
651                                                                                         sizeof(struct huft))) ==
652                                         (struct huft *) NULL) {
653                                         if (h)
654                                                 huft_free(u[0]);
655                                         return 3;       /* not enough memory */
656                                 }
657                                 hufts += z + 1; /* track memory usage */
658                                 *t = q + 1;             /* link to list for huft_free() */
659                                 *(t = &(q->v.t)) = (struct huft *) NULL;
660                                 u[h] = ++q;             /* table starts after link */
661
662                                 /* connect to last table, if there is one */
663                                 if (h) {
664                                         x[h] = i;       /* save pattern for backing up */
665                                         r.b = (uch) l;  /* bits to dump before this table */
666                                         r.e = (uch) (16 + j);   /* bits in this table */
667                                         r.v.t = q;      /* pointer to this table */
668                                         j = i >> (w - l);       /* (get around Turbo C bug) */
669                                         u[h - 1][j] = r;        /* connect to last table */
670                                 }
671                         }
672
673                         /* set up table entry in r */
674                         r.b = (uch) (k - w);
675                         if (p >= v + n)
676                                 r.e = 99;               /* out of values--invalid code */
677                         else if (*p < s) {
678                                 r.e = (uch) (*p < 256 ? 16 : 15);       /* 256 is end-of-block code */
679                                 r.v.n = (ush) (*p);     /* simple code is just the value */
680                                 p++;                    /* one compiler does not like *p++ */
681                         } else {
682                                 r.e = (uch) e[*p - s];  /* non-simple--look up in lists */
683                                 r.v.n = d[*p++ - s];
684                         }
685
686                         /* fill code-like entries with r */
687                         f = 1 << (k - w);
688                         for (j = i >> w; j < z; j += f)
689                                 q[j] = r;
690
691                         /* backwards increment the k-bit code i */
692                         for (j = 1 << (k - 1); i & j; j >>= 1)
693                                 i ^= j;
694                         i ^= j;
695
696                         /* backup over finished tables */
697                         while ((i & ((1 << w) - 1)) != x[h]) {
698                                 h--;                    /* don't need to update q */
699                                 w -= l;
700                         }
701                 }
702         }
703         /* Return true (1) if we were given an incomplete table */
704         return y != 0 && g != 1;
705 }
706
707
708 int inflate_codes(tl, td, bl, bd)
709 struct huft *tl, *td;                   /* literal/length and distance decoder tables */
710 int bl, bd;                                             /* number of bits decoded by tl[] and td[] */
711
712 /* inflate (decompress) the codes in a deflated (compressed) block.
713    Return an error code or zero if it all goes ok. */
714 {
715         register unsigned e;            /* table entry flag/number of extra bits */
716         unsigned n, d;                          /* length and index for copy */
717         unsigned w;                             /* current window position */
718         struct huft *t;                         /* pointer to table entry */
719         unsigned ml, md;                        /* masks for bl and bd bits */
720         register ulg b;                         /* bit buffer */
721         register unsigned k;            /* number of bits in bit buffer */
722
723         /* make local copies of globals */
724         b = bb;                                 /* initialize bit buffer */
725         k = bk;
726         w = outcnt;                             /* initialize window position */
727
728         /* inflate the coded data */
729         ml = mask_bits[bl];                     /* precompute masks for speed */
730         md = mask_bits[bd];
731         for (;;) {                              /* do until end of block */
732                 NEEDBITS((unsigned) bl)
733                         if ((e = (t = tl + ((unsigned) b & ml))->e) > 16)
734                         do {
735                                 if (e == 99)
736                                         return 1;
737                                 DUMPBITS(t->b)
738                                         e -= 16;
739                                 NEEDBITS(e)
740                         } while ((e = (t = t->v.t + ((unsigned) b & mask_bits[e]))->e)
741                                          > 16);
742                 DUMPBITS(t->b)
743                         if (e == 16) {          /* then it's a literal */
744                         window[w++] = (uch) t->v.n;
745                         Tracevv((stderr, "%c", window[w - 1]));
746                         if (w == WSIZE) {
747 //                              flush_output(w);
748                                 outcnt=(w),
749                                 flush_window();
750                                 w = 0;
751                         }
752                 } else {                                /* it's an EOB or a length */
753
754                         /* exit if end of block */
755                         if (e == 15)
756                                 break;
757
758                         /* get length of block to copy */
759                         NEEDBITS(e)
760                                 n = t->v.n + ((unsigned) b & mask_bits[e]);
761                         DUMPBITS(e);
762
763                         /* decode distance of block to copy */
764                         NEEDBITS((unsigned) bd)
765                                 if ((e = (t = td + ((unsigned) b & md))->e) > 16)
766                                 do {
767                                         if (e == 99)
768                                                 return 1;
769                                         DUMPBITS(t->b)
770                                                 e -= 16;
771                                         NEEDBITS(e)
772                                 }
773                                         while (
774                                                    (e =
775                                                         (t =
776                                                          t->v.t + ((unsigned) b & mask_bits[e]))->e) >
777                                                    16);
778                         DUMPBITS(t->b)
779                                 NEEDBITS(e)
780                                 d = w - t->v.n - ((unsigned) b & mask_bits[e]);
781                         DUMPBITS(e)
782                                 Tracevv((stderr, "\\[%d,%d]", w - d, n));
783
784                         /* do the copy */
785                         do {
786                                 n -= (e =
787                                           (e =
788                                            WSIZE - ((d &= WSIZE - 1) > w ? d : w)) >
789                                           n ? n : e);
790 #if !defined(NOMEMCPY) && !defined(DEBUG)
791                                 if (w - d >= e) {       /* (this test assumes unsigned comparison) */
792                                         memcpy(window + w, window + d, e);
793                                         w += e;
794                                         d += e;
795                                 } else                  /* do it slow to avoid memcpy() overlap */
796 #endif                                                  /* !NOMEMCPY */
797                                         do {
798                                                 window[w++] = window[d++];
799                                                 Tracevv((stderr, "%c", window[w - 1]));
800                                         } while (--e);
801                                 if (w == WSIZE) {
802 //                                      flush_output(w);
803                                 outcnt=(w),
804                                 flush_window();
805                                         w = 0;
806                                 }
807                         } while (n);
808                 }
809         }
810
811         /* restore the globals from the locals */
812         outcnt = w;                     /* restore global window pointer */
813         bb = b;                         /* restore global bit buffer */
814         bk = k;
815
816         /* done */
817         return 0;
818 }
819
820 int inflate_fixed()
821 /* decompress an inflated type 1 (fixed Huffman codes) block.  We should
822    either replace this with a custom decoder, or at least precompute the
823    Huffman tables. */
824 {
825         int i;                                          /* temporary variable */
826         struct huft *tl;                        /* literal/length code table */
827         struct huft *td;                        /* distance code table */
828         int bl;                                         /* lookup bits for tl */
829         int bd;                                         /* lookup bits for td */
830         unsigned l[288];                        /* length list for huft_build */
831
832         /* set up literal table */
833         for (i = 0; i < 144; i++)
834                 l[i] = 8;
835         for (; i < 256; i++)
836                 l[i] = 9;
837         for (; i < 280; i++)
838                 l[i] = 7;
839         for (; i < 288; i++)            /* make a complete, but wrong code set */
840                 l[i] = 8;
841         bl = 7;
842         if ((i = huft_build(l, 288, 257, cplens, cplext, &tl, &bl)) != 0)
843                 return i;
844
845         /* set up distance table */
846         for (i = 0; i < 30; i++)        /* make an incomplete code set */
847                 l[i] = 5;
848         bd = 5;
849         if ((i = huft_build(l, 30, 0, cpdist, cpdext, &td, &bd)) > 1) {
850                 huft_free(tl);
851                 return i;
852         }
853
854         /* decompress until an end-of-block code */
855         if (inflate_codes(tl, td, bl, bd))
856                 return 1;
857
858         /* free the decoding tables, return */
859         huft_free(tl);
860         huft_free(td);
861         return 0;
862 }
863
864 int inflate_dynamic()
865 /* decompress an inflated type 2 (dynamic Huffman codes) block. */
866 {
867         int dbits = 6;                                  /* bits in base distance lookup table */
868         int lbits = 9;                                  /* bits in base literal/length lookup table */
869
870         int i;                                          /* temporary variables */
871         unsigned j;
872         unsigned l;                                     /* last length */
873         unsigned m;                                     /* mask for bit lengths table */
874         unsigned n;                                     /* number of lengths to get */
875         struct huft *tl;                        /* literal/length code table */
876         struct huft *td;                        /* distance code table */
877         int bl;                                         /* lookup bits for tl */
878         int bd;                                         /* lookup bits for td */
879         unsigned nb;                            /* number of bit length codes */
880         unsigned nl;                            /* number of literal/length codes */
881         unsigned nd;                            /* number of distance codes */
882
883 #ifdef PKZIP_BUG_WORKAROUND
884         unsigned ll[288 + 32];          /* literal/length and distance code lengths */
885 #else
886         unsigned ll[286 + 30];          /* literal/length and distance code lengths */
887 #endif
888         register ulg b;                         /* bit buffer */
889         register unsigned k;            /* number of bits in bit buffer */
890
891         /* make local bit buffer */
892         b = bb;
893         k = bk;
894
895         /* read in table lengths */
896         NEEDBITS(5)
897                 nl = 257 + ((unsigned) b & 0x1f);       /* number of literal/length codes */
898         DUMPBITS(5)
899                 NEEDBITS(5)
900                 nd = 1 + ((unsigned) b & 0x1f); /* number of distance codes */
901         DUMPBITS(5)
902                 NEEDBITS(4)
903                 nb = 4 + ((unsigned) b & 0xf);  /* number of bit length codes */
904         DUMPBITS(4)
905 #ifdef PKZIP_BUG_WORKAROUND
906                 if (nl > 288 || nd > 32)
907 #else
908                 if (nl > 286 || nd > 30)
909 #endif
910                 return 1;                               /* bad lengths */
911
912         /* read in bit-length-code lengths */
913         for (j = 0; j < nb; j++) {
914                 NEEDBITS(3)
915                         ll[border[j]] = (unsigned) b & 7;
916                 DUMPBITS(3)
917         }
918         for (; j < 19; j++)
919                 ll[border[j]] = 0;
920
921         /* build decoding table for trees--single level, 7 bit lookup */
922         bl = 7;
923         if ((i = huft_build(ll, 19, 19, NULL, NULL, &tl, &bl)) != 0) {
924                 if (i == 1)
925                         huft_free(tl);
926                 return i;                       /* incomplete code set */
927         }
928
929         /* read in literal and distance code lengths */
930         n = nl + nd;
931         m = mask_bits[bl];
932         i = l = 0;
933         while ((unsigned) i < n) {
934                 NEEDBITS((unsigned) bl)
935                         j = (td = tl + ((unsigned) b & m))->b;
936                 DUMPBITS(j)
937                         j = td->v.n;
938                 if (j < 16)                     /* length of code in bits (0..15) */
939                         ll[i++] = l = j;        /* save last length in l */
940                 else if (j == 16) {             /* repeat last length 3 to 6 times */
941                         NEEDBITS(2)
942                                 j = 3 + ((unsigned) b & 3);
943                         DUMPBITS(2)
944                                 if ((unsigned) i + j > n)
945                                 return 1;
946                         while (j--)
947                                 ll[i++] = l;
948                 } else if (j == 17) {   /* 3 to 10 zero length codes */
949                         NEEDBITS(3)
950                                 j = 3 + ((unsigned) b & 7);
951                         DUMPBITS(3)
952                                 if ((unsigned) i + j > n)
953                                 return 1;
954                         while (j--)
955                                 ll[i++] = 0;
956                         l = 0;
957                 } else {                /* j == 18: 11 to 138 zero length codes */
958
959                         NEEDBITS(7)
960                                 j = 11 + ((unsigned) b & 0x7f);
961                         DUMPBITS(7)
962                                 if ((unsigned) i + j > n)
963                                 return 1;
964                         while (j--)
965                                 ll[i++] = 0;
966                         l = 0;
967                 }
968         }
969
970         /* free decoding table for trees */
971         huft_free(tl);
972
973         /* restore the global bit buffer */
974         bb = b;
975         bk = k;
976
977         /* build the decoding tables for literal/length and distance codes */
978         bl = lbits;
979         if ((i = huft_build(ll, nl, 257, cplens, cplext, &tl, &bl)) != 0) {
980                 if (i == 1) {
981                         fprintf(stderr, " incomplete literal tree\n");
982                         huft_free(tl);
983                 }
984                 return i;                       /* incomplete code set */
985         }
986         bd = dbits;
987         if ((i = huft_build(ll + nl, nd, 0, cpdist, cpdext, &td, &bd)) != 0) {
988                 if (i == 1) {
989                         fprintf(stderr, " incomplete distance tree\n");
990                         huft_free(td);
991                 }
992                 huft_free(tl);
993                 return i;                       /* incomplete code set */
994         }
995
996         /* decompress until an end-of-block code */
997         if (inflate_codes(tl, td, bl, bd))
998                 return 1;
999
1000         /* free the decoding tables, return */
1001         huft_free(tl);
1002         huft_free(td);
1003         return 0;
1004 }
1005
1006 /* decompress an inflated block */
1007 int inflate_block(e)
1008 int *e;                                 /* last block flag */
1009 {
1010         unsigned t;                     /* block type */
1011         register ulg b;                 /* bit buffer */
1012         register unsigned k;            /* number of bits in bit buffer */
1013
1014         /* make local bit buffer */
1015         b = bb;
1016         k = bk;
1017
1018         /* read in last block bit */
1019         NEEDBITS(1)
1020                 * e = (int) b & 1;
1021         DUMPBITS(1)
1022
1023                 /* read in block type */
1024                 NEEDBITS(2)
1025                 t = (unsigned) b & 3;
1026         DUMPBITS(2)
1027
1028                 /* restore the global bit buffer */
1029                 bb = b;
1030         bk = k;
1031
1032         /* inflate that block type */
1033         if (t == 2)
1034                 return inflate_dynamic();
1035         if (t == 0)
1036                 return inflate_stored();
1037         if (t == 1)
1038                 return inflate_fixed();
1039
1040         /* bad block type */
1041         return 2;
1042 }
1043
1044 int inflate()
1045 /* decompress an inflated entry */
1046 {
1047         int e;                          /* last block flag */
1048         int r;                          /* result code */
1049         unsigned h;                     /* maximum struct huft's malloc'ed */
1050
1051         /* initialize window, bit buffer */
1052         outcnt = 0;
1053         bk = 0;
1054         bb = 0;
1055
1056         /* decompress until the last block */
1057         h = 0;
1058         do {
1059                 hufts = 0;
1060                 if ((r = inflate_block(&e)) != 0)
1061                         return r;
1062                 if (hufts > h)
1063                         h = hufts;
1064         } while (!e);
1065
1066         /* Undo too much lookahead. The next read will be byte aligned so we
1067          * can discard unused bits in the last meaningful byte.
1068          */
1069         while (bk >= 8) {
1070                 bk -= 8;
1071                 inptr--;
1072         }
1073
1074         /* flush out window */
1075         outcnt=(outcnt),
1076         flush_window();
1077         /* return success */
1078 #ifdef DEBUG
1079         fprintf(stderr, "<%u> ", h);
1080 #endif                                                  /* DEBUG */
1081         return 0;
1082 }
1083
1084 /* ===========================================================================
1085  * Unzip in to out.  This routine works on both gzip and pkzip files.
1086  *
1087  * IN assertions: the buffer inbuf contains already the beginning of
1088  *   the compressed data, from offsets inptr to insize-1 included.
1089  *   The magic header has already been checked. The output buffer is cleared.
1090  */
1091 int unzip(in, out)
1092 int in, out;                                    /* input and output file descriptors */
1093 {
1094         int ext_header = 0;                             /* set if extended local header */
1095         int pkzip = 0;                                  /* set for a pkzip file */
1096         ulg orig_crc = 0;                       /* original crc */
1097         ulg orig_len = 0;                       /* original uncompressed length */
1098         int n;
1099         uch buf[EXTHDR];                        /* extended local header */
1100
1101         ifd = in;
1102         ofd = out;
1103         method = get_method(ifd);
1104         if (method < 0) {
1105                 exit(exit_code);                /* error message already emitted */
1106         }
1107
1108         updcrc(NULL, 0);                        /* initialize crc */
1109
1110         if (pkzip && !ext_header) {     /* crc and length at the end otherwise */
1111                 orig_crc = LG(inbuf + LOCCRC);
1112                 orig_len = LG(inbuf + LOCLEN);
1113         }
1114
1115         /* Decompress */
1116         if (method == DEFLATED) {
1117
1118                 int res = inflate();
1119
1120                 if (res == 3) {
1121                         errorMsg(memory_exhausted);
1122                 } else if (res != 0) {
1123                         errorMsg("invalid compressed data--format violated\n");
1124                 }
1125
1126         } else {
1127                 errorMsg("internal error, invalid method\n");
1128         }
1129
1130         /* Get the crc and original length */
1131         if (!pkzip) {
1132                 /* crc32  (see algorithm.doc)
1133                    * uncompressed input size modulo 2^32
1134                  */
1135                 for (n = 0; n < 8; n++) {
1136                         buf[n] = (uch) get_byte();      /* may cause an error if EOF */
1137                 }
1138                 orig_crc = LG(buf);
1139                 orig_len = LG(buf + 4);
1140
1141         } else if (ext_header) {        /* If extended header, check it */
1142                 /* signature - 4bytes: 0x50 0x4b 0x07 0x08
1143                  * CRC-32 value
1144                  * compressed size 4-bytes
1145                  * uncompressed size 4-bytes
1146                  */
1147                 for (n = 0; n < EXTHDR; n++) {
1148                         buf[n] = (uch) get_byte();      /* may cause an error if EOF */
1149                 }
1150                 orig_crc = LG(buf + 4);
1151                 orig_len = LG(buf + 12);
1152         }
1153
1154         /* Validate decompression */
1155         if (orig_crc != updcrc(outbuf, 0)) {
1156                 errorMsg("invalid compressed data--crc error\n");
1157         }
1158         if (orig_len != (ulg) bytes_out) {
1159                 errorMsg("invalid compressed data--length error\n");
1160         }
1161
1162         /* Check if there are more entries in a pkzip file */
1163         if (pkzip && inptr + 4 < insize && LG(inbuf + inptr) == LOCSIG) {
1164                 fprintf(stderr, "has more than one entry--rest ignored\n");
1165                 if (exit_code == OK)
1166                         exit_code = WARNING;
1167         }
1168         ext_header = pkzip = 0;         /* for next file */
1169         return OK;
1170 }
1171
1172
1173 /* ===========================================================================
1174  * Clear input and output buffers
1175  */
1176 void clear_bufs(void)
1177 {
1178         outcnt = 0;
1179         insize = inptr = 0;
1180         bytes_in = bytes_out = 0L;
1181 }
1182
1183 /* ===========================================================================
1184  * Write the output buffer outbuf[0..outcnt-1] and update bytes_out.
1185  * (used for the compressed data only)
1186  */
1187 void flush_outbuf()
1188 {
1189         if (outcnt == 0)
1190                 return;
1191
1192         if (!test_mode)
1193                 write_buf(ofd, (char *) outbuf, outcnt);
1194         bytes_out += (ulg) outcnt;
1195         outcnt = 0;
1196 }
1197
1198 /* ======================================================================== */
1199 int gunzip_main(int argc, char **argv)
1200 {
1201         int file_count;                         /* number of files to precess */
1202         int tostdout = 0;
1203         int fromstdin = 0;
1204         int result;
1205         int inFileNum;
1206         int outFileNum;
1207         int delInputFile = 0;
1208         int force = 0;
1209         struct stat statBuf;
1210         char *delFileName;
1211         char ifname[MAX_PATH_LEN + 1];  /* input file name */
1212         char ofname[MAX_PATH_LEN + 1];  /* output file name */
1213
1214         if (strcmp(applet_name, "zcat") == 0) {
1215                 force = 1;
1216                 tostdout = 1;
1217         }
1218
1219         /* Parse any options */
1220         while (--argc > 0 && **(++argv) == '-') {
1221                 if (*((*argv) + 1) == '\0') {
1222                         tostdout = 1;
1223                 }
1224                 while (*(++(*argv))) {
1225                         switch (**argv) {
1226                         case 'c':
1227                                 tostdout = 1;
1228                                 break;
1229                         case 't':
1230                                 test_mode = 1;
1231                                 break;
1232                         case 'f':
1233                                 force = 1;
1234                                 break;
1235                         default:
1236                                 usage(gunzip_usage);
1237                         }
1238                 }
1239         }
1240
1241         if (argc <= 0) {
1242                 tostdout = 1;
1243                 fromstdin = 1;
1244         }
1245
1246         if (isatty(fileno(stdin)) && fromstdin==1 && force==0)
1247                 fatalError( "data not read from terminal. Use -f to force it.\n");
1248         if (isatty(fileno(stdout)) && tostdout==1 && force==0)
1249                 fatalError( "data not written to terminal. Use -f to force it.\n");
1250
1251
1252         foreground = signal(SIGINT, SIG_IGN) != SIG_IGN;
1253         if (foreground) {
1254                 (void) signal(SIGINT, (sig_type) abort_gzip);
1255         }
1256 #ifdef SIGTERM
1257         if (signal(SIGTERM, SIG_IGN) != SIG_IGN) {
1258                 (void) signal(SIGTERM, (sig_type) abort_gzip);
1259         }
1260 #endif
1261 #ifdef SIGHUP
1262         if (signal(SIGHUP, SIG_IGN) != SIG_IGN) {
1263                 (void) signal(SIGHUP, (sig_type) abort_gzip);
1264         }
1265 #endif
1266
1267         file_count = argc - optind;
1268
1269         /* Allocate all global buffers (for DYN_ALLOC option) */
1270         inbuf = xmalloc((size_t)((INBUFSIZ+INBUF_EXTRA+1L)*sizeof(uch)));
1271         outbuf = xmalloc((size_t)((OUTBUFSIZ+OUTBUF_EXTRA+1L)*sizeof(uch)));
1272         d_buf = xmalloc((size_t)((DIST_BUFSIZE+1L)*sizeof(ush)));
1273         window = xmalloc((size_t)(((2L*WSIZE)+1L)*sizeof(uch)));
1274         tab_prefix0 = xmalloc((size_t)(((1L<<(BITS-1))+1L)*sizeof(ush)));       
1275         tab_prefix1 = xmalloc((size_t)(((1L<<(BITS-1))+1L)*sizeof(ush)));       
1276
1277         if (fromstdin == 1) {
1278                 strcpy(ofname, "stdin");
1279
1280                 inFileNum = fileno(stdin);
1281                 ifile_size = -1L;               /* convention for unknown size */
1282         } else {
1283                 /* Open up the input file */
1284                 if (argc <= 0)
1285                         usage(gunzip_usage);
1286                 if (strlen(*argv) > MAX_PATH_LEN) {
1287                         errorMsg(name_too_long);
1288                         exit(WARNING);
1289                 }
1290                 strcpy(ifname, *argv);
1291
1292                 /* Open input fille */
1293                 inFileNum = open(ifname, O_RDONLY);
1294                 if (inFileNum < 0) {
1295                         perror(ifname);
1296                         exit(WARNING);
1297                 }
1298                 /* Get the time stamp on the input file. */
1299                 result = stat(ifname, &statBuf);
1300                 if (result < 0) {
1301                         perror(ifname);
1302                         exit(WARNING);
1303                 }
1304                 ifile_size = statBuf.st_size;
1305         }
1306
1307         if (tostdout == 1) {
1308                 /* And get to work */
1309                 strcpy(ofname, "stdout");
1310                 outFileNum = fileno(stdout);
1311
1312                 clear_bufs();                   /* clear input and output buffers */
1313                 part_nb = 0;
1314
1315                 /* Actually do the compression/decompression. */
1316                 unzip(inFileNum, outFileNum);
1317
1318         } else if (test_mode) {
1319                 /* Actually do the compression/decompression. */
1320                 unzip(inFileNum, 2);
1321         } else {
1322                 char *pos;
1323
1324                 /* And get to work */
1325                 if (strlen(ifname) > MAX_PATH_LEN - 4) {
1326                         errorMsg(name_too_long);
1327                         exit(WARNING);
1328                 }
1329                 strcpy(ofname, ifname);
1330                 pos = strstr(ofname, ".gz");
1331                 if (pos != NULL) {
1332                         *pos = '\0';
1333                         delInputFile = 1;
1334                 } else {
1335                         pos = strstr(ofname, ".tgz");
1336                         if (pos != NULL) {
1337                                 *pos = '\0';
1338                                 strcat(pos, ".tar");
1339                                 delInputFile = 1;
1340                         }
1341                 }
1342
1343                 /* Open output fille */
1344 #if (__GLIBC__ >= 2) && (__GLIBC_MINOR__ >= 1)
1345                 outFileNum = open(ofname, O_RDWR | O_CREAT | O_EXCL | O_NOFOLLOW);
1346 #else
1347                 outFileNum = open(ofname, O_RDWR | O_CREAT | O_EXCL);
1348 #endif
1349                 if (outFileNum < 0) {
1350                         perror(ofname);
1351                         exit(WARNING);
1352                 }
1353                 /* Set permissions on the file */
1354                 fchmod(outFileNum, statBuf.st_mode);
1355
1356                 clear_bufs();                   /* clear input and output buffers */
1357                 part_nb = 0;
1358
1359                 /* Actually do the compression/decompression. */
1360                 result = unzip(inFileNum, outFileNum);
1361
1362                 close(outFileNum);
1363                 close(inFileNum);
1364                 /* Delete the original file */
1365                 if (result == OK)
1366                         delFileName = ifname;
1367                 else
1368                         delFileName = ofname;
1369
1370                 if (delInputFile == 1 && unlink(delFileName) < 0) {
1371                         perror(delFileName);
1372                         exit(FALSE);
1373                 }
1374         }
1375         return(exit_code);
1376 }