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