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