Apply Vladimir's latest cleanup patch.
[oweals/busybox.git] / archival / gzip.c
1 /* vi: set sw=4 ts=4: */
2 /*
3  * Gzip implementation for busybox
4  *
5  * Based on GNU gzip Copyright (C) 1992-1993 Jean-loup Gailly.
6  *
7  * Originally adjusted for busybox by Charles P. Wright <cpw@unix.asb.com>
8  *              "this is a stripped down version of gzip I put into busybox, it does
9  *              only standard in to standard out with -9 compression.  It also requires
10  *              the zcat module for some important functions."
11  *
12  * Adjusted further by Erik Andersen <andersen@lineo.com>, <andersee@debian.org>
13  * to support files as well as stdin/stdout, and to generally behave itself wrt
14  * command line handling.
15  *
16  * This program is free software; you can redistribute it and/or modify
17  * it under the terms of the GNU General Public License as published by
18  * the Free Software Foundation; either version 2 of the License, or
19  * (at your option) any later version.
20  *
21  * This program is distributed in the hope that it will be useful,
22  * but WITHOUT ANY WARRANTY; without even the implied warranty of
23  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
24  * General Public License for more details.
25  *
26  * You should have received a copy of the GNU General Public License
27  * along with this program; if not, write to the Free Software
28  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
29  *
30  */
31
32 /* These defines are very important for BusyBox.  Without these,
33  * huge chunks of ram are pre-allocated making the BusyBox bss 
34  * size Freaking Huge(tm), which is a bad thing.*/
35 #define SMALL_MEM
36 #define DYN_ALLOC
37
38 /* I don't like nested includes, but the string and io functions are used
39  * too often
40  */
41 #include <stdlib.h>
42 #include <stdio.h>
43 #include <string.h>
44 #include <unistd.h>
45 #include <errno.h>
46 #include "busybox.h"
47 #define BB_DECLARE_EXTERN
48 #define bb_need_memory_exhausted
49 #include "messages.c"
50
51 #define memzero(s, n)     memset ((void *)(s), 0, (n))
52
53 #ifndef RETSIGTYPE
54 #  define RETSIGTYPE void
55 #endif
56
57 #define local static
58
59 typedef unsigned char uch;
60 typedef unsigned short ush;
61 typedef unsigned long ulg;
62
63 /* Return codes from gzip */
64 #define OK      0
65 #define ERROR   1
66 #define WARNING 2
67
68 /* Compression methods (see algorithm.doc) */
69 #define STORED      0
70 #define COMPRESSED  1
71 #define PACKED      2
72 #define LZHED       3
73 /* methods 4 to 7 reserved */
74 #define DEFLATED    8
75 #define MAX_METHODS 9
76 static int method;                              /* compression method */
77
78 /* To save memory for 16 bit systems, some arrays are overlaid between
79  * the various modules:
80  * deflate:  prev+head   window      d_buf  l_buf  outbuf
81  * unlzw:    tab_prefix  tab_suffix  stack  inbuf  outbuf
82  * inflate:              window             inbuf
83  * unpack:               window             inbuf  prefix_len
84  * unlzh:    left+right  window      c_table inbuf c_len
85  * For compression, input is done in window[]. For decompression, output
86  * is done in window except for unlzw.
87  */
88
89 #ifndef INBUFSIZ
90 #  ifdef SMALL_MEM
91 #    define INBUFSIZ  0x2000    /* input buffer size */
92 #  else
93 #    define INBUFSIZ  0x8000    /* input buffer size */
94 #  endif
95 #endif
96 #define INBUF_EXTRA  64                 /* required by unlzw() */
97
98 #ifndef OUTBUFSIZ
99 #  ifdef SMALL_MEM
100 #    define OUTBUFSIZ   8192    /* output buffer size */
101 #  else
102 #    define OUTBUFSIZ  16384    /* output buffer size */
103 #  endif
104 #endif
105 #define OUTBUF_EXTRA 2048               /* required by unlzw() */
106
107 #ifndef DIST_BUFSIZE
108 #  ifdef SMALL_MEM
109 #    define DIST_BUFSIZE 0x2000 /* buffer for distances, see trees.c */
110 #  else
111 #    define DIST_BUFSIZE 0x8000 /* buffer for distances, see trees.c */
112 #  endif
113 #endif
114
115 #ifdef DYN_ALLOC
116 #  define EXTERN(type, array)  extern type * array
117 #  define DECLARE(type, array, size)  type * array
118 #  define ALLOC(type, array, size) { \
119       array = (type*)calloc((size_t)(((size)+1L)/2), 2*sizeof(type)); \
120       if (array == NULL) error_msg(memory_exhausted); \
121    }
122 #  define FREE(array) {if (array != NULL) free(array), array=NULL;}
123 #else
124 #  define EXTERN(type, array)  extern type array[]
125 #  define DECLARE(type, array, size)  type array[size]
126 #  define ALLOC(type, array, size)
127 #  define FREE(array)
128 #endif
129
130 EXTERN(uch, inbuf);                             /* input buffer */
131 EXTERN(uch, outbuf);                    /* output buffer */
132 EXTERN(ush, d_buf);                             /* buffer for distances, see trees.c */
133 EXTERN(uch, window);                    /* Sliding window and suffix table (unlzw) */
134 #define tab_suffix window
135 #ifndef MAXSEG_64K
136 #  define tab_prefix prev               /* hash link (see deflate.c) */
137 #  define head (prev+WSIZE)             /* hash head (see deflate.c) */
138 EXTERN(ush, tab_prefix);                /* prefix code (see unlzw.c) */
139 #else
140 #  define tab_prefix0 prev
141 #  define head tab_prefix1
142 EXTERN(ush, tab_prefix0);               /* prefix for even codes */
143 EXTERN(ush, tab_prefix1);               /* prefix for odd  codes */
144 #endif
145
146 extern unsigned insize;                 /* valid bytes in inbuf */
147 static unsigned inptr;                  /* index of next byte to be processed in inbuf */
148 extern unsigned outcnt;                 /* bytes in output buffer */
149
150 extern long bytes_in;                   /* number of input bytes */
151 extern long bytes_out;                  /* number of output bytes */
152 extern long header_bytes;               /* number of bytes in gzip header */
153
154 #define isize bytes_in
155 /* for compatibility with old zip sources (to be cleaned) */
156
157 extern int ifd;                                 /* input file descriptor */
158 extern int ofd;                                 /* output file descriptor */
159 extern char ifname[];                   /* input file name or "stdin" */
160 extern char ofname[];                   /* output file name or "stdout" */
161 extern char *progname;                  /* program name */
162
163 extern long time_stamp;                 /* original time stamp (modification time) */
164 extern long ifile_size;                 /* input file size, -1 for devices (debug only) */
165
166 typedef int file_t;                             /* Do not use stdio */
167
168 #define NO_FILE  (-1)                   /* in memory compression */
169
170
171 #define PACK_MAGIC     "\037\036"       /* Magic header for packed files */
172 #define GZIP_MAGIC     "\037\213"       /* Magic header for gzip files, 1F 8B */
173 #define OLD_GZIP_MAGIC "\037\236"       /* Magic header for gzip 0.5 = freeze 1.x */
174 #define LZH_MAGIC      "\037\240"       /* Magic header for SCO LZH Compress files */
175 #define PKZIP_MAGIC    "\120\113\003\004"       /* Magic header for pkzip files */
176
177 /* gzip flag byte */
178 #define ASCII_FLAG   0x01               /* bit 0 set: file probably ascii text */
179 #define CONTINUATION 0x02               /* bit 1 set: continuation of multi-part gzip file */
180 #define EXTRA_FIELD  0x04               /* bit 2 set: extra field present */
181 #define ORIG_NAME    0x08               /* bit 3 set: original file name present */
182 #define COMMENT      0x10               /* bit 4 set: file comment present */
183 #define ENCRYPTED    0x20               /* bit 5 set: file is encrypted */
184 #define RESERVED     0xC0               /* bit 6,7:   reserved */
185
186 /* internal file attribute */
187 #define UNKNOWN 0xffff
188 #define BINARY  0
189 #define ASCII   1
190
191 #ifndef WSIZE
192 #  define WSIZE 0x8000                  /* window size--must be a power of two, and */
193 #endif                                                  /*  at least 32K for zip's deflate method */
194
195 #define MIN_MATCH  3
196 #define MAX_MATCH  258
197 /* The minimum and maximum match lengths */
198
199 #define MIN_LOOKAHEAD (MAX_MATCH+MIN_MATCH+1)
200 /* Minimum amount of lookahead, except at the end of the input file.
201  * See deflate.c for comments about the MIN_MATCH+1.
202  */
203
204 #define MAX_DIST  (WSIZE-MIN_LOOKAHEAD)
205 /* In order to simplify the code, particularly on 16 bit machines, match
206  * distances are limited to MAX_DIST instead of WSIZE.
207  */
208
209 extern int decrypt;                             /* flag to turn on decryption */
210 extern int exit_code;                   /* program exit code */
211 extern int verbose;                             /* be verbose (-v) */
212 extern int quiet;                               /* be quiet (-q) */
213 extern int test;                                /* check .z file integrity */
214 extern int save_orig_name;              /* set if original name must be saved */
215
216 #define get_byte()  (inptr < insize ? inbuf[inptr++] : fill_inbuf(0))
217 #define try_byte()  (inptr < insize ? inbuf[inptr++] : fill_inbuf(1))
218
219 /* put_byte is used for the compressed output, put_ubyte for the
220  * uncompressed output. However unlzw() uses window for its
221  * suffix table instead of its output buffer, so it does not use put_ubyte
222  * (to be cleaned up).
223  */
224 #define put_byte(c) {outbuf[outcnt++]=(uch)(c); if (outcnt==OUTBUFSIZ)\
225    flush_outbuf();}
226 #define put_ubyte(c) {window[outcnt++]=(uch)(c); if (outcnt==WSIZE)\
227    flush_window();}
228
229 /* Output a 16 bit value, lsb first */
230 #define put_short(w) \
231 { if (outcnt < OUTBUFSIZ-2) { \
232     outbuf[outcnt++] = (uch) ((w) & 0xff); \
233     outbuf[outcnt++] = (uch) ((ush)(w) >> 8); \
234   } else { \
235     put_byte((uch)((w) & 0xff)); \
236     put_byte((uch)((ush)(w) >> 8)); \
237   } \
238 }
239
240 /* Output a 32 bit value to the bit stream, lsb first */
241 #define put_long(n) { \
242     put_short((n) & 0xffff); \
243     put_short(((ulg)(n)) >> 16); \
244 }
245
246 #define seekable()    0                 /* force sequential output */
247 #define translate_eol 0                 /* no option -a yet */
248
249 #define tolow(c)  (isupper(c) ? (c)-'A'+'a' : (c))      /* force to lower case */
250
251 /* Macros for getting two-byte and four-byte header values */
252 #define SH(p) ((ush)(uch)((p)[0]) | ((ush)(uch)((p)[1]) << 8))
253 #define LG(p) ((ulg)(SH(p)) | ((ulg)(SH((p)+2)) << 16))
254
255 /* Diagnostic functions */
256 #ifdef DEBUG
257 #  define Assert(cond,msg) {if(!(cond)) error_msg(msg);}
258 #  define Trace(x) fprintf x
259 #  define Tracev(x) {if (verbose) fprintf x ;}
260 #  define Tracevv(x) {if (verbose>1) fprintf x ;}
261 #  define Tracec(c,x) {if (verbose && (c)) fprintf x ;}
262 #  define Tracecv(c,x) {if (verbose>1 && (c)) fprintf x ;}
263 #else
264 #  define Assert(cond,msg)
265 #  define Trace(x)
266 #  define Tracev(x)
267 #  define Tracevv(x)
268 #  define Tracec(c,x)
269 #  define Tracecv(c,x)
270 #endif
271
272 #define WARN(msg) {if (!quiet) fprintf msg ; \
273                    if (exit_code == OK) exit_code = WARNING;}
274
275
276         /* in zip.c: */
277 extern int zip (int in, int out);
278 extern int file_read (char *buf, unsigned size);
279
280         /* in unzip.c */
281 extern int unzip (int in, int out);
282 extern int check_zipfile (int in);
283
284         /* in unpack.c */
285 extern int unpack (int in, int out);
286
287         /* in unlzh.c */
288 extern int unlzh (int in, int out);
289
290         /* in gzip.c */
291 RETSIGTYPE abort_gzip (void);
292
293                 /* in deflate.c */
294 void lm_init (ush * flags);
295 ulg deflate (void);
296
297                 /* in trees.c */
298 void ct_init (ush * attr, int *methodp);
299 int ct_tally (int dist, int lc);
300 ulg flush_block (char *buf, ulg stored_len, int eof);
301
302                 /* in bits.c */
303 void bi_init (file_t zipfile);
304 void send_bits (int value, int length);
305 unsigned bi_reverse (unsigned value, int length);
306 void bi_windup (void);
307 void copy_block (char *buf, unsigned len, int header);
308 extern int (*read_buf) (char *buf, unsigned size);
309
310         /* in util.c: */
311 extern int copy (int in, int out);
312 //extern ulg updcrc (uch * s, unsigned n);
313 //extern void clear_bufs (void);
314 extern int fill_inbuf (int eof_ok);
315 extern void flush_outbuf (void);
316 extern void flush_window (void);
317 //extern void write_buf (int fd, void * buf, unsigned cnt);
318 extern char *strlwr (char *s);
319 extern char *add_envopt (int *argcp, char ***argvp, char *env);
320 //extern void read_error_msg (void);
321 //extern void write_error_msg (void);
322 extern void display_ratio (long num, long den, FILE * file);
323
324         /* in inflate.c */
325 extern int inflate (void);
326
327 /* lzw.h -- define the lzw functions.
328  * Copyright (C) 1992-1993 Jean-loup Gailly.
329  * This is free software; you can redistribute it and/or modify it under the
330  * terms of the GNU General Public License, see the file COPYING.
331  */
332
333 #if !defined(OF) && defined(lint)
334 #  include "gzip.h"
335 #endif
336
337 #ifndef BITS
338 #  define BITS 16
339 #endif
340 #define INIT_BITS 9                             /* Initial number of bits per code */
341
342 #define BIT_MASK    0x1f                /* Mask for 'number of compression bits' */
343 /* Mask 0x20 is reserved to mean a fourth header byte, and 0x40 is free.
344  * It's a pity that old uncompress does not check bit 0x20. That makes
345  * extension of the format actually undesirable because old compress
346  * would just crash on the new format instead of giving a meaningful
347  * error message. It does check the number of bits, but it's more
348  * helpful to say "unsupported format, get a new version" than
349  * "can only handle 16 bits".
350  */
351
352 #define BLOCK_MODE  0x80
353 /* Block compression: if table is full and compression rate is dropping,
354  * clear the dictionary.
355  */
356
357 #define LZW_RESERVED 0x60               /* reserved bits */
358
359 #define CLEAR  256                              /* flush the dictionary */
360 #define FIRST  (CLEAR+1)                /* first free entry */
361
362 extern int maxbits;                             /* max bits per code for LZW */
363 extern int block_mode;                  /* block compress mode -C compatible with 2.0 */
364
365 /* revision.h -- define the version number
366  * Copyright (C) 1992-1993 Jean-loup Gailly.
367  * This is free software; you can redistribute it and/or modify it under the
368  * terms of the GNU General Public License, see the file COPYING.
369  */
370
371 #define VERSION "1.2.4"
372 #define PATCHLEVEL 0
373 #define REVDATE "18 Aug 93"
374
375 /* This version does not support compression into old compress format: */
376 #ifdef LZW
377 #  undef LZW
378 #endif
379
380 /* tailor.h -- target dependent definitions
381  * Copyright (C) 1992-1993 Jean-loup Gailly.
382  * This is free software; you can redistribute it and/or modify it under the
383  * terms of the GNU General Public License, see the file COPYING.
384  */
385
386 /* The target dependent definitions should be defined here only.
387  * The target dependent functions should be defined in tailor.c.
388  */
389
390
391 #if defined(__MSDOS__) && !defined(MSDOS)
392 #  define MSDOS
393 #endif
394
395 #if defined(__OS2__) && !defined(OS2)
396 #  define OS2
397 #endif
398
399 #if defined(OS2) && defined(MSDOS)      /* MS C under OS/2 */
400 #  undef MSDOS
401 #endif
402
403 #ifdef MSDOS
404 #  ifdef __GNUC__
405          /* DJGPP version 1.09+ on MS-DOS.
406           * The DJGPP 1.09 stat() function must be upgraded before gzip will
407           * fully work.
408           * No need for DIRENT, since <unistd.h> defines POSIX_SOURCE which
409           * implies DIRENT.
410           */
411 #    define near
412 #  else
413 #    define MAXSEG_64K
414 #    ifdef __TURBOC__
415 #      define NO_OFF_T
416 #      ifdef __BORLANDC__
417 #        define DIRENT
418 #      else
419 #        define NO_UTIME
420 #      endif
421 #    else                                               /* MSC */
422 #      define HAVE_SYS_UTIME_H
423 #      define NO_UTIME_H
424 #    endif
425 #  endif
426 #  define PATH_SEP2 '\\'
427 #  define PATH_SEP3 ':'
428 #  define MAX_PATH_LEN  128
429 #  define NO_MULTIPLE_DOTS
430 #  define MAX_EXT_CHARS 3
431 #  define Z_SUFFIX "z"
432 #  define NO_CHOWN
433 #  define PROTO
434 #  define STDC_HEADERS
435 #  define NO_SIZE_CHECK
436 #  define casemap(c) tolow(c)   /* Force file names to lower case */
437 #  include <io.h>
438 #  define OS_CODE  0x00
439 #  define SET_BINARY_MODE(fd) setmode(fd, O_BINARY)
440 #  if !defined(NO_ASM) && !defined(ASMV)
441 #    define ASMV
442 #  endif
443 #else
444 #  define near
445 #endif
446
447 #ifdef OS2
448 #  define PATH_SEP2 '\\'
449 #  define PATH_SEP3 ':'
450 #  define MAX_PATH_LEN  260
451 #  ifdef OS2FAT
452 #    define NO_MULTIPLE_DOTS
453 #    define MAX_EXT_CHARS 3
454 #    define Z_SUFFIX "z"
455 #    define casemap(c) tolow(c)
456 #  endif
457 #  define NO_CHOWN
458 #  define PROTO
459 #  define STDC_HEADERS
460 #  include <io.h>
461 #  define OS_CODE  0x06
462 #  define SET_BINARY_MODE(fd) setmode(fd, O_BINARY)
463 #  ifdef _MSC_VER
464 #    define HAVE_SYS_UTIME_H
465 #    define NO_UTIME_H
466 #    define MAXSEG_64K
467 #    undef near
468 #    define near _near
469 #  endif
470 #  ifdef __EMX__
471 #    define HAVE_SYS_UTIME_H
472 #    define NO_UTIME_H
473 #    define DIRENT
474 #    define EXPAND(argc,argv) \
475        {_response(&argc, &argv); _wildcard(&argc, &argv);}
476 #  endif
477 #  ifdef __BORLANDC__
478 #    define DIRENT
479 #  endif
480 #  ifdef __ZTC__
481 #    define NO_DIR
482 #    define NO_UTIME_H
483 #    include <dos.h>
484 #    define EXPAND(argc,argv) \
485        {response_expand(&argc, &argv);}
486 #  endif
487 #endif
488
489 #ifdef WIN32                                    /* Windows NT */
490 #  define HAVE_SYS_UTIME_H
491 #  define NO_UTIME_H
492 #  define PATH_SEP2 '\\'
493 #  define PATH_SEP3 ':'
494 #  define MAX_PATH_LEN  260
495 #  define NO_CHOWN
496 #  define PROTO
497 #  define STDC_HEADERS
498 #  define SET_BINARY_MODE(fd) setmode(fd, O_BINARY)
499 #  include <io.h>
500 #  include <malloc.h>
501 #  ifdef NTFAT
502 #    define NO_MULTIPLE_DOTS
503 #    define MAX_EXT_CHARS 3
504 #    define Z_SUFFIX "z"
505 #    define casemap(c) tolow(c) /* Force file names to lower case */
506 #  endif
507 #  define OS_CODE  0x0b
508 #endif
509
510 #ifdef MSDOS
511 #  ifdef __TURBOC__
512 #    include <alloc.h>
513 #    define DYN_ALLOC
514          /* Turbo C 2.0 does not accept static allocations of large arrays */
515 void *fcalloc(unsigned items, unsigned size);
516 void fcfree(void *ptr);
517 #  else                                                 /* MSC */
518 #    include <malloc.h>
519 #    define fcalloc(nitems,itemsize) halloc((long)(nitems),(itemsize))
520 #    define fcfree(ptr) hfree(ptr)
521 #  endif
522 #else
523 #  ifdef MAXSEG_64K
524 #    define fcalloc(items,size) calloc((items),(size))
525 #  else
526 #    define fcalloc(items,size) malloc((size_t)(items)*(size_t)(size))
527 #  endif
528 #  define fcfree(ptr) free(ptr)
529 #endif
530
531 #if defined(VAXC) || defined(VMS)
532 #  define PATH_SEP ']'
533 #  define PATH_SEP2 ':'
534 #  define SUFFIX_SEP ';'
535 #  define NO_MULTIPLE_DOTS
536 #  define Z_SUFFIX "-gz"
537 #  define RECORD_IO 1
538 #  define casemap(c) tolow(c)
539 #  define OS_CODE  0x02
540 #  define OPTIONS_VAR "GZIP_OPT"
541 #  define STDC_HEADERS
542 #  define NO_UTIME
543 #  define EXPAND(argc,argv) vms_expand_args(&argc,&argv);
544 #  include <file.h>
545 #  define unlink delete
546 #  ifdef VAXC
547 #    define NO_FCNTL_H
548 #    include <unixio.h>
549 #  endif
550 #endif
551
552 #ifdef AMIGA
553 #  define PATH_SEP2 ':'
554 #  define STDC_HEADERS
555 #  define OS_CODE  0x01
556 #  define ASMV
557 #  ifdef __GNUC__
558 #    define DIRENT
559 #    define HAVE_UNISTD_H
560 #  else                                                 /* SASC */
561 #    define NO_STDIN_FSTAT
562 #    define SYSDIR
563 #    define NO_SYMLINK
564 #    define NO_CHOWN
565 #    define NO_FCNTL_H
566 #    include <fcntl.h>                  /* for read() and write() */
567 #    define direct dirent
568 extern void _expand_args(int *argc, char ***argv);
569
570 #    define EXPAND(argc,argv) _expand_args(&argc,&argv);
571 #    undef  O_BINARY                    /* disable useless --ascii option */
572 #  endif
573 #endif
574
575 #if defined(ATARI) || defined(atarist)
576 #  ifndef STDC_HEADERS
577 #    define STDC_HEADERS
578 #    define HAVE_UNISTD_H
579 #    define DIRENT
580 #  endif
581 #  define ASMV
582 #  define OS_CODE  0x05
583 #  ifdef TOSFS
584 #    define PATH_SEP2 '\\'
585 #    define PATH_SEP3 ':'
586 #    define MAX_PATH_LEN  128
587 #    define NO_MULTIPLE_DOTS
588 #    define MAX_EXT_CHARS 3
589 #    define Z_SUFFIX "z"
590 #    define NO_CHOWN
591 #    define casemap(c) tolow(c) /* Force file names to lower case */
592 #    define NO_SYMLINK
593 #  endif
594 #endif
595
596 #ifdef MACOS
597 #  define PATH_SEP ':'
598 #  define DYN_ALLOC
599 #  define PROTO
600 #  define NO_STDIN_FSTAT
601 #  define NO_CHOWN
602 #  define NO_UTIME
603 #  define chmod(file, mode) (0)
604 #  define OPEN(name, flags, mode) open(name, flags)
605 #  define OS_CODE  0x07
606 #  ifdef MPW
607 #    define isatty(fd) ((fd) <= 2)
608 #  endif
609 #endif
610
611 #ifdef __50SERIES                               /* Prime/PRIMOS */
612 #  define PATH_SEP '>'
613 #  define STDC_HEADERS
614 #  define NO_MEMORY_H
615 #  define NO_UTIME_H
616 #  define NO_UTIME
617 #  define NO_CHOWN
618 #  define NO_STDIN_FSTAT
619 #  define NO_SIZE_CHECK
620 #  define NO_SYMLINK
621 #  define RECORD_IO  1
622 #  define casemap(c)  tolow(c)  /* Force file names to lower case */
623 #  define put_char(c) put_byte((c) & 0x7F)
624 #  define get_char(c) ascii2pascii(get_byte())
625 #  define OS_CODE  0x0F                 /* temporary, subject to change */
626 #  ifdef SIGTERM
627 #    undef SIGTERM                              /* We don't want a signal handler for SIGTERM */
628 #  endif
629 #endif
630
631 #if defined(pyr) && !defined(NOMEMCPY)  /* Pyramid */
632 #  define NOMEMCPY                              /* problem with overlapping copies */
633 #endif
634
635 #ifdef TOPS20
636 #  define OS_CODE  0x0a
637 #endif
638
639 #ifndef unix
640 #  define NO_ST_INO                             /* don't rely on inode numbers */
641 #endif
642
643
644         /* Common defaults */
645
646 #ifndef OS_CODE
647 #  define OS_CODE  0x03                 /* assume Unix */
648 #endif
649
650 #ifndef PATH_SEP
651 #  define PATH_SEP '/'
652 #endif
653
654 #ifndef casemap
655 #  define casemap(c) (c)
656 #endif
657
658 #ifndef OPTIONS_VAR
659 #  define OPTIONS_VAR "GZIP"
660 #endif
661
662 #ifndef Z_SUFFIX
663 #  define Z_SUFFIX ".gz"
664 #endif
665
666 #ifdef MAX_EXT_CHARS
667 #  define MAX_SUFFIX  MAX_EXT_CHARS
668 #else
669 #  define MAX_SUFFIX  30
670 #endif
671
672 #ifndef MAKE_LEGAL_NAME
673 #  ifdef NO_MULTIPLE_DOTS
674 #    define MAKE_LEGAL_NAME(name)   make_simple_name(name)
675 #  else
676 #    define MAKE_LEGAL_NAME(name)
677 #  endif
678 #endif
679
680 #ifndef MIN_PART
681 #  define MIN_PART 3
682    /* keep at least MIN_PART chars between dots in a file name. */
683 #endif
684
685 #ifndef EXPAND
686 #  define EXPAND(argc,argv)
687 #endif
688
689 #ifndef RECORD_IO
690 #  define RECORD_IO 0
691 #endif
692
693 #ifndef SET_BINARY_MODE
694 #  define SET_BINARY_MODE(fd)
695 #endif
696
697 #ifndef OPEN
698 #  define OPEN(name, flags, mode) open(name, flags, mode)
699 #endif
700
701 #ifndef get_char
702 #  define get_char() get_byte()
703 #endif
704
705 #ifndef put_char
706 #  define put_char(c) put_byte(c)
707 #endif
708
709 int crc_table_empty = 1;
710
711 /* ========================================================================
712  * Signal and error handler.
713  */
714 void abort_gzip()
715 {
716         exit(ERROR);
717 }
718
719 /* ===========================================================================
720  * Clear input and output buffers
721  */
722 static void clear_bufs(void)
723 {
724         outcnt = 0;
725         insize = inptr = 0;
726         bytes_in = bytes_out = 0L;
727 }
728
729 static void write_error_msg()
730 {
731         fprintf(stderr, "\n");
732         perror("");
733         abort_gzip();
734 }
735
736 /* ===========================================================================
737  * Does the same as write(), but also handles partial pipe writes and checks
738  * for error return.
739  */
740 static void write_buf(fd, buf, cnt)
741 int fd;
742 void * buf;
743 unsigned cnt;
744 {
745         unsigned n;
746
747         while ((n = write(fd, buf, cnt)) != cnt) {
748                 if (n == (unsigned) (-1)) {
749                         write_error_msg();
750                 }
751                 cnt -= n;
752                 buf = (void *) ((char *) buf + n);
753         }
754 }
755
756 /* ========================================================================
757  * Error handlers.
758  */
759 static void read_error_msg()
760 {
761         fprintf(stderr, "\n");
762         if (errno != 0) {
763                 perror("");
764         } else {
765                 fprintf(stderr, "unexpected end of file\n");
766         }
767         abort_gzip();
768 }
769
770 /* ===========================================================================
771  * Run a set of bytes through the crc shift register.  If s is a NULL
772  * pointer, then initialize the crc shift register contents instead.
773  * Return the current crc in either case.
774  */
775 static ulg updcrc(s, n)
776 uch *s;                                 /* pointer to bytes to pump through */
777 unsigned n;                             /* number of bytes in s[] */
778 {
779         static ulg crc = (ulg) 0xffffffffL;     /* shift register contents */
780         register ulg c;                         /* temporary variable */
781         static unsigned long crc_32_tab[256];
782         if (crc_table_empty) {
783                 unsigned long csr;      /* crc shift register */
784                 unsigned long e;      /* polynomial exclusive-or pattern */
785                 int i;                /* counter for all possible eight bit values */
786                 int k;                /* byte being shifted into crc apparatus */
787
788                 /* terms of polynomial defining this crc (except x^32): */
789                 static int p[] = {0,1,2,4,5,7,8,10,11,12,16,22,23,26};
790
791                 /* Make exclusive-or pattern from polynomial (0xedb88320) */
792                 e = 0;
793                 for (i = 0; i < sizeof(p)/sizeof(int); i++)
794                         e |= 1L << (31 - p[i]);
795
796                 /* Compute and print table of CRC's, five per line */
797                 crc_32_tab[0] = 0x00000000L;
798                 for (i = 1; i < 256; i++) {
799                         csr = i;
800                    /* The idea to initialize the register with the byte instead of
801                      * zero was stolen from Haruhiko Okumura's ar002
802                      */
803                         for (k = 8; k; k--)
804                                 csr = csr & 1 ? (csr >> 1) ^ e : csr >> 1;
805                         crc_32_tab[i]=csr;
806                 }
807         }
808
809         if (s == NULL) {
810                 c = 0xffffffffL;
811         } else {
812                 c = crc;
813                 if (n)
814                         do {
815                                 c = crc_32_tab[((int) c ^ (*s++)) & 0xff] ^ (c >> 8);
816                         } while (--n);
817         }
818         crc = c;
819         return c ^ 0xffffffffL;         /* (instead of ~c for 64-bit machines) */
820 }
821
822 /* bits.c -- output variable-length bit strings
823  * Copyright (C) 1992-1993 Jean-loup Gailly
824  * This is free software; you can redistribute it and/or modify it under the
825  * terms of the GNU General Public License, see the file COPYING.
826  */
827
828
829 /*
830  *  PURPOSE
831  *
832  *      Output variable-length bit strings. Compression can be done
833  *      to a file or to memory. (The latter is not supported in this version.)
834  *
835  *  DISCUSSION
836  *
837  *      The PKZIP "deflate" file format interprets compressed file data
838  *      as a sequence of bits.  Multi-bit strings in the file may cross
839  *      byte boundaries without restriction.
840  *
841  *      The first bit of each byte is the low-order bit.
842  *
843  *      The routines in this file allow a variable-length bit value to
844  *      be output right-to-left (useful for literal values). For
845  *      left-to-right output (useful for code strings from the tree routines),
846  *      the bits must have been reversed first with bi_reverse().
847  *
848  *      For in-memory compression, the compressed bit stream goes directly
849  *      into the requested output buffer. The input data is read in blocks
850  *      by the mem_read() function. The buffer is limited to 64K on 16 bit
851  *      machines.
852  *
853  *  INTERFACE
854  *
855  *      void bi_init (FILE *zipfile)
856  *          Initialize the bit string routines.
857  *
858  *      void send_bits (int value, int length)
859  *          Write out a bit string, taking the source bits right to
860  *          left.
861  *
862  *      int bi_reverse (int value, int length)
863  *          Reverse the bits of a bit string, taking the source bits left to
864  *          right and emitting them right to left.
865  *
866  *      void bi_windup (void)
867  *          Write out any remaining bits in an incomplete byte.
868  *
869  *      void copy_block(char *buf, unsigned len, int header)
870  *          Copy a stored block to the zip file, storing first the length and
871  *          its one's complement if requested.
872  *
873  */
874
875 #ifdef DEBUG
876 #  include <stdio.h>
877 #endif
878
879 /* ===========================================================================
880  * Local data used by the "bit string" routines.
881  */
882
883 local file_t zfile;                             /* output gzip file */
884
885 local unsigned short bi_buf;
886
887 /* Output buffer. bits are inserted starting at the bottom (least significant
888  * bits).
889  */
890
891 #define Buf_size (8 * 2*sizeof(char))
892 /* Number of bits used within bi_buf. (bi_buf might be implemented on
893  * more than 16 bits on some systems.)
894  */
895
896 local int bi_valid;
897
898 /* Number of valid bits in bi_buf.  All bits above the last valid bit
899  * are always zero.
900  */
901
902 int (*read_buf) (char *buf, unsigned size);
903
904 /* Current input function. Set to mem_read for in-memory compression */
905
906 #ifdef DEBUG
907 ulg bits_sent;                                  /* bit length of the compressed data */
908 #endif
909
910 /* ===========================================================================
911  * Initialize the bit string routines.
912  */
913 void bi_init(zipfile)
914 file_t zipfile;                                 /* output zip file, NO_FILE for in-memory compression */
915 {
916         zfile = zipfile;
917         bi_buf = 0;
918         bi_valid = 0;
919 #ifdef DEBUG
920         bits_sent = 0L;
921 #endif
922
923         /* Set the defaults for file compression. They are set by memcompress
924          * for in-memory compression.
925          */
926         if (zfile != NO_FILE) {
927                 read_buf = file_read;
928         }
929 }
930
931 /* ===========================================================================
932  * Send a value on a given number of bits.
933  * IN assertion: length <= 16 and value fits in length bits.
934  */
935 void send_bits(value, length)
936 int value;                                              /* value to send */
937 int length;                                             /* number of bits */
938 {
939 #ifdef DEBUG
940         Tracev((stderr, " l %2d v %4x ", length, value));
941         Assert(length > 0 && length <= 15, "invalid length");
942         bits_sent += (ulg) length;
943 #endif
944         /* If not enough room in bi_buf, use (valid) bits from bi_buf and
945          * (16 - bi_valid) bits from value, leaving (width - (16-bi_valid))
946          * unused bits in value.
947          */
948         if (bi_valid > (int) Buf_size - length) {
949                 bi_buf |= (value << bi_valid);
950                 put_short(bi_buf);
951                 bi_buf = (ush) value >> (Buf_size - bi_valid);
952                 bi_valid += length - Buf_size;
953         } else {
954                 bi_buf |= value << bi_valid;
955                 bi_valid += length;
956         }
957 }
958
959 /* ===========================================================================
960  * Reverse the first len bits of a code, using straightforward code (a faster
961  * method would use a table)
962  * IN assertion: 1 <= len <= 15
963  */
964 unsigned bi_reverse(code, len)
965 unsigned code;                                  /* the value to invert */
966 int len;                                                /* its bit length */
967 {
968         register unsigned res = 0;
969
970         do {
971                 res |= code & 1;
972                 code >>= 1, res <<= 1;
973         } while (--len > 0);
974         return res >> 1;
975 }
976
977 /* ===========================================================================
978  * Write out any remaining bits in an incomplete byte.
979  */
980 void bi_windup()
981 {
982         if (bi_valid > 8) {
983                 put_short(bi_buf);
984         } else if (bi_valid > 0) {
985                 put_byte(bi_buf);
986         }
987         bi_buf = 0;
988         bi_valid = 0;
989 #ifdef DEBUG
990         bits_sent = (bits_sent + 7) & ~7;
991 #endif
992 }
993
994 /* ===========================================================================
995  * Copy a stored block to the zip file, storing first the length and its
996  * one's complement if requested.
997  */
998 void copy_block(buf, len, header)
999 char *buf;                                              /* the input data */
1000 unsigned len;                                   /* its length */
1001 int header;                                             /* true if block header must be written */
1002 {
1003         bi_windup();                            /* align on byte boundary */
1004
1005         if (header) {
1006                 put_short((ush) len);
1007                 put_short((ush) ~ len);
1008 #ifdef DEBUG
1009                 bits_sent += 2 * 16;
1010 #endif
1011         }
1012 #ifdef DEBUG
1013         bits_sent += (ulg) len << 3;
1014 #endif
1015         while (len--) {
1016 #ifdef CRYPT
1017                 int t;
1018
1019                 if (key)
1020                         zencode(*buf, t);
1021 #endif
1022                 put_byte(*buf++);
1023         }
1024 }
1025
1026 /* deflate.c -- compress data using the deflation algorithm
1027  * Copyright (C) 1992-1993 Jean-loup Gailly
1028  * This is free software; you can redistribute it and/or modify it under the
1029  * terms of the GNU General Public License, see the file COPYING.
1030  */
1031
1032 /*
1033  *  PURPOSE
1034  *
1035  *      Identify new text as repetitions of old text within a fixed-
1036  *      length sliding window trailing behind the new text.
1037  *
1038  *  DISCUSSION
1039  *
1040  *      The "deflation" process depends on being able to identify portions
1041  *      of the input text which are identical to earlier input (within a
1042  *      sliding window trailing behind the input currently being processed).
1043  *
1044  *      The most straightforward technique turns out to be the fastest for
1045  *      most input files: try all possible matches and select the longest.
1046  *      The key feature of this algorithm is that insertions into the string
1047  *      dictionary are very simple and thus fast, and deletions are avoided
1048  *      completely. Insertions are performed at each input character, whereas
1049  *      string matches are performed only when the previous match ends. So it
1050  *      is preferable to spend more time in matches to allow very fast string
1051  *      insertions and avoid deletions. The matching algorithm for small
1052  *      strings is inspired from that of Rabin & Karp. A brute force approach
1053  *      is used to find longer strings when a small match has been found.
1054  *      A similar algorithm is used in comic (by Jan-Mark Wams) and freeze
1055  *      (by Leonid Broukhis).
1056  *         A previous version of this file used a more sophisticated algorithm
1057  *      (by Fiala and Greene) which is guaranteed to run in linear amortized
1058  *      time, but has a larger average cost, uses more memory and is patented.
1059  *      However the F&G algorithm may be faster for some highly redundant
1060  *      files if the parameter max_chain_length (described below) is too large.
1061  *
1062  *  ACKNOWLEDGEMENTS
1063  *
1064  *      The idea of lazy evaluation of matches is due to Jan-Mark Wams, and
1065  *      I found it in 'freeze' written by Leonid Broukhis.
1066  *      Thanks to many info-zippers for bug reports and testing.
1067  *
1068  *  REFERENCES
1069  *
1070  *      APPNOTE.TXT documentation file in PKZIP 1.93a distribution.
1071  *
1072  *      A description of the Rabin and Karp algorithm is given in the book
1073  *         "Algorithms" by R. Sedgewick, Addison-Wesley, p252.
1074  *
1075  *      Fiala,E.R., and Greene,D.H.
1076  *         Data Compression with Finite Windows, Comm.ACM, 32,4 (1989) 490-595
1077  *
1078  *  INTERFACE
1079  *
1080  *      void lm_init (int pack_level, ush *flags)
1081  *          Initialize the "longest match" routines for a new file
1082  *
1083  *      ulg deflate (void)
1084  *          Processes a new input file and return its compressed length. Sets
1085  *          the compressed length, crc, deflate flags and internal file
1086  *          attributes.
1087  */
1088
1089 #include <stdio.h>
1090
1091 /* ===========================================================================
1092  * Configuration parameters
1093  */
1094
1095 /* Compile with MEDIUM_MEM to reduce the memory requirements or
1096  * with SMALL_MEM to use as little memory as possible. Use BIG_MEM if the
1097  * entire input file can be held in memory (not possible on 16 bit systems).
1098  * Warning: defining these symbols affects HASH_BITS (see below) and thus
1099  * affects the compression ratio. The compressed output
1100  * is still correct, and might even be smaller in some cases.
1101  */
1102
1103 #ifdef SMALL_MEM
1104 #   define HASH_BITS  13                /* Number of bits used to hash strings */
1105 #endif
1106 #ifdef MEDIUM_MEM
1107 #   define HASH_BITS  14
1108 #endif
1109 #ifndef HASH_BITS
1110 #   define HASH_BITS  15
1111    /* For portability to 16 bit machines, do not use values above 15. */
1112 #endif
1113
1114 /* To save space (see unlzw.c), we overlay prev+head with tab_prefix and
1115  * window with tab_suffix. Check that we can do this:
1116  */
1117 #if (WSIZE<<1) > (1<<BITS)
1118 error:cannot overlay window with tab_suffix and prev with tab_prefix0
1119 #endif
1120 #if HASH_BITS > BITS-1
1121 error:cannot overlay head with tab_prefix1
1122 #endif
1123 #define HASH_SIZE (unsigned)(1<<HASH_BITS)
1124 #define HASH_MASK (HASH_SIZE-1)
1125 #define WMASK     (WSIZE-1)
1126 /* HASH_SIZE and WSIZE must be powers of two */
1127 #define NIL 0
1128 /* Tail of hash chains */
1129 #define FAST 4
1130 #define SLOW 2
1131 /* speed options for the general purpose bit flag */
1132 #ifndef TOO_FAR
1133 #  define TOO_FAR 4096
1134 #endif
1135 /* Matches of length 3 are discarded if their distance exceeds TOO_FAR */
1136 /* ===========================================================================
1137  * Local data used by the "longest match" routines.
1138  */
1139 typedef ush Pos;
1140 typedef unsigned IPos;
1141
1142 /* A Pos is an index in the character window. We use short instead of int to
1143  * save space in the various tables. IPos is used only for parameter passing.
1144  */
1145
1146 /* DECLARE(uch, window, 2L*WSIZE); */
1147 /* Sliding window. Input bytes are read into the second half of the window,
1148  * and move to the first half later to keep a dictionary of at least WSIZE
1149  * bytes. With this organization, matches are limited to a distance of
1150  * WSIZE-MAX_MATCH bytes, but this ensures that IO is always
1151  * performed with a length multiple of the block size. Also, it limits
1152  * the window size to 64K, which is quite useful on MSDOS.
1153  * To do: limit the window size to WSIZE+BSZ if SMALL_MEM (the code would
1154  * be less efficient).
1155  */
1156
1157 /* DECLARE(Pos, prev, WSIZE); */
1158 /* Link to older string with same hash index. To limit the size of this
1159  * array to 64K, this link is maintained only for the last 32K strings.
1160  * An index in this array is thus a window index modulo 32K.
1161  */
1162
1163 /* DECLARE(Pos, head, 1<<HASH_BITS); */
1164 /* Heads of the hash chains or NIL. */
1165
1166 ulg window_size = (ulg) 2 * WSIZE;
1167
1168 /* window size, 2*WSIZE except for MMAP or BIG_MEM, where it is the
1169  * input file length plus MIN_LOOKAHEAD.
1170  */
1171
1172 long block_start;
1173
1174 /* window position at the beginning of the current output block. Gets
1175  * negative when the window is moved backwards.
1176  */
1177
1178 local unsigned ins_h;                   /* hash index of string to be inserted */
1179
1180 #define H_SHIFT  ((HASH_BITS+MIN_MATCH-1)/MIN_MATCH)
1181 /* Number of bits by which ins_h and del_h must be shifted at each
1182  * input step. It must be such that after MIN_MATCH steps, the oldest
1183  * byte no longer takes part in the hash key, that is:
1184  *   H_SHIFT * MIN_MATCH >= HASH_BITS
1185  */
1186
1187 unsigned int near prev_length;
1188
1189 /* Length of the best match at previous step. Matches not greater than this
1190  * are discarded. This is used in the lazy match evaluation.
1191  */
1192
1193 unsigned near strstart;                 /* start of string to insert */
1194 unsigned near match_start;              /* start of matching string */
1195 local int eofile;                               /* flag set at end of input file */
1196 local unsigned lookahead;               /* number of valid bytes ahead in window */
1197
1198 unsigned near max_chain_length;
1199
1200 /* To speed up deflation, hash chains are never searched beyond this length.
1201  * A higher limit improves compression ratio but degrades the speed.
1202  */
1203
1204 local unsigned int max_lazy_match;
1205
1206 /* Attempt to find a better match only when the current match is strictly
1207  * smaller than this value. This mechanism is used only for compression
1208  * levels >= 4.
1209  */
1210 #define max_insert_length  max_lazy_match
1211 /* Insert new strings in the hash table only if the match length
1212  * is not greater than this length. This saves time but degrades compression.
1213  * max_insert_length is used only for compression levels <= 3.
1214  */
1215
1216 unsigned near good_match;
1217
1218 /* Use a faster search when the previous match is longer than this */
1219
1220
1221 /* Values for max_lazy_match, good_match and max_chain_length, depending on
1222  * the desired pack level (0..9). The values given below have been tuned to
1223  * exclude worst case performance for pathological files. Better values may be
1224  * found for specific files.
1225  */
1226
1227 typedef struct config {
1228         ush good_length;                        /* reduce lazy search above this match length */
1229         ush max_lazy;                           /* do not perform lazy search above this match length */
1230         ush nice_length;                        /* quit search above this match length */
1231         ush max_chain;
1232 } config;
1233
1234 #ifdef  FULL_SEARCH
1235 # define nice_match MAX_MATCH
1236 #else
1237 int near nice_match;                    /* Stop searching when current match exceeds this */
1238 #endif
1239
1240 local config configuration_table =
1241                                                                 /* 9 */ { 32, 258, 258, 4096 };
1242                                                                 /* maximum compression */
1243
1244 /* Note: the deflate() code requires max_lazy >= MIN_MATCH and max_chain >= 4
1245  * For deflate_fast() (levels <= 3) good is ignored and lazy has a different
1246  * meaning.
1247  */
1248
1249 #define EQUAL 0
1250 /* result of memcmp for equal strings */
1251
1252 /* ===========================================================================
1253  *  Prototypes for local functions.
1254  */
1255 local void fill_window (void);
1256
1257 int longest_match (IPos cur_match);
1258
1259 #ifdef ASMV
1260 void match_init (void);         /* asm code initialization */
1261 #endif
1262
1263 #ifdef DEBUG
1264 local void check_match (IPos start, IPos match, int length);
1265 #endif
1266
1267 /* ===========================================================================
1268  * Update a hash value with the given input byte
1269  * IN  assertion: all calls to to UPDATE_HASH are made with consecutive
1270  *    input characters, so that a running hash key can be computed from the
1271  *    previous key instead of complete recalculation each time.
1272  */
1273 #define UPDATE_HASH(h,c) (h = (((h)<<H_SHIFT) ^ (c)) & HASH_MASK)
1274
1275 /* ===========================================================================
1276  * Insert string s in the dictionary and set match_head to the previous head
1277  * of the hash chain (the most recent string with same hash key). Return
1278  * the previous length of the hash chain.
1279  * IN  assertion: all calls to to INSERT_STRING are made with consecutive
1280  *    input characters and the first MIN_MATCH bytes of s are valid
1281  *    (except for the last MIN_MATCH-1 bytes of the input file).
1282  */
1283 #define INSERT_STRING(s, match_head) \
1284    (UPDATE_HASH(ins_h, window[(s) + MIN_MATCH-1]), \
1285     prev[(s) & WMASK] = match_head = head[ins_h], \
1286     head[ins_h] = (s))
1287
1288 /* ===========================================================================
1289  * Initialize the "longest match" routines for a new file
1290  */
1291 void lm_init(flags)
1292 ush *flags;                                             /* general purpose bit flag */
1293 {
1294         register unsigned j;
1295
1296         /* Initialize the hash table. */
1297 #if defined(MAXSEG_64K) && HASH_BITS == 15
1298         for (j = 0; j < HASH_SIZE; j++)
1299                 head[j] = NIL;
1300 #else
1301         memzero((char *) head, HASH_SIZE * sizeof(*head));
1302 #endif
1303         /* prev will be initialized on the fly */
1304
1305         /* Set the default configuration parameters:
1306          */
1307         max_lazy_match = configuration_table.max_lazy;
1308         good_match = configuration_table.good_length;
1309 #ifndef FULL_SEARCH
1310         nice_match = configuration_table.nice_length;
1311 #endif
1312         max_chain_length = configuration_table.max_chain;
1313         *flags |= SLOW;
1314         /* ??? reduce max_chain_length for binary files */
1315
1316         strstart = 0;
1317         block_start = 0L;
1318 #ifdef ASMV
1319         match_init();                           /* initialize the asm code */
1320 #endif
1321
1322         lookahead = read_buf((char *) window,
1323                                                  sizeof(int) <= 2 ? (unsigned) WSIZE : 2 * WSIZE);
1324
1325         if (lookahead == 0 || lookahead == (unsigned) EOF) {
1326                 eofile = 1, lookahead = 0;
1327                 return;
1328         }
1329         eofile = 0;
1330         /* Make sure that we always have enough lookahead. This is important
1331          * if input comes from a device such as a tty.
1332          */
1333         while (lookahead < MIN_LOOKAHEAD && !eofile)
1334                 fill_window();
1335
1336         ins_h = 0;
1337         for (j = 0; j < MIN_MATCH - 1; j++)
1338                 UPDATE_HASH(ins_h, window[j]);
1339         /* If lookahead < MIN_MATCH, ins_h is garbage, but this is
1340          * not important since only literal bytes will be emitted.
1341          */
1342 }
1343
1344 /* ===========================================================================
1345  * Set match_start to the longest match starting at the given string and
1346  * return its length. Matches shorter or equal to prev_length are discarded,
1347  * in which case the result is equal to prev_length and match_start is
1348  * garbage.
1349  * IN assertions: cur_match is the head of the hash chain for the current
1350  *   string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1
1351  */
1352 #ifndef ASMV
1353 /* For MSDOS, OS/2 and 386 Unix, an optimized version is in match.asm or
1354  * match.s. The code is functionally equivalent, so you can use the C version
1355  * if desired.
1356  */
1357 int longest_match(cur_match)
1358 IPos cur_match;                                 /* current match */
1359 {
1360         unsigned chain_length = max_chain_length;       /* max hash chain length */
1361         register uch *scan = window + strstart; /* current string */
1362         register uch *match;            /* matched string */
1363         register int len;                       /* length of current match */
1364         int best_len = prev_length;     /* best match length so far */
1365         IPos limit =
1366
1367                 strstart > (IPos) MAX_DIST ? strstart - (IPos) MAX_DIST : NIL;
1368         /* Stop when cur_match becomes <= limit. To simplify the code,
1369          * we prevent matches with the string of window index 0.
1370          */
1371
1372 /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
1373  * It is easy to get rid of this optimization if necessary.
1374  */
1375 #if HASH_BITS < 8 || MAX_MATCH != 258
1376   error:Code too clever
1377 #endif
1378 #ifdef UNALIGNED_OK
1379                 /* Compare two bytes at a time. Note: this is not always beneficial.
1380                  * Try with and without -DUNALIGNED_OK to check.
1381                  */
1382         register uch *strend = window + strstart + MAX_MATCH - 1;
1383         register ush scan_start = *(ush *) scan;
1384         register ush scan_end = *(ush *) (scan + best_len - 1);
1385 #else
1386         register uch *strend = window + strstart + MAX_MATCH;
1387         register uch scan_end1 = scan[best_len - 1];
1388         register uch scan_end = scan[best_len];
1389 #endif
1390
1391         /* Do not waste too much time if we already have a good match: */
1392         if (prev_length >= good_match) {
1393                 chain_length >>= 2;
1394         }
1395         Assert(strstart <= window_size - MIN_LOOKAHEAD,
1396                    "insufficient lookahead");
1397
1398         do {
1399                 Assert(cur_match < strstart, "no future");
1400                 match = window + cur_match;
1401
1402                 /* Skip to next match if the match length cannot increase
1403                  * or if the match length is less than 2:
1404                  */
1405 #if (defined(UNALIGNED_OK) && MAX_MATCH == 258)
1406                 /* This code assumes sizeof(unsigned short) == 2. Do not use
1407                  * UNALIGNED_OK if your compiler uses a different size.
1408                  */
1409                 if (*(ush *) (match + best_len - 1) != scan_end ||
1410                         *(ush *) match != scan_start)
1411                         continue;
1412
1413                 /* It is not necessary to compare scan[2] and match[2] since they are
1414                  * always equal when the other bytes match, given that the hash keys
1415                  * are equal and that HASH_BITS >= 8. Compare 2 bytes at a time at
1416                  * strstart+3, +5, ... up to strstart+257. We check for insufficient
1417                  * lookahead only every 4th comparison; the 128th check will be made
1418                  * at strstart+257. If MAX_MATCH-2 is not a multiple of 8, it is
1419                  * necessary to put more guard bytes at the end of the window, or
1420                  * to check more often for insufficient lookahead.
1421                  */
1422                 scan++, match++;
1423                 do {
1424                 } while (*(ush *) (scan += 2) == *(ush *) (match += 2) &&
1425                                  *(ush *) (scan += 2) == *(ush *) (match += 2) &&
1426                                  *(ush *) (scan += 2) == *(ush *) (match += 2) &&
1427                                  *(ush *) (scan += 2) == *(ush *) (match += 2) &&
1428                                  scan < strend);
1429                 /* The funny "do {}" generates better code on most compilers */
1430
1431                 /* Here, scan <= window+strstart+257 */
1432                 Assert(scan <= window + (unsigned) (window_size - 1), "wild scan");
1433                 if (*scan == *match)
1434                         scan++;
1435
1436                 len = (MAX_MATCH - 1) - (int) (strend - scan);
1437                 scan = strend - (MAX_MATCH - 1);
1438
1439 #else                                                   /* UNALIGNED_OK */
1440
1441                 if (match[best_len] != scan_end ||
1442                         match[best_len - 1] != scan_end1 ||
1443                         *match != *scan || *++match != scan[1])
1444                         continue;
1445
1446                 /* The check at best_len-1 can be removed because it will be made
1447                  * again later. (This heuristic is not always a win.)
1448                  * It is not necessary to compare scan[2] and match[2] since they
1449                  * are always equal when the other bytes match, given that
1450                  * the hash keys are equal and that HASH_BITS >= 8.
1451                  */
1452                 scan += 2, match++;
1453
1454                 /* We check for insufficient lookahead only every 8th comparison;
1455                  * the 256th check will be made at strstart+258.
1456                  */
1457                 do {
1458                 } while (*++scan == *++match && *++scan == *++match &&
1459                                  *++scan == *++match && *++scan == *++match &&
1460                                  *++scan == *++match && *++scan == *++match &&
1461                                  *++scan == *++match && *++scan == *++match &&
1462                                  scan < strend);
1463
1464                 len = MAX_MATCH - (int) (strend - scan);
1465                 scan = strend - MAX_MATCH;
1466
1467 #endif                                                  /* UNALIGNED_OK */
1468
1469                 if (len > best_len) {
1470                         match_start = cur_match;
1471                         best_len = len;
1472                         if (len >= nice_match)
1473                                 break;
1474 #ifdef UNALIGNED_OK
1475                         scan_end = *(ush *) (scan + best_len - 1);
1476 #else
1477                         scan_end1 = scan[best_len - 1];
1478                         scan_end = scan[best_len];
1479 #endif
1480                 }
1481         } while ((cur_match = prev[cur_match & WMASK]) > limit
1482                          && --chain_length != 0);
1483
1484         return best_len;
1485 }
1486 #endif                                                  /* ASMV */
1487
1488 #ifdef DEBUG
1489 /* ===========================================================================
1490  * Check that the match at match_start is indeed a match.
1491  */
1492 local void check_match(start, match, length)
1493 IPos start, match;
1494 int length;
1495 {
1496         /* check that the match is indeed a match */
1497         if (memcmp((char *) window + match,
1498                            (char *) window + start, length) != EQUAL) {
1499                 fprintf(stderr,
1500                                 " start %d, match %d, length %d\n", start, match, length);
1501                 error_msg("invalid match");
1502         }
1503         if (verbose > 1) {
1504                 fprintf(stderr, "\\[%d,%d]", start - match, length);
1505                 do {
1506                         putc(window[start++], stderr);
1507                 } while (--length != 0);
1508         }
1509 }
1510 #else
1511 #  define check_match(start, match, length)
1512 #endif
1513
1514 /* ===========================================================================
1515  * Fill the window when the lookahead becomes insufficient.
1516  * Updates strstart and lookahead, and sets eofile if end of input file.
1517  * IN assertion: lookahead < MIN_LOOKAHEAD && strstart + lookahead > 0
1518  * OUT assertions: at least one byte has been read, or eofile is set;
1519  *    file reads are performed for at least two bytes (required for the
1520  *    translate_eol option).
1521  */
1522 local void fill_window()
1523 {
1524         register unsigned n, m;
1525         unsigned more =
1526
1527                 (unsigned) (window_size - (ulg) lookahead - (ulg) strstart);
1528         /* Amount of free space at the end of the window. */
1529
1530         /* If the window is almost full and there is insufficient lookahead,
1531          * move the upper half to the lower one to make room in the upper half.
1532          */
1533         if (more == (unsigned) EOF) {
1534                 /* Very unlikely, but possible on 16 bit machine if strstart == 0
1535                  * and lookahead == 1 (input done one byte at time)
1536                  */
1537                 more--;
1538         } else if (strstart >= WSIZE + MAX_DIST) {
1539                 /* By the IN assertion, the window is not empty so we can't confuse
1540                  * more == 0 with more == 64K on a 16 bit machine.
1541                  */
1542                 Assert(window_size == (ulg) 2 * WSIZE, "no sliding with BIG_MEM");
1543
1544                 memcpy((char *) window, (char *) window + WSIZE, (unsigned) WSIZE);
1545                 match_start -= WSIZE;
1546                 strstart -= WSIZE;              /* we now have strstart >= MAX_DIST: */
1547
1548                 block_start -= (long) WSIZE;
1549
1550                 for (n = 0; n < HASH_SIZE; n++) {
1551                         m = head[n];
1552                         head[n] = (Pos) (m >= WSIZE ? m - WSIZE : NIL);
1553                 }
1554                 for (n = 0; n < WSIZE; n++) {
1555                         m = prev[n];
1556                         prev[n] = (Pos) (m >= WSIZE ? m - WSIZE : NIL);
1557                         /* If n is not on any hash chain, prev[n] is garbage but
1558                          * its value will never be used.
1559                          */
1560                 }
1561                 more += WSIZE;
1562         }
1563         /* At this point, more >= 2 */
1564         if (!eofile) {
1565                 n = read_buf((char *) window + strstart + lookahead, more);
1566                 if (n == 0 || n == (unsigned) EOF) {
1567                         eofile = 1;
1568                 } else {
1569                         lookahead += n;
1570                 }
1571         }
1572 }
1573
1574 /* ===========================================================================
1575  * Flush the current block, with given end-of-file flag.
1576  * IN assertion: strstart is set to the end of the current match.
1577  */
1578 #define FLUSH_BLOCK(eof) \
1579    flush_block(block_start >= 0L ? (char*)&window[(unsigned)block_start] : \
1580                 (char*)NULL, (long)strstart - block_start, (eof))
1581
1582 /* ===========================================================================
1583  * Same as above, but achieves better compression. We use a lazy
1584  * evaluation for matches: a match is finally adopted only if there is
1585  * no better match at the next window position.
1586  */
1587 ulg deflate()
1588 {
1589         IPos hash_head;                         /* head of hash chain */
1590         IPos prev_match;                        /* previous match */
1591         int flush;                                      /* set if current block must be flushed */
1592         int match_available = 0;        /* set if previous match exists */
1593         register unsigned match_length = MIN_MATCH - 1; /* length of best match */
1594
1595 #ifdef DEBUG
1596         extern long isize;                      /* byte length of input file, for debug only */
1597 #endif
1598
1599         /* Process the input block. */
1600         while (lookahead != 0) {
1601                 /* Insert the string window[strstart .. strstart+2] in the
1602                  * dictionary, and set hash_head to the head of the hash chain:
1603                  */
1604                 INSERT_STRING(strstart, hash_head);
1605
1606                 /* Find the longest match, discarding those <= prev_length.
1607                  */
1608                 prev_length = match_length, prev_match = match_start;
1609                 match_length = MIN_MATCH - 1;
1610
1611                 if (hash_head != NIL && prev_length < max_lazy_match &&
1612                         strstart - hash_head <= MAX_DIST) {
1613                         /* To simplify the code, we prevent matches with the string
1614                          * of window index 0 (in particular we have to avoid a match
1615                          * of the string with itself at the start of the input file).
1616                          */
1617                         match_length = longest_match(hash_head);
1618                         /* longest_match() sets match_start */
1619                         if (match_length > lookahead)
1620                                 match_length = lookahead;
1621
1622                         /* Ignore a length 3 match if it is too distant: */
1623                         if (match_length == MIN_MATCH
1624                                 && strstart - match_start > TOO_FAR) {
1625                                 /* If prev_match is also MIN_MATCH, match_start is garbage
1626                                  * but we will ignore the current match anyway.
1627                                  */
1628                                 match_length--;
1629                         }
1630                 }
1631                 /* If there was a match at the previous step and the current
1632                  * match is not better, output the previous match:
1633                  */
1634                 if (prev_length >= MIN_MATCH && match_length <= prev_length) {
1635
1636                         check_match(strstart - 1, prev_match, prev_length);
1637
1638                         flush =
1639                                 ct_tally(strstart - 1 - prev_match,
1640                                                  prev_length - MIN_MATCH);
1641
1642                         /* Insert in hash table all strings up to the end of the match.
1643                          * strstart-1 and strstart are already inserted.
1644                          */
1645                         lookahead -= prev_length - 1;
1646                         prev_length -= 2;
1647                         do {
1648                                 strstart++;
1649                                 INSERT_STRING(strstart, hash_head);
1650                                 /* strstart never exceeds WSIZE-MAX_MATCH, so there are
1651                                  * always MIN_MATCH bytes ahead. If lookahead < MIN_MATCH
1652                                  * these bytes are garbage, but it does not matter since the
1653                                  * next lookahead bytes will always be emitted as literals.
1654                                  */
1655                         } while (--prev_length != 0);
1656                         match_available = 0;
1657                         match_length = MIN_MATCH - 1;
1658                         strstart++;
1659                         if (flush)
1660                                 FLUSH_BLOCK(0), block_start = strstart;
1661
1662                 } else if (match_available) {
1663                         /* If there was no match at the previous position, output a
1664                          * single literal. If there was a match but the current match
1665                          * is longer, truncate the previous match to a single literal.
1666                          */
1667                         Tracevv((stderr, "%c", window[strstart - 1]));
1668                         if (ct_tally(0, window[strstart - 1])) {
1669                                 FLUSH_BLOCK(0), block_start = strstart;
1670                         }
1671                         strstart++;
1672                         lookahead--;
1673                 } else {
1674                         /* There is no previous match to compare with, wait for
1675                          * the next step to decide.
1676                          */
1677                         match_available = 1;
1678                         strstart++;
1679                         lookahead--;
1680                 }
1681                 Assert(strstart <= isize && lookahead <= isize, "a bit too far");
1682
1683                 /* Make sure that we always have enough lookahead, except
1684                  * at the end of the input file. We need MAX_MATCH bytes
1685                  * for the next match, plus MIN_MATCH bytes to insert the
1686                  * string following the next match.
1687                  */
1688                 while (lookahead < MIN_LOOKAHEAD && !eofile)
1689                         fill_window();
1690         }
1691         if (match_available)
1692                 ct_tally(0, window[strstart - 1]);
1693
1694         return FLUSH_BLOCK(1);          /* eof */
1695 }
1696
1697 /* gzip (GNU zip) -- compress files with zip algorithm and 'compress' interface
1698  * Copyright (C) 1992-1993 Jean-loup Gailly
1699  * The unzip code was written and put in the public domain by Mark Adler.
1700  * Portions of the lzw code are derived from the public domain 'compress'
1701  * written by Spencer Thomas, Joe Orost, James Woods, Jim McKie, Steve Davies,
1702  * Ken Turkowski, Dave Mack and Peter Jannesen.
1703  *
1704  * See the license_msg below and the file COPYING for the software license.
1705  * See the file algorithm.doc for the compression algorithms and file formats.
1706  */
1707
1708 /* Compress files with zip algorithm and 'compress' interface.
1709  * See usage() and help() functions below for all options.
1710  * Outputs:
1711  *        file.gz:   compressed file with same mode, owner, and utimes
1712  *     or stdout with -c option or if stdin used as input.
1713  * If the output file name had to be truncated, the original name is kept
1714  * in the compressed file.
1715  * On MSDOS, file.tmp -> file.tmz. On VMS, file.tmp -> file.tmp-gz.
1716  *
1717  * Using gz on MSDOS would create too many file name conflicts. For
1718  * example, foo.txt -> foo.tgz (.tgz must be reserved as shorthand for
1719  * tar.gz). Similarly, foo.dir and foo.doc would both be mapped to foo.dgz.
1720  * I also considered 12345678.txt -> 12345txt.gz but this truncates the name
1721  * too heavily. There is no ideal solution given the MSDOS 8+3 limitation. 
1722  *
1723  * For the meaning of all compilation flags, see comments in Makefile.in.
1724  */
1725
1726 #include <ctype.h>
1727 #include <sys/types.h>
1728 #include <signal.h>
1729 #include <errno.h>
1730
1731                 /* configuration */
1732
1733 #ifdef NO_TIME_H
1734 #  include <sys/time.h>
1735 #else
1736 #  include <time.h>
1737 #endif
1738
1739 #ifndef NO_FCNTL_H
1740 #  include <fcntl.h>
1741 #endif
1742
1743 #ifdef HAVE_UNISTD_H
1744 #  include <unistd.h>
1745 #endif
1746
1747 #if defined(DIRENT)
1748 #  include <dirent.h>
1749 typedef struct dirent dir_type;
1750
1751 #  define NLENGTH(dirent) ((int)strlen((dirent)->d_name))
1752 #  define DIR_OPT "DIRENT"
1753 #else
1754 #  define NLENGTH(dirent) ((dirent)->d_namlen)
1755 #  ifdef SYSDIR
1756 #    include <sys/dir.h>
1757 typedef struct direct dir_type;
1758
1759 #    define DIR_OPT "SYSDIR"
1760 #  else
1761 #    ifdef SYSNDIR
1762 #      include <sys/ndir.h>
1763 typedef struct direct dir_type;
1764
1765 #      define DIR_OPT "SYSNDIR"
1766 #    else
1767 #      ifdef NDIR
1768 #        include <ndir.h>
1769 typedef struct direct dir_type;
1770
1771 #        define DIR_OPT "NDIR"
1772 #      else
1773 #        define NO_DIR
1774 #        define DIR_OPT "NO_DIR"
1775 #      endif
1776 #    endif
1777 #  endif
1778 #endif
1779
1780 #ifndef NO_UTIME
1781 #  ifndef NO_UTIME_H
1782 #    include <utime.h>
1783 #    define TIME_OPT "UTIME"
1784 #  else
1785 #    ifdef HAVE_SYS_UTIME_H
1786 #      include <sys/utime.h>
1787 #      define TIME_OPT "SYS_UTIME"
1788 #    else
1789 struct utimbuf {
1790         time_t actime;
1791         time_t modtime;
1792 };
1793
1794 #      define TIME_OPT ""
1795 #    endif
1796 #  endif
1797 #else
1798 #  define TIME_OPT "NO_UTIME"
1799 #endif
1800
1801 #if !defined(S_ISDIR) && defined(S_IFDIR)
1802 #  define S_ISDIR(m) (((m) & S_IFMT) == S_IFDIR)
1803 #endif
1804 #if !defined(S_ISREG) && defined(S_IFREG)
1805 #  define S_ISREG(m) (((m) & S_IFMT) == S_IFREG)
1806 #endif
1807
1808 typedef RETSIGTYPE(*sig_type) (int);
1809
1810 #ifndef O_BINARY
1811 #  define  O_BINARY  0                  /* creation mode for open() */
1812 #endif
1813
1814 #ifndef O_CREAT
1815    /* Pure BSD system? */
1816 #  include <sys/file.h>
1817 #  ifndef O_CREAT
1818 #    define O_CREAT FCREAT
1819 #  endif
1820 #  ifndef O_EXCL
1821 #    define O_EXCL FEXCL
1822 #  endif
1823 #endif
1824
1825 #ifndef S_IRUSR
1826 #  define S_IRUSR 0400
1827 #endif
1828 #ifndef S_IWUSR
1829 #  define S_IWUSR 0200
1830 #endif
1831 #define RW_USER (S_IRUSR | S_IWUSR)     /* creation mode for open() */
1832
1833 #ifndef MAX_PATH_LEN
1834 #  define MAX_PATH_LEN   1024   /* max pathname length */
1835 #endif
1836
1837 #ifndef SEEK_END
1838 #  define SEEK_END 2
1839 #endif
1840
1841 #ifdef NO_OFF_T
1842 typedef long off_t;
1843 off_t lseek (int fd, off_t offset, int whence);
1844 #endif
1845
1846 /* Separator for file name parts (see shorten_name()) */
1847 #ifdef NO_MULTIPLE_DOTS
1848 #  define PART_SEP "-"
1849 #else
1850 #  define PART_SEP "."
1851 #endif
1852
1853                 /* global buffers */
1854
1855 DECLARE(uch, inbuf, INBUFSIZ + INBUF_EXTRA);
1856 DECLARE(uch, outbuf, OUTBUFSIZ + OUTBUF_EXTRA);
1857 DECLARE(ush, d_buf, DIST_BUFSIZE);
1858 DECLARE(uch, window, 2L * WSIZE);
1859 #ifndef MAXSEG_64K
1860 DECLARE(ush, tab_prefix, 1L << BITS);
1861 #else
1862 DECLARE(ush, tab_prefix0, 1L << (BITS - 1));
1863 DECLARE(ush, tab_prefix1, 1L << (BITS - 1));
1864 #endif
1865
1866                 /* local variables */
1867
1868 static int foreground;                                  /* set if program run in foreground */
1869 static int method = DEFLATED;   /* compression method */
1870 static int exit_code = OK;              /* program exit code */
1871 static int part_nb;                                     /* number of parts in .gz file */
1872 static long time_stamp;                         /* original time stamp (modification time) */
1873 static long ifile_size;                         /* input file size, -1 for devices (debug only) */
1874 static char z_suffix[MAX_SUFFIX + 1];   /* default suffix (can be set with --suffix) */
1875 static int z_len;                                               /* strlen(z_suffix) */
1876
1877 static long bytes_in;                                   /* number of input bytes */
1878 static long bytes_out;                                  /* number of output bytes */
1879 static char ifname[MAX_PATH_LEN];               /* input file name */
1880 static char ofname[MAX_PATH_LEN];               /* output file name */
1881 static int ifd;                                         /* input file descriptor */
1882 static int ofd;                                         /* output file descriptor */
1883 static unsigned insize;                         /* valid bytes in inbuf */
1884 static unsigned outcnt;                         /* bytes in output buffer */
1885
1886 /* local functions */
1887
1888 #define strequ(s1, s2) (strcmp((s1),(s2)) == 0)
1889
1890 /* ======================================================================== */
1891 // int main (argc, argv)
1892 //    int argc;
1893 //    char **argv;
1894 int gzip_main(int argc, char **argv)
1895 {
1896         int result;
1897         int inFileNum;
1898         int outFileNum;
1899         struct stat statBuf;
1900         char *delFileName;
1901         int tostdout = 0;
1902         int fromstdin = 0;
1903         int force = 0;
1904
1905         /* Parse any options */
1906         while (--argc > 0 && **(++argv) == '-') {
1907                 if (*((*argv) + 1) == '\0') {
1908                         tostdout = 1;
1909                 }
1910                 while (*(++(*argv))) {
1911                         switch (**argv) {
1912                         case 'c':
1913                                 tostdout = 1;
1914                                 break;
1915                         case 'f':
1916                                 force = 1;
1917                                 break;
1918                         /* Ignore 1-9 (compression level) options */
1919                         case '1': case '2': case '3': case '4': case '5':
1920                         case '6': case '7': case '8': case '9':
1921                                 break;
1922                         case 'd':
1923                                 exit(gunzip_main(argc, argv));
1924                         default:
1925                                 show_usage();
1926                         }
1927                 }
1928         }
1929         if (argc <= 0 ) {
1930                 fromstdin = 1;
1931                 tostdout = 1;
1932         }
1933
1934         if (isatty(fileno(stdin)) && fromstdin==1 && force==0)
1935                 error_msg_and_die( "data not read from terminal. Use -f to force it.");
1936         if (isatty(fileno(stdout)) && tostdout==1 && force==0)
1937                 error_msg_and_die( "data not written to terminal. Use -f to force it.");
1938
1939         foreground = signal(SIGINT, SIG_IGN) != SIG_IGN;
1940         if (foreground) {
1941                 (void) signal(SIGINT, (sig_type) abort_gzip);
1942         }
1943 #ifdef SIGTERM
1944         if (signal(SIGTERM, SIG_IGN) != SIG_IGN) {
1945                 (void) signal(SIGTERM, (sig_type) abort_gzip);
1946         }
1947 #endif
1948 #ifdef SIGHUP
1949         if (signal(SIGHUP, SIG_IGN) != SIG_IGN) {
1950                 (void) signal(SIGHUP, (sig_type) abort_gzip);
1951         }
1952 #endif
1953
1954         strncpy(z_suffix, Z_SUFFIX, sizeof(z_suffix) - 1);
1955         z_len = strlen(z_suffix);
1956
1957         /* Allocate all global buffers (for DYN_ALLOC option) */
1958         ALLOC(uch, inbuf, INBUFSIZ + INBUF_EXTRA);
1959         ALLOC(uch, outbuf, OUTBUFSIZ + OUTBUF_EXTRA);
1960         ALLOC(ush, d_buf, DIST_BUFSIZE);
1961         ALLOC(uch, window, 2L * WSIZE);
1962 #ifndef MAXSEG_64K
1963         ALLOC(ush, tab_prefix, 1L << BITS);
1964 #else
1965         ALLOC(ush, tab_prefix0, 1L << (BITS - 1));
1966         ALLOC(ush, tab_prefix1, 1L << (BITS - 1));
1967 #endif
1968
1969         if (fromstdin == 1) {
1970                 strcpy(ofname, "stdin");
1971
1972                 inFileNum = fileno(stdin);
1973                 time_stamp = 0;                 /* time unknown by default */
1974                 ifile_size = -1L;               /* convention for unknown size */
1975         } else {
1976                 /* Open up the input file */
1977                 if (argc <= 0)
1978                         show_usage();
1979                 strncpy(ifname, *argv, MAX_PATH_LEN);
1980
1981                 /* Open input file */
1982                 inFileNum = open(ifname, O_RDONLY);
1983                 if (inFileNum < 0)
1984                         perror_msg_and_die("%s", ifname);
1985                 /* Get the time stamp on the input file. */
1986                 if (stat(ifname, &statBuf) < 0)
1987                         perror_msg_and_die("%s", ifname);
1988                 time_stamp = statBuf.st_ctime;
1989                 ifile_size = statBuf.st_size;
1990         }
1991
1992
1993         if (tostdout == 1) {
1994                 /* And get to work */
1995                 strcpy(ofname, "stdout");
1996                 outFileNum = fileno(stdout);
1997                 SET_BINARY_MODE(fileno(stdout));
1998
1999                 clear_bufs();                   /* clear input and output buffers */
2000                 part_nb = 0;
2001
2002                 /* Actually do the compression/decompression. */
2003                 zip(inFileNum, outFileNum);
2004
2005         } else {
2006
2007                 /* And get to work */
2008                 strncpy(ofname, ifname, MAX_PATH_LEN - 4);
2009                 strcat(ofname, ".gz");
2010
2011
2012                 /* Open output fille */
2013 #if (__GLIBC__ >= 2) && (__GLIBC_MINOR__ >= 1)
2014                 outFileNum = open(ofname, O_RDWR | O_CREAT | O_EXCL | O_NOFOLLOW);
2015 #else
2016                 outFileNum = open(ofname, O_RDWR | O_CREAT | O_EXCL);
2017 #endif
2018                 if (outFileNum < 0)
2019                         perror_msg_and_die("%s", ofname);
2020                 SET_BINARY_MODE(outFileNum);
2021                 /* Set permissions on the file */
2022                 fchmod(outFileNum, statBuf.st_mode);
2023
2024                 clear_bufs();                   /* clear input and output buffers */
2025                 part_nb = 0;
2026
2027                 /* Actually do the compression/decompression. */
2028                 result = zip(inFileNum, outFileNum);
2029                 close(outFileNum);
2030                 close(inFileNum);
2031                 /* Delete the original file */
2032                 if (result == OK)
2033                         delFileName = ifname;
2034                 else
2035                         delFileName = ofname;
2036
2037                 if (unlink(delFileName) < 0)
2038                         perror_msg_and_die("%s", delFileName);
2039         }
2040
2041         return(exit_code);
2042 }
2043
2044 /* trees.c -- output deflated data using Huffman coding
2045  * Copyright (C) 1992-1993 Jean-loup Gailly
2046  * This is free software; you can redistribute it and/or modify it under the
2047  * terms of the GNU General Public License, see the file COPYING.
2048  */
2049
2050 /*
2051  *  PURPOSE
2052  *
2053  *      Encode various sets of source values using variable-length
2054  *      binary code trees.
2055  *
2056  *  DISCUSSION
2057  *
2058  *      The PKZIP "deflation" process uses several Huffman trees. The more
2059  *      common source values are represented by shorter bit sequences.
2060  *
2061  *      Each code tree is stored in the ZIP file in a compressed form
2062  *      which is itself a Huffman encoding of the lengths of
2063  *      all the code strings (in ascending order by source values).
2064  *      The actual code strings are reconstructed from the lengths in
2065  *      the UNZIP process, as described in the "application note"
2066  *      (APPNOTE.TXT) distributed as part of PKWARE's PKZIP program.
2067  *
2068  *  REFERENCES
2069  *
2070  *      Lynch, Thomas J.
2071  *          Data Compression:  Techniques and Applications, pp. 53-55.
2072  *          Lifetime Learning Publications, 1985.  ISBN 0-534-03418-7.
2073  *
2074  *      Storer, James A.
2075  *          Data Compression:  Methods and Theory, pp. 49-50.
2076  *          Computer Science Press, 1988.  ISBN 0-7167-8156-5.
2077  *
2078  *      Sedgewick, R.
2079  *          Algorithms, p290.
2080  *          Addison-Wesley, 1983. ISBN 0-201-06672-6.
2081  *
2082  *  INTERFACE
2083  *
2084  *      void ct_init (ush *attr, int *methodp)
2085  *          Allocate the match buffer, initialize the various tables and save
2086  *          the location of the internal file attribute (ascii/binary) and
2087  *          method (DEFLATE/STORE)
2088  *
2089  *      void ct_tally (int dist, int lc);
2090  *          Save the match info and tally the frequency counts.
2091  *
2092  *      long flush_block (char *buf, ulg stored_len, int eof)
2093  *          Determine the best encoding for the current block: dynamic trees,
2094  *          static trees or store, and output the encoded block to the zip
2095  *          file. Returns the total compressed length for the file so far.
2096  *
2097  */
2098
2099 #include <ctype.h>
2100
2101 /* ===========================================================================
2102  * Constants
2103  */
2104
2105 #define MAX_BITS 15
2106 /* All codes must not exceed MAX_BITS bits */
2107
2108 #define MAX_BL_BITS 7
2109 /* Bit length codes must not exceed MAX_BL_BITS bits */
2110
2111 #define LENGTH_CODES 29
2112 /* number of length codes, not counting the special END_BLOCK code */
2113
2114 #define LITERALS  256
2115 /* number of literal bytes 0..255 */
2116
2117 #define END_BLOCK 256
2118 /* end of block literal code */
2119
2120 #define L_CODES (LITERALS+1+LENGTH_CODES)
2121 /* number of Literal or Length codes, including the END_BLOCK code */
2122
2123 #define D_CODES   30
2124 /* number of distance codes */
2125
2126 #define BL_CODES  19
2127 /* number of codes used to transfer the bit lengths */
2128
2129
2130 local int near extra_lbits[LENGTH_CODES]        /* extra bits for each length code */
2131         = { 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4,
2132                 4, 4, 5, 5, 5, 5, 0 };
2133
2134 local int near extra_dbits[D_CODES]     /* extra bits for each distance code */
2135         = { 0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9,
2136                 10, 10, 11, 11, 12, 12, 13, 13 };
2137
2138 local int near extra_blbits[BL_CODES]   /* extra bits for each bit length code */
2139 = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 3, 7 };
2140
2141 #define STORED_BLOCK 0
2142 #define STATIC_TREES 1
2143 #define DYN_TREES    2
2144 /* The three kinds of block type */
2145
2146 #ifndef LIT_BUFSIZE
2147 #  ifdef SMALL_MEM
2148 #    define LIT_BUFSIZE  0x2000
2149 #  else
2150 #  ifdef MEDIUM_MEM
2151 #    define LIT_BUFSIZE  0x4000
2152 #  else
2153 #    define LIT_BUFSIZE  0x8000
2154 #  endif
2155 #  endif
2156 #endif
2157 #ifndef DIST_BUFSIZE
2158 #  define DIST_BUFSIZE  LIT_BUFSIZE
2159 #endif
2160 /* Sizes of match buffers for literals/lengths and distances.  There are
2161  * 4 reasons for limiting LIT_BUFSIZE to 64K:
2162  *   - frequencies can be kept in 16 bit counters
2163  *   - if compression is not successful for the first block, all input data is
2164  *     still in the window so we can still emit a stored block even when input
2165  *     comes from standard input.  (This can also be done for all blocks if
2166  *     LIT_BUFSIZE is not greater than 32K.)
2167  *   - if compression is not successful for a file smaller than 64K, we can
2168  *     even emit a stored file instead of a stored block (saving 5 bytes).
2169  *   - creating new Huffman trees less frequently may not provide fast
2170  *     adaptation to changes in the input data statistics. (Take for
2171  *     example a binary file with poorly compressible code followed by
2172  *     a highly compressible string table.) Smaller buffer sizes give
2173  *     fast adaptation but have of course the overhead of transmitting trees
2174  *     more frequently.
2175  *   - I can't count above 4
2176  * The current code is general and allows DIST_BUFSIZE < LIT_BUFSIZE (to save
2177  * memory at the expense of compression). Some optimizations would be possible
2178  * if we rely on DIST_BUFSIZE == LIT_BUFSIZE.
2179  */
2180 #if LIT_BUFSIZE > INBUFSIZ
2181 error cannot overlay l_buf and inbuf
2182 #endif
2183 #define REP_3_6      16
2184 /* repeat previous bit length 3-6 times (2 bits of repeat count) */
2185 #define REPZ_3_10    17
2186 /* repeat a zero length 3-10 times  (3 bits of repeat count) */
2187 #define REPZ_11_138  18
2188 /* repeat a zero length 11-138 times  (7 bits of repeat count) *//* ===========================================================================
2189  * Local data
2190  *//* Data structure describing a single value and its code string. */ typedef struct ct_data {
2191         union {
2192                 ush freq;                               /* frequency count */
2193                 ush code;                               /* bit string */
2194         } fc;
2195         union {
2196                 ush dad;                                /* father node in Huffman tree */
2197                 ush len;                                /* length of bit string */
2198         } dl;
2199 } ct_data;
2200
2201 #define Freq fc.freq
2202 #define Code fc.code
2203 #define Dad  dl.dad
2204 #define Len  dl.len
2205
2206 #define HEAP_SIZE (2*L_CODES+1)
2207 /* maximum heap size */
2208
2209 local ct_data near dyn_ltree[HEAP_SIZE];        /* literal and length tree */
2210 local ct_data near dyn_dtree[2 * D_CODES + 1];  /* distance tree */
2211
2212 local ct_data near static_ltree[L_CODES + 2];
2213
2214 /* The static literal tree. Since the bit lengths are imposed, there is no
2215  * need for the L_CODES extra codes used during heap construction. However
2216  * The codes 286 and 287 are needed to build a canonical tree (see ct_init
2217  * below).
2218  */
2219
2220 local ct_data near static_dtree[D_CODES];
2221
2222 /* The static distance tree. (Actually a trivial tree since all codes use
2223  * 5 bits.)
2224  */
2225
2226 local ct_data near bl_tree[2 * BL_CODES + 1];
2227
2228 /* Huffman tree for the bit lengths */
2229
2230 typedef struct tree_desc {
2231         ct_data near *dyn_tree;         /* the dynamic tree */
2232         ct_data near *static_tree;      /* corresponding static tree or NULL */
2233         int near *extra_bits;           /* extra bits for each code or NULL */
2234         int extra_base;                         /* base index for extra_bits */
2235         int elems;                                      /* max number of elements in the tree */
2236         int max_length;                         /* max bit length for the codes */
2237         int max_code;                           /* largest code with non zero frequency */
2238 } tree_desc;
2239
2240 local tree_desc near l_desc =
2241         { dyn_ltree, static_ltree, extra_lbits, LITERALS + 1, L_CODES,
2242                 MAX_BITS, 0 };
2243
2244 local tree_desc near d_desc =
2245         { dyn_dtree, static_dtree, extra_dbits, 0, D_CODES, MAX_BITS, 0 };
2246
2247 local tree_desc near bl_desc =
2248         { bl_tree, (ct_data near *) 0, extra_blbits, 0, BL_CODES, MAX_BL_BITS,
2249                 0 };
2250
2251
2252 local ush near bl_count[MAX_BITS + 1];
2253
2254 /* number of codes at each bit length for an optimal tree */
2255
2256 local uch near bl_order[BL_CODES]
2257 = { 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15 };
2258
2259 /* The lengths of the bit length codes are sent in order of decreasing
2260  * probability, to avoid transmitting the lengths for unused bit length codes.
2261  */
2262
2263 local int near heap[2 * L_CODES + 1];   /* heap used to build the Huffman trees */
2264 local int heap_len;                             /* number of elements in the heap */
2265 local int heap_max;                             /* element of largest frequency */
2266
2267 /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used.
2268  * The same heap array is used to build all trees.
2269  */
2270
2271 local uch near depth[2 * L_CODES + 1];
2272
2273 /* Depth of each subtree used as tie breaker for trees of equal frequency */
2274
2275 local uch length_code[MAX_MATCH - MIN_MATCH + 1];
2276
2277 /* length code for each normalized match length (0 == MIN_MATCH) */
2278
2279 local uch dist_code[512];
2280
2281 /* distance codes. The first 256 values correspond to the distances
2282  * 3 .. 258, the last 256 values correspond to the top 8 bits of
2283  * the 15 bit distances.
2284  */
2285
2286 local int near base_length[LENGTH_CODES];
2287
2288 /* First normalized length for each code (0 = MIN_MATCH) */
2289
2290 local int near base_dist[D_CODES];
2291
2292 /* First normalized distance for each code (0 = distance of 1) */
2293
2294 #define l_buf inbuf
2295 /* DECLARE(uch, l_buf, LIT_BUFSIZE);  buffer for literals or lengths */
2296
2297 /* DECLARE(ush, d_buf, DIST_BUFSIZE); buffer for distances */
2298
2299 local uch near flag_buf[(LIT_BUFSIZE / 8)];
2300
2301 /* flag_buf is a bit array distinguishing literals from lengths in
2302  * l_buf, thus indicating the presence or absence of a distance.
2303  */
2304
2305 local unsigned last_lit;                /* running index in l_buf */
2306 local unsigned last_dist;               /* running index in d_buf */
2307 local unsigned last_flags;              /* running index in flag_buf */
2308 local uch flags;                                /* current flags not yet saved in flag_buf */
2309 local uch flag_bit;                             /* current bit used in flags */
2310
2311 /* bits are filled in flags starting at bit 0 (least significant).
2312  * Note: these flags are overkill in the current code since we don't
2313  * take advantage of DIST_BUFSIZE == LIT_BUFSIZE.
2314  */
2315
2316 local ulg opt_len;                              /* bit length of current block with optimal trees */
2317 local ulg static_len;                   /* bit length of current block with static trees */
2318
2319 local ulg compressed_len;               /* total bit length of compressed file */
2320
2321 local ulg input_len;                    /* total byte length of input file */
2322
2323 /* input_len is for debugging only since we can get it by other means. */
2324
2325 ush *file_type;                                 /* pointer to UNKNOWN, BINARY or ASCII */
2326 int *file_method;                               /* pointer to DEFLATE or STORE */
2327
2328 #ifdef DEBUG
2329 extern ulg bits_sent;                   /* bit length of the compressed data */
2330 extern long isize;                              /* byte length of input file */
2331 #endif
2332
2333 extern long block_start;                /* window offset of current block */
2334 extern unsigned near strstart;  /* window offset of current string */
2335
2336 /* ===========================================================================
2337  * Local (static) routines in this file.
2338  */
2339
2340 local void init_block (void);
2341 local void pqdownheap (ct_data near * tree, int k);
2342 local void gen_bitlen (tree_desc near * desc);
2343 local void gen_codes (ct_data near * tree, int max_code);
2344 local void build_tree (tree_desc near * desc);
2345 local void scan_tree (ct_data near * tree, int max_code);
2346 local void send_tree (ct_data near * tree, int max_code);
2347 local int build_bl_tree (void);
2348 local void send_all_trees (int lcodes, int dcodes, int blcodes);
2349 local void compress_block (ct_data near * ltree, ct_data near * dtree);
2350 local void set_file_type (void);
2351
2352
2353 #ifndef DEBUG
2354 #  define send_code(c, tree) send_bits(tree[c].Code, tree[c].Len)
2355    /* Send a code of the given tree. c and tree must not have side effects */
2356
2357 #else                                                   /* DEBUG */
2358 #  define send_code(c, tree) \
2359      { if (verbose>1) fprintf(stderr,"\ncd %3d ",(c)); \
2360        send_bits(tree[c].Code, tree[c].Len); }
2361 #endif
2362
2363 #define d_code(dist) \
2364    ((dist) < 256 ? dist_code[dist] : dist_code[256+((dist)>>7)])
2365 /* Mapping from a distance to a distance code. dist is the distance - 1 and
2366  * must not have side effects. dist_code[256] and dist_code[257] are never
2367  * used.
2368  */
2369
2370 /* the arguments must not have side effects */
2371
2372 /* ===========================================================================
2373  * Allocate the match buffer, initialize the various tables and save the
2374  * location of the internal file attribute (ascii/binary) and method
2375  * (DEFLATE/STORE).
2376  */
2377 void ct_init(attr, methodp)
2378 ush *attr;                                              /* pointer to internal file attribute */
2379 int *methodp;                                   /* pointer to compression method */
2380 {
2381         int n;                                          /* iterates over tree elements */
2382         int bits;                                       /* bit counter */
2383         int length;                                     /* length value */
2384         int code;                                       /* code value */
2385         int dist;                                       /* distance index */
2386
2387         file_type = attr;
2388         file_method = methodp;
2389         compressed_len = input_len = 0L;
2390
2391         if (static_dtree[0].Len != 0)
2392                 return;                                 /* ct_init already called */
2393
2394         /* Initialize the mapping length (0..255) -> length code (0..28) */
2395         length = 0;
2396         for (code = 0; code < LENGTH_CODES - 1; code++) {
2397                 base_length[code] = length;
2398                 for (n = 0; n < (1 << extra_lbits[code]); n++) {
2399                         length_code[length++] = (uch) code;
2400                 }
2401         }
2402         Assert(length == 256, "ct_init: length != 256");
2403         /* Note that the length 255 (match length 258) can be represented
2404          * in two different ways: code 284 + 5 bits or code 285, so we
2405          * overwrite length_code[255] to use the best encoding:
2406          */
2407         length_code[length - 1] = (uch) code;
2408
2409         /* Initialize the mapping dist (0..32K) -> dist code (0..29) */
2410         dist = 0;
2411         for (code = 0; code < 16; code++) {
2412                 base_dist[code] = dist;
2413                 for (n = 0; n < (1 << extra_dbits[code]); n++) {
2414                         dist_code[dist++] = (uch) code;
2415                 }
2416         }
2417         Assert(dist == 256, "ct_init: dist != 256");
2418         dist >>= 7;                                     /* from now on, all distances are divided by 128 */
2419         for (; code < D_CODES; code++) {
2420                 base_dist[code] = dist << 7;
2421                 for (n = 0; n < (1 << (extra_dbits[code] - 7)); n++) {
2422                         dist_code[256 + dist++] = (uch) code;
2423                 }
2424         }
2425         Assert(dist == 256, "ct_init: 256+dist != 512");
2426
2427         /* Construct the codes of the static literal tree */
2428         for (bits = 0; bits <= MAX_BITS; bits++)
2429                 bl_count[bits] = 0;
2430         n = 0;
2431         while (n <= 143)
2432                 static_ltree[n++].Len = 8, bl_count[8]++;
2433         while (n <= 255)
2434                 static_ltree[n++].Len = 9, bl_count[9]++;
2435         while (n <= 279)
2436                 static_ltree[n++].Len = 7, bl_count[7]++;
2437         while (n <= 287)
2438                 static_ltree[n++].Len = 8, bl_count[8]++;
2439         /* Codes 286 and 287 do not exist, but we must include them in the
2440          * tree construction to get a canonical Huffman tree (longest code
2441          * all ones)
2442          */
2443         gen_codes((ct_data near *) static_ltree, L_CODES + 1);
2444
2445         /* The static distance tree is trivial: */
2446         for (n = 0; n < D_CODES; n++) {
2447                 static_dtree[n].Len = 5;
2448                 static_dtree[n].Code = bi_reverse(n, 5);
2449         }
2450
2451         /* Initialize the first block of the first file: */
2452         init_block();
2453 }
2454
2455 /* ===========================================================================
2456  * Initialize a new block.
2457  */
2458 local void init_block()
2459 {
2460         int n;                                          /* iterates over tree elements */
2461
2462         /* Initialize the trees. */
2463         for (n = 0; n < L_CODES; n++)
2464                 dyn_ltree[n].Freq = 0;
2465         for (n = 0; n < D_CODES; n++)
2466                 dyn_dtree[n].Freq = 0;
2467         for (n = 0; n < BL_CODES; n++)
2468                 bl_tree[n].Freq = 0;
2469
2470         dyn_ltree[END_BLOCK].Freq = 1;
2471         opt_len = static_len = 0L;
2472         last_lit = last_dist = last_flags = 0;
2473         flags = 0;
2474         flag_bit = 1;
2475 }
2476
2477 #define SMALLEST 1
2478 /* Index within the heap array of least frequent node in the Huffman tree */
2479
2480
2481 /* ===========================================================================
2482  * Remove the smallest element from the heap and recreate the heap with
2483  * one less element. Updates heap and heap_len.
2484  */
2485 #define pqremove(tree, top) \
2486 {\
2487     top = heap[SMALLEST]; \
2488     heap[SMALLEST] = heap[heap_len--]; \
2489     pqdownheap(tree, SMALLEST); \
2490 }
2491
2492 /* ===========================================================================
2493  * Compares to subtrees, using the tree depth as tie breaker when
2494  * the subtrees have equal frequency. This minimizes the worst case length.
2495  */
2496 #define smaller(tree, n, m) \
2497    (tree[n].Freq < tree[m].Freq || \
2498    (tree[n].Freq == tree[m].Freq && depth[n] <= depth[m]))
2499
2500 /* ===========================================================================
2501  * Restore the heap property by moving down the tree starting at node k,
2502  * exchanging a node with the smallest of its two sons if necessary, stopping
2503  * when the heap property is re-established (each father smaller than its
2504  * two sons).
2505  */
2506 local void pqdownheap(tree, k)
2507 ct_data near *tree;                             /* the tree to restore */
2508 int k;                                                  /* node to move down */
2509 {
2510         int v = heap[k];
2511         int j = k << 1;                         /* left son of k */
2512
2513         while (j <= heap_len) {
2514                 /* Set j to the smallest of the two sons: */
2515                 if (j < heap_len && smaller(tree, heap[j + 1], heap[j]))
2516                         j++;
2517
2518                 /* Exit if v is smaller than both sons */
2519                 if (smaller(tree, v, heap[j]))
2520                         break;
2521
2522                 /* Exchange v with the smallest son */
2523                 heap[k] = heap[j];
2524                 k = j;
2525
2526                 /* And continue down the tree, setting j to the left son of k */
2527                 j <<= 1;
2528         }
2529         heap[k] = v;
2530 }
2531
2532 /* ===========================================================================
2533  * Compute the optimal bit lengths for a tree and update the total bit length
2534  * for the current block.
2535  * IN assertion: the fields freq and dad are set, heap[heap_max] and
2536  *    above are the tree nodes sorted by increasing frequency.
2537  * OUT assertions: the field len is set to the optimal bit length, the
2538  *     array bl_count contains the frequencies for each bit length.
2539  *     The length opt_len is updated; static_len is also updated if stree is
2540  *     not null.
2541  */
2542 local void gen_bitlen(desc)
2543 tree_desc near *desc;                   /* the tree descriptor */
2544 {
2545         ct_data near *tree = desc->dyn_tree;
2546         int near *extra = desc->extra_bits;
2547         int base = desc->extra_base;
2548         int max_code = desc->max_code;
2549         int max_length = desc->max_length;
2550         ct_data near *stree = desc->static_tree;
2551         int h;                                          /* heap index */
2552         int n, m;                                       /* iterate over the tree elements */
2553         int bits;                                       /* bit length */
2554         int xbits;                                      /* extra bits */
2555         ush f;                                          /* frequency */
2556         int overflow = 0;                       /* number of elements with bit length too large */
2557
2558         for (bits = 0; bits <= MAX_BITS; bits++)
2559                 bl_count[bits] = 0;
2560
2561         /* In a first pass, compute the optimal bit lengths (which may
2562          * overflow in the case of the bit length tree).
2563          */
2564         tree[heap[heap_max]].Len = 0;   /* root of the heap */
2565
2566         for (h = heap_max + 1; h < HEAP_SIZE; h++) {
2567                 n = heap[h];
2568                 bits = tree[tree[n].Dad].Len + 1;
2569                 if (bits > max_length)
2570                         bits = max_length, overflow++;
2571                 tree[n].Len = (ush) bits;
2572                 /* We overwrite tree[n].Dad which is no longer needed */
2573
2574                 if (n > max_code)
2575                         continue;                       /* not a leaf node */
2576
2577                 bl_count[bits]++;
2578                 xbits = 0;
2579                 if (n >= base)
2580                         xbits = extra[n - base];
2581                 f = tree[n].Freq;
2582                 opt_len += (ulg) f *(bits + xbits);
2583
2584                 if (stree)
2585                         static_len += (ulg) f *(stree[n].Len + xbits);
2586         }
2587         if (overflow == 0)
2588                 return;
2589
2590         Trace((stderr, "\nbit length overflow\n"));
2591         /* This happens for example on obj2 and pic of the Calgary corpus */
2592
2593         /* Find the first bit length which could increase: */
2594         do {
2595                 bits = max_length - 1;
2596                 while (bl_count[bits] == 0)
2597                         bits--;
2598                 bl_count[bits]--;               /* move one leaf down the tree */
2599                 bl_count[bits + 1] += 2;        /* move one overflow item as its brother */
2600                 bl_count[max_length]--;
2601                 /* The brother of the overflow item also moves one step up,
2602                  * but this does not affect bl_count[max_length]
2603                  */
2604                 overflow -= 2;
2605         } while (overflow > 0);
2606
2607         /* Now recompute all bit lengths, scanning in increasing frequency.
2608          * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all
2609          * lengths instead of fixing only the wrong ones. This idea is taken
2610          * from 'ar' written by Haruhiko Okumura.)
2611          */
2612         for (bits = max_length; bits != 0; bits--) {
2613                 n = bl_count[bits];
2614                 while (n != 0) {
2615                         m = heap[--h];
2616                         if (m > max_code)
2617                                 continue;
2618                         if (tree[m].Len != (unsigned) bits) {
2619                                 Trace(
2620                                           (stderr, "code %d bits %d->%d\n", m, tree[m].Len,
2621                                            bits));
2622                                 opt_len +=
2623                                         ((long) bits -
2624                                          (long) tree[m].Len) * (long) tree[m].Freq;
2625                                 tree[m].Len = (ush) bits;
2626                         }
2627                         n--;
2628                 }
2629         }
2630 }
2631
2632 /* ===========================================================================
2633  * Generate the codes for a given tree and bit counts (which need not be
2634  * optimal).
2635  * IN assertion: the array bl_count contains the bit length statistics for
2636  * the given tree and the field len is set for all tree elements.
2637  * OUT assertion: the field code is set for all tree elements of non
2638  *     zero code length.
2639  */
2640 local void gen_codes(tree, max_code)
2641 ct_data near *tree;                             /* the tree to decorate */
2642 int max_code;                                   /* largest code with non zero frequency */
2643 {
2644         ush next_code[MAX_BITS + 1];    /* next code value for each bit length */
2645         ush code = 0;                           /* running code value */
2646         int bits;                                       /* bit index */
2647         int n;                                          /* code index */
2648
2649         /* The distribution counts are first used to generate the code values
2650          * without bit reversal.
2651          */
2652         for (bits = 1; bits <= MAX_BITS; bits++) {
2653                 next_code[bits] = code = (code + bl_count[bits - 1]) << 1;
2654         }
2655         /* Check that the bit counts in bl_count are consistent. The last code
2656          * must be all ones.
2657          */
2658         Assert(code + bl_count[MAX_BITS] - 1 == (1 << MAX_BITS) - 1,
2659                    "inconsistent bit counts");
2660         Tracev((stderr, "\ngen_codes: max_code %d ", max_code));
2661
2662         for (n = 0; n <= max_code; n++) {
2663                 int len = tree[n].Len;
2664
2665                 if (len == 0)
2666                         continue;
2667                 /* Now reverse the bits */
2668                 tree[n].Code = bi_reverse(next_code[len]++, len);
2669
2670                 Tracec(tree != static_ltree,
2671                            (stderr, "\nn %3d %c l %2d c %4x (%x) ", n,
2672                                 (isgraph(n) ? n : ' '), len, tree[n].Code,
2673                                 next_code[len] - 1));
2674         }
2675 }
2676
2677 /* ===========================================================================
2678  * Construct one Huffman tree and assigns the code bit strings and lengths.
2679  * Update the total bit length for the current block.
2680  * IN assertion: the field freq is set for all tree elements.
2681  * OUT assertions: the fields len and code are set to the optimal bit length
2682  *     and corresponding code. The length opt_len is updated; static_len is
2683  *     also updated if stree is not null. The field max_code is set.
2684  */
2685 local void build_tree(desc)
2686 tree_desc near *desc;                   /* the tree descriptor */
2687 {
2688         ct_data near *tree = desc->dyn_tree;
2689         ct_data near *stree = desc->static_tree;
2690         int elems = desc->elems;
2691         int n, m;                                       /* iterate over heap elements */
2692         int max_code = -1;                      /* largest code with non zero frequency */
2693         int node = elems;                       /* next internal node of the tree */
2694
2695         /* Construct the initial heap, with least frequent element in
2696          * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1].
2697          * heap[0] is not used.
2698          */
2699         heap_len = 0, heap_max = HEAP_SIZE;
2700
2701         for (n = 0; n < elems; n++) {
2702                 if (tree[n].Freq != 0) {
2703                         heap[++heap_len] = max_code = n;
2704                         depth[n] = 0;
2705                 } else {
2706                         tree[n].Len = 0;
2707                 }
2708         }
2709
2710         /* The pkzip format requires that at least one distance code exists,
2711          * and that at least one bit should be sent even if there is only one
2712          * possible code. So to avoid special checks later on we force at least
2713          * two codes of non zero frequency.
2714          */
2715         while (heap_len < 2) {
2716                 int new = heap[++heap_len] = (max_code < 2 ? ++max_code : 0);
2717
2718                 tree[new].Freq = 1;
2719                 depth[new] = 0;
2720                 opt_len--;
2721                 if (stree)
2722                         static_len -= stree[new].Len;
2723                 /* new is 0 or 1 so it does not have extra bits */
2724         }
2725         desc->max_code = max_code;
2726
2727         /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,
2728          * establish sub-heaps of increasing lengths:
2729          */
2730         for (n = heap_len / 2; n >= 1; n--)
2731                 pqdownheap(tree, n);
2732
2733         /* Construct the Huffman tree by repeatedly combining the least two
2734          * frequent nodes.
2735          */
2736         do {
2737                 pqremove(tree, n);              /* n = node of least frequency */
2738                 m = heap[SMALLEST];             /* m = node of next least frequency */
2739
2740                 heap[--heap_max] = n;   /* keep the nodes sorted by frequency */
2741                 heap[--heap_max] = m;
2742
2743                 /* Create a new node father of n and m */
2744                 tree[node].Freq = tree[n].Freq + tree[m].Freq;
2745                 depth[node] = (uch) (MAX(depth[n], depth[m]) + 1);
2746                 tree[n].Dad = tree[m].Dad = (ush) node;
2747 #ifdef DUMP_BL_TREE
2748                 if (tree == bl_tree) {
2749                         fprintf(stderr, "\nnode %d(%d), sons %d(%d) %d(%d)",
2750                                         node, tree[node].Freq, n, tree[n].Freq, m,
2751                                         tree[m].Freq);
2752                 }
2753 #endif
2754                 /* and insert the new node in the heap */
2755                 heap[SMALLEST] = node++;
2756                 pqdownheap(tree, SMALLEST);
2757
2758         } while (heap_len >= 2);
2759
2760         heap[--heap_max] = heap[SMALLEST];
2761
2762         /* At this point, the fields freq and dad are set. We can now
2763          * generate the bit lengths.
2764          */
2765         gen_bitlen((tree_desc near *) desc);
2766
2767         /* The field len is now set, we can generate the bit codes */
2768         gen_codes((ct_data near *) tree, max_code);
2769 }
2770
2771 /* ===========================================================================
2772  * Scan a literal or distance tree to determine the frequencies of the codes
2773  * in the bit length tree. Updates opt_len to take into account the repeat
2774  * counts. (The contribution of the bit length codes will be added later
2775  * during the construction of bl_tree.)
2776  */
2777 local void scan_tree(tree, max_code)
2778 ct_data near *tree;                             /* the tree to be scanned */
2779 int max_code;                                   /* and its largest code of non zero frequency */
2780 {
2781         int n;                                          /* iterates over all tree elements */
2782         int prevlen = -1;                       /* last emitted length */
2783         int curlen;                                     /* length of current code */
2784         int nextlen = tree[0].Len;      /* length of next code */
2785         int count = 0;                          /* repeat count of the current code */
2786         int max_count = 7;                      /* max repeat count */
2787         int min_count = 4;                      /* min repeat count */
2788
2789         if (nextlen == 0)
2790                 max_count = 138, min_count = 3;
2791         tree[max_code + 1].Len = (ush) 0xffff;  /* guard */
2792
2793         for (n = 0; n <= max_code; n++) {
2794                 curlen = nextlen;
2795                 nextlen = tree[n + 1].Len;
2796                 if (++count < max_count && curlen == nextlen) {
2797                         continue;
2798                 } else if (count < min_count) {
2799                         bl_tree[curlen].Freq += count;
2800                 } else if (curlen != 0) {
2801                         if (curlen != prevlen)
2802                                 bl_tree[curlen].Freq++;
2803                         bl_tree[REP_3_6].Freq++;
2804                 } else if (count <= 10) {
2805                         bl_tree[REPZ_3_10].Freq++;
2806                 } else {
2807                         bl_tree[REPZ_11_138].Freq++;
2808                 }
2809                 count = 0;
2810                 prevlen = curlen;
2811                 if (nextlen == 0) {
2812                         max_count = 138, min_count = 3;
2813                 } else if (curlen == nextlen) {
2814                         max_count = 6, min_count = 3;
2815                 } else {
2816                         max_count = 7, min_count = 4;
2817                 }
2818         }
2819 }
2820
2821 /* ===========================================================================
2822  * Send a literal or distance tree in compressed form, using the codes in
2823  * bl_tree.
2824  */
2825 local void send_tree(tree, max_code)
2826 ct_data near *tree;                             /* the tree to be scanned */
2827 int max_code;                                   /* and its largest code of non zero frequency */
2828 {
2829         int n;                                          /* iterates over all tree elements */
2830         int prevlen = -1;                       /* last emitted length */
2831         int curlen;                                     /* length of current code */
2832         int nextlen = tree[0].Len;      /* length of next code */
2833         int count = 0;                          /* repeat count of the current code */
2834         int max_count = 7;                      /* max repeat count */
2835         int min_count = 4;                      /* min repeat count */
2836
2837 /* tree[max_code+1].Len = -1; *//* guard already set */
2838         if (nextlen == 0)
2839                 max_count = 138, min_count = 3;
2840
2841         for (n = 0; n <= max_code; n++) {
2842                 curlen = nextlen;
2843                 nextlen = tree[n + 1].Len;
2844                 if (++count < max_count && curlen == nextlen) {
2845                         continue;
2846                 } else if (count < min_count) {
2847                         do {
2848                                 send_code(curlen, bl_tree);
2849                         } while (--count != 0);
2850
2851                 } else if (curlen != 0) {
2852                         if (curlen != prevlen) {
2853                                 send_code(curlen, bl_tree);
2854                                 count--;
2855                         }
2856                         Assert(count >= 3 && count <= 6, " 3_6?");
2857                         send_code(REP_3_6, bl_tree);
2858                         send_bits(count - 3, 2);
2859
2860                 } else if (count <= 10) {
2861                         send_code(REPZ_3_10, bl_tree);
2862                         send_bits(count - 3, 3);
2863
2864                 } else {
2865                         send_code(REPZ_11_138, bl_tree);
2866                         send_bits(count - 11, 7);
2867                 }
2868                 count = 0;
2869                 prevlen = curlen;
2870                 if (nextlen == 0) {
2871                         max_count = 138, min_count = 3;
2872                 } else if (curlen == nextlen) {
2873                         max_count = 6, min_count = 3;
2874                 } else {
2875                         max_count = 7, min_count = 4;
2876                 }
2877         }
2878 }
2879
2880 /* ===========================================================================
2881  * Construct the Huffman tree for the bit lengths and return the index in
2882  * bl_order of the last bit length code to send.
2883  */
2884 local int build_bl_tree()
2885 {
2886         int max_blindex;                        /* index of last bit length code of non zero freq */
2887
2888         /* Determine the bit length frequencies for literal and distance trees */
2889         scan_tree((ct_data near *) dyn_ltree, l_desc.max_code);
2890         scan_tree((ct_data near *) dyn_dtree, d_desc.max_code);
2891
2892         /* Build the bit length tree: */
2893         build_tree((tree_desc near *) (&bl_desc));
2894         /* opt_len now includes the length of the tree representations, except
2895          * the lengths of the bit lengths codes and the 5+5+4 bits for the counts.
2896          */
2897
2898         /* Determine the number of bit length codes to send. The pkzip format
2899          * requires that at least 4 bit length codes be sent. (appnote.txt says
2900          * 3 but the actual value used is 4.)
2901          */
2902         for (max_blindex = BL_CODES - 1; max_blindex >= 3; max_blindex--) {
2903                 if (bl_tree[bl_order[max_blindex]].Len != 0)
2904                         break;
2905         }
2906         /* Update opt_len to include the bit length tree and counts */
2907         opt_len += 3 * (max_blindex + 1) + 5 + 5 + 4;
2908         Tracev(
2909                    (stderr, "\ndyn trees: dyn %ld, stat %ld", opt_len,
2910                         static_len));
2911
2912         return max_blindex;
2913 }
2914
2915 /* ===========================================================================
2916  * Send the header for a block using dynamic Huffman trees: the counts, the
2917  * lengths of the bit length codes, the literal tree and the distance tree.
2918  * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.
2919  */
2920 local void send_all_trees(lcodes, dcodes, blcodes)
2921 int lcodes, dcodes, blcodes;    /* number of codes for each tree */
2922 {
2923         int rank;                                       /* index in bl_order */
2924
2925         Assert(lcodes >= 257 && dcodes >= 1
2926                    && blcodes >= 4, "not enough codes");
2927         Assert(lcodes <= L_CODES && dcodes <= D_CODES
2928                    && blcodes <= BL_CODES, "too many codes");
2929         Tracev((stderr, "\nbl counts: "));
2930         send_bits(lcodes - 257, 5);     /* not +255 as stated in appnote.txt */
2931         send_bits(dcodes - 1, 5);
2932         send_bits(blcodes - 4, 4);      /* not -3 as stated in appnote.txt */
2933         for (rank = 0; rank < blcodes; rank++) {
2934                 Tracev((stderr, "\nbl code %2d ", bl_order[rank]));
2935                 send_bits(bl_tree[bl_order[rank]].Len, 3);
2936         }
2937         Tracev((stderr, "\nbl tree: sent %ld", bits_sent));
2938
2939         send_tree((ct_data near *) dyn_ltree, lcodes - 1);      /* send the literal tree */
2940         Tracev((stderr, "\nlit tree: sent %ld", bits_sent));
2941
2942         send_tree((ct_data near *) dyn_dtree, dcodes - 1);      /* send the distance tree */
2943         Tracev((stderr, "\ndist tree: sent %ld", bits_sent));
2944 }
2945
2946 /* ===========================================================================
2947  * Determine the best encoding for the current block: dynamic trees, static
2948  * trees or store, and output the encoded block to the zip file. This function
2949  * returns the total compressed length for the file so far.
2950  */
2951 ulg flush_block(buf, stored_len, eof)
2952 char *buf;                                              /* input block, or NULL if too old */
2953 ulg stored_len;                                 /* length of input block */
2954 int eof;                                                /* true if this is the last block for a file */
2955 {
2956         ulg opt_lenb, static_lenb;      /* opt_len and static_len in bytes */
2957         int max_blindex;                        /* index of last bit length code of non zero freq */
2958
2959         flag_buf[last_flags] = flags;   /* Save the flags for the last 8 items */
2960
2961         /* Check if the file is ascii or binary */
2962         if (*file_type == (ush) UNKNOWN)
2963                 set_file_type();
2964
2965         /* Construct the literal and distance trees */
2966         build_tree((tree_desc near *) (&l_desc));
2967         Tracev((stderr, "\nlit data: dyn %ld, stat %ld", opt_len, static_len));
2968
2969         build_tree((tree_desc near *) (&d_desc));
2970         Tracev(
2971                    (stderr, "\ndist data: dyn %ld, stat %ld", opt_len,
2972                         static_len));
2973         /* At this point, opt_len and static_len are the total bit lengths of
2974          * the compressed block data, excluding the tree representations.
2975          */
2976
2977         /* Build the bit length tree for the above two trees, and get the index
2978          * in bl_order of the last bit length code to send.
2979          */
2980         max_blindex = build_bl_tree();
2981
2982         /* Determine the best encoding. Compute first the block length in bytes */
2983         opt_lenb = (opt_len + 3 + 7) >> 3;
2984         static_lenb = (static_len + 3 + 7) >> 3;
2985         input_len += stored_len;        /* for debugging only */
2986
2987         Trace(
2988                   (stderr,
2989                    "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u dist %u ",
2990                    opt_lenb, opt_len, static_lenb, static_len, stored_len,
2991                    last_lit, last_dist));
2992
2993         if (static_lenb <= opt_lenb)
2994                 opt_lenb = static_lenb;
2995
2996         /* If compression failed and this is the first and last block,
2997          * and if the zip file can be seeked (to rewrite the local header),
2998          * the whole file is transformed into a stored file:
2999          */
3000 #ifdef FORCE_METHOD
3001 #else
3002         if (stored_len <= opt_lenb && eof && compressed_len == 0L
3003                 && seekable()) {
3004 #endif
3005                 /* Since LIT_BUFSIZE <= 2*WSIZE, the input data must be there: */
3006                 if (buf == (char *) 0)
3007                         error_msg("block vanished");
3008
3009                 copy_block(buf, (unsigned) stored_len, 0);      /* without header */
3010                 compressed_len = stored_len << 3;
3011                 *file_method = STORED;
3012
3013 #ifdef FORCE_METHOD
3014 #else
3015         } else if (stored_len + 4 <= opt_lenb && buf != (char *) 0) {
3016                 /* 4: two words for the lengths */
3017 #endif
3018                 /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.
3019                  * Otherwise we can't have processed more than WSIZE input bytes since
3020                  * the last block flush, because compression would have been
3021                  * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to
3022                  * transform a block into a stored block.
3023                  */
3024                 send_bits((STORED_BLOCK << 1) + eof, 3);        /* send block type */
3025                 compressed_len = (compressed_len + 3 + 7) & ~7L;
3026                 compressed_len += (stored_len + 4) << 3;
3027
3028                 copy_block(buf, (unsigned) stored_len, 1);      /* with header */
3029
3030 #ifdef FORCE_METHOD
3031 #else
3032         } else if (static_lenb == opt_lenb) {
3033 #endif
3034                 send_bits((STATIC_TREES << 1) + eof, 3);
3035                 compress_block((ct_data near *) static_ltree,
3036                                            (ct_data near *) static_dtree);
3037                 compressed_len += 3 + static_len;
3038         } else {
3039                 send_bits((DYN_TREES << 1) + eof, 3);
3040                 send_all_trees(l_desc.max_code + 1, d_desc.max_code + 1,
3041                                            max_blindex + 1);
3042                 compress_block((ct_data near *) dyn_ltree,
3043                                            (ct_data near *) dyn_dtree);
3044                 compressed_len += 3 + opt_len;
3045         }
3046         Assert(compressed_len == bits_sent, "bad compressed size");
3047         init_block();
3048
3049         if (eof) {
3050                 Assert(input_len == isize, "bad input size");
3051                 bi_windup();
3052                 compressed_len += 7;    /* align on byte boundary */
3053         }
3054         Tracev((stderr, "\ncomprlen %lu(%lu) ", compressed_len >> 3,
3055                         compressed_len - 7 * eof));
3056
3057         return compressed_len >> 3;
3058 }
3059
3060 /* ===========================================================================
3061  * Save the match info and tally the frequency counts. Return true if
3062  * the current block must be flushed.
3063  */
3064 int ct_tally(dist, lc)
3065 int dist;                                               /* distance of matched string */
3066 int lc;                                                 /* match length-MIN_MATCH or unmatched char (if dist==0) */
3067 {
3068         l_buf[last_lit++] = (uch) lc;
3069         if (dist == 0) {
3070                 /* lc is the unmatched char */
3071                 dyn_ltree[lc].Freq++;
3072         } else {
3073                 /* Here, lc is the match length - MIN_MATCH */
3074                 dist--;                                 /* dist = match distance - 1 */
3075                 Assert((ush) dist < (ush) MAX_DIST &&
3076                            (ush) lc <= (ush) (MAX_MATCH - MIN_MATCH) &&
3077                            (ush) d_code(dist) < (ush) D_CODES, "ct_tally: bad match");
3078
3079                 dyn_ltree[length_code[lc] + LITERALS + 1].Freq++;
3080                 dyn_dtree[d_code(dist)].Freq++;
3081
3082                 d_buf[last_dist++] = (ush) dist;
3083                 flags |= flag_bit;
3084         }
3085         flag_bit <<= 1;
3086
3087         /* Output the flags if they fill a byte: */
3088         if ((last_lit & 7) == 0) {
3089                 flag_buf[last_flags++] = flags;
3090                 flags = 0, flag_bit = 1;
3091         }
3092         /* Try to guess if it is profitable to stop the current block here */
3093         if ((last_lit & 0xfff) == 0) {
3094                 /* Compute an upper bound for the compressed length */
3095                 ulg out_length = (ulg) last_lit * 8L;
3096                 ulg in_length = (ulg) strstart - block_start;
3097                 int dcode;
3098
3099                 for (dcode = 0; dcode < D_CODES; dcode++) {
3100                         out_length +=
3101                                 (ulg) dyn_dtree[dcode].Freq * (5L + extra_dbits[dcode]);
3102                 }
3103                 out_length >>= 3;
3104                 Trace(
3105                           (stderr,
3106                            "\nlast_lit %u, last_dist %u, in %ld, out ~%ld(%ld%%) ",
3107                            last_lit, last_dist, in_length, out_length,
3108                            100L - out_length * 100L / in_length));
3109                 if (last_dist < last_lit / 2 && out_length < in_length / 2)
3110                         return 1;
3111         }
3112         return (last_lit == LIT_BUFSIZE - 1 || last_dist == DIST_BUFSIZE);
3113         /* We avoid equality with LIT_BUFSIZE because of wraparound at 64K
3114          * on 16 bit machines and because stored blocks are restricted to
3115          * 64K-1 bytes.
3116          */
3117 }
3118
3119 /* ===========================================================================
3120  * Send the block data compressed using the given Huffman trees
3121  */
3122 local void compress_block(ltree, dtree)
3123 ct_data near *ltree;                    /* literal tree */
3124 ct_data near *dtree;                    /* distance tree */
3125 {
3126         unsigned dist;                          /* distance of matched string */
3127         int lc;                                         /* match length or unmatched char (if dist == 0) */
3128         unsigned lx = 0;                        /* running index in l_buf */
3129         unsigned dx = 0;                        /* running index in d_buf */
3130         unsigned fx = 0;                        /* running index in flag_buf */
3131         uch flag = 0;                           /* current flags */
3132         unsigned code;                          /* the code to send */
3133         int extra;                                      /* number of extra bits to send */
3134
3135         if (last_lit != 0)
3136                 do {
3137                         if ((lx & 7) == 0)
3138                                 flag = flag_buf[fx++];
3139                         lc = l_buf[lx++];
3140                         if ((flag & 1) == 0) {
3141                                 send_code(lc, ltree);   /* send a literal byte */
3142                                 Tracecv(isgraph(lc), (stderr, " '%c' ", lc));
3143                         } else {
3144                                 /* Here, lc is the match length - MIN_MATCH */
3145                                 code = length_code[lc];
3146                                 send_code(code + LITERALS + 1, ltree);  /* send the length code */
3147                                 extra = extra_lbits[code];
3148                                 if (extra != 0) {
3149                                         lc -= base_length[code];
3150                                         send_bits(lc, extra);   /* send the extra length bits */
3151                                 }
3152                                 dist = d_buf[dx++];
3153                                 /* Here, dist is the match distance - 1 */
3154                                 code = d_code(dist);
3155                                 Assert(code < D_CODES, "bad d_code");
3156
3157                                 send_code(code, dtree); /* send the distance code */
3158                                 extra = extra_dbits[code];
3159                                 if (extra != 0) {
3160                                         dist -= base_dist[code];
3161                                         send_bits(dist, extra); /* send the extra distance bits */
3162                                 }
3163                         }                                       /* literal or match pair ? */
3164                         flag >>= 1;
3165                 } while (lx < last_lit);
3166
3167         send_code(END_BLOCK, ltree);
3168 }
3169
3170 /* ===========================================================================
3171  * Set the file type to ASCII or BINARY, using a crude approximation:
3172  * binary if more than 20% of the bytes are <= 6 or >= 128, ascii otherwise.
3173  * IN assertion: the fields freq of dyn_ltree are set and the total of all
3174  * frequencies does not exceed 64K (to fit in an int on 16 bit machines).
3175  */
3176 local void set_file_type()
3177 {
3178         int n = 0;
3179         unsigned ascii_freq = 0;
3180         unsigned bin_freq = 0;
3181
3182         while (n < 7)
3183                 bin_freq += dyn_ltree[n++].Freq;
3184         while (n < 128)
3185                 ascii_freq += dyn_ltree[n++].Freq;
3186         while (n < LITERALS)
3187                 bin_freq += dyn_ltree[n++].Freq;
3188         *file_type = bin_freq > (ascii_freq >> 2) ? BINARY : ASCII;
3189         if (*file_type == BINARY && translate_eol) {
3190                 error_msg("-l used on binary file");
3191         }
3192 }
3193
3194 /* util.c -- utility functions for gzip support
3195  * Copyright (C) 1992-1993 Jean-loup Gailly
3196  * This is free software; you can redistribute it and/or modify it under the
3197  * terms of the GNU General Public License, see the file COPYING.
3198  */
3199
3200 #include <ctype.h>
3201 #include <errno.h>
3202 #include <sys/types.h>
3203
3204 #ifdef HAVE_UNISTD_H
3205 #  include <unistd.h>
3206 #endif
3207 #ifndef NO_FCNTL_H
3208 #  include <fcntl.h>
3209 #endif
3210
3211 /* ===========================================================================
3212  * Copy input to output unchanged: zcat == cat with --force.
3213  * IN assertion: insize bytes have already been read in inbuf.
3214  */
3215 int copy(in, out)
3216 int in, out;                                    /* input and output file descriptors */
3217 {
3218         errno = 0;
3219         while (insize != 0 && (int) insize != EOF) {
3220                 write_buf(out, (char *) inbuf, insize);
3221                 bytes_out += insize;
3222                 insize = read(in, (char *) inbuf, INBUFSIZ);
3223         }
3224         if ((int) insize == EOF && errno != 0) {
3225                 read_error_msg();
3226         }
3227         bytes_in = bytes_out;
3228         return OK;
3229 }
3230
3231 /* ========================================================================
3232  * Put string s in lower case, return s.
3233  */
3234 char *strlwr(s)
3235 char *s;
3236 {
3237         char *t;
3238
3239         for (t = s; *t; t++)
3240                 *t = tolow(*t);
3241         return s;
3242 }
3243
3244 #if defined(NO_STRING_H) && !defined(STDC_HEADERS)
3245
3246 /* Provide missing strspn and strcspn functions. */
3247
3248 int strspn (const char *s, const char *accept);
3249 int strcspn (const char *s, const char *reject);
3250
3251 /* ========================================================================
3252  * Return the length of the maximum initial segment
3253  * of s which contains only characters in accept.
3254  */
3255 int strspn(s, accept)
3256 const char *s;
3257 const char *accept;
3258 {
3259         register const char *p;
3260         register const char *a;
3261         register int count = 0;
3262
3263         for (p = s; *p != '\0'; ++p) {
3264                 for (a = accept; *a != '\0'; ++a) {
3265                         if (*p == *a)
3266                                 break;
3267                 }
3268                 if (*a == '\0')
3269                         return count;
3270                 ++count;
3271         }
3272         return count;
3273 }
3274
3275 /* ========================================================================
3276  * Return the length of the maximum inital segment of s
3277  * which contains no characters from reject.
3278  */
3279 int strcspn(s, reject)
3280 const char *s;
3281 const char *reject;
3282 {
3283         register int count = 0;
3284
3285         while (*s != '\0') {
3286                 if (strchr(reject, *s++) != NULL)
3287                         return count;
3288                 ++count;
3289         }
3290         return count;
3291 }
3292
3293 #endif                                                  /* NO_STRING_H */
3294
3295 /* ========================================================================
3296  * Add an environment variable (if any) before argv, and update argc.
3297  * Return the expanded environment variable to be freed later, or NULL 
3298  * if no options were added to argv.
3299  */
3300 #define SEPARATOR       " \t"           /* separators in env variable */
3301
3302 char *add_envopt(argcp, argvp, env)
3303 int *argcp;                                             /* pointer to argc */
3304 char ***argvp;                                  /* pointer to argv */
3305 char *env;                                              /* name of environment variable */
3306 {
3307         char *p;                                        /* running pointer through env variable */
3308         char **oargv;                           /* runs through old argv array */
3309         char **nargv;                           /* runs through new argv array */
3310         int oargc = *argcp;                     /* old argc */
3311         int nargc = 0;                          /* number of arguments in env variable */
3312
3313         env = (char *) getenv(env);
3314         if (env == NULL)
3315                 return NULL;
3316
3317         p = (char *) xmalloc(strlen(env) + 1);
3318         env = strcpy(p, env);           /* keep env variable intact */
3319
3320         for (p = env; *p; nargc++) {    /* move through env */
3321                 p += strspn(p, SEPARATOR);      /* skip leading separators */
3322                 if (*p == '\0')
3323                         break;
3324
3325                 p += strcspn(p, SEPARATOR);     /* find end of word */
3326                 if (*p)
3327                         *p++ = '\0';            /* mark it */
3328         }
3329         if (nargc == 0) {
3330                 free(env);
3331                 return NULL;
3332         }
3333         *argcp += nargc;
3334         /* Allocate the new argv array, with an extra element just in case
3335          * the original arg list did not end with a NULL.
3336          */
3337         nargv = (char **) calloc(*argcp + 1, sizeof(char *));
3338
3339         if (nargv == NULL)
3340                 error_msg(memory_exhausted);
3341         oargv = *argvp;
3342         *argvp = nargv;
3343
3344         /* Copy the program name first */
3345         if (oargc-- < 0)
3346                 error_msg("argc<=0");
3347         *(nargv++) = *(oargv++);
3348
3349         /* Then copy the environment args */
3350         for (p = env; nargc > 0; nargc--) {
3351                 p += strspn(p, SEPARATOR);      /* skip separators */
3352                 *(nargv++) = p;                 /* store start */
3353                 while (*p++);                   /* skip over word */
3354         }
3355
3356         /* Finally copy the old args and add a NULL (usual convention) */
3357         while (oargc--)
3358                 *(nargv++) = *(oargv++);
3359         *nargv = NULL;
3360         return env;
3361 }
3362
3363 /* ========================================================================
3364  * Display compression ratio on the given stream on 6 characters.
3365  */
3366 void display_ratio(num, den, file)
3367 long num;
3368 long den;
3369 FILE *file;
3370 {
3371         long ratio;                                     /* 1000 times the compression ratio */
3372
3373         if (den == 0) {
3374                 ratio = 0;                              /* no compression */
3375         } else if (den < 2147483L) {    /* (2**31 -1)/1000 */
3376                 ratio = 1000L * num / den;
3377         } else {
3378                 ratio = num / (den / 1000L);
3379         }
3380         if (ratio < 0) {
3381                 putc('-', file);
3382                 ratio = -ratio;
3383         } else {
3384                 putc(' ', file);
3385         }
3386         fprintf(file, "%2ld.%1ld%%", ratio / 10L, ratio % 10L);
3387 }
3388
3389
3390 /* zip.c -- compress files to the gzip or pkzip format
3391  * Copyright (C) 1992-1993 Jean-loup Gailly
3392  * This is free software; you can redistribute it and/or modify it under the
3393  * terms of the GNU General Public License, see the file COPYING.
3394  */
3395
3396 #include <ctype.h>
3397 #include <sys/types.h>
3398
3399 #ifdef HAVE_UNISTD_H
3400 #  include <unistd.h>
3401 #endif
3402 #ifndef NO_FCNTL_H
3403 #  include <fcntl.h>
3404 #endif
3405
3406 local ulg crc;                                  /* crc on uncompressed file data */
3407 long header_bytes;                              /* number of bytes in gzip header */
3408
3409 /* ===========================================================================
3410  * Deflate in to out.
3411  * IN assertions: the input and output buffers are cleared.
3412  *   The variables time_stamp and save_orig_name are initialized.
3413  */
3414 int zip(in, out)
3415 int in, out;                                    /* input and output file descriptors */
3416 {
3417         uch my_flags = 0;                               /* general purpose bit flags */
3418         ush attr = 0;                           /* ascii/binary flag */
3419         ush deflate_flags = 0;          /* pkzip -es, -en or -ex equivalent */
3420
3421         ifd = in;
3422         ofd = out;
3423         outcnt = 0;
3424
3425         /* Write the header to the gzip file. See algorithm.doc for the format */
3426
3427
3428         method = DEFLATED;
3429         put_byte(GZIP_MAGIC[0]);        /* magic header */
3430         put_byte(GZIP_MAGIC[1]);
3431         put_byte(DEFLATED);                     /* compression method */
3432
3433         put_byte(my_flags);                     /* general flags */
3434         put_long(time_stamp);
3435
3436         /* Write deflated file to zip file */
3437         crc = updcrc(0, 0);
3438
3439         bi_init(out);
3440         ct_init(&attr, &method);
3441         lm_init(&deflate_flags);
3442
3443         put_byte((uch) deflate_flags);  /* extra flags */
3444         put_byte(OS_CODE);                      /* OS identifier */
3445
3446         header_bytes = (long) outcnt;
3447
3448         (void) deflate();
3449
3450         /* Write the crc and uncompressed size */
3451         put_long(crc);
3452         put_long(isize);
3453         header_bytes += 2 * sizeof(long);
3454
3455         flush_outbuf();
3456         return OK;
3457 }
3458
3459
3460 /* ===========================================================================
3461  * Read a new buffer from the current input file, perform end-of-line
3462  * translation, and update the crc and input file size.
3463  * IN assertion: size >= 2 (for end-of-line translation)
3464  */
3465 int file_read(buf, size)
3466 char *buf;
3467 unsigned size;
3468 {
3469         unsigned len;
3470
3471         Assert(insize == 0, "inbuf not empty");
3472
3473         len = read(ifd, buf, size);
3474         if (len == (unsigned) (-1) || len == 0)
3475                 return (int) len;
3476
3477         crc = updcrc((uch *) buf, len);
3478         isize += (ulg) len;
3479         return (int) len;
3480 }
3481
3482 /* ===========================================================================
3483  * Write the output buffer outbuf[0..outcnt-1] and update bytes_out.
3484  * (used for the compressed data only)
3485  */
3486 void flush_outbuf()
3487 {
3488         if (outcnt == 0)
3489                 return;
3490
3491         write_buf(ofd, (char *) outbuf, outcnt);
3492         bytes_out += (ulg) outcnt;
3493         outcnt = 0;
3494 }