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