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