b29bdf7c124d69878fab4eea3dd31e3aae426520
[oweals/busybox.git] / archival / gunzip.c
1 /* vi: set sw=4 ts=4: */
2 /*
3  * Gzip implementation for busybox
4  *
5  * Based on GNU gzip 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
30 #include "internal.h"
31 #include <getopt.h>
32
33 /* These defines are very important for BusyBox.  Without these,
34  * huge chunks of ram are pre-allocated making the BusyBox bss 
35  * size Freaking Huge(tm), which is a bad thing.*/
36 #define SMALL_MEM
37 #define DYN_ALLOC
38
39 #define BB_DECLARE_EXTERN
40 #define bb_need_memory_exhausted
41 #define bb_need_name_too_long
42 #include "messages.c"
43
44
45 /* gzip (GNU zip) -- compress files with zip algorithm and 'compress' interface
46  * Copyright (C) 1992-1993 Jean-loup Gailly
47  * The unzip code was written and put in the public domain by Mark Adler.
48  * Portions of the lzw code are derived from the public domain 'compress'
49  * written by Spencer Thomas, Joe Orost, James Woods, Jim McKie, Steve Davies,
50  * Ken Turkowski, Dave Mack and Peter Jannesen.
51  *
52  * See the license_msg below and the file COPYING for the software license.
53  * See the file algorithm.doc for the compression algorithms and file formats.
54  */
55
56 #if 0
57 static char *license_msg[] = {
58         "   Copyright (C) 1992-1993 Jean-loup Gailly",
59         "   This program is free software; you can redistribute it and/or modify",
60         "   it under the terms of the GNU General Public License as published by",
61         "   the Free Software Foundation; either version 2, or (at your option)",
62         "   any later version.",
63         "",
64         "   This program is distributed in the hope that it will be useful,",
65         "   but WITHOUT ANY WARRANTY; without even the implied warranty of",
66         "   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the",
67         "   GNU General Public License for more details.",
68         "",
69         "   You should have received a copy of the GNU General Public License",
70         "   along with this program; if not, write to the Free Software",
71         "   Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.",
72         0
73 };
74 #endif
75
76 /* Compress files with zip algorithm and 'compress' interface.
77  * See usage() and help() functions below for all options.
78  * Outputs:
79  *        file.gz:   compressed file with same mode, owner, and utimes
80  *     or stdout with -c option or if stdin used as input.
81  * If the output file name had to be truncated, the original name is kept
82  * in the compressed file.
83  * On MSDOS, file.tmp -> file.tmz. On VMS, file.tmp -> file.tmp-gz.
84  *
85  * Using gz on MSDOS would create too many file name conflicts. For
86  * example, foo.txt -> foo.tgz (.tgz must be reserved as shorthand for
87  * tar.gz). Similarly, foo.dir and foo.doc would both be mapped to foo.dgz.
88  * I also considered 12345678.txt -> 12345txt.gz but this truncates the name
89  * too heavily. There is no ideal solution given the MSDOS 8+3 limitation. 
90  *
91  * For the meaning of all compilation flags, see comments in Makefile.in.
92  */
93
94 #include <ctype.h>
95 #include <sys/types.h>
96 #include <signal.h>
97 #include <sys/stat.h>
98 #include <errno.h>
99
100 /* #include "tailor.h" */
101
102 /* tailor.h -- target dependent definitions
103  * Copyright (C) 1992-1993 Jean-loup Gailly.
104  * This is free software; you can redistribute it and/or modify it under the
105  * terms of the GNU General Public License, see the file COPYING.
106  */
107
108 /* The target dependent definitions should be defined here only.
109  * The target dependent functions should be defined in tailor.c.
110  */
111
112 #define RECORD_IO 0
113
114 #define get_char() get_byte()
115 #define put_char(c) put_byte(c)
116
117
118 /* I don't like nested includes, but the string and io functions are used
119  * too often
120  */
121 #include <stdio.h>
122 #if !defined(NO_STRING_H) || defined(STDC_HEADERS)
123 #  include <string.h>
124 #  if !defined(STDC_HEADERS) && !defined(NO_MEMORY_H) && !defined(__GNUC__)
125 #    include <memory.h>
126 #  endif
127 #  define memzero(s, n)     memset ((void *)(s), 0, (n))
128 #else
129 #  include <strings.h>
130 #  define strchr            index
131 #  define strrchr           rindex
132 #  define memcpy(d, s, n)   bcopy((s), (d), (n))
133 #  define memcmp(s1, s2, n) bcmp((s1), (s2), (n))
134 #  define memzero(s, n)     bzero((s), (n))
135 #endif
136
137 #ifndef RETSIGTYPE
138 #  define RETSIGTYPE void
139 #endif
140
141 #define local static
142
143 typedef unsigned char uch;
144 typedef unsigned short ush;
145 typedef unsigned long ulg;
146
147 /* Return codes from gzip */
148 #define OK      0
149 #define ERROR   1
150 #define WARNING 2
151
152 /* Compression methods (see algorithm.doc) */
153 #define DEFLATED    8
154
155 extern int method;                              /* compression method */
156
157 /* To save memory for 16 bit systems, some arrays are overlaid between
158  * the various modules:
159  * deflate:  prev+head   window      d_buf  l_buf  outbuf
160  * unlzw:    tab_prefix  tab_suffix  stack  inbuf  outbuf
161  * inflate:              window             inbuf
162  * unpack:               window             inbuf  prefix_len
163  * unlzh:    left+right  window      c_table inbuf c_len
164  * For compression, input is done in window[]. For decompression, output
165  * is done in window except for unlzw.
166  */
167
168 #ifndef INBUFSIZ
169 #  ifdef SMALL_MEM
170 #    define INBUFSIZ  0x2000    /* input buffer size */
171 #  else
172 #    define INBUFSIZ  0x8000    /* input buffer size */
173 #  endif
174 #endif
175 #define INBUF_EXTRA  64                 /* required by unlzw() */
176
177 #ifndef OUTBUFSIZ
178 #  ifdef SMALL_MEM
179 #    define OUTBUFSIZ   8192    /* output buffer size */
180 #  else
181 #    define OUTBUFSIZ  16384    /* output buffer size */
182 #  endif
183 #endif
184 #define OUTBUF_EXTRA 2048               /* required by unlzw() */
185
186 #define SMALL_MEM
187
188 #ifndef DIST_BUFSIZE
189 #  ifdef SMALL_MEM
190 #    define DIST_BUFSIZE 0x2000 /* buffer for distances, see trees.c */
191 #  else
192 #    define DIST_BUFSIZE 0x8000 /* buffer for distances, see trees.c */
193 #  endif
194 #endif
195
196 /*#define DYN_ALLOC*/
197
198 #ifdef DYN_ALLOC
199 #  define EXTERN(type, array)  extern type * array
200 #  define DECLARE(type, array, size)  type * array
201 #  define ALLOC(type, array, size) { \
202       array = (type*)calloc((size_t)(((size)+1L)/2), 2*sizeof(type)); \
203       if (array == NULL) errorMsg(memory_exhausted); \
204    }
205 #  define FREE(array) {if (array != NULL) free(array), array=NULL;}
206 #else
207 #  define EXTERN(type, array)  extern type array[]
208 #  define DECLARE(type, array, size)  type array[size]
209 #  define ALLOC(type, array, size)
210 #  define FREE(array)
211 #endif
212
213 EXTERN(uch, inbuf);                             /* input buffer */
214 EXTERN(uch, outbuf);                    /* output buffer */
215 EXTERN(ush, d_buf);                             /* buffer for distances, see trees.c */
216 EXTERN(uch, window);                    /* Sliding window and suffix table (unlzw) */
217 #define tab_suffix window
218 #ifndef MAXSEG_64K
219 #  define tab_prefix prev               /* hash link (see deflate.c) */
220 #  define head (prev+WSIZE)             /* hash head (see deflate.c) */
221 EXTERN(ush, tab_prefix);                /* prefix code (see unlzw.c) */
222 #else
223 #  define tab_prefix0 prev
224 #  define head tab_prefix1
225 EXTERN(ush, tab_prefix0);               /* prefix for even codes */
226 EXTERN(ush, tab_prefix1);               /* prefix for odd  codes */
227 #endif
228
229 extern unsigned insize;                 /* valid bytes in inbuf */
230 extern unsigned inptr;                  /* index of next byte to be processed in inbuf */
231 extern unsigned outcnt;                 /* bytes in output buffer */
232
233 extern long bytes_in;                   /* number of input bytes */
234 extern long bytes_out;                  /* number of output bytes */
235 extern long header_bytes;               /* number of bytes in gzip header */
236
237 extern long ifile_size;                 /* input file size, -1 for devices (debug only) */
238
239 typedef int file_t;                             /* Do not use stdio */
240
241 #define NO_FILE  (-1)                   /* in memory compression */
242
243
244 #define GZIP_MAGIC     "\037\213"       /* Magic header for gzip files, 1F 8B */
245
246 /* gzip flag byte */
247 #define ASCII_FLAG   0x01               /* bit 0 set: file probably ascii text */
248 #define CONTINUATION 0x02               /* bit 1 set: continuation of multi-part gzip file */
249 #define EXTRA_FIELD  0x04               /* bit 2 set: extra field present */
250 #define ORIG_NAME    0x08               /* bit 3 set: original file name present */
251 #define COMMENT      0x10               /* bit 4 set: file comment present */
252 #define ENCRYPTED    0x20               /* bit 5 set: file is encrypted */
253 #define RESERVED     0xC0               /* bit 6,7:   reserved */
254
255 #ifndef WSIZE
256 #  define WSIZE 0x8000                  /* window size--must be a power of two, and */
257 #endif                                                  /*  at least 32K for zip's deflate method */
258
259 #define MIN_MATCH  3
260 #define MAX_MATCH  258
261 /* The minimum and maximum match lengths */
262
263 #define MIN_LOOKAHEAD (MAX_MATCH+MIN_MATCH+1)
264 /* Minimum amount of lookahead, except at the end of the input file.
265  * See deflate.c for comments about the MIN_MATCH+1.
266  */
267
268 #define MAX_DIST  (WSIZE-MIN_LOOKAHEAD)
269 /* In order to simplify the code, particularly on 16 bit machines, match
270  * distances are limited to MAX_DIST instead of WSIZE.
271  */
272
273 extern int exit_code;                   /* program exit code */
274 extern int verbose;                             /* be verbose (-v) */
275 extern int level;                               /* compression level */
276 extern int test;                                /* check .z file integrity */
277 extern int save_orig_name;              /* set if original name must be saved */
278
279 #define get_byte()  (inptr < insize ? inbuf[inptr++] : fill_inbuf(0))
280 #define try_byte()  (inptr < insize ? inbuf[inptr++] : fill_inbuf(1))
281
282 /* put_byte is used for the compressed output, put_ubyte for the
283  * uncompressed output. However unlzw() uses window for its
284  * suffix table instead of its output buffer, so it does not use put_ubyte
285  * (to be cleaned up).
286  */
287 #define put_byte(c) {outbuf[outcnt++]=(uch)(c); if (outcnt==OUTBUFSIZ)\
288    flush_outbuf();}
289 #define put_ubyte(c) {window[outcnt++]=(uch)(c); if (outcnt==WSIZE)\
290    flush_window();}
291
292 /* Output a 16 bit value, lsb first */
293 #define put_short(w) \
294 { if (outcnt < OUTBUFSIZ-2) { \
295     outbuf[outcnt++] = (uch) ((w) & 0xff); \
296     outbuf[outcnt++] = (uch) ((ush)(w) >> 8); \
297   } else { \
298     put_byte((uch)((w) & 0xff)); \
299     put_byte((uch)((ush)(w) >> 8)); \
300   } \
301 }
302
303 /* Output a 32 bit value to the bit stream, lsb first */
304 #define put_long(n) { \
305     put_short((n) & 0xffff); \
306     put_short(((ulg)(n)) >> 16); \
307 }
308
309 #define seekable()    0                 /* force sequential output */
310 #define translate_eol 0                 /* no option -a yet */
311
312 #define tolow(c)  (isupper(c) ? (c)-'A'+'a' : (c))      /* force to lower case */
313
314 /* Macros for getting two-byte and four-byte header values */
315 #define SH(p) ((ush)(uch)((p)[0]) | ((ush)(uch)((p)[1]) << 8))
316 #define LG(p) ((ulg)(SH(p)) | ((ulg)(SH((p)+2)) << 16))
317
318 /* Diagnostic functions */
319 #ifdef DEBUG
320 #  define Assert(cond,msg) {if(!(cond)) errorMsg(msg);}
321 #  define Trace(x) fprintf x
322 #  define Tracev(x) {if (verbose) fprintf x ;}
323 #  define Tracevv(x) {if (verbose>1) fprintf x ;}
324 #  define Tracec(c,x) {if (verbose && (c)) fprintf x ;}
325 #  define Tracecv(c,x) {if (verbose>1 && (c)) fprintf x ;}
326 #else
327 #  define Assert(cond,msg)
328 #  define Trace(x)
329 #  define Tracev(x)
330 #  define Tracevv(x)
331 #  define Tracec(c,x)
332 #  define Tracecv(c,x)
333 #endif
334
335 #define WARN(msg) {fprintf msg ; \
336                    if (exit_code == OK) exit_code = WARNING;}
337
338         /* in unzip.c */
339 extern int unzip (int in, int out);
340
341         /* in gzip.c */
342 RETSIGTYPE abort_gzip (void);
343
344                 /* in deflate.c */
345 void lm_init (int pack_level, ush * flags);
346 ulg deflate (void);
347
348                 /* in trees.c */
349 void ct_init (ush * attr, int *method);
350 int ct_tally (int dist, int lc);
351 ulg flush_block (char *buf, ulg stored_len, int eof);
352
353                 /* in bits.c */
354 void bi_init (file_t zipfile);
355 void send_bits (int value, int length);
356 unsigned bi_reverse (unsigned value, int length);
357 void bi_windup (void);
358 void copy_block (char *buf, unsigned len, int header);
359
360         /* in util.c: */
361 extern ulg updcrc (uch * s, unsigned n);
362 extern void clear_bufs (void);
363 static int fill_inbuf (int eof_ok);
364 extern void flush_outbuf (void);
365 static void flush_window (void);
366 extern void write_buf (int fd, void * buf, unsigned cnt);
367
368 #ifndef __linux__
369 static char *basename (char *fname);
370 #endif                                                  /* not __linux__ */
371 void read_error_msg (void);
372 void write_error_msg (void);
373
374         /* in inflate.c */
375 static int inflate (void);
376
377 /* #include "lzw.h" */
378
379 /* lzw.h -- define the lzw functions.
380  * Copyright (C) 1992-1993 Jean-loup Gailly.
381  * This is free software; you can redistribute it and/or modify it under the
382  * terms of the GNU General Public License, see the file COPYING.
383  */
384
385 #if !defined(OF) && defined(lint)
386 #  include "gzip.h"
387 #endif
388
389 #ifndef BITS
390 #  define BITS 16
391 #endif
392 #define INIT_BITS 9                             /* Initial number of bits per code */
393
394 #define LZW_MAGIC  "\037\235"   /* Magic header for lzw files, 1F 9D */
395
396 #define BIT_MASK    0x1f                /* Mask for 'number of compression bits' */
397 /* Mask 0x20 is reserved to mean a fourth header byte, and 0x40 is free.
398  * It's a pity that old uncompress does not check bit 0x20. That makes
399  * extension of the format actually undesirable because old compress
400  * would just crash on the new format instead of giving a meaningful
401  * error message. It does check the number of bits, but it's more
402  * helpful to say "unsupported format, get a new version" than
403  * "can only handle 16 bits".
404  */
405
406 #define BLOCK_MODE  0x80
407 /* Block compression: if table is full and compression rate is dropping,
408  * clear the dictionary.
409  */
410
411 #define LZW_RESERVED 0x60               /* reserved bits */
412
413 #define CLEAR  256                              /* flush the dictionary */
414 #define FIRST  (CLEAR+1)                /* first free entry */
415
416 extern int maxbits;                             /* max bits per code for LZW */
417 extern int block_mode;                  /* block compress mode -C compatible with 2.0 */
418
419 extern int lzw (int in, int out);
420 extern int unlzw (int in, int out);
421
422
423 /* #include "revision.h" */
424
425 /* revision.h -- define the version number
426  * Copyright (C) 1992-1993 Jean-loup Gailly.
427  * This is free software; you can redistribute it and/or modify it under the
428  * terms of the GNU General Public License, see the file COPYING.
429  */
430
431 #define VERSION "1.2.4"
432 #define PATCHLEVEL 0
433 #define REVDATE "18 Aug 93"
434
435 /* This version does not support compression into old compress format: */
436 #ifdef LZW
437 #  undef LZW
438 #endif
439
440 #include <time.h>
441 #include <fcntl.h>
442 #include <unistd.h>
443 #include <stdlib.h>
444 #if defined(DIRENT)
445 #  include <dirent.h>
446 typedef struct dirent dir_type;
447
448 #  define NLENGTH(dirent) ((int)strlen((dirent)->d_name))
449 #  define DIR_OPT "DIRENT"
450 #else
451 #  define NLENGTH(dirent) ((dirent)->d_namlen)
452 #  ifdef SYSDIR
453 #    include <sys/dir.h>
454 typedef struct direct dir_type;
455
456 #    define DIR_OPT "SYSDIR"
457 #  else
458 #    ifdef SYSNDIR
459 #      include <sys/ndir.h>
460 typedef struct direct dir_type;
461
462 #      define DIR_OPT "SYSNDIR"
463 #    else
464 #      ifdef NDIR
465 #        include <ndir.h>
466 typedef struct direct dir_type;
467
468 #        define DIR_OPT "NDIR"
469 #      else
470 #        define NO_DIR
471 #        define DIR_OPT "NO_DIR"
472 #      endif
473 #    endif
474 #  endif
475 #endif
476 #if !defined(S_ISDIR) && defined(S_IFDIR)
477 #  define S_ISDIR(m) (((m) & S_IFMT) == S_IFDIR)
478 #endif
479 #if !defined(S_ISREG) && defined(S_IFREG)
480 #  define S_ISREG(m) (((m) & S_IFMT) == S_IFREG)
481 #endif
482 typedef RETSIGTYPE(*sig_type) (int);
483
484 #ifndef O_BINARY
485 #  define  O_BINARY  0                  /* creation mode for open() */
486 #endif
487
488 #ifndef O_CREAT
489    /* Pure BSD system? */
490 #  include <sys/file.h>
491 #  ifndef O_CREAT
492 #    define O_CREAT FCREAT
493 #  endif
494 #  ifndef O_EXCL
495 #    define O_EXCL FEXCL
496 #  endif
497 #endif
498
499 #ifndef S_IRUSR
500 #  define S_IRUSR 0400
501 #endif
502 #ifndef S_IWUSR
503 #  define S_IWUSR 0200
504 #endif
505 #define RW_USER (S_IRUSR | S_IWUSR)     /* creation mode for open() */
506
507 #ifndef MAX_PATH_LEN                    /* max pathname length */
508 #  ifdef BUFSIZ
509 #    define MAX_PATH_LEN   BUFSIZ
510 #  else
511 #    define MAX_PATH_LEN   1024
512 #  endif
513 #endif
514
515 #ifndef SEEK_END
516 #  define SEEK_END 2
517 #endif
518
519 #ifdef NO_OFF_T
520 typedef long off_t;
521 off_t lseek (int fd, off_t offset, int whence);
522 #endif
523
524
525                 /* global buffers */
526
527 DECLARE(uch, inbuf, INBUFSIZ + INBUF_EXTRA);
528 DECLARE(uch, outbuf, OUTBUFSIZ + OUTBUF_EXTRA);
529 DECLARE(ush, d_buf, DIST_BUFSIZE);
530 DECLARE(uch, window, 2L * WSIZE);
531 #ifndef MAXSEG_64K
532 DECLARE(ush, tab_prefix, 1L << BITS);
533 #else
534 DECLARE(ush, tab_prefix0, 1L << (BITS - 1));
535 DECLARE(ush, tab_prefix1, 1L << (BITS - 1));
536 #endif
537
538                 /* local variables */
539
540 int test_mode = 0;                              /* check file integrity option */
541 int foreground;                                 /* set if program run in foreground */
542 int maxbits = BITS;                             /* max bits per code for LZW */
543 int method = DEFLATED;                  /* compression method */
544 int exit_code = OK;                             /* program exit code */
545 int last_member;                                /* set for .zip and .Z files */
546 int part_nb;                                    /* number of parts in .gz file */
547 long ifile_size;                                /* input file size, -1 for devices (debug only) */
548
549 long bytes_in;                                  /* number of input bytes */
550 long bytes_out;                                 /* number of output bytes */
551 long total_in = 0;                              /* input bytes for all files */
552 long total_out = 0;                             /* output bytes for all files */
553 struct stat istat;                              /* status for input file */
554 int ifd;                                                /* input file descriptor */
555 int ofd;                                                /* output file descriptor */
556 unsigned insize;                                /* valid bytes in inbuf */
557 unsigned inptr;                                 /* index of next byte to be processed in inbuf */
558 unsigned outcnt;                                /* bytes in output buffer */
559
560 long header_bytes;                              /* number of bytes in gzip header */
561
562 /* local functions */
563
564 local int get_method (int in);
565
566 #define strequ(s1, s2) (strcmp((s1),(s2)) == 0)
567
568 /* ======================================================================== */
569 int gunzip_main(int argc, char **argv)
570 {
571         int file_count;                         /* number of files to precess */
572         int to_stdout = 0;
573         int fromstdin = 0;
574         int result;
575         int inFileNum;
576         int outFileNum;
577         int delInputFile = 0;
578         struct stat statBuf;
579         char *delFileName;
580         char ifname[MAX_PATH_LEN + 1];  /* input file name */
581         char ofname[MAX_PATH_LEN + 1];  /* output file name */
582
583         if (strcmp(applet_name, "zcat") == 0) {
584                 to_stdout = 1;
585                 if (argc == 1) {
586                         fromstdin = 1;
587                 }
588         }
589
590         /* Parse any options */
591         while (--argc > 0 && **(++argv) == '-') {
592                 if (*((*argv) + 1) == '\0') {
593                         fromstdin = 1;
594                         to_stdout = 1;
595                 }
596                 while (*(++(*argv))) {
597                         switch (**argv) {
598                         case 'c':
599                                 to_stdout = 1;
600                                 break;
601                         case 't':
602                                 test_mode = 1;
603                                 break;
604
605                         default:
606                                 usage(gunzip_usage);
607                         }
608                 }
609         }
610
611         foreground = signal(SIGINT, SIG_IGN) != SIG_IGN;
612         if (foreground) {
613                 (void) signal(SIGINT, (sig_type) abort_gzip);
614         }
615 #ifdef SIGTERM
616         if (signal(SIGTERM, SIG_IGN) != SIG_IGN) {
617                 (void) signal(SIGTERM, (sig_type) abort_gzip);
618         }
619 #endif
620 #ifdef SIGHUP
621         if (signal(SIGHUP, SIG_IGN) != SIG_IGN) {
622                 (void) signal(SIGHUP, (sig_type) abort_gzip);
623         }
624 #endif
625
626         file_count = argc - optind;
627
628         /* Allocate all global buffers (for DYN_ALLOC option) */
629         ALLOC(uch, inbuf, INBUFSIZ + INBUF_EXTRA);
630         ALLOC(uch, outbuf, OUTBUFSIZ + OUTBUF_EXTRA);
631         ALLOC(ush, d_buf, DIST_BUFSIZE);
632         ALLOC(uch, window, 2L * WSIZE);
633 #ifndef MAXSEG_64K
634         ALLOC(ush, tab_prefix, 1L << BITS);
635 #else
636         ALLOC(ush, tab_prefix0, 1L << (BITS - 1));
637         ALLOC(ush, tab_prefix1, 1L << (BITS - 1));
638 #endif
639
640         if (fromstdin == 1) {
641                 strcpy(ofname, "stdin");
642
643                 inFileNum = fileno(stdin);
644                 ifile_size = -1L;               /* convention for unknown size */
645         } else {
646                 /* Open up the input file */
647                 if (*argv == '\0')
648                         usage(gunzip_usage);
649                 if (strlen(*argv) > MAX_PATH_LEN) {
650                         errorMsg(name_too_long);
651                         exit(WARNING);
652                 }
653                 strcpy(ifname, *argv);
654
655                 /* Open input fille */
656                 inFileNum = open(ifname, O_RDONLY);
657                 if (inFileNum < 0) {
658                         perror(ifname);
659                         exit(WARNING);
660                 }
661                 /* Get the time stamp on the input file. */
662                 result = stat(ifname, &statBuf);
663                 if (result < 0) {
664                         perror(ifname);
665                         exit(WARNING);
666                 }
667                 ifile_size = statBuf.st_size;
668         }
669
670         if (to_stdout == 1) {
671                 /* And get to work */
672                 strcpy(ofname, "stdout");
673                 outFileNum = fileno(stdout);
674
675                 clear_bufs();                   /* clear input and output buffers */
676                 part_nb = 0;
677
678                 /* Actually do the compression/decompression. */
679                 unzip(inFileNum, outFileNum);
680
681         } else if (test_mode) {
682                 /* Actually do the compression/decompression. */
683                 unzip(inFileNum, 2);
684         } else {
685                 char *pos;
686
687                 /* And get to work */
688                 if (strlen(ifname) > MAX_PATH_LEN - 4) {
689                         errorMsg(name_too_long);
690                         exit(WARNING);
691                 }
692                 strcpy(ofname, ifname);
693                 pos = strstr(ofname, ".gz");
694                 if (pos != NULL) {
695                         *pos = '\0';
696                         delInputFile = 1;
697                 } else {
698                         pos = strstr(ofname, ".tgz");
699                         if (pos != NULL) {
700                                 *pos = '\0';
701                                 strcat(pos, ".tar");
702                                 delInputFile = 1;
703                         }
704                 }
705
706                 /* Open output fille */
707 #if (__GLIBC__ >= 2) && (__GLIBC_MINOR__ >= 1)
708                 outFileNum = open(ofname, O_RDWR | O_CREAT | O_EXCL | O_NOFOLLOW);
709 #else
710                 outFileNum = open(ofname, O_RDWR | O_CREAT | O_EXCL);
711 #endif
712                 if (outFileNum < 0) {
713                         perror(ofname);
714                         exit(WARNING);
715                 }
716                 /* Set permissions on the file */
717                 fchmod(outFileNum, statBuf.st_mode);
718
719                 clear_bufs();                   /* clear input and output buffers */
720                 part_nb = 0;
721
722                 /* Actually do the compression/decompression. */
723                 result = unzip(inFileNum, outFileNum);
724
725                 close(outFileNum);
726                 close(inFileNum);
727                 /* Delete the original file */
728                 if (result == OK)
729                         delFileName = ifname;
730                 else
731                         delFileName = ofname;
732
733                 if (delInputFile == 1 && unlink(delFileName) < 0) {
734                         perror(delFileName);
735                         exit(FALSE);
736                 }
737         }
738         return(exit_code);
739 }
740
741
742 /* ========================================================================
743  * Check the magic number of the input file and update ofname if an
744  * original name was given and to_stdout is not set.
745  * Return the compression method, -1 for error, -2 for warning.
746  * Set inptr to the offset of the next byte to be processed.
747  * Updates time_stamp if there is one and --no-time is not used.
748  * This function may be called repeatedly for an input file consisting
749  * of several contiguous gzip'ed members.
750  * IN assertions: there is at least one remaining compressed member.
751  *   If the member is a zip file, it must be the only one.
752  */
753 local int get_method(in)
754 int in;                                                 /* input file descriptor */
755 {
756         uch flags;                                      /* compression flags */
757         char magic[2];                          /* magic header */
758
759         magic[0] = (char) get_byte();
760         magic[1] = (char) get_byte();
761         method = -1;                            /* unknown yet */
762         part_nb++;                                      /* number of parts in gzip file */
763         header_bytes = 0;
764         last_member = RECORD_IO;
765         /* assume multiple members in gzip file except for record oriented I/O */
766
767         if (memcmp(magic, GZIP_MAGIC, 2) == 0) {
768
769                 method = (int) get_byte();
770                 if (method != DEFLATED) {
771                         errorMsg("unknown method %d -- get newer version of gzip\n",
772                                         method);
773                         exit_code = ERROR;
774                         return -1;
775                 }
776                 flags = (uch) get_byte();
777
778                 (ulg) get_byte();               /* Ignore time stamp */
779                 (ulg) get_byte();
780                 (ulg) get_byte();
781                 (ulg) get_byte();
782
783                 (void) get_byte();              /* Ignore extra flags for the moment */
784                 (void) get_byte();              /* Ignore OS type for the moment */
785
786                 if ((flags & EXTRA_FIELD) != 0) {
787                         unsigned len = (unsigned) get_byte();
788
789                         len |= ((unsigned) get_byte()) << 8;
790
791                         while (len--)
792                                 (void) get_byte();
793                 }
794
795                 /* Discard original name if any */
796                 if ((flags & ORIG_NAME) != 0) {
797                         while (get_char() != 0) /* null */
798                                 ;
799                 }
800
801                 /* Discard file comment if any */
802                 if ((flags & COMMENT) != 0) {
803                         while (get_char() != 0) /* null */
804                                 ;
805                 }
806                 if (part_nb == 1) {
807                         header_bytes = inptr + 2 * sizeof(long);        /* include crc and size */
808                 }
809
810         }
811
812         if (method >= 0)
813                 return method;
814
815         if (part_nb == 1) {
816                 fprintf(stderr, "\nnot in gzip format\n");
817                 exit_code = ERROR;
818                 return -1;
819         } else {
820                 WARN((stderr, "\ndecompression OK, trailing garbage ignored\n"));
821                 return -2;
822         }
823 }
824
825 /* ========================================================================
826  * Signal and error handler.
827  */
828 RETSIGTYPE abort_gzip()
829 {
830         exit(ERROR);
831 }
832
833 /* unzip.c -- decompress files in gzip or pkzip format.
834  * Copyright (C) 1992-1993 Jean-loup Gailly
835  * This is free software; you can redistribute it and/or modify it under the
836  * terms of the GNU General Public License, see the file COPYING.
837  *
838  * The code in this file is derived from the file funzip.c written
839  * and put in the public domain by Mark Adler.
840  */
841
842 /*
843    This version can extract files in gzip or pkzip format.
844    For the latter, only the first entry is extracted, and it has to be
845    either deflated or stored.
846  */
847
848 /* #include "crypt.h" */
849
850 /* crypt.h (dummy version) -- do not perform encryption
851  * Hardly worth copyrighting :-)
852  */
853
854 #ifdef CRYPT
855 #  undef CRYPT                                  /* dummy version */
856 #endif
857
858 #define RAND_HEAD_LEN  12               /* length of encryption random header */
859
860 #define zencode
861 #define zdecode
862
863 /* PKZIP header definitions */
864 #define LOCSIG 0x04034b50L              /* four-byte lead-in (lsb first) */
865 #define LOCFLG 6                                /* offset of bit flag */
866 #define  CRPFLG 1                               /*  bit for encrypted entry */
867 #define  EXTFLG 8                               /*  bit for extended local header */
868 #define LOCHOW 8                                /* offset of compression method */
869 #define LOCTIM 10                               /* file mod time (for decryption) */
870 #define LOCCRC 14                               /* offset of crc */
871 #define LOCSIZ 18                               /* offset of compressed size */
872 #define LOCLEN 22                               /* offset of uncompressed length */
873 #define LOCFIL 26                               /* offset of file name field length */
874 #define LOCEXT 28                               /* offset of extra field length */
875 #define LOCHDR 30                               /* size of local header, including sig */
876 #define EXTHDR 16                               /* size of extended local header, inc sig */
877
878
879 /* Globals */
880
881 char *key;                                              /* not used--needed to link crypt.c */
882 int pkzip = 0;                                  /* set for a pkzip file */
883 int ext_header = 0;                             /* set if extended local header */
884
885 /* ===========================================================================
886  * Unzip in to out.  This routine works on both gzip and pkzip files.
887  *
888  * IN assertions: the buffer inbuf contains already the beginning of
889  *   the compressed data, from offsets inptr to insize-1 included.
890  *   The magic header has already been checked. The output buffer is cleared.
891  */
892 int unzip(in, out)
893 int in, out;                                    /* input and output file descriptors */
894 {
895         ulg orig_crc = 0;                       /* original crc */
896         ulg orig_len = 0;                       /* original uncompressed length */
897         int n;
898         uch buf[EXTHDR];                        /* extended local header */
899
900         ifd = in;
901         ofd = out;
902         method = get_method(ifd);
903         if (method < 0) {
904                 exit(exit_code);                /* error message already emitted */
905         }
906
907         updcrc(NULL, 0);                        /* initialize crc */
908
909         if (pkzip && !ext_header) {     /* crc and length at the end otherwise */
910                 orig_crc = LG(inbuf + LOCCRC);
911                 orig_len = LG(inbuf + LOCLEN);
912         }
913
914         /* Decompress */
915         if (method == DEFLATED) {
916
917                 int res = inflate();
918
919                 if (res == 3) {
920                         errorMsg(memory_exhausted);
921                 } else if (res != 0) {
922                         errorMsg("invalid compressed data--format violated");
923                 }
924
925         } else {
926                 errorMsg("internal error, invalid method");
927         }
928
929         /* Get the crc and original length */
930         if (!pkzip) {
931                 /* crc32  (see algorithm.doc)
932                    * uncompressed input size modulo 2^32
933                  */
934                 for (n = 0; n < 8; n++) {
935                         buf[n] = (uch) get_byte();      /* may cause an error if EOF */
936                 }
937                 orig_crc = LG(buf);
938                 orig_len = LG(buf + 4);
939
940         } else if (ext_header) {        /* If extended header, check it */
941                 /* signature - 4bytes: 0x50 0x4b 0x07 0x08
942                  * CRC-32 value
943                  * compressed size 4-bytes
944                  * uncompressed size 4-bytes
945                  */
946                 for (n = 0; n < EXTHDR; n++) {
947                         buf[n] = (uch) get_byte();      /* may cause an error if EOF */
948                 }
949                 orig_crc = LG(buf + 4);
950                 orig_len = LG(buf + 12);
951         }
952
953         /* Validate decompression */
954         if (orig_crc != updcrc(outbuf, 0)) {
955                 errorMsg("invalid compressed data--crc error");
956         }
957         if (orig_len != (ulg) bytes_out) {
958                 errorMsg("invalid compressed data--length error");
959         }
960
961         /* Check if there are more entries in a pkzip file */
962         if (pkzip && inptr + 4 < insize && LG(inbuf + inptr) == LOCSIG) {
963                 WARN((stderr, "has more than one entry--rest ignored\n"));
964         }
965         ext_header = pkzip = 0;         /* for next file */
966         return OK;
967 }
968
969 /* util.c -- utility functions for gzip support
970  * Copyright (C) 1992-1993 Jean-loup Gailly
971  * This is free software; you can redistribute it and/or modify it under the
972  * terms of the GNU General Public License, see the file COPYING.
973  */
974
975 #include <ctype.h>
976 #include <errno.h>
977 #include <sys/types.h>
978
979 #ifdef HAVE_UNISTD_H
980 #  include <unistd.h>
981 #endif
982 #ifndef NO_FCNTL_H
983 #  include <fcntl.h>
984 #endif
985
986 #if defined(STDC_HEADERS) || !defined(NO_STDLIB_H)
987 #  include <stdlib.h>
988 #else
989 extern int errno;
990 #endif
991
992 static const ulg crc_32_tab[];  /* crc table, defined below */
993
994 /* ===========================================================================
995  * Run a set of bytes through the crc shift register.  If s is a NULL
996  * pointer, then initialize the crc shift register contents instead.
997  * Return the current crc in either case.
998  */
999 ulg updcrc(s, n)
1000 uch *s;                                                 /* pointer to bytes to pump through */
1001 unsigned n;                                             /* number of bytes in s[] */
1002 {
1003         register ulg c;                         /* temporary variable */
1004
1005         static ulg crc = (ulg) 0xffffffffL;     /* shift register contents */
1006
1007         if (s == NULL) {
1008                 c = 0xffffffffL;
1009         } else {
1010                 c = crc;
1011                 if (n)
1012                         do {
1013                                 c = crc_32_tab[((int) c ^ (*s++)) & 0xff] ^ (c >> 8);
1014                         } while (--n);
1015         }
1016         crc = c;
1017         return c ^ 0xffffffffL;         /* (instead of ~c for 64-bit machines) */
1018 }
1019
1020 /* ===========================================================================
1021  * Clear input and output buffers
1022  */
1023 void clear_bufs(void)
1024 {
1025         outcnt = 0;
1026         insize = inptr = 0;
1027         bytes_in = bytes_out = 0L;
1028 }
1029
1030 /* ===========================================================================
1031  * Fill the input buffer. This is called only when the buffer is empty.
1032  */
1033 int fill_inbuf(eof_ok)
1034 int eof_ok;                                             /* set if EOF acceptable as a result */
1035 {
1036         int len;
1037
1038         /* Read as much as possible */
1039         insize = 0;
1040         errno = 0;
1041         do {
1042                 len = read(ifd, (char *) inbuf + insize, INBUFSIZ - insize);
1043                 if (len == 0 || len == EOF)
1044                         break;
1045                 insize += len;
1046         } while (insize < INBUFSIZ);
1047
1048         if (insize == 0) {
1049                 if (eof_ok)
1050                         return EOF;
1051                 read_error_msg();
1052         }
1053         bytes_in += (ulg) insize;
1054         inptr = 1;
1055         return inbuf[0];
1056 }
1057
1058 /* ===========================================================================
1059  * Write the output buffer outbuf[0..outcnt-1] and update bytes_out.
1060  * (used for the compressed data only)
1061  */
1062 void flush_outbuf()
1063 {
1064         if (outcnt == 0)
1065                 return;
1066
1067         if (!test_mode)
1068                 write_buf(ofd, (char *) outbuf, outcnt);
1069         bytes_out += (ulg) outcnt;
1070         outcnt = 0;
1071 }
1072
1073 /* ===========================================================================
1074  * Write the output window window[0..outcnt-1] and update crc and bytes_out.
1075  * (Used for the decompressed data only.)
1076  */
1077 void flush_window()
1078 {
1079         if (outcnt == 0)
1080                 return;
1081         updcrc(window, outcnt);
1082
1083         if (!test_mode)
1084                 write_buf(ofd, (char *) window, outcnt);
1085         bytes_out += (ulg) outcnt;
1086         outcnt = 0;
1087 }
1088
1089 /* ===========================================================================
1090  * Does the same as write(), but also handles partial pipe writes and checks
1091  * for error return.
1092  */
1093 void write_buf(fd, buf, cnt)
1094 int fd;
1095 void * buf;
1096 unsigned cnt;
1097 {
1098         unsigned n;
1099
1100         while ((n = write(fd, buf, cnt)) != cnt) {
1101                 if (n == (unsigned) (-1)) {
1102                         write_error_msg();
1103                 }
1104                 cnt -= n;
1105                 buf = (void *) ((char *) buf + n);
1106         }
1107 }
1108
1109 #if defined(NO_STRING_H) && !defined(STDC_HEADERS)
1110
1111 /* Provide missing strspn and strcspn functions. */
1112
1113 #  ifndef __STDC__
1114 #    define const
1115 #  endif
1116
1117 int strspn (const char *s, const char *accept);
1118 int strcspn (const char *s, const char *reject);
1119
1120 /* ========================================================================
1121  * Return the length of the maximum initial segment
1122  * of s which contains only characters in accept.
1123  */
1124 int strspn(s, accept)
1125 const char *s;
1126 const char *accept;
1127 {
1128         register const char *p;
1129         register const char *a;
1130         register int count = 0;
1131
1132         for (p = s; *p != '\0'; ++p) {
1133                 for (a = accept; *a != '\0'; ++a) {
1134                         if (*p == *a)
1135                                 break;
1136                 }
1137                 if (*a == '\0')
1138                         return count;
1139                 ++count;
1140         }
1141         return count;
1142 }
1143
1144 /* ========================================================================
1145  * Return the length of the maximum inital segment of s
1146  * which contains no characters from reject.
1147  */
1148 int strcspn(s, reject)
1149 const char *s;
1150 const char *reject;
1151 {
1152         register int count = 0;
1153
1154         while (*s != '\0') {
1155                 if (strchr(reject, *s++) != NULL)
1156                         return count;
1157                 ++count;
1158         }
1159         return count;
1160 }
1161
1162 #endif                                                  /* NO_STRING_H */
1163
1164
1165 /* ========================================================================
1166  * Error handlers.
1167  */
1168 void read_error_msg()
1169 {
1170         fprintf(stderr, "\n");
1171         if (errno != 0) {
1172                 perror("");
1173         } else {
1174                 fprintf(stderr, "unexpected end of file\n");
1175         }
1176         abort_gzip();
1177 }
1178
1179 void write_error_msg()
1180 {
1181         fprintf(stderr, "\n");
1182         perror("");
1183         abort_gzip();
1184 }
1185
1186
1187 /* ========================================================================
1188  * Table of CRC-32's of all single-byte values (made by makecrc.c)
1189  */
1190 static const ulg crc_32_tab[] = {
1191         0x00000000L, 0x77073096L, 0xee0e612cL, 0x990951baL, 0x076dc419L,
1192         0x706af48fL, 0xe963a535L, 0x9e6495a3L, 0x0edb8832L, 0x79dcb8a4L,
1193         0xe0d5e91eL, 0x97d2d988L, 0x09b64c2bL, 0x7eb17cbdL, 0xe7b82d07L,
1194         0x90bf1d91L, 0x1db71064L, 0x6ab020f2L, 0xf3b97148L, 0x84be41deL,
1195         0x1adad47dL, 0x6ddde4ebL, 0xf4d4b551L, 0x83d385c7L, 0x136c9856L,
1196         0x646ba8c0L, 0xfd62f97aL, 0x8a65c9ecL, 0x14015c4fL, 0x63066cd9L,
1197         0xfa0f3d63L, 0x8d080df5L, 0x3b6e20c8L, 0x4c69105eL, 0xd56041e4L,
1198         0xa2677172L, 0x3c03e4d1L, 0x4b04d447L, 0xd20d85fdL, 0xa50ab56bL,
1199         0x35b5a8faL, 0x42b2986cL, 0xdbbbc9d6L, 0xacbcf940L, 0x32d86ce3L,
1200         0x45df5c75L, 0xdcd60dcfL, 0xabd13d59L, 0x26d930acL, 0x51de003aL,
1201         0xc8d75180L, 0xbfd06116L, 0x21b4f4b5L, 0x56b3c423L, 0xcfba9599L,
1202         0xb8bda50fL, 0x2802b89eL, 0x5f058808L, 0xc60cd9b2L, 0xb10be924L,
1203         0x2f6f7c87L, 0x58684c11L, 0xc1611dabL, 0xb6662d3dL, 0x76dc4190L,
1204         0x01db7106L, 0x98d220bcL, 0xefd5102aL, 0x71b18589L, 0x06b6b51fL,
1205         0x9fbfe4a5L, 0xe8b8d433L, 0x7807c9a2L, 0x0f00f934L, 0x9609a88eL,
1206         0xe10e9818L, 0x7f6a0dbbL, 0x086d3d2dL, 0x91646c97L, 0xe6635c01L,
1207         0x6b6b51f4L, 0x1c6c6162L, 0x856530d8L, 0xf262004eL, 0x6c0695edL,
1208         0x1b01a57bL, 0x8208f4c1L, 0xf50fc457L, 0x65b0d9c6L, 0x12b7e950L,
1209         0x8bbeb8eaL, 0xfcb9887cL, 0x62dd1ddfL, 0x15da2d49L, 0x8cd37cf3L,
1210         0xfbd44c65L, 0x4db26158L, 0x3ab551ceL, 0xa3bc0074L, 0xd4bb30e2L,
1211         0x4adfa541L, 0x3dd895d7L, 0xa4d1c46dL, 0xd3d6f4fbL, 0x4369e96aL,
1212         0x346ed9fcL, 0xad678846L, 0xda60b8d0L, 0x44042d73L, 0x33031de5L,
1213         0xaa0a4c5fL, 0xdd0d7cc9L, 0x5005713cL, 0x270241aaL, 0xbe0b1010L,
1214         0xc90c2086L, 0x5768b525L, 0x206f85b3L, 0xb966d409L, 0xce61e49fL,
1215         0x5edef90eL, 0x29d9c998L, 0xb0d09822L, 0xc7d7a8b4L, 0x59b33d17L,
1216         0x2eb40d81L, 0xb7bd5c3bL, 0xc0ba6cadL, 0xedb88320L, 0x9abfb3b6L,
1217         0x03b6e20cL, 0x74b1d29aL, 0xead54739L, 0x9dd277afL, 0x04db2615L,
1218         0x73dc1683L, 0xe3630b12L, 0x94643b84L, 0x0d6d6a3eL, 0x7a6a5aa8L,
1219         0xe40ecf0bL, 0x9309ff9dL, 0x0a00ae27L, 0x7d079eb1L, 0xf00f9344L,
1220         0x8708a3d2L, 0x1e01f268L, 0x6906c2feL, 0xf762575dL, 0x806567cbL,
1221         0x196c3671L, 0x6e6b06e7L, 0xfed41b76L, 0x89d32be0L, 0x10da7a5aL,
1222         0x67dd4accL, 0xf9b9df6fL, 0x8ebeeff9L, 0x17b7be43L, 0x60b08ed5L,
1223         0xd6d6a3e8L, 0xa1d1937eL, 0x38d8c2c4L, 0x4fdff252L, 0xd1bb67f1L,
1224         0xa6bc5767L, 0x3fb506ddL, 0x48b2364bL, 0xd80d2bdaL, 0xaf0a1b4cL,
1225         0x36034af6L, 0x41047a60L, 0xdf60efc3L, 0xa867df55L, 0x316e8eefL,
1226         0x4669be79L, 0xcb61b38cL, 0xbc66831aL, 0x256fd2a0L, 0x5268e236L,
1227         0xcc0c7795L, 0xbb0b4703L, 0x220216b9L, 0x5505262fL, 0xc5ba3bbeL,
1228         0xb2bd0b28L, 0x2bb45a92L, 0x5cb36a04L, 0xc2d7ffa7L, 0xb5d0cf31L,
1229         0x2cd99e8bL, 0x5bdeae1dL, 0x9b64c2b0L, 0xec63f226L, 0x756aa39cL,
1230         0x026d930aL, 0x9c0906a9L, 0xeb0e363fL, 0x72076785L, 0x05005713L,
1231         0x95bf4a82L, 0xe2b87a14L, 0x7bb12baeL, 0x0cb61b38L, 0x92d28e9bL,
1232         0xe5d5be0dL, 0x7cdcefb7L, 0x0bdbdf21L, 0x86d3d2d4L, 0xf1d4e242L,
1233         0x68ddb3f8L, 0x1fda836eL, 0x81be16cdL, 0xf6b9265bL, 0x6fb077e1L,
1234         0x18b74777L, 0x88085ae6L, 0xff0f6a70L, 0x66063bcaL, 0x11010b5cL,
1235         0x8f659effL, 0xf862ae69L, 0x616bffd3L, 0x166ccf45L, 0xa00ae278L,
1236         0xd70dd2eeL, 0x4e048354L, 0x3903b3c2L, 0xa7672661L, 0xd06016f7L,
1237         0x4969474dL, 0x3e6e77dbL, 0xaed16a4aL, 0xd9d65adcL, 0x40df0b66L,
1238         0x37d83bf0L, 0xa9bcae53L, 0xdebb9ec5L, 0x47b2cf7fL, 0x30b5ffe9L,
1239         0xbdbdf21cL, 0xcabac28aL, 0x53b39330L, 0x24b4a3a6L, 0xbad03605L,
1240         0xcdd70693L, 0x54de5729L, 0x23d967bfL, 0xb3667a2eL, 0xc4614ab8L,
1241         0x5d681b02L, 0x2a6f2b94L, 0xb40bbe37L, 0xc30c8ea1L, 0x5a05df1bL,
1242         0x2d02ef8dL
1243 };
1244
1245 /* inflate.c -- Not copyrighted 1992 by Mark Adler
1246    version c10p1, 10 January 1993 */
1247
1248 /* You can do whatever you like with this source file, though I would
1249    prefer that if you modify it and redistribute it that you include
1250    comments to that effect with your name and the date.  Thank you.
1251    [The history has been moved to the file ChangeLog.]
1252  */
1253
1254 /*
1255    Inflate deflated (PKZIP's method 8 compressed) data.  The compression
1256    method searches for as much of the current string of bytes (up to a
1257    length of 258) in the previous 32K bytes.  If it doesn't find any
1258    matches (of at least length 3), it codes the next byte.  Otherwise, it
1259    codes the length of the matched string and its distance backwards from
1260    the current position.  There is a single Huffman code that codes both
1261    single bytes (called "literals") and match lengths.  A second Huffman
1262    code codes the distance information, which follows a length code.  Each
1263    length or distance code actually represents a base value and a number
1264    of "extra" (sometimes zero) bits to get to add to the base value.  At
1265    the end of each deflated block is a special end-of-block (EOB) literal/
1266    length code.  The decoding process is basically: get a literal/length
1267    code; if EOB then done; if a literal, emit the decoded byte; if a
1268    length then get the distance and emit the referred-to bytes from the
1269    sliding window of previously emitted data.
1270
1271    There are (currently) three kinds of inflate blocks: stored, fixed, and
1272    dynamic.  The compressor deals with some chunk of data at a time, and
1273    decides which method to use on a chunk-by-chunk basis.  A chunk might
1274    typically be 32K or 64K.  If the chunk is uncompressible, then the
1275    "stored" method is used.  In this case, the bytes are simply stored as
1276    is, eight bits per byte, with none of the above coding.  The bytes are
1277    preceded by a count, since there is no longer an EOB code.
1278
1279    If the data is compressible, then either the fixed or dynamic methods
1280    are used.  In the dynamic method, the compressed data is preceded by
1281    an encoding of the literal/length and distance Huffman codes that are
1282    to be used to decode this block.  The representation is itself Huffman
1283    coded, and so is preceded by a description of that code.  These code
1284    descriptions take up a little space, and so for small blocks, there is
1285    a predefined set of codes, called the fixed codes.  The fixed method is
1286    used if the block codes up smaller that way (usually for quite small
1287    chunks), otherwise the dynamic method is used.  In the latter case, the
1288    codes are customized to the probabilities in the current block, and so
1289    can code it much better than the pre-determined fixed codes.
1290  
1291    The Huffman codes themselves are decoded using a mutli-level table
1292    lookup, in order to maximize the speed of decoding plus the speed of
1293    building the decoding tables.  See the comments below that precede the
1294    lbits and dbits tuning parameters.
1295  */
1296
1297
1298 /*
1299    Notes beyond the 1.93a appnote.txt:
1300
1301    1. Distance pointers never point before the beginning of the output
1302       stream.
1303    2. Distance pointers can point back across blocks, up to 32k away.
1304    3. There is an implied maximum of 7 bits for the bit length table and
1305       15 bits for the actual data.
1306    4. If only one code exists, then it is encoded using one bit.  (Zero
1307       would be more efficient, but perhaps a little confusing.)  If two
1308       codes exist, they are coded using one bit each (0 and 1).
1309    5. There is no way of sending zero distance codes--a dummy must be
1310       sent if there are none.  (History: a pre 2.0 version of PKZIP would
1311       store blocks with no distance codes, but this was discovered to be
1312       too harsh a criterion.)  Valid only for 1.93a.  2.04c does allow
1313       zero distance codes, which is sent as one code of zero bits in
1314       length.
1315    6. There are up to 286 literal/length codes.  Code 256 represents the
1316       end-of-block.  Note however that the static length tree defines
1317       288 codes just to fill out the Huffman codes.  Codes 286 and 287
1318       cannot be used though, since there is no length base or extra bits
1319       defined for them.  Similarly, there are up to 30 distance codes.
1320       However, static trees define 32 codes (all 5 bits) to fill out the
1321       Huffman codes, but the last two had better not show up in the data.
1322    7. Unzip can check dynamic Huffman blocks for complete code sets.
1323       The exception is that a single code would not be complete (see #4).
1324    8. The five bits following the block type is really the number of
1325       literal codes sent minus 257.
1326    9. Length codes 8,16,16 are interpreted as 13 length codes of 8 bits
1327       (1+6+6).  Therefore, to output three times the length, you output
1328       three codes (1+1+1), whereas to output four times the same length,
1329       you only need two codes (1+3).  Hmm.
1330   10. In the tree reconstruction algorithm, Code = Code + Increment
1331       only if BitLength(i) is not zero.  (Pretty obvious.)
1332   11. Correction: 4 Bits: # of Bit Length codes - 4     (4 - 19)
1333   12. Note: length code 284 can represent 227-258, but length code 285
1334       really is 258.  The last length deserves its own, short code
1335       since it gets used a lot in very redundant files.  The length
1336       258 is special since 258 - 3 (the min match length) is 255.
1337   13. The literal/length and distance code bit lengths are read as a
1338       single stream of lengths.  It is possible (and advantageous) for
1339       a repeat code (16, 17, or 18) to go across the boundary between
1340       the two sets of lengths.
1341  */
1342
1343 #include <sys/types.h>
1344
1345 #if defined(STDC_HEADERS) || !defined(NO_STDLIB_H)
1346 #  include <stdlib.h>
1347 #endif
1348
1349
1350 #define slide window
1351
1352 /* Huffman code lookup table entry--this entry is four bytes for machines
1353    that have 16-bit pointers (e.g. PC's in the small or medium model).
1354    Valid extra bits are 0..13.  e == 15 is EOB (end of block), e == 16
1355    means that v is a literal, 16 < e < 32 means that v is a pointer to
1356    the next table, which codes e - 16 bits, and lastly e == 99 indicates
1357    an unused code.  If a code with e == 99 is looked up, this implies an
1358    error in the data. */
1359 struct huft {
1360         uch e;                                          /* number of extra bits or operation */
1361         uch b;                                          /* number of bits in this code or subcode */
1362         union {
1363                 ush n;                                  /* literal, length base, or distance base */
1364                 struct huft *t;                 /* pointer to next level of table */
1365         } v;
1366 };
1367
1368
1369 /* Function prototypes */
1370 int huft_build (unsigned *, unsigned, unsigned, ush *, ush *,
1371                                    struct huft **, int *);
1372 int huft_free (struct huft *);
1373 int inflate_codes (struct huft *, struct huft *, int, int);
1374 int inflate_stored (void);
1375 int inflate_fixed (void);
1376 int inflate_dynamic (void);
1377 int inflate_block (int *);
1378 int inflate (void);
1379
1380
1381 /* The inflate algorithm uses a sliding 32K byte window on the uncompressed
1382    stream to find repeated byte strings.  This is implemented here as a
1383    circular buffer.  The index is updated simply by incrementing and then
1384    and'ing with 0x7fff (32K-1). */
1385 /* It is left to other modules to supply the 32K area.  It is assumed
1386    to be usable as if it were declared "uch slide[32768];" or as just
1387    "uch *slide;" and then malloc'ed in the latter case.  The definition
1388    must be in unzip.h, included above. */
1389 /* unsigned wp;             current position in slide */
1390 #define wp outcnt
1391 #define flush_output(w) (wp=(w),flush_window())
1392
1393 /* Tables for deflate from PKZIP's appnote.txt. */
1394 static unsigned border[] = {    /* Order of the bit length code lengths */
1395         16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15
1396 };
1397 static ush cplens[] = {                 /* Copy lengths for literal codes 257..285 */
1398         3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,
1399         35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0
1400 };
1401
1402                 /* note: see note #13 above about the 258 in this list. */
1403 static ush cplext[] = {                 /* Extra bits for literal codes 257..285 */
1404         0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2,
1405         3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0, 99, 99
1406 };                                                              /* 99==invalid */
1407 static ush cpdist[] = {                 /* Copy offsets for distance codes 0..29 */
1408         1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,
1409         257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,
1410         8193, 12289, 16385, 24577
1411 };
1412 static ush cpdext[] = {                 /* Extra bits for distance codes */
1413         0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6,
1414         7, 7, 8, 8, 9, 9, 10, 10, 11, 11,
1415         12, 12, 13, 13
1416 };
1417
1418
1419
1420 /* Macros for inflate() bit peeking and grabbing.
1421    The usage is:
1422    
1423         NEEDBITS(j)
1424         x = b & mask_bits[j];
1425         DUMPBITS(j)
1426
1427    where NEEDBITS makes sure that b has at least j bits in it, and
1428    DUMPBITS removes the bits from b.  The macros use the variable k
1429    for the number of bits in b.  Normally, b and k are register
1430    variables for speed, and are initialized at the beginning of a
1431    routine that uses these macros from a global bit buffer and count.
1432
1433    If we assume that EOB will be the longest code, then we will never
1434    ask for bits with NEEDBITS that are beyond the end of the stream.
1435    So, NEEDBITS should not read any more bytes than are needed to
1436    meet the request.  Then no bytes need to be "returned" to the buffer
1437    at the end of the last block.
1438
1439    However, this assumption is not true for fixed blocks--the EOB code
1440    is 7 bits, but the other literal/length codes can be 8 or 9 bits.
1441    (The EOB code is shorter than other codes because fixed blocks are
1442    generally short.  So, while a block always has an EOB, many other
1443    literal/length codes have a significantly lower probability of
1444    showing up at all.)  However, by making the first table have a
1445    lookup of seven bits, the EOB code will be found in that first
1446    lookup, and so will not require that too many bits be pulled from
1447    the stream.
1448  */
1449
1450 ulg bb;                                                 /* bit buffer */
1451 unsigned bk;                                    /* bits in bit buffer */
1452
1453 ush mask_bits[] = {
1454         0x0000,
1455         0x0001, 0x0003, 0x0007, 0x000f, 0x001f, 0x003f, 0x007f, 0x00ff,
1456         0x01ff, 0x03ff, 0x07ff, 0x0fff, 0x1fff, 0x3fff, 0x7fff, 0xffff
1457 };
1458
1459 #ifdef CRYPT
1460 uch cc;
1461
1462 #  define NEXTBYTE() (cc = get_byte(), zdecode(cc), cc)
1463 #else
1464 #  define NEXTBYTE()  (uch)get_byte()
1465 #endif
1466 #define NEEDBITS(n) {while(k<(n)){b|=((ulg)NEXTBYTE())<<k;k+=8;}}
1467 #define DUMPBITS(n) {b>>=(n);k-=(n);}
1468
1469
1470 /*
1471    Huffman code decoding is performed using a multi-level table lookup.
1472    The fastest way to decode is to simply build a lookup table whose
1473    size is determined by the longest code.  However, the time it takes
1474    to build this table can also be a factor if the data being decoded
1475    is not very long.  The most common codes are necessarily the
1476    shortest codes, so those codes dominate the decoding time, and hence
1477    the speed.  The idea is you can have a shorter table that decodes the
1478    shorter, more probable codes, and then point to subsidiary tables for
1479    the longer codes.  The time it costs to decode the longer codes is
1480    then traded against the time it takes to make longer tables.
1481
1482    This results of this trade are in the variables lbits and dbits
1483    below.  lbits is the number of bits the first level table for literal/
1484    length codes can decode in one step, and dbits is the same thing for
1485    the distance codes.  Subsequent tables are also less than or equal to
1486    those sizes.  These values may be adjusted either when all of the
1487    codes are shorter than that, in which case the longest code length in
1488    bits is used, or when the shortest code is *longer* than the requested
1489    table size, in which case the length of the shortest code in bits is
1490    used.
1491
1492    There are two different values for the two tables, since they code a
1493    different number of possibilities each.  The literal/length table
1494    codes 286 possible values, or in a flat code, a little over eight
1495    bits.  The distance table codes 30 possible values, or a little less
1496    than five bits, flat.  The optimum values for speed end up being
1497    about one bit more than those, so lbits is 8+1 and dbits is 5+1.
1498    The optimum values may differ though from machine to machine, and
1499    possibly even between compilers.  Your mileage may vary.
1500  */
1501
1502
1503 int lbits = 9;                                  /* bits in base literal/length lookup table */
1504 int dbits = 6;                                  /* bits in base distance lookup table */
1505
1506
1507 /* If BMAX needs to be larger than 16, then h and x[] should be ulg. */
1508 #define BMAX 16                                 /* maximum bit length of any code (16 for explode) */
1509 #define N_MAX 288                               /* maximum number of codes in any set */
1510
1511
1512 unsigned hufts;                                 /* track memory usage */
1513
1514
1515 int huft_build(b, n, s, d, e, t, m)
1516 unsigned *b;                                    /* code lengths in bits (all assumed <= BMAX) */
1517 unsigned n;                                             /* number of codes (assumed <= N_MAX) */
1518 unsigned s;                                             /* number of simple-valued codes (0..s-1) */
1519 ush *d;                                                 /* list of base values for non-simple codes */
1520 ush *e;                                                 /* list of extra bits for non-simple codes */
1521 struct huft **t;                                /* result: starting table */
1522 int *m;                                                 /* maximum lookup bits, returns actual */
1523
1524 /* Given a list of code lengths and a maximum table size, make a set of
1525    tables to decode that set of codes.  Return zero on success, one if
1526    the given code set is incomplete (the tables are still built in this
1527    case), two if the input is invalid (all zero length codes or an
1528    oversubscribed set of lengths), and three if not enough memory. */
1529 {
1530         unsigned a;                                     /* counter for codes of length k */
1531         unsigned c[BMAX + 1];           /* bit length count table */
1532         unsigned f;                                     /* i repeats in table every f entries */
1533         int g;                                          /* maximum code length */
1534         int h;                                          /* table level */
1535         register unsigned i;            /* counter, current code */
1536         register unsigned j;            /* counter */
1537         register int k;                         /* number of bits in current code */
1538         int l;                                          /* bits per table (returned in m) */
1539         register unsigned *p;           /* pointer into c[], b[], or v[] */
1540         register struct huft *q;        /* points to current table */
1541         struct huft r;                          /* table entry for structure assignment */
1542         struct huft *u[BMAX];           /* table stack */
1543         unsigned v[N_MAX];                      /* values in order of bit length */
1544         register int w;                         /* bits before this table == (l * h) */
1545         unsigned x[BMAX + 1];           /* bit offsets, then code stack */
1546         unsigned *xp;                           /* pointer into x */
1547         int y;                                          /* number of dummy codes added */
1548         unsigned z;                                     /* number of entries in current table */
1549
1550
1551         /* Generate counts for each bit length */
1552         memzero(c, sizeof(c));
1553         p = b;
1554         i = n;
1555         do {
1556                 Tracecv(*p,
1557                                 (stderr,
1558                                  (n - i >= ' '
1559                                   && n - i <= '~' ? "%c %d\n" : "0x%x %d\n"), n - i, *p));
1560                 c[*p]++;                                /* assume all entries <= BMAX */
1561                 p++;                                    /* Can't combine with above line (Solaris bug) */
1562         } while (--i);
1563         if (c[0] == n) {                        /* null input--all zero length codes */
1564                 *t = (struct huft *) NULL;
1565                 *m = 0;
1566                 return 0;
1567         }
1568
1569
1570         /* Find minimum and maximum length, bound *m by those */
1571         l = *m;
1572         for (j = 1; j <= BMAX; j++)
1573                 if (c[j])
1574                         break;
1575         k = j;                                          /* minimum code length */
1576         if ((unsigned) l < j)
1577                 l = j;
1578         for (i = BMAX; i; i--)
1579                 if (c[i])
1580                         break;
1581         g = i;                                          /* maximum code length */
1582         if ((unsigned) l > i)
1583                 l = i;
1584         *m = l;
1585
1586
1587         /* Adjust last length count to fill out codes, if needed */
1588         for (y = 1 << j; j < i; j++, y <<= 1)
1589                 if ((y -= c[j]) < 0)
1590                         return 2;                       /* bad input: more codes than bits */
1591         if ((y -= c[i]) < 0)
1592                 return 2;
1593         c[i] += y;
1594
1595
1596         /* Generate starting offsets into the value table for each length */
1597         x[1] = j = 0;
1598         p = c + 1;
1599         xp = x + 2;
1600         while (--i) {                           /* note that i == g from above */
1601                 *xp++ = (j += *p++);
1602         }
1603
1604
1605         /* Make a table of values in order of bit lengths */
1606         p = b;
1607         i = 0;
1608         do {
1609                 if ((j = *p++) != 0)
1610                         v[x[j]++] = i;
1611         } while (++i < n);
1612
1613
1614         /* Generate the Huffman codes and for each, make the table entries */
1615         x[0] = i = 0;                           /* first Huffman code is zero */
1616         p = v;                                          /* grab values in bit order */
1617         h = -1;                                         /* no tables yet--level -1 */
1618         w = -l;                                         /* bits decoded == (l * h) */
1619         u[0] = (struct huft *) NULL;    /* just to keep compilers happy */
1620         q = (struct huft *) NULL;       /* ditto */
1621         z = 0;                                          /* ditto */
1622
1623         /* go through the bit lengths (k already is bits in shortest code) */
1624         for (; k <= g; k++) {
1625                 a = c[k];
1626                 while (a--) {
1627                         /* here i is the Huffman code of length k bits for value *p */
1628                         /* make tables up to required level */
1629                         while (k > w + l) {
1630                                 h++;
1631                                 w += l;                 /* previous table always l bits */
1632
1633                                 /* compute minimum size table less than or equal to l bits */
1634                                 z = (z = g - w) > (unsigned) l ? l : z; /* upper limit on table size */
1635                                 if ((f = 1 << (j = k - w)) > a + 1) {   /* try a k-w bit table *//* too few codes for k-w bit table */
1636                                         f -= a + 1;     /* deduct codes from patterns left */
1637                                         xp = c + k;
1638                                         while (++j < z) {       /* try smaller tables up to z bits */
1639                                                 if ((f <<= 1) <= *++xp)
1640                                                         break;  /* enough codes to use up j bits */
1641                                                 f -= *xp;       /* else deduct codes from patterns */
1642                                         }
1643                                 }
1644                                 z = 1 << j;             /* table entries for j-bit table */
1645
1646                                 /* allocate and link in new table */
1647                                 if (
1648                                         (q =
1649                                          (struct huft *) malloc((z + 1) *
1650                                                                                         sizeof(struct huft))) ==
1651                                         (struct huft *) NULL) {
1652                                         if (h)
1653                                                 huft_free(u[0]);
1654                                         return 3;       /* not enough memory */
1655                                 }
1656                                 hufts += z + 1; /* track memory usage */
1657                                 *t = q + 1;             /* link to list for huft_free() */
1658                                 *(t = &(q->v.t)) = (struct huft *) NULL;
1659                                 u[h] = ++q;             /* table starts after link */
1660
1661                                 /* connect to last table, if there is one */
1662                                 if (h) {
1663                                         x[h] = i;       /* save pattern for backing up */
1664                                         r.b = (uch) l;  /* bits to dump before this table */
1665                                         r.e = (uch) (16 + j);   /* bits in this table */
1666                                         r.v.t = q;      /* pointer to this table */
1667                                         j = i >> (w - l);       /* (get around Turbo C bug) */
1668                                         u[h - 1][j] = r;        /* connect to last table */
1669                                 }
1670                         }
1671
1672                         /* set up table entry in r */
1673                         r.b = (uch) (k - w);
1674                         if (p >= v + n)
1675                                 r.e = 99;               /* out of values--invalid code */
1676                         else if (*p < s) {
1677                                 r.e = (uch) (*p < 256 ? 16 : 15);       /* 256 is end-of-block code */
1678                                 r.v.n = (ush) (*p);     /* simple code is just the value */
1679                                 p++;                    /* one compiler does not like *p++ */
1680                         } else {
1681                                 r.e = (uch) e[*p - s];  /* non-simple--look up in lists */
1682                                 r.v.n = d[*p++ - s];
1683                         }
1684
1685                         /* fill code-like entries with r */
1686                         f = 1 << (k - w);
1687                         for (j = i >> w; j < z; j += f)
1688                                 q[j] = r;
1689
1690                         /* backwards increment the k-bit code i */
1691                         for (j = 1 << (k - 1); i & j; j >>= 1)
1692                                 i ^= j;
1693                         i ^= j;
1694
1695                         /* backup over finished tables */
1696                         while ((i & ((1 << w) - 1)) != x[h]) {
1697                                 h--;                    /* don't need to update q */
1698                                 w -= l;
1699                         }
1700                 }
1701         }
1702
1703
1704         /* Return true (1) if we were given an incomplete table */
1705         return y != 0 && g != 1;
1706 }
1707
1708
1709
1710 int huft_free(t)
1711 struct huft *t;                                 /* table to free */
1712
1713 /* Free the malloc'ed tables built by huft_build(), which makes a linked
1714    list of the tables it made, with the links in a dummy first entry of
1715    each table. */
1716 {
1717         register struct huft *p, *q;
1718
1719
1720         /* Go through linked list, freeing from the malloced (t[-1]) address. */
1721         p = t;
1722         while (p != (struct huft *) NULL) {
1723                 q = (--p)->v.t;
1724                 free((char *) p);
1725                 p = q;
1726         }
1727         return 0;
1728 }
1729
1730
1731 int inflate_codes(tl, td, bl, bd)
1732 struct huft *tl, *td;                   /* literal/length and distance decoder tables */
1733 int bl, bd;                                             /* number of bits decoded by tl[] and td[] */
1734
1735 /* inflate (decompress) the codes in a deflated (compressed) block.
1736    Return an error code or zero if it all goes ok. */
1737 {
1738         register unsigned e;            /* table entry flag/number of extra bits */
1739         unsigned n, d;                          /* length and index for copy */
1740         unsigned w;                                     /* current window position */
1741         struct huft *t;                         /* pointer to table entry */
1742         unsigned ml, md;                        /* masks for bl and bd bits */
1743         register ulg b;                         /* bit buffer */
1744         register unsigned k;            /* number of bits in bit buffer */
1745
1746
1747         /* make local copies of globals */
1748         b = bb;                                         /* initialize bit buffer */
1749         k = bk;
1750         w = wp;                                         /* initialize window position */
1751
1752         /* inflate the coded data */
1753         ml = mask_bits[bl];                     /* precompute masks for speed */
1754         md = mask_bits[bd];
1755         for (;;) {                                      /* do until end of block */
1756                 NEEDBITS((unsigned) bl)
1757                         if ((e = (t = tl + ((unsigned) b & ml))->e) > 16)
1758                         do {
1759                                 if (e == 99)
1760                                         return 1;
1761                                 DUMPBITS(t->b)
1762                                         e -= 16;
1763                                 NEEDBITS(e)
1764                         } while ((e = (t = t->v.t + ((unsigned) b & mask_bits[e]))->e)
1765                                          > 16);
1766                 DUMPBITS(t->b)
1767                         if (e == 16) {          /* then it's a literal */
1768                         slide[w++] = (uch) t->v.n;
1769                         Tracevv((stderr, "%c", slide[w - 1]));
1770                         if (w == WSIZE) {
1771                                 flush_output(w);
1772                                 w = 0;
1773                         }
1774                 } else {                                /* it's an EOB or a length */
1775
1776                         /* exit if end of block */
1777                         if (e == 15)
1778                                 break;
1779
1780                         /* get length of block to copy */
1781                         NEEDBITS(e)
1782                                 n = t->v.n + ((unsigned) b & mask_bits[e]);
1783                         DUMPBITS(e);
1784
1785                         /* decode distance of block to copy */
1786                         NEEDBITS((unsigned) bd)
1787                                 if ((e = (t = td + ((unsigned) b & md))->e) > 16)
1788                                 do {
1789                                         if (e == 99)
1790                                                 return 1;
1791                                         DUMPBITS(t->b)
1792                                                 e -= 16;
1793                                         NEEDBITS(e)
1794                                 }
1795                                         while (
1796                                                    (e =
1797                                                         (t =
1798                                                          t->v.t + ((unsigned) b & mask_bits[e]))->e) >
1799                                                    16);
1800                         DUMPBITS(t->b)
1801                                 NEEDBITS(e)
1802                                 d = w - t->v.n - ((unsigned) b & mask_bits[e]);
1803                         DUMPBITS(e)
1804                                 Tracevv((stderr, "\\[%d,%d]", w - d, n));
1805
1806                         /* do the copy */
1807                         do {
1808                                 n -= (e =
1809                                           (e =
1810                                            WSIZE - ((d &= WSIZE - 1) > w ? d : w)) >
1811                                           n ? n : e);
1812 #if !defined(NOMEMCPY) && !defined(DEBUG)
1813                                 if (w - d >= e) {       /* (this test assumes unsigned comparison) */
1814                                         memcpy(slide + w, slide + d, e);
1815                                         w += e;
1816                                         d += e;
1817                                 } else                  /* do it slow to avoid memcpy() overlap */
1818 #endif                                                  /* !NOMEMCPY */
1819                                         do {
1820                                                 slide[w++] = slide[d++];
1821                                                 Tracevv((stderr, "%c", slide[w - 1]));
1822                                         } while (--e);
1823                                 if (w == WSIZE) {
1824                                         flush_output(w);
1825                                         w = 0;
1826                                 }
1827                         } while (n);
1828                 }
1829         }
1830
1831
1832         /* restore the globals from the locals */
1833         wp = w;                                         /* restore global window pointer */
1834         bb = b;                                         /* restore global bit buffer */
1835         bk = k;
1836
1837         /* done */
1838         return 0;
1839 }
1840
1841
1842
1843 int inflate_stored()
1844 /* "decompress" an inflated type 0 (stored) block. */
1845 {
1846         unsigned n;                                     /* number of bytes in block */
1847         unsigned w;                                     /* current window position */
1848         register ulg b;                         /* bit buffer */
1849         register unsigned k;            /* number of bits in bit buffer */
1850
1851
1852         /* make local copies of globals */
1853         b = bb;                                         /* initialize bit buffer */
1854         k = bk;
1855         w = wp;                                         /* initialize window position */
1856
1857
1858         /* go to byte boundary */
1859         n = k & 7;
1860         DUMPBITS(n);
1861
1862
1863         /* get the length and its complement */
1864         NEEDBITS(16)
1865                 n = ((unsigned) b & 0xffff);
1866         DUMPBITS(16)
1867                 NEEDBITS(16)
1868                 if (n != (unsigned) ((~b) & 0xffff))
1869                 return 1;                               /* error in compressed data */
1870         DUMPBITS(16)
1871
1872
1873                 /* read and output the compressed data */
1874                 while (n--) {
1875                 NEEDBITS(8)
1876                         slide[w++] = (uch) b;
1877                 if (w == WSIZE) {
1878                         flush_output(w);
1879                         w = 0;
1880                 }
1881                 DUMPBITS(8)
1882         }
1883
1884
1885         /* restore the globals from the locals */
1886         wp = w;                                         /* restore global window pointer */
1887         bb = b;                                         /* restore global bit buffer */
1888         bk = k;
1889         return 0;
1890 }
1891
1892
1893
1894 int inflate_fixed()
1895 /* decompress an inflated type 1 (fixed Huffman codes) block.  We should
1896    either replace this with a custom decoder, or at least precompute the
1897    Huffman tables. */
1898 {
1899         int i;                                          /* temporary variable */
1900         struct huft *tl;                        /* literal/length code table */
1901         struct huft *td;                        /* distance code table */
1902         int bl;                                         /* lookup bits for tl */
1903         int bd;                                         /* lookup bits for td */
1904         unsigned l[288];                        /* length list for huft_build */
1905
1906
1907         /* set up literal table */
1908         for (i = 0; i < 144; i++)
1909                 l[i] = 8;
1910         for (; i < 256; i++)
1911                 l[i] = 9;
1912         for (; i < 280; i++)
1913                 l[i] = 7;
1914         for (; i < 288; i++)            /* make a complete, but wrong code set */
1915                 l[i] = 8;
1916         bl = 7;
1917         if ((i = huft_build(l, 288, 257, cplens, cplext, &tl, &bl)) != 0)
1918                 return i;
1919
1920
1921         /* set up distance table */
1922         for (i = 0; i < 30; i++)        /* make an incomplete code set */
1923                 l[i] = 5;
1924         bd = 5;
1925         if ((i = huft_build(l, 30, 0, cpdist, cpdext, &td, &bd)) > 1) {
1926                 huft_free(tl);
1927                 return i;
1928         }
1929
1930
1931         /* decompress until an end-of-block code */
1932         if (inflate_codes(tl, td, bl, bd))
1933                 return 1;
1934
1935
1936         /* free the decoding tables, return */
1937         huft_free(tl);
1938         huft_free(td);
1939         return 0;
1940 }
1941
1942
1943
1944 int inflate_dynamic()
1945 /* decompress an inflated type 2 (dynamic Huffman codes) block. */
1946 {
1947         int i;                                          /* temporary variables */
1948         unsigned j;
1949         unsigned l;                                     /* last length */
1950         unsigned m;                                     /* mask for bit lengths table */
1951         unsigned n;                                     /* number of lengths to get */
1952         struct huft *tl;                        /* literal/length code table */
1953         struct huft *td;                        /* distance code table */
1954         int bl;                                         /* lookup bits for tl */
1955         int bd;                                         /* lookup bits for td */
1956         unsigned nb;                            /* number of bit length codes */
1957         unsigned nl;                            /* number of literal/length codes */
1958         unsigned nd;                            /* number of distance codes */
1959
1960 #ifdef PKZIP_BUG_WORKAROUND
1961         unsigned ll[288 + 32];          /* literal/length and distance code lengths */
1962 #else
1963         unsigned ll[286 + 30];          /* literal/length and distance code lengths */
1964 #endif
1965         register ulg b;                         /* bit buffer */
1966         register unsigned k;            /* number of bits in bit buffer */
1967
1968
1969         /* make local bit buffer */
1970         b = bb;
1971         k = bk;
1972
1973
1974         /* read in table lengths */
1975         NEEDBITS(5)
1976                 nl = 257 + ((unsigned) b & 0x1f);       /* number of literal/length codes */
1977         DUMPBITS(5)
1978                 NEEDBITS(5)
1979                 nd = 1 + ((unsigned) b & 0x1f); /* number of distance codes */
1980         DUMPBITS(5)
1981                 NEEDBITS(4)
1982                 nb = 4 + ((unsigned) b & 0xf);  /* number of bit length codes */
1983         DUMPBITS(4)
1984 #ifdef PKZIP_BUG_WORKAROUND
1985                 if (nl > 288 || nd > 32)
1986 #else
1987                 if (nl > 286 || nd > 30)
1988 #endif
1989                 return 1;                               /* bad lengths */
1990
1991
1992         /* read in bit-length-code lengths */
1993         for (j = 0; j < nb; j++) {
1994                 NEEDBITS(3)
1995                         ll[border[j]] = (unsigned) b & 7;
1996                 DUMPBITS(3)
1997         }
1998         for (; j < 19; j++)
1999                 ll[border[j]] = 0;
2000
2001
2002         /* build decoding table for trees--single level, 7 bit lookup */
2003         bl = 7;
2004         if ((i = huft_build(ll, 19, 19, NULL, NULL, &tl, &bl)) != 0) {
2005                 if (i == 1)
2006                         huft_free(tl);
2007                 return i;                               /* incomplete code set */
2008         }
2009
2010
2011         /* read in literal and distance code lengths */
2012         n = nl + nd;
2013         m = mask_bits[bl];
2014         i = l = 0;
2015         while ((unsigned) i < n) {
2016                 NEEDBITS((unsigned) bl)
2017                         j = (td = tl + ((unsigned) b & m))->b;
2018                 DUMPBITS(j)
2019                         j = td->v.n;
2020                 if (j < 16)                             /* length of code in bits (0..15) */
2021                         ll[i++] = l = j;        /* save last length in l */
2022                 else if (j == 16) {             /* repeat last length 3 to 6 times */
2023                         NEEDBITS(2)
2024                                 j = 3 + ((unsigned) b & 3);
2025                         DUMPBITS(2)
2026                                 if ((unsigned) i + j > n)
2027                                 return 1;
2028                         while (j--)
2029                                 ll[i++] = l;
2030                 } else if (j == 17) {   /* 3 to 10 zero length codes */
2031                         NEEDBITS(3)
2032                                 j = 3 + ((unsigned) b & 7);
2033                         DUMPBITS(3)
2034                                 if ((unsigned) i + j > n)
2035                                 return 1;
2036                         while (j--)
2037                                 ll[i++] = 0;
2038                         l = 0;
2039                 } else {                                /* j == 18: 11 to 138 zero length codes */
2040
2041                         NEEDBITS(7)
2042                                 j = 11 + ((unsigned) b & 0x7f);
2043                         DUMPBITS(7)
2044                                 if ((unsigned) i + j > n)
2045                                 return 1;
2046                         while (j--)
2047                                 ll[i++] = 0;
2048                         l = 0;
2049                 }
2050         }
2051
2052
2053         /* free decoding table for trees */
2054         huft_free(tl);
2055
2056
2057         /* restore the global bit buffer */
2058         bb = b;
2059         bk = k;
2060
2061
2062         /* build the decoding tables for literal/length and distance codes */
2063         bl = lbits;
2064         if ((i = huft_build(ll, nl, 257, cplens, cplext, &tl, &bl)) != 0) {
2065                 if (i == 1) {
2066                         fprintf(stderr, " incomplete literal tree\n");
2067                         huft_free(tl);
2068                 }
2069                 return i;                               /* incomplete code set */
2070         }
2071         bd = dbits;
2072         if ((i = huft_build(ll + nl, nd, 0, cpdist, cpdext, &td, &bd)) != 0) {
2073                 if (i == 1) {
2074                         fprintf(stderr, " incomplete distance tree\n");
2075 #ifdef PKZIP_BUG_WORKAROUND
2076                         i = 0;
2077                 }
2078 #else
2079                         huft_free(td);
2080                 }
2081                 huft_free(tl);
2082                 return i;                               /* incomplete code set */
2083 #endif
2084         }
2085
2086
2087         /* decompress until an end-of-block code */
2088         if (inflate_codes(tl, td, bl, bd))
2089                 return 1;
2090
2091
2092         /* free the decoding tables, return */
2093         huft_free(tl);
2094         huft_free(td);
2095         return 0;
2096 }
2097
2098
2099
2100 int inflate_block(e)
2101 int *e;                                                 /* last block flag */
2102
2103 /* decompress an inflated block */
2104 {
2105         unsigned t;                                     /* block type */
2106         register ulg b;                         /* bit buffer */
2107         register unsigned k;            /* number of bits in bit buffer */
2108
2109
2110         /* make local bit buffer */
2111         b = bb;
2112         k = bk;
2113
2114
2115         /* read in last block bit */
2116         NEEDBITS(1)
2117                 * e = (int) b & 1;
2118         DUMPBITS(1)
2119
2120
2121                 /* read in block type */
2122                 NEEDBITS(2)
2123                 t = (unsigned) b & 3;
2124         DUMPBITS(2)
2125
2126
2127                 /* restore the global bit buffer */
2128                 bb = b;
2129         bk = k;
2130
2131
2132         /* inflate that block type */
2133         if (t == 2)
2134                 return inflate_dynamic();
2135         if (t == 0)
2136                 return inflate_stored();
2137         if (t == 1)
2138                 return inflate_fixed();
2139
2140
2141         /* bad block type */
2142         return 2;
2143 }
2144
2145
2146
2147 int inflate()
2148 /* decompress an inflated entry */
2149 {
2150         int e;                                          /* last block flag */
2151         int r;                                          /* result code */
2152         unsigned h;                                     /* maximum struct huft's malloc'ed */
2153
2154
2155         /* initialize window, bit buffer */
2156         wp = 0;
2157         bk = 0;
2158         bb = 0;
2159
2160
2161         /* decompress until the last block */
2162         h = 0;
2163         do {
2164                 hufts = 0;
2165                 if ((r = inflate_block(&e)) != 0)
2166                         return r;
2167                 if (hufts > h)
2168                         h = hufts;
2169         } while (!e);
2170
2171         /* Undo too much lookahead. The next read will be byte aligned so we
2172          * can discard unused bits in the last meaningful byte.
2173          */
2174         while (bk >= 8) {
2175                 bk -= 8;
2176                 inptr--;
2177         }
2178
2179         /* flush out slide */
2180         flush_output(wp);
2181
2182
2183         /* return success */
2184 #ifdef DEBUG
2185         fprintf(stderr, "<%u> ", h);
2186 #endif                                                  /* DEBUG */
2187         return 0;
2188 }