1 /******************************************************************************
2 *
3 *  NSSDC/CDF                                GnuZIP compression/decompression.
4 *
5 *  Version 1.0b, 2-Sep-97.
6 *
7 *  Modification history:
8 *
9 *   V1.0  27-Aug-96, J Love     Original version, but...the `zip' and `unzip'
10 *                               routines (and their supporting routines) are
11 *                               modified versions of routines provided by the
12 *                               named institutions and/or individuals.
13 *   V1.0a 20-Dec-96, J Love	Renamed BIT macro to avoid collision on
14 *				Linux systems.  Eliminated sanity check if
15 *				using Salford C.
16 *   V1.0b  2-Sep-97, J Love	Type casting for ANSI C.
17 *
18 ******************************************************************************/
19 
20 #include "cdflib.h"
21 
22 #if !SUPPORT_GZIP_c && defined(BORLANDC)
23 #pragma warn -par
24 #endif
25 
26 /******************************************************************************
27 * Macros.
28 ******************************************************************************/
29 
30 #if 0                   /* MS-DOS? */
31 #define SMALL_MEM
32 #endif
33 
34 #if 0                   /* MacOS? */
35 #define MEDIUM_MEM
36 #endif
37 
38 #define N_BORDER        19
39 #define N_CPLENS        31
40 #define N_CPLEXT        31
41 #define N_CPDIST        30
42 #define N_CPDEXT        30
43 #define N_MASK_BITS     17
44 #define N_CRC_32_TAB    256
45 
46 #define BL_CODES  19
47 /* number of codes used to transfer the bit lengths */
48 
49 #define MAX_BITS 15
50 /* All codes must not exceed MAX_BITS bits */
51 
52 #define LITERALS  256
53 /* number of literal bytes 0..255 */
54 
55 #define LENGTH_CODES 29
56 /* number of length codes, not counting the special END_BLOCK code */
57 
58 #define L_CODES (LITERALS+1+LENGTH_CODES)
59 /* number of Literal or Length codes, including the END_BLOCK code */
60 
61 #define D_CODES   30
62 /* number of distance codes */
63 
64 #define HEAP_SIZE (2*L_CODES+1)
65 /* maximum heap size */
66 
67 #define MIN_MATCH  3
68 #define MAX_MATCH  258
69 /* The minimum and maximum match lengths */
70 
71 #ifndef LIT_BUFSIZE
72 #ifdef SMALL_MEM
73 #define LIT_BUFSIZE  0x2000
74 #else
75 #ifdef MEDIUM_MEM
76 #define LIT_BUFSIZE  0x4000
77 #else
78 #define LIT_BUFSIZE  0x8000
79 #endif
80 #endif
81 #endif
82 
83 /******************************************************************************
84 * Typedef's and structure definitions.
85 ******************************************************************************/
86 
87 typedef unsigned char  uch;
88 typedef unsigned short ush;
89 typedef unsigned long  ulg;
90 
91 typedef ush Pos;
92 typedef unsigned IPos;
93 /* A Pos is an index in the character window. We use short instead of int to
94  * save space in the various tables. IPos is used only for parameter passing.
95  */
96 
97 typedef struct {
98    ush good_length; /* reduce lazy search above this match length */
99    ush max_lazy;    /* do not perform lazy search above this match length */
100    ush nice_length; /* quit search above this match length */
101    ush max_chain;
102 } config;
103 
104 /* Data structure describing a single value and its code string. */
105 typedef struct ct_data {
106     union {
107 	ush  freq;       /* frequency count */
108 	ush  code;       /* bit string */
109     } fc;
110     union {
111 	ush  dad;        /* father node in Huffman tree */
112 	ush  len;        /* length of bit string */
113     } dl;
114 } ct_data;
115 
116 typedef struct tree_desc {
117     ct_data *dyn_tree;      /* the dynamic tree */
118     ct_data *static_tree;   /* corresponding static tree or NULL */
119     int     *extra_bits;    /* extra bits for each code or NULL */
120     int     extra_base;          /* base index for extra_bits */
121     int     elems;               /* max number of elements in the tree */
122     int     max_length;          /* max bit length for the codes */
123     int     max_code;            /* largest code with non zero frequency */
124 } tree_desc;
125 
126 /* Huffman code lookup table entry--this entry is four bytes for machines
127    that have 16-bit pointers (e.g. PC's in the small or medium model).
128    Valid extra bits are 0..13.  e == 15 is EOB (end of block), e == 16
129    means that v is a literal, 16 < e < 32 means that v is a pointer to
130    the next table, which codes e - 16 bits, and lastly e == 99 indicates
131    an unused code.  If a code with e == 99 is looked up, this implies an
132    error in the data. */
133 
134 struct huft {
135   uch e;                /* number of extra bits or operation */
136   uch b;                /* number of bits in this code or subcode */
137   union {
138     ush n;              /* literal, length base, or distance base */
139     struct huft *t;     /* pointer to next level of table */
140   } v;
141 };
142 
143 struct gZipStruct {
144   vFILE *iFp;
145   vFILE *oFp;
146   CDFstatus iError;     /* Returned if input file error. */
147   CDFstatus oError;     /* Returned if output file error. */
148   long ifile_size;      /* input file size */
149   unsigned short bi_buf;/* Output buffer. bits are inserted starting
150 			   at the bottom (least significant bits). */
151   int bi_valid;         /* Number of valid bits in bi_buf.  All bits above
152 			   the last valid bit are always zero. */
153   long block_start;     /* window position at the beginning of the current
154 			   output block. Gets negative when the window is
155 			   moved backwards. */
156   unsigned ins_h;       /* hash index of string to be inserted */
157   unsigned strstart;    /* start of string to insert */
158   unsigned match_start; /* start of matching string */
159   int eofile;           /* flag set at end of input file */
160   unsigned lookahead;   /* number of valid bytes ahead in window */
161   unsigned int prev_length;
162 			/* Length of the best match at previous step. Matches
163 			   not greater than this are discarded. This is used
164 			   in the lazy match evaluation. */
165   ush bl_count[MAX_BITS+1];
166 			/* number of codes at each bit length for an optimal
167 			   tree */
168   int heap[2*L_CODES+1];/* heap used to build the Huffman trees */
169   int heap_len;         /* number of elements in the heap */
170   int heap_max;         /* element of largest frequency */
171   /* The sons of heap[n] are heap[2*n] and heap[2*n+1].
172    * heap[0] is not used.
173    * The same heap array is used to build all trees.
174    */
175   uch depth[2*L_CODES+1];
176 			/* Depth of each subtree used as tie breaker for
177 			   trees of equal frequency */
178   uch length_code[MAX_MATCH-MIN_MATCH+1];
179 			/* length code for each normalized match length
180 			   (0 == MIN_MATCH) */
181   uch dist_code[512];   /* distance codes. The first 256 values correspond
182 			   to the distances 3 .. 258, the last 256 values
183 			   correspond to the top 8 bits of the 15 bit
184 			   distances. */
185   int base_length[LENGTH_CODES];
186 			/* First normalized length for each code
187 			   (0 = MIN_MATCH) */
188   int base_dist[D_CODES];
189 			/* First normalized distance for each code
190 			   (0 = distance of 1) */
191   uch flag_buf[(LIT_BUFSIZE/8)];
192 			/* flag_buf is a bit array distinguishing literals
193 			   from lengths in l_buf (inbuf), thus indicating the
194 			   presence or absence of a distance. */
195   unsigned last_lit;    /* running index in l_buf (inbuf) */
196   unsigned last_dist;   /* running index in d_buf */
197   unsigned last_flags;  /* running index in flag_buf */
198   uch tree_flags;       /* current flags not yet saved in flag_buf */
199   uch flag_bit;         /* current bit used in flags */
200 			/* bits are filled in flags starting at bit 0 (least
201 			   significant).  Note: these flags are overkill in
202 			   the current code since we don't take advantage of
203 			   DIST_BUFSIZE == LIT_BUFSIZE. */
204   ulg opt_len;          /* bit length of current block with optimal trees */
205   ulg static_len;       /* bit length of current block with static trees */
206   int level;            /* compression level */
207   unsigned outcnt;      /* bytes in output buffer */
208   long bytes_in;        /* number of input bytes */
209   long bytes_out;       /* number of output bytes */
210   ulg crc;              /* crc on uncompressed file data */
211   ulg crcReg;           /* shift register contents */
212   config configuration_table[10];
213   uch bl_order[BL_CODES];
214 			/* The lengths of the bit length codes are sent in
215 			   order of decreasing probability, to avoid
216 			   transmitting the lengths for unused bit length
217 			   codes. */
218   int extra_lbits[LENGTH_CODES];
219 			/* extra bits for each length code */
220   ct_data dyn_ltree[HEAP_SIZE];
221 			/* literal and length tree */
222   ct_data static_ltree[L_CODES+2];
223 			/* The static literal tree. Since the bit lengths are
224 			   imposed, there is no need for the L_CODES extra
225 			   codes used during heap construction. However, the
226 			   codes 286 and 287 are needed to build a canonical
227 			   tree (see ct_init below). */
228   tree_desc l_desc;
229   int extra_dbits[D_CODES];
230 			/* extra bits for each distance code */
231   ct_data dyn_dtree[2*D_CODES+1];
232 			/* distance tree */
233   ct_data static_dtree[D_CODES];
234 			/* The static distance tree. (Actually a trivial tree
235 			   since all codes use 5 bits.) */
236   tree_desc d_desc;
237   int extra_blbits[BL_CODES];
238 			/* extra bits for each bit length code */
239   ct_data bl_tree[2*BL_CODES+1];
240 			/* Huffman tree for the bit lengths */
241   tree_desc bl_desc;
242   ulg crc_32_tab[N_CRC_32_TAB];
243 			/* Table of CRC-32's of all single-byte values (made
244 			   by makecrc.c) */
245   uch *inbuf;           /* input buffer */
246   uch *outbuf;          /* output buffer */
247   ush *d_buf;           /* buffer for distances, see trees.c */
248   uch *window;          /* Sliding window and suffix table (unlzw) */
249   ush *prev;
250   ush *head;
251 };
252 typedef struct gZipStruct GZ;
253 typedef struct gZipStruct *GZp;
254 
255 struct gUnZipStruct {
256   vFILE *iFp;
257   vFILE *oFp;
258   CDFstatus iError;     /* Returned if input file error. */
259   CDFstatus oError;     /* Returned if output file error. */
260   ulg bb;               /* bit buffer */
261   unsigned bk;          /* bits in bit buffer */
262   unsigned hufts;       /* track memory usage */
263   unsigned outcnt;      /* bytes in output buffer */
264   long bytes_in;        /* number of input bytes */
265   long bytes_out;       /* number of output bytes */
266   ulg crcReg;           /* shift register contents */
267   unsigned insize;      /* valid bytes in inbuf */
268   unsigned inptr;       /* index of next byte to be processed in inbuf */
269   unsigned border[N_BORDER];
270 			/* Order of the bit length code lengths */
271   ush cplens[N_CPLENS]; /* Copy lengths for literal codes 257..285 */
272   ush cplext[N_CPLEXT]; /* Extra bits for literal codes 257..285 */
273   ush cpdist[N_CPDIST]; /* Copy offsets for distance codes 0..29 */
274   ush cpdext[N_CPDEXT]; /* Extra bits for distance codes */
275   ush mask_bits[N_MASK_BITS];
276   ulg crc_32_tab[N_CRC_32_TAB];
277 			/* Table of CRC-32's of all single-byte values (made
278 			   by makecrc.c) */
279   uch *inbuf;           /* input buffer */
280   uch *window;          /* Sliding window and suffix table (unlzw) */
281 };
282 typedef struct gUnZipStruct GU;
283 typedef struct gUnZipStruct *GUp;
284 
285 /******************************************************************************
286 * More macros.
287 ******************************************************************************/
288 
289 #define OS_CODE         0xFF    /* Does it really matter? - JTL */
290 				/* <Operating System,OS_CODE>:
291 				   <MS-DOS,0x0> <OS2,0x6> <WindowsNT,0xB>
292 				   <VMS,0x2> <UNIX,0x3> <amiga,0x1>
293 				   <atari,0x5> <MacOS,0x7> <PRIMOS,0xF>
294 				   <TOPS20,0xA> */
295 
296 #define OF(args) PROTOARGs(args)
297 #define memzero(s,n) memset((void*)(s),0,(n))
298 
299 /* Compression methods (see algorithm.doc) */
300 #define DEFLATED    8
301 
302 /* To save memory for 16 bit systems, some arrays are overlaid between
303  * the various modules:
304  * deflate:  prev+head   window      d_buf  l_buf  outbuf
305  * unlzw:    tab_prefix  tab_suffix  stack  inbuf  outbuf
306  * inflate:              window             inbuf
307  * unpack:               window             inbuf  prefix_len
308  * unlzh:    left+right  window      c_table inbuf c_len
309  * For compression, input is done in window[]. For decompression, output
310  * is done in window except for unlzw.
311  */
312 
313 #ifndef INBUFSIZ
314 #ifdef SMALL_MEM
315 #define INBUFSIZ  0x2000  /* input buffer size */
316 #else
317 #define INBUFSIZ  0x8000  /* input buffer size */
318 #endif
319 #endif
320 #define INBUF_EXTRA  64     /* required by unlzw() */
321 
322 #ifndef OUTBUFSIZ
323 #ifdef SMALL_MEM
324 #define OUTBUFSIZ   8192  /* output buffer size */
325 #else
326 #define OUTBUFSIZ  16384  /* output buffer size */
327 #endif
328 #endif
329 #define OUTBUF_EXTRA 2048   /* required by unlzw() */
330 
331 #ifndef DIST_BUFSIZE
332 #ifdef SMALL_MEM
333 #define DIST_BUFSIZE 0x2000 /* buffer for distances, see trees.c */
334 #else
335 #define DIST_BUFSIZE 0x8000 /* buffer for distances, see trees.c */
336 #endif
337 #endif
338 
339 #define GZIP_MAGIC     "\037\213" /* Magic header for gzip files, 1F 8B */
340 
341 /* gzip flag byte */
342 #define ASCII_FLAG   0x01 /* bit 0 set: file probably ascii text */
343 #define CONTINUATION 0x02 /* bit 1 set: continuation of multi-part gzip file */
344 #define EXTRA_FIELD  0x04 /* bit 2 set: extra field present */
345 #define ORIG_NAME    0x08 /* bit 3 set: original file name present */
346 #define COMMENT      0x10 /* bit 4 set: file comment present */
347 #define ENCRYPTED    0x20 /* bit 5 set: file is encrypted */
348 #define RESERVED     0xC0 /* bit 6,7:   reserved */
349 
350 #ifndef WSIZE
351 #define WSIZE 0x8000     /* window size--must be a power of two, and */
352 #endif                     /*  at least 32K for zip's deflate method */
353 #define WINDOW_SIZE ((ulg)2*WSIZE)
354 
355 #define MIN_LOOKAHEAD (MAX_MATCH+MIN_MATCH+1)
356 /* Minimum amount of lookahead, except at the end of the input file.
357  * See deflate.c for comments about the MIN_MATCH+1.
358  */
359 
360 #define MAX_DIST  (WSIZE-MIN_LOOKAHEAD)
361 /* In order to simplify the code, particularly on 16 bit machines, match
362  * distances are limited to MAX_DIST instead of WSIZE.
363  */
364 
365 /* Macros for getting two-byte and four-byte header values */
366 #define SH(p) ((ush)(uch)((p)[0]) | ((ush)(uch)((p)[1]) << 8))
367 #define LG(p) ((ulg)(SH(p)) | ((ulg)(SH((p)+2)) << 16))
368 
369 /* lzw.h -- define the lzw functions.
370  * Copyright (C) 1992-1993 Jean-loup Gailly.
371  * This is free software; you can redistribute it and/or modify it under the
372  * terms of the GNU General Public License, see the file COPYING.
373  */
374 
375 #define LBITS 9         /* bits in base literal/length lookup table */
376 #define DBITS 6         /* bits in base distance lookup table */
377 
378 #ifndef BITSx
379 #define BITSx 16
380 #endif
381 #define INIT_BITS 9              /* Initial number of bits per code */
382 
383 #define BUF_SIZE (8 * 2*sizeof(char))
384 /* Number of bits used within bi_buf. (bi_buf might be implemented on
385  * more than 16 bits on some systems.)
386  */
387 
388 /* Compile with MEDIUM_MEM to reduce the memory requirements or
389  * with SMALL_MEM to use as little memory as possible. Use BIG_MEM if the
390  * entire input file can be held in memory (not possible on 16 bit systems).
391  * Warning: defining these symbols affects HASH_BITS (see below) and thus
392  * affects the compression ratio. The compressed output
393  * is still correct, and might even be smaller in some cases.
394  */
395 
396 #ifdef SMALL_MEM
397 #define HASH_BITS  13  /* Number of bits used to hash strings */
398 #endif
399 #ifdef MEDIUM_MEM
400 #define HASH_BITS  14
401 #endif
402 #ifndef HASH_BITS
403 #define HASH_BITS  15
404    /* For portability to 16 bit machines, do not use values above 15. */
405 #endif
406 
407 /* To save space (see unlzw.c), we overlay prev+head with tab_prefix and
408  * window with tab_suffix. Check that we can do this:
409  */
410 #if !defined(SALFORDC)
411 #if (WSIZE<<1) > (1<<BITSx)
412    error: cannot overlay window with tab_suffix and prev with tab_prefix0
413 #endif
414 #endif
415 #if HASH_BITS > BITSx-1
416    error: cannot overlay head with tab_prefix1
417 #endif
418 #if EOF != (-1)
419    error: EOF != (-1)
420 #endif
421 
422 #define HASH_SIZE (unsigned)(1<<HASH_BITS)
423 #define HASH_MASK (HASH_SIZE-1)
424 #define WMASK     (WSIZE-1)
425 /* HASH_SIZE and WSIZE must be powers of two */
426 
427 #define NIL 0
428 /* Tail of hash chains */
429 
430 #define FAST 4
431 #define SLOW 2
432 /* speed options for the general purpose bit flag */
433 
434 #ifndef TOO_FAR
435 #define TOO_FAR 4096
436 #endif
437 /* Matches of length 3 are discarded if their distance exceeds TOO_FAR */
438 
439 #define H_SHIFT  ((HASH_BITS+MIN_MATCH-1)/MIN_MATCH)
440 /* Number of bits by which ins_h and del_h must be shifted at each
441  * input step. It must be such that after MIN_MATCH steps, the oldest
442  * byte no longer takes part in the hash key, that is:
443  *   H_SHIFT * MIN_MATCH >= HASH_BITS
444  */
445 
446 /* ===========================================================================
447  * Constants
448  */
449 
450 #define MAX_BL_BITS 7
451 /* Bit length codes must not exceed MAX_BL_BITS bits */
452 
453 #define END_BLOCK 256
454 /* end of block literal code */
455 
456 #define STORED_BLOCK 0
457 #define STATIC_TREES 1
458 #define DYN_TREES    2
459 /* The three kinds of block type */
460 
461 #ifndef DIST_BUFSIZE
462 #define DIST_BUFSIZE  LIT_BUFSIZE
463 #endif
464 /* Sizes of match buffers for literals/lengths and distances.  There are
465  * 4 reasons for limiting LIT_BUFSIZE to 64K:
466  *   - frequencies can be kept in 16 bit counters
467  *   - if compression is not successful for the first block, all input data is
468  *     still in the window so we can still emit a stored block even when input
469  *     comes from standard input.  (This can also be done for all blocks if
470  *     LIT_BUFSIZE is not greater than 32K.)
471  *   - if compression is not successful for a file smaller than 64K, we can
472  *     even emit a stored file instead of a stored block (saving 5 bytes).
473  *   - creating new Huffman trees less frequently may not provide fast
474  *     adaptation to changes in the input data statistics. (Take for
475  *     example a binary file with poorly compressible code followed by
476  *     a highly compressible string table.) Smaller buffer sizes give
477  *     fast adaptation but have of course the overhead of transmitting trees
478  *     more frequently.
479  *   - I can't count above 4
480  * The current code is general and allows DIST_BUFSIZE < LIT_BUFSIZE (to save
481  * memory at the expense of compression). Some optimizations would be possible
482  * if we rely on DIST_BUFSIZE == LIT_BUFSIZE.
483  */
484 #if LIT_BUFSIZE > INBUFSIZ
485     error cannot overlay l_buf and inbuf
486 #endif
487 
488 #define REP_3_6      16
489 /* repeat previous bit length 3-6 times (2 bits of repeat count) */
490 
491 #define REPZ_3_10    17
492 /* repeat a zero length 3-10 times  (3 bits of repeat count) */
493 
494 #define REPZ_11_138  18
495 /* repeat a zero length 11-138 times  (7 bits of repeat count) */
496 
497 #define send_code(gz_, c_, tree_) \
498 send_bits(gz_, tree_[c_].fc.code, tree_[c_].dl.len)
499    /* Send a code of the given tree. c and tree must not have side effects */
500 
501 #define d_code(dist_,dist_code_) \
502    ((dist_) < 256 ? dist_code_[dist_] : dist_code_[256+((dist_)>>7)])
503 /* Mapping from a distance to a distance code. dist is the distance - 1 and
504  * must not have side effects. dist_code[256] and dist_code[257] are never
505  * used.
506  */
507 
508 /* The inflate algorithm uses a sliding 32K byte window on the uncompressed
509    stream to find repeated byte strings.  This is implemented here as a
510    circular buffer.  The index is updated simply by incrementing and then
511    and'ing with 0x7fff (32K-1). */
512 /* It is left to other modules to supply the 32K area.  It is assumed
513    to be usable as if it were declared "uch slide[32768];" or as just
514    "uch *slide;" and then malloc'ed in the latter case.  The definition
515    must be in unzip.h, included above. */
516 
517 /* Macros for inflate() bit peeking and grabbing.
518    The usage is:
519 
520 	NEEDBITS(gu,b,k,j)
521 	x = b & mask_bits[j];
522 	DUMPBITS(b,k,j)
523 
524    where NEEDBITS makes sure that b has at least j bits in it, and
525    DUMPBITS removes the bits from b.  The macros use the variable k
526    for the number of bits in b.  Normally, b and k are register
527    variables for speed, and are initialized at the beginning of a
528    routine that uses these macros from a global bit buffer and count.
529 
530    If we assume that EOB will be the longest code, then we will never
531    ask for bits with NEEDBITS that are beyond the end of the stream.
532    So, NEEDBITS should not read any more bytes than are needed to
533    meet the request.  Then no bytes need to be "returned" to the buffer
534    at the end of the last block.
535 
536    However, this assumption is not true for fixed blocks--the EOB code
537    is 7 bits, but the other literal/length codes can be 8 or 9 bits.
538    (The EOB code is shorter than other codes because fixed blocks are
539    generally short.  So, while a block always has an EOB, many other
540    literal/length codes have a significantly lower probability of
541    showing up at all.)  However, by making the first table have a
542    lookup of seven bits, the EOB code will be found in that first
543    lookup, and so will not require that too many bits be pulled from
544    the stream.
545  */
546 
547 #define NEEDBITS(gu_,b_,k_,n_) { \
548   while (k_ < (n_)) { \
549     uch byte_; \
550     if (!GetByte(gu_,&byte_)) return 4; /* Read error. */ \
551     b_ |= (((ulg)byte_) << k_); \
552     k_ += 8; \
553   } \
554 }
555 
556 #define DUMPBITS(b_,k_,n_) { \
557 b_ >>= (n_); \
558 k_ -= (n_); \
559 }
560 
561 /* If BMAX needs to be larger than 16, then h and x[] should be ulg. */
562 #define BMAX 16         /* maximum bit length of any code (16 for explode) */
563 #define N_MAX 288       /* maximum number of codes in any set */
564 
565 /******************************************************************************
566 * Function prototypes.
567 ******************************************************************************/
568 
569 #if SUPPORT_GZIP
570 static void initCRC OF((ulg crc_32_tab[N_CRC_32_TAB]));
571 static Logical PutByte OF((GZp gz, unsigned c));
572 static Logical PutShort OF((GZp gz, unsigned w));
573 static Logical PutLong OF((GZp gz, ulg n));
574 static Logical GetByte OF((GUp gu, uch *byte));
575 static CDFstatus zip OF((
576   vFILE *iFp, Int32 iSize, CDFstatus iError, vFILE *oFp, Int32 *oSize,
577   CDFstatus oError, Int32 level
578 ));
579 static GZp initZip OF((
580   vFILE *iFp, vFILE *oFp, Int32 iSize, Int32 level, CDFstatus iError,
581   CDFstatus oError
582 ));
583 static void freeZip OF((GZp gz));
584 static int file_read OF((GZp gz, char *buf,  unsigned size));
585 static CDFstatus unzip OF((
586   vFILE *iFp, vFILE *oFp, CDFstatus iError, CDFstatus oError
587 ));
588 static GUp initUnZip OF((
589   vFILE *iFp, vFILE *oFp, CDFstatus iError, CDFstatus oError
590 ));
591 static void freeUnZip OF((GUp gu));
592 static Logical lm_init OF((GZp gz, ush *flags));
593 static CDFstatus deflate OF((GZp gz));
594 static void ct_init OF((GZp gz));
595 static int ct_tally OF((GZp gz, int dist, int lc));
596 static Logical flush_block OF((GZp gz, char *buf, ulg stored_len, int eof));
597 static void bi_init OF((GZp gz));
598 static Logical send_bits OF((GZp gz, int value, int length));
599 static unsigned bi_reverse OF((unsigned value, int length));
600 static Logical bi_windup  OF((GZp gz));
601 static Logical copy_block OF((GZp gz, char *buf, unsigned len, int header));
602 static ulg updcrc OF((
603   uch *s, unsigned n, ulg *crcReg, ulg crc_32_tab[N_CRC_32_TAB]
604 ));
605 static Logical fill_inbuf OF((GUp gu, uch *byte));
606 static Logical flush_outbuf OF((GZp gz));
607 static Logical flush_window OF((GUp gu));
608 static Logical write_buf OF((vFILE *vFp, void *buf, unsigned cnt));
609 static int inflate OF((GUp gu));
610 static Logical fill_window OF((GZp gz));
611 static CDFstatus deflate_fast OF((GZp gz));
612 static int longest_match OF((GZp gz, IPos cur_match));
613 static void init_block OF((GZp gz));
614 static void pqdownheap OF((GZp gz, ct_data *tree, int k));
615 static void gen_bitlen OF((GZp gz, tree_desc *desc));
616 static void gen_codes OF((GZp gz, ct_data *tree, int max_code));
617 static void build_tree_gz OF((GZp gz, tree_desc *desc));
618 static void scan_tree OF((GZp gz, ct_data *tree, int max_code));
619 static Logical send_tree OF((GZp gz, ct_data *tree, int max_code));
620 static int  build_bl_tree OF((GZp gz));
621 static Logical send_all_trees OF((
622   GZp gz, int lcodes, int dcodes, int blcodes
623 ));
624 static Logical compress_block OF((GZp gz, ct_data *ltree, ct_data *dtree));
625 static int huft_build OF((
626   GUp gu, unsigned *b, unsigned n, unsigned s, ush *d, ush *e,
627   struct huft **t, int *m
628 ));
629 static int huft_free OF((struct huft *t));
630 static int inflate_codes OF((
631   GUp gu, struct huft *tl, struct huft *td, int bl, int bd
632 ));
633 static int inflate_stored OF((GUp gu));
634 static int inflate_fixed OF((GUp gu));
635 static int inflate_dynamic OF((GUp gu));
636 static int inflate_block OF((GUp gu, int *e));
637 static int inflate OF((GUp gu));
638 #endif
639 
640 /******************************************************************************
641 * CompressGZIP.
642 ******************************************************************************/
643 
CompressGZIP(srcFp,srcOffset,srcSize,srcError,destFp,destOffset,destSize,destError,level)644 STATICforIDL CDFstatus CompressGZIP (srcFp, srcOffset, srcSize, srcError,
645 				     destFp, destOffset, destSize, destError,
646 				     level)
647 vFILE *srcFp;
648 Int32 srcOffset;
649 Int32 srcSize;
650 CDFstatus srcError;
651 vFILE *destFp;
652 Int32 destOffset;
653 Int32 *destSize;
654 CDFstatus destError;
655 Int32 level;
656 {
657 #if SUPPORT_GZIP
658   CDFstatus pStatus = CDF_OK;
659   if (!SEEKv(srcFp,(long)srcOffset,vSEEK_SET)) return srcError;
660   if (!SEEKv(destFp,(long)destOffset,vSEEK_SET)) return destError;
661   if (!sX(zip(srcFp,srcSize,srcError,
662 	      destFp,destSize,destError,level),&pStatus)) return pStatus;
663   return pStatus;
664 #else
665   return UNKNOWN_COMPRESSION;
666 #endif
667 }
668 
669 /******************************************************************************
670 * DecompressGZIP.
671 ******************************************************************************/
672 
DecompressGZIP(srcFp,srcOffset,srcError,destFp,destOffset,destError)673 STATICforIDL CDFstatus DecompressGZIP (srcFp, srcOffset, srcError, destFp,
674 				       destOffset, destError)
675 vFILE *srcFp;
676 Int32 srcOffset;
677 CDFstatus srcError;
678 vFILE *destFp;
679 Int32 destOffset;
680 CDFstatus destError;
681 {
682 #if SUPPORT_GZIP
683   CDFstatus pStatus = CDF_OK;
684   if (!SEEKv(srcFp,(long)srcOffset,vSEEK_SET)) return srcError;
685   if (!SEEKv(destFp,(long)destOffset,vSEEK_SET)) return destError;
686   if (!sX(unzip(srcFp,destFp,srcError,destError),&pStatus)) return pStatus;
687   return pStatus;
688 #else
689   return UNKNOWN_COMPRESSION;
690 #endif
691 }
692 
693 #if SUPPORT_GZIP
694 /******************************************************************************
695 * zip.
696 *   Returns as soon as an error occurs.  Any memory allocated will be freed
697 * by the calling routine.  If successful, this routine frees the memory.
698 ******************************************************************************/
699 
700 /* zip.c -- compress files to the gzip or pkzip format
701  * Copyright (C) 1992-1993 Jean-loup Gailly
702  * This is free software; you can redistribute it and/or modify it under the
703  * terms of the GNU General Public License, see the file COPYING.
704  */
705 
706 /* ===========================================================================
707  * Deflate in to out.
708  * IN assertions: the input and output buffers are cleared.
709  *   The variables time_stamp and save_orig_name are initialized.
710  */
711 
zip(iFp,iSize,iError,oFp,oSize,oError,level)712 static CDFstatus zip (iFp, iSize, iError, oFp, oSize, oError, level)
713 vFILE *iFp;
714 Int32 iSize;
715 CDFstatus iError;
716 vFILE *oFp;
717 Int32 *oSize;
718 CDFstatus oError;
719 Int32 level;
720 {
721   CDFstatus pStatus = CDF_OK;
722   uch  flags2 = 0;         /* general purpose bit flags */
723   ush  deflate_flags = 0;  /* pkzip -es, -en or -ex equivalent */
724   long time_stamp = 0;  /* JTL */
725   GZp gz;
726   gz = initZip (iFp, oFp, iSize, level, iError, oError);
727   if (gz == NULL) return BAD_MALLOC;
728   /* Write the header to the gzip file. See algorithm.doc for the format */
729   if (!PutByte(gz,(unsigned)GZIP_MAGIC[0])) return gz->oError;
730 						/* magic header[0]. */
731   if (!PutByte(gz,(unsigned)GZIP_MAGIC[1])) return gz->oError;
732 						/* magic header[1]. */
733   if (!PutByte(gz,(unsigned)DEFLATED)) return gz->oError;
734 						/* compression method. */
735   if (!PutByte(gz,(unsigned)flags2)) return gz->oError;
736 						/* general flags. */
737   if (!PutLong(gz,time_stamp)) return gz->oError;
738 						/* time stamp. */
739   /* Write deflated file to zip file */
740   gz->crc = updcrc (0, 0, &(gz->crcReg), gz->crc_32_tab);
741   bi_init(gz);
742   ct_init(gz);
743   if (!lm_init(gz,&deflate_flags)) return gz->iError;   /* Read error. */
744   if (!PutByte(gz,(unsigned)deflate_flags)) return gz->oError;
745 						/* extra flags. */
746   if (!PutByte(gz,(unsigned)OS_CODE)) return gz->oError;
747 						/* OS identifier. */
748   if (!sX(deflate(gz),&pStatus)) return pStatus;
749   /* Write the crc and uncompressed size */
750   if (!PutLong(gz,gz->crc)) return gz->oError;
751   if (!PutLong(gz,gz->bytes_in)) return gz->oError;
752   if (!flush_outbuf(gz)) return gz->oError;     /* Write error. */
753   *oSize = (Int32) gz->bytes_out;
754   freeZip (gz);
755   return pStatus;
756 }
757 
758 /******************************************************************************
759 * initZip.
760 *   Returns as soon as an error occurs.  Any memory allocated will be freed
761 * by the calling routine.
762 ******************************************************************************/
763 
initZip(iFp,oFp,iSize,level,iError,oError)764 static GZp initZip (iFp, oFp, iSize, level, iError, oError)
765 vFILE *iFp;
766 vFILE *oFp;
767 Int32 iSize;
768 Int32 level;
769 CDFstatus iError;
770 CDFstatus oError;
771 {
772     GZp gz = (GZp) CallocateMemory ((size_t) 1, sizeof(GZ), NULL);
773     if (gz == NULL) return NULL;
774     gz->inbuf = (uch *) CallocateMemory ((size_t) (INBUFSIZ+INBUF_EXTRA),
775 					 sizeof(uch), NULL);
776     if (gz->inbuf == NULL) return NULL;
777     gz->outbuf = (uch *) CallocateMemory ((size_t) (OUTBUFSIZ+OUTBUF_EXTRA),
778 					  sizeof(uch), NULL);
779     if (gz->outbuf == NULL) return NULL;
780     gz->d_buf = (ush *) CallocateMemory ((size_t) (DIST_BUFSIZE),
781 					 sizeof(ush), NULL);
782     if (gz->d_buf == NULL) return NULL;
783     gz->window = (uch *) CallocateMemory ((size_t) (2L*WSIZE),
784 					  sizeof(uch), NULL);
785     if (gz->window == NULL) return NULL;
786     gz->prev = (ush *) CallocateMemory ((size_t) (1L<<(BITSx-1)),
787 					sizeof(ush), NULL);
788     if (gz->prev == NULL) return NULL;
789     gz->head = (ush *) CallocateMemory ((size_t) (1L<<(BITSx-1)),
790 					sizeof(ush), NULL);
791     if (gz->head == NULL) return NULL;
792 
793     gz->iFp = iFp;
794     gz->oFp = oFp;
795     gz->ifile_size = (long) iSize;
796     gz->level = (int) level;
797     gz->outcnt = 0;
798     gz->bytes_in = 0;
799     gz->bytes_out = 0;
800     gz->crcReg = (ulg) 0xffffffffL;
801     gz->iError = iError;
802     gz->oError = oError;
803 
804     gz->configuration_table[0].good_length = 0;
805     gz->configuration_table[0].max_lazy = 0;
806     gz->configuration_table[0].nice_length = 0;
807     gz->configuration_table[0].max_chain = 0;
808     gz->configuration_table[1].good_length = 4;
809     gz->configuration_table[1].max_lazy = 4;
810     gz->configuration_table[1].nice_length = 8;
811     gz->configuration_table[1].max_chain = 4;
812     gz->configuration_table[2].good_length = 4;
813     gz->configuration_table[2].max_lazy = 5;
814     gz->configuration_table[2].nice_length = 16;
815     gz->configuration_table[2].max_chain = 8;
816     gz->configuration_table[3].good_length = 4;
817     gz->configuration_table[3].max_lazy = 6;
818     gz->configuration_table[3].nice_length = 32;
819     gz->configuration_table[3].max_chain = 32;
820     gz->configuration_table[4].good_length = 4;
821     gz->configuration_table[4].max_lazy = 4;
822     gz->configuration_table[4].nice_length = 16;
823     gz->configuration_table[4].max_chain = 16;
824     gz->configuration_table[5].good_length = 8;
825     gz->configuration_table[5].max_lazy = 16;
826     gz->configuration_table[5].nice_length = 32;
827     gz->configuration_table[5].max_chain = 32;
828     gz->configuration_table[6].good_length = 8;
829     gz->configuration_table[6].max_lazy = 16;
830     gz->configuration_table[6].nice_length = 128;
831     gz->configuration_table[6].max_chain = 128;
832     gz->configuration_table[7].good_length = 8;
833     gz->configuration_table[7].max_lazy = 32;
834     gz->configuration_table[7].nice_length = 128;
835     gz->configuration_table[7].max_chain = 256;
836     gz->configuration_table[8].good_length = 32;
837     gz->configuration_table[8].max_lazy = 128;
838     gz->configuration_table[8].nice_length = 258;
839     gz->configuration_table[8].max_chain = 1024;
840     gz->configuration_table[9].good_length = 32;
841     gz->configuration_table[9].max_lazy = 258;
842     gz->configuration_table[9].nice_length = 258;
843     gz->configuration_table[9].max_chain = 4096;
844 
845     gz->bl_order[0] = 16;
846     gz->bl_order[1] = 17;
847     gz->bl_order[2] = 18;
848     gz->bl_order[3] = 0;
849     gz->bl_order[4] = 8;
850     gz->bl_order[5] = 7;
851     gz->bl_order[6] = 9;
852     gz->bl_order[7] = 6;
853     gz->bl_order[8] = 10;
854     gz->bl_order[9] = 5;
855     gz->bl_order[10] = 11;
856     gz->bl_order[11] = 4;
857     gz->bl_order[12] = 12;
858     gz->bl_order[13] = 3;
859     gz->bl_order[14] = 13;
860     gz->bl_order[15] = 2;
861     gz->bl_order[16] = 14;
862     gz->bl_order[17] = 1;
863     gz->bl_order[18] = 15;
864 
865     gz->extra_lbits[0] = 0;
866     gz->extra_lbits[1] = 0;
867     gz->extra_lbits[2] = 0;
868     gz->extra_lbits[3] = 0;
869     gz->extra_lbits[4] = 0;
870     gz->extra_lbits[5] = 0;
871     gz->extra_lbits[6] = 0;
872     gz->extra_lbits[7] = 0;
873     gz->extra_lbits[8] = 1;
874     gz->extra_lbits[9] = 1;
875     gz->extra_lbits[10] = 1;
876     gz->extra_lbits[11] = 1;
877     gz->extra_lbits[12] = 2;
878     gz->extra_lbits[13] = 2;
879     gz->extra_lbits[14] = 2;
880     gz->extra_lbits[15] = 2;
881     gz->extra_lbits[16] = 3;
882     gz->extra_lbits[17] = 3;
883     gz->extra_lbits[18] = 3;
884     gz->extra_lbits[19] = 3;
885     gz->extra_lbits[20] = 4;
886     gz->extra_lbits[21] = 4;
887     gz->extra_lbits[22] = 4;
888     gz->extra_lbits[23] = 4;
889     gz->extra_lbits[24] = 5;
890     gz->extra_lbits[25] = 5;
891     gz->extra_lbits[26] = 5;
892     gz->extra_lbits[27] = 5;
893     gz->extra_lbits[28] = 0;
894 
895     gz->extra_dbits[0] = 0;
896     gz->extra_dbits[1] = 0;
897     gz->extra_dbits[2] = 0;
898     gz->extra_dbits[3] = 0;
899     gz->extra_dbits[4] = 1;
900     gz->extra_dbits[5] = 1;
901     gz->extra_dbits[6] = 2;
902     gz->extra_dbits[7] = 2;
903     gz->extra_dbits[8] = 3;
904     gz->extra_dbits[9] = 3;
905     gz->extra_dbits[10] = 4;
906     gz->extra_dbits[11] = 4;
907     gz->extra_dbits[12] = 5;
908     gz->extra_dbits[13] = 5;
909     gz->extra_dbits[14] = 6;
910     gz->extra_dbits[15] = 6;
911     gz->extra_dbits[16] = 7;
912     gz->extra_dbits[17] = 7;
913     gz->extra_dbits[18] = 8;
914     gz->extra_dbits[19] = 8;
915     gz->extra_dbits[20] = 9;
916     gz->extra_dbits[21] = 9;
917     gz->extra_dbits[22] = 10;
918     gz->extra_dbits[23] = 10;
919     gz->extra_dbits[24] = 11;
920     gz->extra_dbits[25] = 11;
921     gz->extra_dbits[26] = 12;
922     gz->extra_dbits[27] = 12;
923     gz->extra_dbits[28] = 13;
924     gz->extra_dbits[29] = 13;
925 
926     gz->extra_blbits[0] = 0;
927     gz->extra_blbits[1] = 0;
928     gz->extra_blbits[2] = 0;
929     gz->extra_blbits[3] = 0;
930     gz->extra_blbits[4] = 0;
931     gz->extra_blbits[5] = 0;
932     gz->extra_blbits[6] = 0;
933     gz->extra_blbits[7] = 0;
934     gz->extra_blbits[8] = 0;
935     gz->extra_blbits[9] = 0;
936     gz->extra_blbits[10] = 0;
937     gz->extra_blbits[11] = 0;
938     gz->extra_blbits[12] = 0;
939     gz->extra_blbits[13] = 0;
940     gz->extra_blbits[14] = 0;
941     gz->extra_blbits[15] = 0;
942     gz->extra_blbits[16] = 2;
943     gz->extra_blbits[17] = 3;
944     gz->extra_blbits[18] = 7;
945 
946     gz->l_desc.dyn_tree = gz->dyn_ltree;
947     gz->l_desc.static_tree = gz->static_ltree;
948     gz->l_desc.extra_bits = gz->extra_lbits;
949     gz->l_desc.extra_base = LITERALS+1;
950     gz->l_desc.elems = L_CODES;
951     gz->l_desc.max_length = MAX_BITS;
952     gz->l_desc.max_code = 0;
953 
954     gz->d_desc.dyn_tree = gz->dyn_dtree;
955     gz->d_desc.static_tree = gz->static_dtree;
956     gz->d_desc.extra_bits = gz->extra_dbits;
957     gz->d_desc.extra_base = 0;
958     gz->d_desc.elems = D_CODES;
959     gz->d_desc.max_length = MAX_BITS;
960     gz->d_desc.max_code = 0;
961 
962     gz->bl_desc.dyn_tree = gz->bl_tree;
963     gz->bl_desc.static_tree = NULL;
964     gz->bl_desc.extra_bits = gz->extra_blbits;
965     gz->bl_desc.extra_base = 0;
966     gz->bl_desc.elems = BL_CODES;
967     gz->bl_desc.max_length = MAX_BL_BITS;
968     gz->bl_desc.max_code = 0;
969 
970     initCRC (gz->crc_32_tab);
971 
972     return gz;
973 }
974 
975 /******************************************************************************
976 * freeZip.
977 ******************************************************************************/
978 
freeZip(gz)979 static void freeZip (gz)
980 GZp gz;
981 {
982   cdf_FreeMemory (gz->head, NULL);
983   cdf_FreeMemory (gz->prev, NULL);
984   cdf_FreeMemory (gz->window, NULL);
985   cdf_FreeMemory (gz->d_buf, NULL);
986   cdf_FreeMemory (gz->outbuf, NULL);
987   cdf_FreeMemory (gz->inbuf, NULL);
988   cdf_FreeMemory (gz, NULL);
989   return;
990 }
991 
992 /******************************************************************************
993 * unzip.
994 *   Returns as soon as an error occurs.  Any memory allocated will be freed
995 * by the calling routine.  If successful, this routine frees the memory.
996 ******************************************************************************/
997 
998 /* unzip.c -- decompress files in gzip or pkzip format.
999  * Copyright (C) 1992-1993 Jean-loup Gailly
1000  * This is free software; you can redistribute it and/or modify it under the
1001  * terms of the GNU General Public License, see the file COPYING.
1002  *
1003  * The code in this file is derived from the file funzip.c written
1004  * and put in the public domain by Mark Adler.
1005  */
1006 
1007 /*
1008    This version can extract files in gzip or pkzip format.
1009    For the latter, only the first entry is extracted, and it has to be
1010    either deflated or stored.
1011  */
1012 
1013 /* ===========================================================================
1014  * Unzip in to out.  This routine works on both gzip and pkzip files.
1015  *
1016  * IN assertions: the buffer inbuf contains already the beginning of
1017  *   the compressed data, from offsets inptr to insize-1 included.
1018  *   The magic header has already been checked. The output buffer is cleared.
1019  */
1020 
unzip(iFp,oFp,iError,oError)1021 static CDFstatus unzip (iFp, oFp, iError, oError)
1022 vFILE *iFp;
1023 vFILE *oFp;
1024 CDFstatus iError;
1025 CDFstatus oError;
1026 {
1027   ulg orig_crc = 0;       /* original crc */
1028   ulg orig_len = 0;       /* original uncompressed length */
1029   int n; uch buf[8], byte;
1030   /* uch flags1; */    /* compression flags */
1031   /* char magic[2]; */ /* magic header */
1032   /* ulg stamp; */     /* time stamp */
1033   int method; GUp gu;
1034   gu = initUnZip (iFp, oFp, iError, oError);
1035   if (gu == NULL) return BAD_MALLOC;
1036   if (!GetByte(gu,&byte)) return gu->iError;		/* magic[0]. */
1037   if (!GetByte(gu,&byte)) return gu->iError;		/* magic[1]. */
1038   if (!GetByte(gu,&byte)) return gu->iError;		/* method. */
1039   method = (int) byte;
1040   if (!GetByte(gu,&byte)) return gu->iError;		/* flags1. */
1041   if (!GetByte(gu,&byte)) return gu->iError;		/* stamp[0]. */
1042   if (!GetByte(gu,&byte)) return gu->iError;		/* stamp[1]. */
1043   if (!GetByte(gu,&byte)) return gu->iError;		/* stamp[2]. */
1044   if (!GetByte(gu,&byte)) return gu->iError;		/* stamp[3]. */
1045   if (!GetByte(gu,&byte)) return gu->iError;		/* "extra flags". */
1046   if (!GetByte(gu,&byte)) return gu->iError;		/* "OS type". */
1047   updcrc (NULL, 0, &(gu->crcReg), gu->crc_32_tab);      /* initialize crc */
1048   /* Decompress */
1049   if (method == DEFLATED)  {
1050     switch (inflate(gu)) {
1051       case 0:
1052 	break;  /* Success. */
1053       case 1:
1054       case 2:
1055 	return DECOMPRESSION_ERROR;
1056       case 3:
1057 	return BAD_MALLOC;
1058       case 4:
1059 	return gu->iError;      /* Read error. */
1060       case 5:
1061 	return gu->oError;      /* Write error. */
1062       default:
1063 	return CDF_INTERNAL_ERROR;      /* ??? */
1064     }
1065   }
1066   else {
1067     /* error("internal error, invalid method"); */
1068     return DECOMPRESSION_ERROR;
1069   }
1070   /* Get the crc and original length */
1071   /* crc32  (see algorithm.doc)
1072    * uncompressed input size modulo 2^32
1073    */
1074   for (n = 0; n < 8; n++) {
1075      if (!GetByte(gu,&byte)) return gu->iError;
1076      buf[n] = (uch) byte;
1077   }
1078   orig_crc = LG(buf);
1079   orig_len = LG(buf+4);
1080   /* Validate decompression */
1081   if (orig_crc != updcrc(gu->window,0,&(gu->crcReg),gu->crc_32_tab)) {
1082 						/* JTL: outbuf --> window */
1083     /* error("invalid compressed data--crc error"); */
1084     return DECOMPRESSION_ERROR;
1085   }
1086   if (orig_len != (ulg)gu->bytes_out) {
1087     /* error("invalid compressed data--length error"); */
1088     return DECOMPRESSION_ERROR;
1089   }
1090   freeUnZip (gu);
1091   return CDF_OK;
1092 }
1093 
1094 /******************************************************************************
1095 * initUnZip.
1096 *   Returns as soon as an error occurs.  Any memory allocated will be freed
1097 * by the calling routine.
1098 ******************************************************************************/
1099 
initUnZip(iFp,oFp,iError,oError)1100 static GUp initUnZip (iFp, oFp, iError, oError)
1101 vFILE *iFp;
1102 vFILE *oFp;
1103 CDFstatus iError;
1104 CDFstatus oError;
1105 {
1106     GUp gu = (GUp) CallocateMemory ((size_t) 1, sizeof(GU), NULL);
1107     if (gu == NULL) return NULL;
1108     gu->inbuf = (uch *) CallocateMemory ((size_t) (INBUFSIZ+INBUF_EXTRA),
1109 					 sizeof(uch), NULL);
1110     if (gu->inbuf == NULL) return NULL;
1111     gu->window = (uch *) CallocateMemory ((size_t) (2L*WSIZE), sizeof(uch),
1112 					  NULL);
1113     if (gu->window == NULL) return NULL;
1114 
1115     gu->iFp = iFp;
1116     gu->oFp = oFp;
1117     gu->iError = iError;
1118     gu->oError = oError;
1119     gu->outcnt = 0;
1120     gu->bytes_in = 0;
1121     gu->bytes_out = 0;
1122     gu->insize = 0;
1123     gu->inptr = 0;
1124     gu->crcReg = (ulg) 0xffffffffL;
1125 
1126     gu->border[0] = 16;
1127     gu->border[1] = 17;
1128     gu->border[2] = 18;
1129     gu->border[3] = 0;
1130     gu->border[4] = 8;
1131     gu->border[5] = 7;
1132     gu->border[6] = 9;
1133     gu->border[7] = 6;
1134     gu->border[8] = 10;
1135     gu->border[9] = 5;
1136     gu->border[10] = 11;
1137     gu->border[11] = 4;
1138     gu->border[12] = 12;
1139     gu->border[13] = 3;
1140     gu->border[14] = 13;
1141     gu->border[15] = 2;
1142     gu->border[16] = 14;
1143     gu->border[17] = 1;
1144     gu->border[18] = 15;
1145 
1146     gu->cplens[0] = 3;
1147     gu->cplens[1] = 4;
1148     gu->cplens[2] = 5;
1149     gu->cplens[3] = 6;
1150     gu->cplens[4] = 7;
1151     gu->cplens[5] = 8;
1152     gu->cplens[6] = 9;
1153     gu->cplens[7] = 10;
1154     gu->cplens[8] = 11;
1155     gu->cplens[9] = 13;
1156     gu->cplens[10] = 15;
1157     gu->cplens[11] = 17;
1158     gu->cplens[12] = 19;
1159     gu->cplens[13] = 23;
1160     gu->cplens[14] = 27;
1161     gu->cplens[15] = 31;
1162     gu->cplens[16] = 35;
1163     gu->cplens[17] = 43;
1164     gu->cplens[18] = 51;
1165     gu->cplens[19] = 59;
1166     gu->cplens[20] = 67;
1167     gu->cplens[21] = 83;
1168     gu->cplens[22] = 99;
1169     gu->cplens[23] = 115;
1170     gu->cplens[24] = 131;
1171     gu->cplens[25] = 163;
1172     gu->cplens[26] = 195;
1173     gu->cplens[27] = 227;
1174     gu->cplens[28] = 258;
1175     gu->cplens[29] = 0;
1176     gu->cplens[30] = 0;
1177 
1178     gu->cplext[0] = 0;
1179     gu->cplext[1] = 0;
1180     gu->cplext[2] = 0;
1181     gu->cplext[3] = 0;
1182     gu->cplext[4] = 0;
1183     gu->cplext[5] = 0;
1184     gu->cplext[6] = 0;
1185     gu->cplext[7] = 0;
1186     gu->cplext[8] = 1;
1187     gu->cplext[9] = 1;
1188     gu->cplext[10] = 1;
1189     gu->cplext[11] = 1;
1190     gu->cplext[12] = 2;
1191     gu->cplext[13] = 2;
1192     gu->cplext[14] = 2;
1193     gu->cplext[15] = 2;
1194     gu->cplext[16] = 3;
1195     gu->cplext[17] = 3;
1196     gu->cplext[18] = 3;
1197     gu->cplext[19] = 3;
1198     gu->cplext[20] = 4;
1199     gu->cplext[21] = 4;
1200     gu->cplext[22] = 4;
1201     gu->cplext[23] = 4;
1202     gu->cplext[24] = 5;
1203     gu->cplext[25] = 5;
1204     gu->cplext[26] = 5;
1205     gu->cplext[27] = 5;
1206     gu->cplext[28] = 0;
1207     gu->cplext[29] = 99;
1208     gu->cplext[30] = 99;
1209 
1210     gu->cpdist[0] = 1;
1211     gu->cpdist[1] = 2;
1212     gu->cpdist[2] = 3;
1213     gu->cpdist[3] = 4;
1214     gu->cpdist[4] = 5;
1215     gu->cpdist[5] = 7;
1216     gu->cpdist[6] = 9;
1217     gu->cpdist[7] = 13;
1218     gu->cpdist[8] = 17;
1219     gu->cpdist[9] = 25;
1220     gu->cpdist[10] = 33;
1221     gu->cpdist[11] = 49;
1222     gu->cpdist[12] = 65;
1223     gu->cpdist[13] = 97;
1224     gu->cpdist[14] = 129;
1225     gu->cpdist[15] = 193;
1226     gu->cpdist[16] = 257;
1227     gu->cpdist[17] = 385;
1228     gu->cpdist[18] = 513;
1229     gu->cpdist[19] = 769;
1230     gu->cpdist[20] = 1025;
1231     gu->cpdist[21] = 1537;
1232     gu->cpdist[22] = 2049;
1233     gu->cpdist[23] = 3073;
1234     gu->cpdist[24] = 4097;
1235     gu->cpdist[25] = 6145;
1236     gu->cpdist[26] = 8193;
1237     gu->cpdist[27] = 12289;
1238     gu->cpdist[28] = 16385;
1239     gu->cpdist[29] = 24577;
1240 
1241     gu->cpdext[0] = 0;
1242     gu->cpdext[1] = 0;
1243     gu->cpdext[2] = 0;
1244     gu->cpdext[3] = 0;
1245     gu->cpdext[4] = 1;
1246     gu->cpdext[5] = 1;
1247     gu->cpdext[6] = 2;
1248     gu->cpdext[7] = 2;
1249     gu->cpdext[8] = 3;
1250     gu->cpdext[9] = 3;
1251     gu->cpdext[10] = 4;
1252     gu->cpdext[11] = 4;
1253     gu->cpdext[12] = 5;
1254     gu->cpdext[13] = 5;
1255     gu->cpdext[14] = 6;
1256     gu->cpdext[15] = 6;
1257     gu->cpdext[16] = 7;
1258     gu->cpdext[17] = 7;
1259     gu->cpdext[18] = 8;
1260     gu->cpdext[19] = 8;
1261     gu->cpdext[20] = 9;
1262     gu->cpdext[21] = 9;
1263     gu->cpdext[22] = 10;
1264     gu->cpdext[23] = 10;
1265     gu->cpdext[24] = 11;
1266     gu->cpdext[25] = 11;
1267     gu->cpdext[26] = 12;
1268     gu->cpdext[27] = 12;
1269     gu->cpdext[28] = 13;
1270     gu->cpdext[29] = 13;
1271 
1272     gu->mask_bits[0] = 0x0000;
1273     gu->mask_bits[1] = 0x0001;
1274     gu->mask_bits[2] = 0x0003;
1275     gu->mask_bits[3] = 0x0007;
1276     gu->mask_bits[4] = 0x000f;
1277     gu->mask_bits[5] = 0x001f;
1278     gu->mask_bits[6] = 0x003f;
1279     gu->mask_bits[7] = 0x007f;
1280     gu->mask_bits[8] = 0x00ff;
1281     gu->mask_bits[9] = 0x01ff;
1282     gu->mask_bits[10] = 0x03ff;
1283     gu->mask_bits[11] = 0x07ff;
1284     gu->mask_bits[12] = 0x0fff;
1285     gu->mask_bits[13] = 0x1fff;
1286     gu->mask_bits[14] = 0x3fff;
1287     gu->mask_bits[15] = 0x7fff;
1288     gu->mask_bits[16] = 0xffff;
1289 
1290     initCRC (gu->crc_32_tab);
1291 
1292     return gu;
1293 }
1294 
1295 /******************************************************************************
1296 * freeUnZip.
1297 ******************************************************************************/
1298 
freeUnZip(gu)1299 static void freeUnZip (gu)
1300 GUp gu;
1301 {
1302   cdf_FreeMemory (gu->window, NULL);
1303   cdf_FreeMemory (gu->inbuf, NULL);
1304   cdf_FreeMemory (gu, NULL);
1305   return;
1306 }
1307 
1308 /* ===========================================================================
1309  * Read a new buffer from the current input file, perform end-of-line
1310  * translation, and update the crc and input file size.
1311  * IN assertion: size >= 2 (for end-of-line translation)
1312  */
1313 /* Returns:     >0      number of bytes read,   - JTL...
1314 		0       fake EOF,
1315 		-1      error or real EOF.
1316 */
1317 
file_read(gz,buf,size)1318 static int file_read(gz, buf, size)
1319     GZp gz;
1320     char *buf;
1321     unsigned size;
1322 {
1323     unsigned len;
1324     long remaining = gz->ifile_size - gz->bytes_in; /* JTL... */
1325     if (remaining == 0) return 0;                       /* Fake `EOF'. */
1326     size = (unsigned) MINIMUM((long)size,remaining);        /* ...JTL */
1327     len = (unsigned) V_read (buf, (size_t) 1, (size_t) size, gz->iFp);
1328     if (len == 0) return (int)(-1);     /* V_read returns 0 if an error. */
1329     gz->crc = updcrc ((uch*) buf, len, &(gz->crcReg), gz->crc_32_tab);
1330     gz->bytes_in += (ulg)len;
1331     return (int)len;
1332 }
1333 
1334 
1335 
1336 /* bits.c -- output variable-length bit strings
1337  * Copyright (C) 1992-1993 Jean-loup Gailly
1338  * This is free software; you can redistribute it and/or modify it under the
1339  * terms of the GNU General Public License, see the file COPYING.
1340  */
1341 
1342 
1343 /*
1344  *  PURPOSE
1345  *
1346  *      Output variable-length bit strings. Compression can be done
1347  *      to a file or to memory. (The latter is not supported in this version.)
1348  *
1349  *  DISCUSSION
1350  *
1351  *      The PKZIP "deflate" file format interprets compressed file data
1352  *      as a sequence of bits.  Multi-bit strings in the file may cross
1353  *      byte boundaries without restriction.
1354  *
1355  *      The first bit of each byte is the low-order bit.
1356  *
1357  *      The routines in this file allow a variable-length bit value to
1358  *      be output right-to-left (useful for literal values). For
1359  *      left-to-right output (useful for code strings from the tree routines),
1360  *      the bits must have been reversed first with bi_reverse().
1361  *
1362  *      For in-memory compression, the compressed bit stream goes directly
1363  *      into the requested output buffer. The input data is read in blocks
1364  *      by the mem_read() function. The buffer is limited to 64K on 16 bit
1365  *      machines.
1366  *
1367  *  INTERFACE
1368  *
1369  *      void bi_init (GZp gz)
1370  *          Initialize the bit string routines.
1371  *
1372  *      Logical send_bits (GZp gz, int value, int length)
1373  *          Write out a bit string, taking the source bits right to
1374  *          left.
1375  *
1376  *      int bi_reverse (int value, int length)
1377  *          Reverse the bits of a bit string, taking the source bits left to
1378  *          right and emitting them right to left.
1379  *
1380  *      Logical bi_windup (GZp gz)
1381  *          Write out any remaining bits in an incomplete byte.
1382  *
1383  *      Logical copy_block(GZp gz, char *buf, unsigned len, int header)
1384  *          Copy a stored block to the zip file, storing first the length and
1385  *          its one's complement if requested.
1386  *
1387  */
1388 
1389 /* ===========================================================================
1390  * Initialize the bit string routines.
1391  */
bi_init(gz)1392 static void bi_init (gz)
1393 GZp gz;
1394 {
1395     gz->bi_buf = 0;
1396     gz->bi_valid = 0;
1397 }
1398 
1399 /* ===========================================================================
1400  * Send a value on a given number of bits.
1401  * IN assertion: length <= 16 and value fits in length bits.
1402  */
send_bits(gz,value,length)1403 static Logical send_bits(gz, value, length)
1404     GZp gz;
1405     int value;  /* value to send */
1406     int length; /* number of bits */
1407 {
1408     /* If not enough room in bi_buf, use (valid) bits from bi_buf and
1409      * (16 - bi_valid) bits from value, leaving (width - (16-bi_valid))
1410      * unused bits in value.
1411      */
1412     if (gz->bi_valid > (int)BUF_SIZE - length) {
1413 	gz->bi_buf |= (value << gz->bi_valid);
1414 	if (!PutShort(gz,(unsigned)gz->bi_buf)) return FALSE;
1415 	gz->bi_buf = (ush)value >> (BUF_SIZE - gz->bi_valid);
1416 	gz->bi_valid += length - BUF_SIZE;
1417     } else {
1418 	gz->bi_buf |= value << gz->bi_valid;
1419 	gz->bi_valid += length;
1420     }
1421     return TRUE;
1422 }
1423 
1424 /* ===========================================================================
1425  * Reverse the first len bits of a code, using straightforward code (a faster
1426  * method would use a table)
1427  * IN assertion: 1 <= len <= 15
1428  */
bi_reverse(code,len)1429 static unsigned bi_reverse(code, len)
1430     unsigned code; /* the value to invert */
1431     int len;       /* its bit length */
1432 {
1433     register unsigned res = 0;
1434     do {
1435 	res |= code & 1;
1436 	code >>= 1, res <<= 1;
1437     } while (--len > 0);
1438     return res >> 1;
1439 }
1440 
1441 /* ===========================================================================
1442  * Write out any remaining bits in an incomplete byte.
1443  */
bi_windup(gz)1444 static Logical bi_windup(gz)
1445 GZp gz;
1446 {
1447     if (gz->bi_valid > 8) {
1448 	if (!PutShort(gz,(unsigned)gz->bi_buf)) return FALSE;
1449     } else if (gz->bi_valid > 0) {
1450 	if (!PutByte(gz,(unsigned)gz->bi_buf)) return FALSE;
1451     }
1452     gz->bi_buf = 0;
1453     gz->bi_valid = 0;
1454     return TRUE;
1455 }
1456 
1457 /* ===========================================================================
1458  * Copy a stored block to the zip file, storing first the length and its
1459  * one's complement if requested.
1460  */
copy_block(gz,buf,len,header)1461 static Logical copy_block(gz, buf, len, header)
1462     GZp gz;
1463     char     *buf;    /* the input data */
1464     unsigned len;     /* its length */
1465     int      header;  /* true if block header must be written */
1466 {
1467     if (!bi_windup(gz)) return FALSE;              /* align on byte boundary */
1468     if (header) {
1469 	if (!PutShort(gz,(unsigned)len)) return FALSE;
1470 	if (!PutShort(gz,(unsigned)~len)) return FALSE;
1471     }
1472     while (len--) {
1473 	if (!PutByte(gz,(unsigned)*buf++)) return FALSE;
1474     }
1475     return TRUE;
1476 }
1477 
1478 
1479 /* deflate.c -- compress data using the deflation algorithm
1480  * Copyright (C) 1992-1993 Jean-loup Gailly
1481  * This is free software; you can redistribute it and/or modify it under the
1482  * terms of the GNU General Public License, see the file COPYING.
1483  */
1484 
1485 /*
1486  *  PURPOSE
1487  *
1488  *      Identify new text as repetitions of old text within a fixed-
1489  *      length sliding window trailing behind the new text.
1490  *
1491  *  DISCUSSION
1492  *
1493  *      The "deflation" process depends on being able to identify portions
1494  *      of the input text which are identical to earlier input (within a
1495  *      sliding window trailing behind the input currently being processed).
1496  *
1497  *      The most straightforward technique turns out to be the fastest for
1498  *      most input files: try all possible matches and select the longest.
1499  *      The key feature of this algorithm is that insertions into the string
1500  *      dictionary are very simple and thus fast, and deletions are avoided
1501  *      completely. Insertions are performed at each input character, whereas
1502  *      string matches are performed only when the previous match ends. So it
1503  *      is preferable to spend more time in matches to allow very fast string
1504  *      insertions and avoid deletions. The matching algorithm for small
1505  *      strings is inspired from that of Rabin & Karp. A brute force approach
1506  *      is used to find longer strings when a small match has been found.
1507  *      A similar algorithm is used in comic (by Jan-Mark Wams) and freeze
1508  *      (by Leonid Broukhis).
1509  *         A previous version of this file used a more sophisticated algorithm
1510  *      (by Fiala and Greene) which is guaranteed to run in linear amortized
1511  *      time, but has a larger average cost, uses more memory and is patented.
1512  *      However the F&G algorithm may be faster for some highly redundant
1513  *      files if the parameter max_chain_length (described below) is too large.
1514  *
1515  *  ACKNOWLEDGEMENTS
1516  *
1517  *      The idea of lazy evaluation of matches is due to Jan-Mark Wams, and
1518  *      I found it in 'freeze' written by Leonid Broukhis.
1519  *      Thanks to many info-zippers for bug reports and testing.
1520  *
1521  *  REFERENCES
1522  *
1523  *      APPNOTE.TXT documentation file in PKZIP 1.93a distribution.
1524  *
1525  *      A description of the Rabin and Karp algorithm is given in the book
1526  *         "Algorithms" by R. Sedgewick, Addison-Wesley, p252.
1527  *
1528  *      Fiala,E.R., and Greene,D.H.
1529  *         Data Compression with Finite Windows, Comm.ACM, 32,4 (1989) 490-595
1530  *
1531  *  INTERFACE
1532  *
1533  *      Logical lm_init (GZp gz, ush *flags)
1534  *          Initialize the "longest match" routines for a new file
1535  *
1536  *      ulg deflate (GZp gz)
1537  *          Processes a new input file and return its compressed length. Sets
1538  *          the compressed length, crc, deflate flags and internal file
1539  *          attributes.
1540  */
1541 
1542 /* ===========================================================================
1543  * Initialize the "longest match" routines for a new file
1544  */
lm_init(gz,flags)1545 static Logical lm_init (gz, flags)
1546     GZp gz;
1547     ush *flags;     /* general purpose bit flag */
1548 {
1549     register unsigned j;
1550 
1551     /* Initialize the hash table. */
1552 #if HASH_BITS == 15
1553     for (j = 0;  j < HASH_SIZE; j++) gz->head[j] = NIL;
1554 #else
1555     memzero((char *)gz->head, HASH_SIZE * sizeof(*gz->head));
1556 #endif
1557     /* prev will be initialized on the fly */
1558 
1559     /* Set the default configuration parameters:
1560      */
1561     if (gz->level == 1) {
1562        *flags |= FAST;
1563     } else if (gz->level == 9) {
1564        *flags |= SLOW;
1565     }
1566     /* ??? reduce max_chain_length for binary files */
1567 
1568     gz->strstart = 0;
1569     gz->block_start = 0L;
1570 
1571     gz->lookahead = file_read(gz, (char *) gz->window,
1572 			  sizeof(int) <= 2 ? (unsigned)WSIZE : 2*WSIZE);
1573     if (gz->lookahead == (unsigned)(-1)) {
1574       return FALSE;             /* Error/real EOF shouldn't ever occur - JTL */
1575     }
1576     if (gz->lookahead == 0) {
1577        gz->eofile = 1, gz->lookahead = 0;
1578        return TRUE;
1579     }
1580     gz->eofile = 0;
1581     /* Make sure that we always have enough lookahead. This is important
1582      * if input comes from a device such as a tty.
1583      */
1584     while (gz->lookahead < MIN_LOOKAHEAD && !gz->eofile) {
1585       if (!fill_window(gz)) return FALSE;
1586     }
1587 
1588     gz->ins_h = 0;
1589     for (j=0; j<MIN_MATCH-1; j++) {
1590        gz->ins_h = ((gz->ins_h << H_SHIFT) ^ gz->window[j]) & HASH_MASK;
1591     }
1592     /* If lookahead < MIN_MATCH, gz->ins_h is garbage, but this is
1593      * not important since only literal bytes will be emitted.
1594      */
1595     return TRUE;
1596 }
1597 
1598 /* ===========================================================================
1599  * Set match_start to the longest match starting at the given string and
1600  * return its length. Matches shorter or equal to prev_length are discarded,
1601  * in which case the result is equal to prev_length and match_start is
1602  * garbage.
1603  * IN assertions: cur_match is the head of the hash chain for the current
1604  *   string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1
1605  */
1606 
longest_match(gz,cur_match)1607 static int longest_match(gz, cur_match)
1608     GZp gz;
1609     IPos cur_match;                             /* current match */
1610 {
1611     unsigned chain_length = gz->configuration_table[gz->level].max_chain;
1612 						/* max hash chain length */
1613     register uch *scan = gz->window + gz->strstart;     /* current string */
1614     register uch *match;                        /* matched string */
1615     register int len;                           /* length of current match */
1616     int best_len = gz->prev_length;                 /* best match length so far */
1617     IPos limit = gz->strstart > (IPos)MAX_DIST ? gz->strstart - (IPos)MAX_DIST : NIL;
1618     /* Stop when cur_match becomes <= limit. To simplify the code,
1619      * we prevent matches with the string of window index 0.
1620      */
1621 
1622 /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
1623  * It is easy to get rid of this optimization if necessary.
1624  */
1625 #if HASH_BITS < 8 || MAX_MATCH != 258
1626    error: Code too clever
1627 #endif
1628 
1629 #ifdef UNALIGNED_OK
1630     /* Compare two bytes at a time. Note: this is not always beneficial.
1631      * Try with and without -DUNALIGNED_OK to check.
1632      */
1633     register uch *strend = gz->window + gz->strstart + MAX_MATCH - 1;
1634     register ush scan_start = *(ush*)scan;
1635     register ush scan_end   = *(ush*)(scan+best_len-1);
1636 #else
1637     register uch *strend = gz->window + gz->strstart + MAX_MATCH;
1638     register uch scan_end1  = scan[best_len-1];
1639     register uch scan_end   = scan[best_len];
1640 #endif
1641 
1642     /* Do not waste too much time if we already have a good match: */
1643     if (gz->prev_length >= gz->configuration_table[gz->level].good_length) {
1644 	chain_length >>= 2;
1645     }
1646 
1647     do {
1648 	match = gz->window + cur_match;
1649 
1650 	/* Skip to next match if the match length cannot increase
1651 	 * or if the match length is less than 2:
1652 	 */
1653 #if (defined(UNALIGNED_OK) && MAX_MATCH == 258)
1654 	/* This code assumes sizeof(unsigned short) == 2. Do not use
1655 	 * UNALIGNED_OK if your compiler uses a different size.
1656 	 */
1657 	if (*(ush*)(match+best_len-1) != scan_end ||
1658 	    *(ush*)match != scan_start) continue;
1659 
1660 	/* It is not necessary to compare scan[2] and match[2] since they are
1661 	 * always equal when the other bytes match, given that the hash keys
1662 	 * are equal and that HASH_BITS >= 8. Compare 2 bytes at a time at
1663 	 * strstart+3, +5, ... up to strstart+257. We check for insufficient
1664 	 * lookahead only every 4th comparison; the 128th check will be made
1665 	 * at strstart+257. If MAX_MATCH-2 is not a multiple of 8, it is
1666 	 * necessary to put more guard bytes at the end of the window, or
1667 	 * to check more often for insufficient lookahead.
1668 	 */
1669 	scan++, match++;
1670 	do {
1671 	} while (*(ush*)(scan+=2) == *(ush*)(match+=2) &&
1672 		 *(ush*)(scan+=2) == *(ush*)(match+=2) &&
1673 		 *(ush*)(scan+=2) == *(ush*)(match+=2) &&
1674 		 *(ush*)(scan+=2) == *(ush*)(match+=2) &&
1675 		 scan < strend);
1676 	/* The funny "do {}" generates better code on most compilers */
1677 
1678 	/* Here, scan <= window+strstart+257 */
1679 	if (*scan == *match) scan++;
1680 
1681 	len = (MAX_MATCH - 1) - (int)(strend-scan);
1682 	scan = strend - (MAX_MATCH-1);
1683 
1684 #else /* UNALIGNED_OK */
1685 
1686 	if (match[best_len]   != scan_end  ||
1687 	    match[best_len-1] != scan_end1 ||
1688 	    *match            != *scan     ||
1689 	    *++match          != scan[1])      continue;
1690 
1691 	/* The check at best_len-1 can be removed because it will be made
1692 	 * again later. (This heuristic is not always a win.)
1693 	 * It is not necessary to compare scan[2] and match[2] since they
1694 	 * are always equal when the other bytes match, given that
1695 	 * the hash keys are equal and that HASH_BITS >= 8.
1696 	 */
1697 	scan += 2, match++;
1698 
1699 	/* We check for insufficient lookahead only every 8th comparison;
1700 	 * the 256th check will be made at strstart+258.
1701 	 */
1702 	do {
1703 	} while (*++scan == *++match && *++scan == *++match &&
1704 		 *++scan == *++match && *++scan == *++match &&
1705 		 *++scan == *++match && *++scan == *++match &&
1706 		 *++scan == *++match && *++scan == *++match &&
1707 		 scan < strend);
1708 
1709 	len = MAX_MATCH - (int)(strend - scan);
1710 	scan = strend - MAX_MATCH;
1711 
1712 #endif /* UNALIGNED_OK */
1713 
1714 	if (len > best_len) {
1715 	    gz->match_start = cur_match;
1716 	    best_len = len;
1717 	    if (len >=
1718 		(int) gz->configuration_table[gz->level].nice_length) break;
1719 #ifdef UNALIGNED_OK
1720 	    scan_end = *(ush*)(scan+best_len-1);
1721 #else
1722 	    scan_end1  = scan[best_len-1];
1723 	    scan_end   = scan[best_len];
1724 #endif
1725 	}
1726     } while ((cur_match = gz->prev[cur_match & WMASK]) > limit
1727 	     && --chain_length != 0);
1728 
1729     return best_len;
1730 }
1731 
1732 /* ===========================================================================
1733  * Fill the window when the lookahead becomes insufficient.
1734  * Updates strstart and lookahead, and sets eofile if end of input file.
1735  * IN assertion: lookahead < MIN_LOOKAHEAD && strstart + lookahead > 0
1736  * OUT assertions: at least one byte has been read, or eofile is set;
1737  *    file reads are performed for at least two bytes (required for the
1738  *    translate_eol option).
1739  */
fill_window(gz)1740 static Logical fill_window(gz)
1741 GZp gz;
1742 {
1743     register unsigned n, m;
1744     unsigned more = (unsigned)(WINDOW_SIZE - (ulg)gz->lookahead - (ulg)gz->strstart);
1745     /* Amount of free space at the end of the window. */
1746 
1747     /* If the window is almost full and there is insufficient lookahead,
1748      * move the upper half to the lower one to make room in the upper half.
1749      */
1750     if (more == (unsigned)EOF) {
1751 	/* Very unlikely, but possible on 16 bit machine if strstart == 0
1752 	 * and lookahead == 1 (input done one byte at time)
1753 	 */
1754 	more--;
1755     } else if (gz->strstart >= WSIZE+MAX_DIST) {
1756 	/* By the IN assertion, the window is not empty so we can't confuse
1757 	 * more == 0 with more == 64K on a 16 bit machine.
1758 	 */
1759 	memcpy((char*)gz->window, (char*)gz->window+WSIZE, (unsigned)WSIZE);
1760 	gz->match_start -= WSIZE;
1761 	gz->strstart    -= WSIZE; /* we now have strstart >= MAX_DIST: */
1762 	gz->block_start -= (long) WSIZE;
1763 	for (n = 0; n < HASH_SIZE; n++) {
1764 	    m = gz->head[n];
1765 	    gz->head[n] = (Pos)(m >= WSIZE ? m-WSIZE : NIL);
1766 	}
1767 	for (n = 0; n < WSIZE; n++) {
1768 	    m = gz->prev[n];
1769 	    gz->prev[n] = (Pos)(m >= WSIZE ? m-WSIZE : NIL);
1770 	    /* If n is not on any hash chain, prev[n] is garbage but
1771 	     * its value will never be used.
1772 	     */
1773 	}
1774 	more += WSIZE;
1775     }
1776     /* At this point, more >= 2 */
1777     if (!gz->eofile) {
1778 	n = file_read(gz, (char*)gz->window+gz->strstart+gz->lookahead, more);
1779 	if (n == (unsigned)(-1)) {
1780 	  return FALSE;         /* Error/real EOF should never occur - JTL */
1781 	}
1782 	if (n == 0) {
1783 	    gz->eofile = 1;
1784 	}
1785 	else {
1786 	    gz->lookahead += n;
1787 	}
1788     }
1789     return TRUE;
1790 }
1791 
1792 /* ===========================================================================
1793  * Processes a new input file and return its compressed length. This
1794  * function does not perform lazy evaluationof matches and inserts
1795  * new strings in the dictionary only for unmatched strings or for short
1796  * matches. It is used only for the fast compression options.
1797  */
deflate_fast(gz)1798 static CDFstatus deflate_fast(gz)
1799 GZp gz;
1800 {
1801     IPos hash_head; /* head of the hash chain */
1802     int flush;      /* set if current block must be flushed */
1803     unsigned match_length = 0;  /* length of best match */
1804 
1805     gz->prev_length = MIN_MATCH-1;
1806     while (gz->lookahead != 0) {
1807 	/* Insert the string window[strstart .. strstart+2] in the
1808 	 * dictionary, and set hash_head to the head of the hash chain:
1809 	 */
1810 	gz->ins_h = ((gz->ins_h << H_SHIFT) ^ gz->window[(gz->strstart) + MIN_MATCH-1]) & HASH_MASK;
1811 	gz->prev[(gz->strstart) & WMASK] = hash_head = gz->head[gz->ins_h];
1812 	gz->head[gz->ins_h] = (gz->strstart);
1813 
1814 	/* Find the longest match, discarding those <= prev_length.
1815 	 * At this point we have always match_length < MIN_MATCH
1816 	 */
1817 	if (hash_head != NIL && gz->strstart - hash_head <= MAX_DIST) {
1818 	    /* To simplify the code, we prevent matches with the string
1819 	     * of window index 0 (in particular we have to avoid a match
1820 	     * of the string with itself at the start of the input file).
1821 	     */
1822 	    match_length = longest_match (gz, hash_head);
1823 	    /* longest_match() sets match_start */
1824 	    if (match_length > gz->lookahead) match_length = gz->lookahead;
1825 	}
1826 	if (match_length >= MIN_MATCH) {
1827 	    flush = ct_tally (gz, gz->strstart - gz->match_start,
1828 			      match_length - MIN_MATCH);
1829 	    gz->lookahead -= match_length;
1830 	    /* Insert new strings in the hash table only if the match length
1831 	     * is not too large. This saves time but degrades compression.
1832 	     */
1833 	    if (match_length <= gz->configuration_table[gz->level].max_lazy) {
1834 		match_length--; /* string at strstart already in hash table */
1835 		do {
1836 		    gz->strstart++;
1837 		    gz->ins_h = ((gz->ins_h << H_SHIFT) ^ gz->window[(gz->strstart) +
1838 			     MIN_MATCH-1]) & HASH_MASK;
1839 		    gz->prev[(gz->strstart) & WMASK] = hash_head = gz->head[gz->ins_h];
1840 		    gz->head[gz->ins_h] = (gz->strstart);
1841 
1842 		    /* strstart never exceeds WSIZE-MAX_MATCH, so there are
1843 		     * always MIN_MATCH bytes ahead. If lookahead < MIN_MATCH
1844 		     * these bytes are garbage, but it does not matter since
1845 		     * the next lookahead bytes will be emitted as literals.
1846 		     */
1847 		} while (--match_length != 0);
1848 		gz->strstart++;
1849 	    } else {
1850 		gz->strstart += match_length;
1851 		match_length = 0;
1852 		gz->ins_h = gz->window[gz->strstart];
1853 		gz->ins_h = ((gz->ins_h << H_SHIFT) ^ gz->window[gz->strstart+1]) & HASH_MASK;
1854 	    }
1855 	} else {
1856 	    /* No match, output a literal byte */
1857 	    flush = ct_tally (gz, 0, gz->window[gz->strstart]);
1858 	    gz->lookahead--;
1859 	    gz->strstart++;
1860 	}
1861 	if (flush) {
1862 	  if (!flush_block(gz, gz->block_start >= 0L ?
1863 			   (char*) &(gz->window[(unsigned)gz->block_start]) :
1864 			   (char*) NULL,
1865 			   (long) gz->strstart - gz->block_start,
1866 			   0)) return gz->oError;       /* Write error. */
1867 	  gz->block_start = gz->strstart;
1868 	}
1869 
1870 	/* Make sure that we always have enough lookahead, except
1871 	 * at the end of the input file. We need MAX_MATCH bytes
1872 	 * for the next match, plus MIN_MATCH bytes to insert the
1873 	 * string following the next match.
1874 	 */
1875 	while (gz->lookahead < MIN_LOOKAHEAD && !gz->eofile) {
1876 	  if (!fill_window(gz)) return gz->iError;      /* Read error. */
1877 	}
1878     }
1879     if (!flush_block(gz, gz->block_start >= 0L ?
1880 		     (char *) &(gz->window[(unsigned)gz->block_start]) :
1881 		     (char *) NULL,
1882 		     (long) gz->strstart - gz->block_start,
1883 		     1)) return gz->oError; /* Write error. */  /* eof */
1884     return CDF_OK;
1885 }
1886 
1887 /* ===========================================================================
1888  * Same as above, but achieves better compression. We use a lazy
1889  * evaluation for matches: a match is finally adopted only if there is
1890  * no better match at the next window position.
1891  */
deflate(gz)1892 static CDFstatus deflate(gz)
1893 GZp gz;
1894 {
1895     IPos hash_head;          /* head of hash chain */
1896     IPos prev_match;         /* previous match */
1897     int flush;               /* set if current block must be flushed */
1898     int match_available = 0; /* set if previous match exists */
1899     register unsigned match_length = MIN_MATCH-1; /* length of best match */
1900 
1901     if (gz->level <= 3) return deflate_fast(gz); /* optimized for speed */
1902 
1903     /* Process the input block. */
1904     while (gz->lookahead != 0) {
1905 	/* Insert the string window[strstart .. strstart+2] in the
1906 	 * dictionary, and set hash_head to the head of the hash chain:
1907 	 */
1908 	gz->ins_h = ((gz->ins_h << H_SHIFT) ^ gz->window[(gz->strstart) + MIN_MATCH-1]) &
1909 		HASH_MASK;
1910 	gz->prev[(gz->strstart) & WMASK] = hash_head = gz->head[gz->ins_h];
1911 	gz->head[gz->ins_h] = (gz->strstart);
1912 
1913 	/* Find the longest match, discarding those <= prev_length.
1914 	 */
1915 	gz->prev_length = match_length, prev_match = gz->match_start;
1916 	match_length = MIN_MATCH-1;
1917 
1918 	if (hash_head != NIL &&
1919 	    gz->prev_length < gz->configuration_table[gz->level].max_lazy &&
1920 	    gz->strstart - hash_head <= MAX_DIST) {
1921 	    /* To simplify the code, we prevent matches with the string
1922 	     * of window index 0 (in particular we have to avoid a match
1923 	     * of the string with itself at the start of the input file).
1924 	     */
1925 	    match_length = longest_match (gz, hash_head);
1926 	    /* longest_match() sets match_start */
1927 	    if (match_length > gz->lookahead) match_length = gz->lookahead;
1928 
1929 	    /* Ignore a length 3 match if it is too distant: */
1930 	    if (match_length == MIN_MATCH && gz->strstart-gz->match_start > TOO_FAR){
1931 		/* If prev_match is also MIN_MATCH, match_start is garbage
1932 		 * but we will ignore the current match anyway.
1933 		 */
1934 		match_length--;
1935 	    }
1936 	}
1937 	/* If there was a match at the previous step and the current
1938 	 * match is not better, output the previous match:
1939 	 */
1940 	if (gz->prev_length >= MIN_MATCH && match_length <= gz->prev_length) {
1941 	    flush = ct_tally (gz, gz->strstart - 1 - prev_match,
1942 			      gz->prev_length - MIN_MATCH);
1943 	    /* Insert in hash table all strings up to the end of the match.
1944 	     * strstart-1 and strstart are already inserted.
1945 	     */
1946 	    gz->lookahead -= gz->prev_length-1;
1947 	    gz->prev_length -= 2;
1948 	    do {
1949 		gz->strstart++;
1950 		gz->ins_h = ((gz->ins_h << H_SHIFT) ^ gz->window[(gz->strstart) + MIN_MATCH-1]) & HASH_MASK;
1951 		gz->prev[(gz->strstart) & WMASK] = hash_head = gz->head[gz->ins_h];
1952 		gz->head[gz->ins_h] = (gz->strstart);
1953 
1954 		/* strstart never exceeds WSIZE-MAX_MATCH, so there are
1955 		 * always MIN_MATCH bytes ahead. If lookahead < MIN_MATCH
1956 		 * these bytes are garbage, but it does not matter since the
1957 		 * next lookahead bytes will always be emitted as literals.
1958 		 */
1959 	    } while (--gz->prev_length != 0);
1960 	    match_available = 0;
1961 	    match_length = MIN_MATCH-1;
1962 	    gz->strstart++;
1963 	    if (flush) {
1964 	      if (!flush_block(gz, gz->block_start >= 0L ?
1965 			       (char *) &(gz->window[(unsigned)gz->block_start]) :
1966 			       (char *) NULL, (long) gz->strstart - gz->block_start,
1967 			       0)) return gz->oError;   /* Write error. */
1968 	      gz->block_start = gz->strstart;
1969 	    }
1970 	} else if (match_available) {
1971 	    /* If there was no match at the previous position, output a
1972 	     * single literal. If there was a match but the current match
1973 	     * is longer, truncate the previous match to a single literal.
1974 	     */
1975 	    if (ct_tally (gz, 0, gz->window[gz->strstart-1])) {
1976 	      if (!flush_block(gz, gz->block_start >= 0L ?
1977 			       (char *) &(gz->window[(unsigned)gz->block_start]) :
1978 			       (char *) NULL, (long) gz->strstart - gz->block_start,
1979 			       0)) return gz->oError;   /* Write error. */
1980 	      gz->block_start = gz->strstart;
1981 	    }
1982 	    gz->strstart++;
1983 	    gz->lookahead--;
1984 	} else {
1985 	    /* There is no previous match to compare with, wait for
1986 	     * the next step to decide.
1987 	     */
1988 	    match_available = 1;
1989 	    gz->strstart++;
1990 	    gz->lookahead--;
1991 	}
1992 
1993 	/* Make sure that we always have enough lookahead, except
1994 	 * at the end of the input file. We need MAX_MATCH bytes
1995 	 * for the next match, plus MIN_MATCH bytes to insert the
1996 	 * string following the next match.
1997 	 */
1998 	while (gz->lookahead < MIN_LOOKAHEAD && !gz->eofile) {
1999 	  if (!fill_window(gz)) return gz->iError;      /* Read error. */
2000 	}
2001     }
2002     if (match_available) ct_tally (gz, 0, gz->window[gz->strstart-1]);
2003 
2004     if (!flush_block(gz, gz->block_start >= 0L ?
2005 		     (char *) &(gz->window[(unsigned)gz->block_start]) :
2006 		     (char *) NULL,
2007 		     (long) gz->strstart - gz->block_start,
2008 		     1)) return gz->oError; /* Write error. */  /* eof */
2009     return CDF_OK;
2010 }
2011 
2012 
2013 
2014 /* trees.c -- output deflated data using Huffman coding
2015  * Copyright (C) 1992-1993 Jean-loup Gailly
2016  * This is free software; you can redistribute it and/or modify it under the
2017  * terms of the GNU General Public License, see the file COPYING.
2018  */
2019 
2020 /*
2021  *  PURPOSE
2022  *
2023  *      Encode various sets of source values using variable-length
2024  *      binary code trees.
2025  *
2026  *  DISCUSSION
2027  *
2028  *      The PKZIP "deflation" process uses several Huffman trees. The more
2029  *      common source values are represented by shorter bit sequences.
2030  *
2031  *      Each code tree is stored in the ZIP file in a compressed form
2032  *      which is itself a Huffman encoding of the lengths of
2033  *      all the code strings (in ascending order by source values).
2034  *      The actual code strings are reconstructed from the lengths in
2035  *      the UNZIP process, as described in the "application note"
2036  *      (APPNOTE.TXT) distributed as part of PKWARE's PKZIP program.
2037  *
2038  *  REFERENCES
2039  *
2040  *      Lynch, Thomas J.
2041  *          Data Compression:  Techniques and Applications, pp. 53-55.
2042  *          Lifetime Learning Publications, 1985.  ISBN 0-534-03418-7.
2043  *
2044  *      Storer, James A.
2045  *          Data Compression:  Methods and Theory, pp. 49-50.
2046  *          Computer Science Press, 1988.  ISBN 0-7167-8156-5.
2047  *
2048  *      Sedgewick, R.
2049  *          Algorithms, p290.
2050  *          Addison-Wesley, 1983. ISBN 0-201-06672-6.
2051  *
2052  *  INTERFACE
2053  *
2054  *      void ct_init (GZp gz)
2055  *          Allocate the match buffer, initialize the various tables.
2056  *
2057  *      void ct_tally (GZp gz, int dist, int lc);
2058  *          Save the match info and tally the frequency counts.
2059  *
2060  *      Logical flush_block (GZp gz, char *buf, ulg stored_len, int eof)
2061  *          Determine the best encoding for the current block: dynamic trees,
2062  *          static trees or store, and output the encoded block to the zip
2063  *          file.
2064  *
2065  */
2066 
2067 /* ===========================================================================
2068  * Allocate the match buffer and initialize the various tables.
2069  */
ct_init(gz)2070 static void ct_init(gz)
2071 GZp gz;
2072 {
2073     int n;        /* iterates over tree elements */
2074     int bits;     /* bit counter */
2075     int length;   /* length value */
2076     int code;     /* code value */
2077     int dist;     /* distance index */
2078 
2079     if (gz->static_dtree[0].dl.len != 0) return; /* ct_init already called */
2080 
2081     /* Initialize the mapping length (0..255) -> length code (0..28) */
2082     length = 0;
2083     for (code = 0; code < LENGTH_CODES-1; code++) {
2084 	gz->base_length[code] = length;
2085 	for (n = 0; n < (1<<gz->extra_lbits[code]); n++) {
2086 	    gz->length_code[length++] = (uch)code;
2087 	}
2088     }
2089     /* Note that the length 255 (match length 258) can be represented
2090      * in two different ways: code 284 + 5 bits or code 285, so we
2091      * overwrite length_code[255] to use the best encoding:
2092      */
2093     gz->length_code[length-1] = (uch)code;
2094 
2095     /* Initialize the mapping dist (0..32K) -> dist code (0..29) */
2096     dist = 0;
2097     for (code = 0 ; code < 16; code++) {
2098 	gz->base_dist[code] = dist;
2099 	for (n = 0; n < (1<<gz->extra_dbits[code]); n++) {
2100 	    gz->dist_code[dist++] = (uch)code;
2101 	}
2102     }
2103     dist >>= 7; /* from now on, all distances are divided by 128 */
2104     for ( ; code < D_CODES; code++) {
2105 	gz->base_dist[code] = dist << 7;
2106 	for (n = 0; n < (1<<(gz->extra_dbits[code]-7)); n++) {
2107 	    gz->dist_code[256 + dist++] = (uch)code;
2108 	}
2109     }
2110 
2111     /* Construct the codes of the static literal tree */
2112     for (bits = 0; bits <= MAX_BITS; bits++) gz->bl_count[bits] = 0;
2113     n = 0;
2114     while (n <= 143) gz->static_ltree[n++].dl.len = 8, gz->bl_count[8]++;
2115     while (n <= 255) gz->static_ltree[n++].dl.len = 9, gz->bl_count[9]++;
2116     while (n <= 279) gz->static_ltree[n++].dl.len = 7, gz->bl_count[7]++;
2117     while (n <= 287) gz->static_ltree[n++].dl.len = 8, gz->bl_count[8]++;
2118     /* Codes 286 and 287 do not exist, but we must include them in the
2119      * tree construction to get a canonical Huffman tree (longest code
2120      * all ones)
2121      */
2122     gen_codes(gz, (ct_data *)gz->static_ltree, L_CODES+1);
2123 
2124     /* The static distance tree is trivial: */
2125     for (n = 0; n < D_CODES; n++) {
2126 	gz->static_dtree[n].dl.len = 5;
2127 	gz->static_dtree[n].fc.code = bi_reverse(n, 5);
2128     }
2129 
2130     /* Initialize the first block of the first file: */
2131     init_block(gz);
2132 }
2133 
2134 /* ===========================================================================
2135  * Initialize a new block.
2136  */
init_block(gz)2137 static void init_block(gz)
2138 GZp gz;
2139 {
2140     int n; /* iterates over tree elements */
2141 
2142     /* Initialize the trees. */
2143     for (n = 0; n < L_CODES;  n++) gz->dyn_ltree[n].fc.freq = 0;
2144     for (n = 0; n < D_CODES;  n++) gz->dyn_dtree[n].fc.freq = 0;
2145     for (n = 0; n < BL_CODES; n++) gz->bl_tree[n].fc.freq = 0;
2146 
2147     gz->dyn_ltree[END_BLOCK].fc.freq = 1;
2148     gz->opt_len = gz->static_len = 0L;
2149     gz->last_lit = gz->last_dist = gz->last_flags = 0;
2150     gz->tree_flags = 0; gz->flag_bit = 1;
2151     return;
2152 }
2153 
2154 #define SMALLEST 1
2155 /* Index within the heap array of least frequent node in the Huffman tree */
2156 
2157 /* ===========================================================================
2158  * Compares to subtrees, using the tree depth as tie breaker when
2159  * the subtrees have equal frequency. This minimizes the worst case length.
2160  */
2161 #define smaller(tree_, depth_, n_, m_) \
2162    (tree_[n_].fc.freq < tree_[m_].fc.freq || \
2163    (tree_[n_].fc.freq == tree_[m_].fc.freq && depth_[n_] <= depth_[m_]))
2164 
2165 /* ===========================================================================
2166  * Restore the heap property by moving down the tree starting at node k,
2167  * exchanging a node with the smallest of its two sons if necessary, stopping
2168  * when the heap property is re-established (each father smaller than its
2169  * two sons).
2170  */
pqdownheap(gz,tree,k)2171 static void pqdownheap (gz, tree, k)
2172     GZp gz;
2173     ct_data *tree;  /* the tree to restore */
2174     int k;               /* node to move down */
2175 {
2176     int v = gz->heap[k];
2177     int j = k << 1;  /* left son of k */
2178     while (j <= gz->heap_len) {
2179 	/* Set j to the smallest of the two sons: */
2180 	if (j < gz->heap_len && smaller(tree, gz->depth, gz->heap[j+1], gz->heap[j])) j++;
2181 
2182 	/* Exit if v is smaller than both sons */
2183 	if (smaller(tree, gz->depth, v, gz->heap[j])) break;
2184 
2185 	/* Exchange v with the smallest son */
2186 	gz->heap[k] = gz->heap[j];  k = j;
2187 
2188 	/* And continue down the tree, setting j to the left son of k */
2189 	j <<= 1;
2190     }
2191     gz->heap[k] = v;
2192     return;
2193 }
2194 
2195 /* ===========================================================================
2196  * Compute the optimal bit lengths for a tree and update the total bit length
2197  * for the current block.
2198  * IN assertion: the fields freq and dad are set, heap[heap_max] and
2199  *    above are the tree nodes sorted by increasing frequency.
2200  * OUT assertions: the field len is set to the optimal bit length, the
2201  *     array bl_count contains the frequencies for each bit length.
2202  *     The length opt_len is updated; static_len is also updated if stree is
2203  *     not null.
2204  */
gen_bitlen(gz,desc)2205 static void gen_bitlen(gz, desc)
2206     GZp gz;
2207     tree_desc *desc; /* the tree descriptor */
2208 {
2209     ct_data *tree  = desc->dyn_tree;
2210     int *extra     = desc->extra_bits;
2211     int base            = desc->extra_base;
2212     int max_code        = desc->max_code;
2213     int max_length      = desc->max_length;
2214     ct_data *stree = desc->static_tree;
2215     int h;              /* heap index */
2216     int n, m;           /* iterate over the tree elements */
2217     int bits;           /* bit length */
2218     int xbits;          /* extra bits */
2219     ush f;              /* frequency */
2220     int overflow = 0;   /* number of elements with bit length too large */
2221 
2222     for (bits = 0; bits <= MAX_BITS; bits++) gz->bl_count[bits] = 0;
2223 
2224     /* In a first pass, compute the optimal bit lengths (which may
2225      * overflow in the case of the bit length tree).
2226      */
2227     tree[gz->heap[gz->heap_max]].dl.len = 0; /* root of the heap */
2228 
2229     for (h = gz->heap_max+1; h < HEAP_SIZE; h++) {
2230 	n = gz->heap[h];
2231 	bits = tree[tree[n].dl.dad].dl.len + 1;
2232 	if (bits > max_length) bits = max_length, overflow++;
2233 	tree[n].dl.len = (ush)bits;
2234 	/* We overwrite tree[n].dl.dad which is no longer needed */
2235 
2236 	if (n > max_code) continue; /* not a leaf node */
2237 
2238 	gz->bl_count[bits]++;
2239 	xbits = 0;
2240 	if (n >= base) xbits = extra[n-base];
2241 	f = tree[n].fc.freq;
2242 	gz->opt_len += (ulg)f * (bits + xbits);
2243 	if (stree) gz->static_len += (ulg)f * (stree[n].dl.len + xbits);
2244     }
2245     if (overflow == 0) return;
2246 
2247     /* Find the first bit length which could increase: */
2248     do {
2249 	bits = max_length-1;
2250 	while (gz->bl_count[bits] == 0) bits--;
2251 	gz->bl_count[bits]--;      /* move one leaf down the tree */
2252 	gz->bl_count[bits+1] += 2; /* move one overflow item as its brother */
2253 	gz->bl_count[max_length]--;
2254 	/* The brother of the overflow item also moves one step up,
2255 	 * but this does not affect bl_count[max_length]
2256 	 */
2257 	overflow -= 2;
2258     } while (overflow > 0);
2259 
2260     /* Now recompute all bit lengths, scanning in increasing frequency.
2261      * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all
2262      * lengths instead of fixing only the wrong ones. This idea is taken
2263      * from 'ar' written by Haruhiko Okumura.)
2264      */
2265     for (bits = max_length; bits != 0; bits--) {
2266 	n = gz->bl_count[bits];
2267 	while (n != 0) {
2268 	    m = gz->heap[--h];
2269 	    if (m > max_code) continue;
2270 	    if (tree[m].dl.len != (unsigned) bits) {
2271 		gz->opt_len += ((long)bits-(long)tree[m].dl.len) *
2272 			   (long)tree[m].fc.freq;
2273 		tree[m].dl.len = (ush)bits;
2274 	    }
2275 	    n--;
2276 	}
2277     }
2278     return;
2279 }
2280 
2281 /* ===========================================================================
2282  * Generate the codes for a given tree and bit counts (which need not be
2283  * optimal).
2284  * IN assertion: the array bl_count contains the bit length statistics for
2285  * the given tree and the field len is set for all tree elements.
2286  * OUT assertion: the field code is set for all tree elements of non
2287  *     zero code length.
2288  */
gen_codes(gz,tree,max_code)2289 static void gen_codes (gz, tree, max_code)
2290     GZp gz;
2291     ct_data *tree;        /* the tree to decorate */
2292     int max_code;              /* largest code with non zero frequency */
2293 {
2294     ush next_code[MAX_BITS+1]; /* next code value for each bit length */
2295     ush code = 0;              /* running code value */
2296     int bits;                  /* bit index */
2297     int n;                     /* code index */
2298 
2299     /* The distribution counts are first used to generate the code values
2300      * without bit reversal.
2301      */
2302     for (bits = 1; bits <= MAX_BITS; bits++) {
2303 	next_code[bits] = code = (code + gz->bl_count[bits-1]) << 1;
2304     }
2305     /* Check that the bit counts in bl_count are consistent. The last code
2306      * must be all ones.
2307      */
2308 
2309     for (n = 0;  n <= max_code; n++) {
2310 	int len = tree[n].dl.len;
2311 	if (len == 0) continue;
2312 	/* Now reverse the bits */
2313 	tree[n].fc.code = bi_reverse(next_code[len]++, len);
2314     }
2315     return;
2316 }
2317 
2318 /* ===========================================================================
2319  * Construct one Huffman tree and assigns the code bit strings and lengths.
2320  * Update the total bit length for the current block.
2321  * IN assertion: the field freq is set for all tree elements.
2322  * OUT assertions: the fields len and code are set to the optimal bit length
2323  *     and corresponding code. The length opt_len is updated; static_len is
2324  *     also updated if stree is not null. The field max_code is set.
2325  */
build_tree_gz(gz,desc)2326 static void build_tree_gz(gz, desc)
2327     GZp gz;
2328     tree_desc *desc; /* the tree descriptor */
2329 {
2330     ct_data *tree   = desc->dyn_tree;
2331     ct_data *stree  = desc->static_tree;
2332     int elems            = desc->elems;
2333     int n, m;          /* iterate over heap elements */
2334     int max_code = -1; /* largest code with non zero frequency */
2335     int node = elems;  /* next internal node of the tree */
2336 
2337     /* Construct the initial heap, with least frequent element in
2338      * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1].
2339      * heap[0] is not used.
2340      */
2341     gz->heap_len = 0, gz->heap_max = HEAP_SIZE;
2342 
2343     for (n = 0; n < elems; n++) {
2344 	if (tree[n].fc.freq != 0) {
2345 	    gz->heap[++gz->heap_len] = max_code = n;
2346 	    gz->depth[n] = 0;
2347 	} else {
2348 	    tree[n].dl.len = 0;
2349 	}
2350     }
2351 
2352     /* The pkzip format requires that at least one distance code exists,
2353      * and that at least one bit should be sent even if there is only one
2354      * possible code. So to avoid special checks later on we force at least
2355      * two codes of non zero frequency.
2356      */
2357     while (gz->heap_len < 2) {
2358 	int new = gz->heap[++gz->heap_len] = (max_code < 2 ? ++max_code : 0);
2359 	tree[new].fc.freq = 1;
2360 	gz->depth[new] = 0;
2361 	gz->opt_len--; if (stree) gz->static_len -= stree[new].dl.len;
2362 	/* new is 0 or 1 so it does not have extra bits */
2363     }
2364     desc->max_code = max_code;
2365 
2366     /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,
2367      * establish sub-heaps of increasing lengths:
2368      */
2369     for (n = gz->heap_len/2; n >= 1; n--) pqdownheap (gz, tree, n);
2370 
2371     /* Construct the Huffman tree by repeatedly combining the least two
2372      * frequent nodes.
2373      */
2374     do {
2375 	n = gz->heap[SMALLEST];
2376 	gz->heap[SMALLEST] = gz->heap[gz->heap_len--];
2377 	pqdownheap (gz, tree, SMALLEST);
2378 			     /* n = node of least frequency */
2379 	m = gz->heap[SMALLEST];  /* m = node of next least frequency */
2380 
2381 	gz->heap[--gz->heap_max] = n; /* keep the nodes sorted by frequency */
2382 	gz->heap[--gz->heap_max] = m;
2383 
2384 	/* Create a new node father of n and m */
2385 	tree[node].fc.freq = tree[n].fc.freq + tree[m].fc.freq;
2386 	gz->depth[node] = (uch) (MAXIMUM(gz->depth[n],gz->depth[m]) + 1);
2387 	tree[n].dl.dad = tree[m].dl.dad = (ush)node;
2388 	/* and insert the new node in the heap */
2389 	gz->heap[SMALLEST] = node++;
2390 	pqdownheap (gz, tree, SMALLEST);
2391 
2392     } while (gz->heap_len >= 2);
2393 
2394     gz->heap[--gz->heap_max] = gz->heap[SMALLEST];
2395 
2396     /* At this point, the fields freq and dad are set. We can now
2397      * generate the bit lengths.
2398      */
2399     gen_bitlen(gz, (tree_desc *)desc);
2400 
2401     /* The field len is now set, we can generate the bit codes */
2402     gen_codes (gz, (ct_data *)tree, max_code);
2403 
2404     return;
2405 }
2406 
2407 /* ===========================================================================
2408  * Scan a literal or distance tree to determine the frequencies of the codes
2409  * in the bit length tree. Updates opt_len to take into account the repeat
2410  * counts. (The contribution of the bit length codes will be added later
2411  * during the construction of bl_tree.)
2412  */
scan_tree(gz,tree,max_code)2413 static void scan_tree (gz, tree, max_code)
2414     GZp gz;
2415     ct_data *tree; /* the tree to be scanned */
2416     int max_code;       /* and its largest code of non zero frequency */
2417 {
2418     int n;                     /* iterates over all tree elements */
2419     int prevlen = -1;          /* last emitted length */
2420     int curlen;                /* length of current code */
2421     int nextlen = tree[0].dl.len; /* length of next code */
2422     int count = 0;             /* repeat count of the current code */
2423     int max_count = 7;         /* max repeat count */
2424     int min_count = 4;         /* min repeat count */
2425 
2426     if (nextlen == 0) max_count = 138, min_count = 3;
2427     tree[max_code+1].dl.len = (ush)0xffff; /* guard */
2428 
2429     for (n = 0; n <= max_code; n++) {
2430 	curlen = nextlen; nextlen = tree[n+1].dl.len;
2431 	if (++count < max_count && curlen == nextlen) {
2432 	    continue;
2433 	} else if (count < min_count) {
2434 	    gz->bl_tree[curlen].fc.freq += count;
2435 	} else if (curlen != 0) {
2436 	    if (curlen != prevlen) gz->bl_tree[curlen].fc.freq++;
2437 	    gz->bl_tree[REP_3_6].fc.freq++;
2438 	} else if (count <= 10) {
2439 	    gz->bl_tree[REPZ_3_10].fc.freq++;
2440 	} else {
2441 	    gz->bl_tree[REPZ_11_138].fc.freq++;
2442 	}
2443 	count = 0; prevlen = curlen;
2444 	if (nextlen == 0) {
2445 	    max_count = 138, min_count = 3;
2446 	} else if (curlen == nextlen) {
2447 	    max_count = 6, min_count = 3;
2448 	} else {
2449 	    max_count = 7, min_count = 4;
2450 	}
2451     }
2452     return;
2453 }
2454 
2455 /* ===========================================================================
2456  * Send a literal or distance tree in compressed form, using the codes in
2457  * bl_tree.
2458  */
send_tree(gz,tree,max_code)2459 static Logical send_tree (gz, tree, max_code)
2460     GZp gz;
2461     ct_data *tree; /* the tree to be scanned */
2462     int max_code;       /* and its largest code of non zero frequency */
2463 {
2464     int n;                     /* iterates over all tree elements */
2465     int prevlen = -1;          /* last emitted length */
2466     int curlen;                /* length of current code */
2467     int nextlen = tree[0].dl.len; /* length of next code */
2468     int count = 0;             /* repeat count of the current code */
2469     int max_count = 7;         /* max repeat count */
2470     int min_count = 4;         /* min repeat count */
2471 
2472     /* tree[max_code+1].dl.len = -1; */  /* guard already set */
2473     if (nextlen == 0) max_count = 138, min_count = 3;
2474 
2475     for (n = 0; n <= max_code; n++) {
2476 	curlen = nextlen; nextlen = tree[n+1].dl.len;
2477 	if (++count < max_count && curlen == nextlen) {
2478 	    continue;
2479 	} else if (count < min_count) {
2480 	    do {
2481 	      if (!send_code(gz,curlen,gz->bl_tree)) return FALSE;
2482 	    } while (--count != 0);
2483 	} else if (curlen != 0) {
2484 	    if (curlen != prevlen) {
2485 		if (!send_code(gz,curlen,gz->bl_tree)) return FALSE;
2486 		count--;
2487 	    }
2488 	    if (!send_code(gz,REP_3_6,gz->bl_tree)) return FALSE;
2489 	    if (!send_bits(gz,count-3,2)) return FALSE;
2490 
2491 	} else if (count <= 10) {
2492 	    if (!send_code(gz,REPZ_3_10,gz->bl_tree)) return FALSE;
2493 	    if (!send_bits(gz,count-3,3)) return FALSE;
2494 
2495 	} else {
2496 	    if (!send_code(gz,REPZ_11_138,gz->bl_tree)) return FALSE;
2497 	    if (!send_bits(gz,count-11,7)) return FALSE;
2498 	}
2499 	count = 0; prevlen = curlen;
2500 	if (nextlen == 0) {
2501 	    max_count = 138, min_count = 3;
2502 	} else if (curlen == nextlen) {
2503 	    max_count = 6, min_count = 3;
2504 	} else {
2505 	    max_count = 7, min_count = 4;
2506 	}
2507     }
2508     return TRUE;
2509 }
2510 
2511 /* ===========================================================================
2512  * Construct the Huffman tree for the bit lengths and return the index in
2513  * bl_order of the last bit length code to send.
2514  */
build_bl_tree(gz)2515 static int build_bl_tree(gz)
2516 GZp gz;
2517 {
2518     int max_blindex;  /* index of last bit length code of non zero freq */
2519 
2520     /* Determine the bit length frequencies for literal and distance trees */
2521     scan_tree(gz, (ct_data *)gz->dyn_ltree, gz->l_desc.max_code);
2522     scan_tree(gz, (ct_data *)gz->dyn_dtree, gz->d_desc.max_code);
2523 
2524     /* Build the bit length tree: */
2525     build_tree_gz(gz, (tree_desc *)(&(gz->bl_desc)));
2526     /* opt_len now includes the length of the tree representations, except
2527      * the lengths of the bit lengths codes and the 5+5+4 bits for the counts.
2528      */
2529 
2530     /* Determine the number of bit length codes to send. The pkzip format
2531      * requires that at least 4 bit length codes be sent. (appnote.txt says
2532      * 3 but the actual value used is 4.)
2533      */
2534     for (max_blindex = BL_CODES-1; max_blindex >= 3; max_blindex--) {
2535 	if (gz->bl_tree[gz->bl_order[max_blindex]].dl.len != 0) break;
2536     }
2537     /* Update opt_len to include the bit length tree and counts */
2538     gz->opt_len += 3*(max_blindex+1) + 5+5+4;
2539 
2540     return max_blindex;
2541 }
2542 
2543 /* ===========================================================================
2544  * Send the header for a block using dynamic Huffman trees: the counts, the
2545  * lengths of the bit length codes, the literal tree and the distance tree.
2546  * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.
2547  */
send_all_trees(gz,lcodes,dcodes,blcodes)2548 static Logical send_all_trees (gz, lcodes, dcodes, blcodes)
2549     GZp gz;
2550     int lcodes, dcodes, blcodes; /* number of codes for each tree */
2551 {
2552     int rank;                    /* index in bl_order */
2553     if (!send_bits(gz,lcodes-257,5)) return FALSE;
2554 				 /* not +255 as stated in appnote.txt */
2555     if (!send_bits(gz,dcodes-1,5)) return FALSE;
2556     if (!send_bits(gz,blcodes-4,4)) return FALSE;
2557 				 /* not -3 as stated in appnote.txt */
2558     for (rank = 0; rank < blcodes; rank++) {
2559 	if (!send_bits(gz,gz->bl_tree[gz->bl_order[rank]].dl.len,3)) return FALSE;
2560     }
2561     if (!send_tree(gz,(ct_data *)gz->dyn_ltree,lcodes-1)) return FALSE;
2562 						 /* send the literal tree */
2563     if (!send_tree(gz,(ct_data *)gz->dyn_dtree,dcodes-1)) return FALSE;
2564 						 /* send the distance tree*/
2565     return TRUE;
2566 }
2567 
2568 /* ===========================================================================
2569  * Determine the best encoding for the current block: dynamic trees, static
2570  * trees or store, and output the encoded block to the zip file.
2571  */
flush_block(gz,buf,stored_len,eof)2572 static Logical flush_block(gz, buf, stored_len, eof)
2573     GZp gz;
2574     char *buf;        /* input block, or NULL if too old */
2575     ulg stored_len;   /* length of input block */
2576     int eof;          /* true if this is the last block for a file */
2577 {
2578     ulg opt_lenb, static_lenb; /* opt_len and static_len in bytes */
2579     int max_blindex;  /* index of last bit length code of non zero freq */
2580 
2581     gz->flag_buf[gz->last_flags] = gz->tree_flags;
2582 		      /*Save the flags for the last 8 items */
2583 
2584     /* Construct the literal and distance trees */
2585     build_tree_gz(gz, (tree_desc *)(&(gz->l_desc)));
2586 
2587     build_tree_gz(gz, (tree_desc *)(&(gz->d_desc)));
2588     /* At this point, opt_len and static_len are the total bit lengths of
2589      * the compressed block data, excluding the tree representations.
2590      */
2591 
2592     /* Build the bit length tree for the above two trees, and get the index
2593      * in bl_order of the last bit length code to send.
2594      */
2595     max_blindex = build_bl_tree(gz);
2596 
2597     /* Determine the best encoding. Compute first the block length in bytes */
2598     opt_lenb = (gz->opt_len+3+7)>>3;
2599     static_lenb = (gz->static_len+3+7)>>3;
2600 
2601     if (static_lenb <= opt_lenb) opt_lenb = static_lenb;
2602 
2603     if (stored_len+4 <= opt_lenb && buf != (char*)0) {
2604 	/* 4: two words for the lengths */
2605 	/* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.
2606 	 * Otherwise we can't have processed more than WSIZE input bytes since
2607 	 * the last block flush, because compression would have been
2608 	 * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to
2609 	 * transform a block into a stored block.
2610 	 */
2611 	if (!send_bits(gz,(STORED_BLOCK<<1)+eof, 3)) return FALSE;
2612 						  /* send block type */
2613 	if (!copy_block(gz,buf,(unsigned)stored_len,1)) return FALSE;
2614 							 /* with header */
2615     }
2616     else
2617       if (static_lenb == opt_lenb) {
2618 	if (!send_bits(gz,(STATIC_TREES<<1)+eof,3)) return FALSE;
2619 	if (!compress_block(gz,(ct_data *)gz->static_ltree,
2620 			    (ct_data *)gz->static_dtree)) return FALSE;
2621       }
2622       else {
2623 	if (!send_bits(gz,(DYN_TREES<<1)+eof,3)) return FALSE;
2624 	if (!send_all_trees(gz,gz->l_desc.max_code+1,
2625 			    gz->d_desc.max_code+1,
2626 			    max_blindex+1)) return FALSE;
2627 	if (!compress_block(gz,(ct_data *)gz->dyn_ltree,
2628 			    (ct_data *)gz->dyn_dtree)) return FALSE;
2629       }
2630 
2631     init_block(gz);
2632 
2633     if (eof) {
2634 	if (!bi_windup(gz)) return FALSE;
2635     }
2636 
2637     return TRUE;
2638 }
2639 
2640 /* ===========================================================================
2641  * Save the match info and tally the frequency counts. Return true if
2642  * the current block must be flushed.
2643  */
ct_tally(gz,dist,lc)2644 static int ct_tally (gz, dist, lc)
2645     GZp gz;
2646     int dist;  /* distance of matched string */
2647     int lc;    /* match length-MIN_MATCH or unmatched char (if dist==0) */
2648 {
2649     gz->inbuf[gz->last_lit++] = (uch)lc;
2650     if (dist == 0) {
2651 	/* lc is the unmatched char */
2652 	gz->dyn_ltree[lc].fc.freq++;
2653     } else {
2654 	/* Here, lc is the match length - MIN_MATCH */
2655 	dist--;             /* dist = match distance - 1 */
2656 
2657 	gz->dyn_ltree[gz->length_code[lc]+LITERALS+1].fc.freq++;
2658 	gz->dyn_dtree[d_code(dist,gz->dist_code)].fc.freq++;
2659 
2660 	gz->d_buf[gz->last_dist++] = (ush)dist;
2661 	gz->tree_flags |= gz->flag_bit;
2662     }
2663     gz->flag_bit <<= 1;
2664 
2665     /* Output the flags if they fill a byte: */
2666     if ((gz->last_lit & 7) == 0) {
2667 	gz->flag_buf[gz->last_flags++] = gz->tree_flags;
2668 	gz->tree_flags = 0, gz->flag_bit = 1;
2669     }
2670     /* Try to guess if it is profitable to stop the current block here */
2671     if (gz->level > 2 && (gz->last_lit & 0xfff) == 0) {
2672 	/* Compute an upper bound for the compressed length */
2673 	ulg out_length = (ulg)gz->last_lit*8L;
2674 	ulg in_length = (ulg)gz->strstart - gz->block_start;
2675 	int dcode;
2676 	for (dcode = 0; dcode < D_CODES; dcode++) {
2677 	    out_length += (ulg)gz->dyn_dtree[dcode].fc.freq *
2678 			  (5L+gz->extra_dbits[dcode]);
2679 	}
2680 	out_length >>= 3;
2681 	if (gz->last_dist < gz->last_lit/2 && out_length < in_length/2) return 1;
2682     }
2683     return (gz->last_lit == LIT_BUFSIZE-1 || gz->last_dist == DIST_BUFSIZE);
2684     /* We avoid equality with LIT_BUFSIZE because of wraparound at 64K
2685      * on 16 bit machines and because stored blocks are restricted to
2686      * 64K-1 bytes.
2687      */
2688 }
2689 
2690 /* ===========================================================================
2691  * Send the block data compressed using the given Huffman trees
2692  */
compress_block(gz,ltree,dtree)2693 static Logical compress_block (gz, ltree, dtree)
2694     GZp gz;
2695     ct_data *ltree; /* literal tree */
2696     ct_data *dtree; /* distance tree */
2697 {
2698     unsigned dist;      /* distance of matched string */
2699     int lc;             /* match length or unmatched char (if dist == 0) */
2700     unsigned lx = 0;    /* running index in l_buf (inbuf) */
2701     unsigned dx = 0;    /* running index in d_buf */
2702     unsigned fx = 0;    /* running index in flag_buf */
2703     uch flag = 0;       /* current flags */
2704     unsigned code;      /* the code to send */
2705     int extra;          /* number of extra bits to send */
2706 
2707     if (gz->last_lit != 0) do {
2708 	if ((lx & 7) == 0) flag = gz->flag_buf[fx++];
2709 	lc = gz->inbuf[lx++];
2710 	if ((flag & 1) == 0) {
2711 	    if (!send_code(gz,lc,ltree)) return FALSE;
2712 					 /* send a literal byte */
2713 	} else {
2714 	    /* Here, lc is the match length - MIN_MATCH */
2715 	    code = gz->length_code[lc];
2716 	    if (!send_code(gz,code+LITERALS+1,ltree)) return FALSE;
2717 						 /* send the length code */
2718 	    extra = gz->extra_lbits[code];
2719 	    if (extra != 0) {
2720 		lc -= gz->base_length[code];
2721 		if (!send_bits(gz,lc,extra)) return FALSE;
2722 					       /* send the extra length bits */
2723 	    }
2724 	    dist = gz->d_buf[dx++];
2725 	    /* Here, dist is the match distance - 1 */
2726 	    code = d_code(dist,gz->dist_code);
2727 
2728 	    if (!send_code(gz,code,dtree)) return FALSE;
2729 					       /* send the distance code */
2730 	    extra = gz->extra_dbits[code];
2731 	    if (extra != 0) {
2732 		dist -= gz->base_dist[code];
2733 		if (!send_bits(gz,dist,extra)) return FALSE;
2734 					   /* send the extra distance bits */
2735 	    }
2736 	} /* literal or match pair ? */
2737 	flag >>= 1;
2738     } while (lx < gz->last_lit);
2739     if (!send_code(gz,END_BLOCK,ltree)) return FALSE;
2740     return TRUE;
2741 }
2742 
2743 
2744 
2745 /* util.c -- utility functions for gzip support
2746  * Copyright (C) 1992-1993 Jean-loup Gailly
2747  * This is free software; you can redistribute it and/or modify it under the
2748  * terms of the GNU General Public License, see the file COPYING.
2749  */
2750 
2751 /* ===========================================================================
2752  * Run a set of bytes through the crc shift register.  If s is a NULL
2753  * pointer, then initialize the crc shift register contents instead.
2754  * Return the current crc in either case.
2755  */
updcrc(s,n,crcReg,crc_32_tab)2756 static ulg updcrc (s, n, crcReg, crc_32_tab)
2757     uch *s;                 /* pointer to bytes to pump through */
2758     unsigned n;             /* number of bytes in s[] */
2759     ulg *crcReg;            /* shift register contents */
2760     ulg crc_32_tab[N_CRC_32_TAB];
2761 			    /* Table of CRC-32's of all single-byte values. */
2762 {
2763     register ulg c;         /* temporary variable */
2764 
2765     if (s == NULL) {
2766 	c = 0xffffffffL;
2767     } else {
2768 	c = *crcReg;
2769 	if (n) do {
2770 	    c = crc_32_tab[((int)c ^ (*s++)) & 0xff] ^ (c >> 8);
2771 	} while (--n);
2772     }
2773     *crcReg = c;
2774     return c ^ 0xffffffffL;       /* (instead of ~c for 64-bit machines) */
2775 }
2776 
2777 /* ===========================================================================
2778  * Fill the input buffer. This is called only when the buffer is empty.
2779  */
fill_inbuf(gu,byte)2780 static Logical fill_inbuf (gu, byte)   /* JTL */
2781 GUp gu;
2782 uch *byte;
2783 {
2784     int len;
2785     /* Read as much as possible */
2786     gu->insize = 0;
2787     do {
2788 	len = (int) V_read ((char *) gu->inbuf + gu->insize, (size_t) 1,
2789 			    (size_t) (INBUFSIZ - gu->insize), gu->iFp);
2790 	if (len == 0) break;    /* V_read returns 0 if an error. */
2791 	gu->insize += len;
2792     } while (gu->insize < INBUFSIZ);
2793     if (gu->insize == 0) return FALSE;
2794     gu->bytes_in += (ulg)gu->insize;
2795     gu->inptr = 1;
2796     *byte = gu->inbuf[0];
2797     return TRUE;
2798 }
2799 
2800 /* ===========================================================================
2801  * Write the output buffer outbuf[0..outcnt-1] and update bytes_out.
2802  * (used for the compressed data only)
2803  */
flush_outbuf(gz)2804 static Logical flush_outbuf(gz)
2805 GZp gz;
2806 {
2807     if (gz->outcnt == 0) return TRUE;
2808     if (!write_buf(gz->oFp,(char *)gz->outbuf,gz->outcnt)) return FALSE;
2809     gz->bytes_out += (ulg)gz->outcnt;
2810     gz->outcnt = 0;
2811     return TRUE;
2812 }
2813 
2814 /* ===========================================================================
2815  * Write the output window window[0..outcnt-1] and update crc and bytes_out.
2816  * (Used for the decompressed data only.)
2817  */
flush_window(gu)2818 static Logical flush_window(gu)
2819 GUp gu;
2820 {
2821     if (gu->outcnt == 0) return TRUE;
2822     updcrc (gu->window, gu->outcnt, &(gu->crcReg), gu->crc_32_tab);
2823     if (!write_buf(gu->oFp,(char *)gu->window,gu->outcnt)) return FALSE;
2824     gu->bytes_out += (ulg)gu->outcnt;
2825     gu->outcnt = 0;
2826     return TRUE;
2827 }
2828 
2829 /* ===========================================================================
2830  * Does the same as write(), but also handles partial pipe writes and checks
2831  * for error return.
2832  */
write_buf(vFp,buf,cnt)2833 static Logical write_buf(vFp, buf, cnt)
2834     vFILE     *vFp;
2835     void      *buf;
2836     unsigned  cnt;
2837 {
2838     unsigned  n;
2839     while (cnt > 0) {
2840 	n = (unsigned) V_write (buf, (size_t) 1, (size_t) cnt, vFp);
2841 	if (n == 0) return FALSE;       /* V_write returns 0 if error. */
2842 	cnt -= n;
2843 	buf = (void *)((char*)buf+n);
2844     }
2845     return TRUE;
2846 }
2847 
2848 /* inflate.c -- Not copyrighted 1992 by Mark Adler
2849    version c10p1, 10 January 1993 */
2850 
2851 /* You can do whatever you like with this source file, though I would
2852    prefer that if you modify it and redistribute it that you include
2853    comments to that effect with your name and the date.  Thank you.
2854    [The history has been moved to the file ChangeLog.]
2855  */
2856 
2857 /*
2858    Inflate deflated (PKZIP's method 8 compressed) data.  The compression
2859    method searches for as much of the current string of bytes (up to a
2860    length of 258) in the previous 32K bytes.  If it doesn't find any
2861    matches (of at least length 3), it codes the next byte.  Otherwise, it
2862    codes the length of the matched string and its distance backwards from
2863    the current position.  There is a single Huffman code that codes both
2864    single bytes (called "literals") and match lengths.  A second Huffman
2865    code codes the distance information, which follows a length code.  Each
2866    length or distance code actually represents a base value and a number
2867    of "extra" (sometimes zero) bits to get to add to the base value.  At
2868    the end of each deflated block is a special end-of-block (EOB) literal/
2869    length code.  The decoding process is basically: get a literal/length
2870    code; if EOB then done; if a literal, emit the decoded byte; if a
2871    length then get the distance and emit the referred-to bytes from the
2872    sliding window of previously emitted data.
2873 
2874    There are (currently) three kinds of inflate blocks: stored, fixed, and
2875    dynamic.  The compressor deals with some chunk of data at a time, and
2876    decides which method to use on a chunk-by-chunk basis.  A chunk might
2877    typically be 32K or 64K.  If the chunk is uncompressible, then the
2878    "stored" method is used.  In this case, the bytes are simply stored as
2879    is, eight bits per byte, with none of the above coding.  The bytes are
2880    preceded by a count, since there is no longer an EOB code.
2881 
2882    If the data is compressible, then either the fixed or dynamic methods
2883    are used.  In the dynamic method, the compressed data is preceded by
2884    an encoding of the literal/length and distance Huffman codes that are
2885    to be used to decode this block.  The representation is itself Huffman
2886    coded, and so is preceded by a description of that code.  These code
2887    descriptions take up a little space, and so for small blocks, there is
2888    a predefined set of codes, called the fixed codes.  The fixed method is
2889    used if the block codes up smaller that way (usually for quite small
2890    chunks), otherwise the dynamic method is used.  In the latter case, the
2891    codes are customized to the probabilities in the current block, and so
2892    can code it much better than the pre-determined fixed codes.
2893 
2894    The Huffman codes themselves are decoded using a mutli-level table
2895    lookup, in order to maximize the speed of decoding plus the speed of
2896    building the decoding tables.  See the comments below that precede the
2897    LBITS and DBITS tuning parameters.
2898  */
2899 
2900 
2901 /*
2902    Notes beyond the 1.93a appnote.txt:
2903 
2904    1. Distance pointers never point before the beginning of the output
2905       stream.
2906    2. Distance pointers can point back across blocks, up to 32k away.
2907    3. There is an implied maximum of 7 bits for the bit length table and
2908       15 bits for the actual data.
2909    4. If only one code exists, then it is encoded using one bit.  (Zero
2910       would be more efficient, but perhaps a little confusing.)  If two
2911       codes exist, they are coded using one bit each (0 and 1).
2912    5. There is no way of sending zero distance codes--a dummy must be
2913       sent if there are none.  (History: a pre 2.0 version of PKZIP would
2914       store blocks with no distance codes, but this was discovered to be
2915       too harsh a criterion.)  Valid only for 1.93a.  2.04c does allow
2916       zero distance codes, which is sent as one code of zero bits in
2917       length.
2918    6. There are up to 286 literal/length codes.  Code 256 represents the
2919       end-of-block.  Note however that the static length tree defines
2920       288 codes just to fill out the Huffman codes.  Codes 286 and 287
2921       cannot be used though, since there is no length base or extra bits
2922       defined for them.  Similarly, there are up to 30 distance codes.
2923       However, static trees define 32 codes (all 5 bits) to fill out the
2924       Huffman codes, but the last two had better not show up in the data.
2925    7. Unzip can check dynamic Huffman blocks for complete code sets.
2926       The exception is that a single code would not be complete (see #4).
2927    8. The five bits following the block type is really the number of
2928       literal codes sent minus 257.
2929    9. Length codes 8,16,16 are interpreted as 13 length codes of 8 bits
2930       (1+6+6).  Therefore, to output three times the length, you output
2931       three codes (1+1+1), whereas to output four times the same length,
2932       you only need two codes (1+3).  Hmm.
2933   10. In the tree reconstruction algorithm, Code = Code + Increment
2934       only if BitLength(i) is not zero.  (Pretty obvious.)
2935   11. Correction: 4 Bits: #of Bit Length codes - 4     (4 - 19)
2936   12. Note: length code 284 can represent 227-258, but length code 285
2937       really is 258.  The last length deserves its own, short code
2938       since it gets used a lot in very redundant files.  The length
2939       258 is special since 258 - 3 (the min match length) is 255.
2940   13. The literal/length and distance code bit lengths are read as a
2941       single stream of lengths.  It is possible (and advantageous) for
2942       a repeat code (16, 17, or 18) to go across the boundary between
2943       the two sets of lengths.
2944  */
2945 
2946 
huft_build(gu,b,n,s,d,e,t,m)2947 static int huft_build(gu, b, n, s, d, e, t, m)
2948 GUp gu;
2949 unsigned *b;            /* code lengths in bits (all assumed <= BMAX) */
2950 unsigned n;             /* number of codes (assumed <= N_MAX) */
2951 unsigned s;             /* number of simple-valued codes (0..s-1) */
2952 ush *d;                 /* list of base values for non-simple codes */
2953 ush *e;                 /* list of extra bits for non-simple codes */
2954 struct huft **t;        /* result: starting table */
2955 int *m;                 /* maximum lookup bits, returns actual */
2956 /* Given a list of code lengths and a maximum table size, make a set of
2957    tables to decode that set of codes.  Return zero on success, one if
2958    the given code set is incomplete (the tables are still built in this
2959    case), two if the input is invalid (all zero length codes or an
2960    oversubscribed set of lengths), and three if not enough memory. */
2961 {
2962   unsigned a;                   /* counter for codes of length k */
2963   unsigned c[BMAX+1];           /* bit length count table */
2964   unsigned f;                   /* i repeats in table every f entries */
2965   int g;                        /* maximum code length */
2966   int h;                        /* table level */
2967   register unsigned i;          /* counter, current code */
2968   register unsigned j;          /* counter */
2969   register int k;               /* number of bits in current code */
2970   int l;                        /* bits per table (returned in m) */
2971   register unsigned *p;         /* pointer into c[], b[], or v[] */
2972   register struct huft *q;      /* points to current table */
2973   struct huft r;                /* table entry for structure assignment */
2974   struct huft *u[BMAX];         /* table stack */
2975   unsigned v[N_MAX];            /* values in order of bit length */
2976   register int w;               /* bits before this table == (l * h) */
2977   unsigned x[BMAX+1];           /* bit offsets, then code stack */
2978   unsigned *xp;                 /* pointer into x */
2979   int y;                        /* number of dummy codes added */
2980   unsigned z;                   /* number of entries in current table */
2981 
2982   /* Generate counts for each bit length */
2983   memzero(c, sizeof(c));
2984   p = b;  i = n;
2985   do {
2986     c[*p]++;                    /* assume all entries <= BMAX */
2987     p++;                      /* Can't combine with above line (Solaris bug) */
2988   } while (--i);
2989   if (c[0] == n)                /* null input--all zero length codes */
2990   {
2991     *t = (struct huft *)NULL;
2992     *m = 0;
2993     return 0;
2994   }
2995 
2996 
2997   /* Find minimum and maximum length, bound *m by those */
2998   l = *m;
2999   for (j = 1; j <= BMAX; j++)
3000     if (c[j])
3001       break;
3002   k = j;                        /* minimum code length */
3003   if ((unsigned)l < j)
3004     l = j;
3005   for (i = BMAX; i; i--)
3006     if (c[i])
3007       break;
3008   g = i;                        /* maximum code length */
3009   if ((unsigned)l > i)
3010     l = i;
3011   *m = l;
3012 
3013 
3014   /* Adjust last length count to fill out codes, if needed */
3015   for (y = 1 << j; j < i; j++, y <<= 1)
3016     if ((y -= c[j]) < 0)
3017       return 2;                 /* bad input: more codes than bits */
3018   if ((y -= c[i]) < 0)
3019     return 2;
3020   c[i] += y;
3021 
3022 
3023   /* Generate starting offsets into the value table for each length */
3024   x[1] = j = 0;
3025   p = c + 1;  xp = x + 2;
3026   while (--i) {                 /* note that i == g from above */
3027     *xp++ = (j += *p++);
3028   }
3029 
3030 
3031   /* Make a table of values in order of bit lengths */
3032   p = b;  i = 0;
3033   do {
3034     if ((j = *p++) != 0)
3035       v[x[j]++] = i;
3036   } while (++i < n);
3037 
3038 
3039   /* Generate the Huffman codes and for each, make the table entries */
3040   x[0] = i = 0;                 /* first Huffman code is zero */
3041   p = v;                        /* grab values in bit order */
3042   h = -1;                       /* no tables yet--level -1 */
3043   w = -l;                       /* bits decoded == (l * h) */
3044   u[0] = (struct huft *)NULL;   /* just to keep compilers happy */
3045   q = (struct huft *)NULL;      /* ditto */
3046   z = 0;                        /* ditto */
3047 
3048   /* go through the bit lengths (k already is bits in shortest code) */
3049   for (; k <= g; k++)
3050   {
3051     a = c[k];
3052     while (a--)
3053     {
3054       /* here i is the Huffman code of length k bits for value *p */
3055       /* make tables up to required level */
3056       while (k > w + l)
3057       {
3058 	h++;
3059 	w += l;                 /* previous table always l bits */
3060 
3061 	/* compute minimum size table less than or equal to l bits */
3062 	z = (z = g - w) > (unsigned)l ? l : z;  /* upper limit on table size */
3063 	if ((f = 1 << (j = k - w)) > a + 1)     /* try a k-w bit table */
3064 	{                       /* too few codes for k-w bit table */
3065 	  f -= a + 1;           /* deduct codes from patterns left */
3066 	  xp = c + k;
3067 	  while (++j < z)       /* try smaller tables up to z bits */
3068 	  {
3069 	    if ((f <<= 1) <= *++xp)
3070 	      break;            /* enough codes to use up j bits */
3071 	    f -= *xp;           /* else deduct codes from patterns */
3072 	  }
3073 	}
3074 	z = 1 << j;             /* table entries for j-bit table */
3075 
3076 	/* allocate and link in new table */
3077 	if ((q = (struct huft *)
3078 	    CallocateMemory((size_t) 1,
3079 			    (z + 1) * sizeof(struct huft),NULL)) == NULL) {
3080 	  if (h) huft_free(u[0]);
3081 	  return 3;             /* not enough memory */
3082 	}
3083 	gu->hufts += z + 1;         /* track memory usage */
3084 	*t = q + 1;             /* link to list for huft_free() */
3085 	*(t = &(q->v.t)) = (struct huft *)NULL;
3086 	u[h] = ++q;             /* table starts after link */
3087 
3088 	/* connect to last table, if there is one */
3089 	if (h)
3090 	{
3091 	  x[h] = i;             /* save pattern for backing up */
3092 	  r.b = (uch)l;         /* bits to dump before this table */
3093 	  r.e = (uch)(16 + j);  /* bits in this table */
3094 	  r.v.t = q;            /* pointer to this table */
3095 	  j = i >> (w - l);     /* (get around Turbo C bug) */
3096 	  u[h-1][j] = r;        /* connect to last table */
3097 	}
3098       }
3099 
3100       /* set up table entry in r */
3101       r.b = (uch)(k - w);
3102       if (p >= v + n)
3103 	r.e = 99;               /* out of values--invalid code */
3104       else if (*p < s)
3105       {
3106 	r.e = (uch)(*p < 256 ? 16 : 15);    /* 256 is end-of-block code */
3107 	r.v.n = (ush)(*p);             /* simple code is just the value */
3108 	p++;                           /* one compiler does not like *p++ */
3109       }
3110       else
3111       {
3112 	r.e = (uch)e[*p - s];   /* non-simple--look up in lists */
3113 	r.v.n = d[*p++ - s];
3114       }
3115 
3116       /* fill code-like entries with r */
3117       f = 1 << (k - w);
3118       for (j = i >> w; j < z; j += f)
3119 	q[j] = r;
3120 
3121       /* backwards increment the k-bit code i */
3122       for (j = 1 << (k - 1); i & j; j >>= 1)
3123 	i ^= j;
3124       i ^= j;
3125 
3126       /* backup over finished tables */
3127       while ((i & ((1 << w) - 1)) != x[h])
3128       {
3129 	h--;                    /* don't need to update q */
3130 	w -= l;
3131       }
3132     }
3133   }
3134 
3135   /* Return 1 if we were given an incomplete table */
3136   return (y != 0 && g != 1 ? 1 : 0);
3137 }
3138 
3139 
3140 
huft_free(t)3141 static int huft_free(t)
3142 struct huft *t;         /* table to free */
3143 /* Free the malloc'ed tables built by huft_build(), which makes a linked
3144    list of the tables it made, with the links in a dummy first entry of
3145    each table. */
3146 {
3147   register struct huft *p, *q;
3148 
3149 
3150   /* Go through linked list, freeing from the malloced (t[-1]) address. */
3151   p = t;
3152   while (p != (struct huft *)NULL)
3153   {
3154     q = (--p)->v.t;
3155     cdf_FreeMemory ((char *) p, NULL);
3156     p = q;
3157   }
3158   return 0;
3159 }
3160 
3161 
inflate_codes(gu,tl,td,bl,bd)3162 static int inflate_codes(gu, tl, td, bl, bd)
3163 GUp gu;
3164 struct huft *tl, *td;   /* literal/length and distance decoder tables */
3165 int bl, bd;             /* number of bits decoded by tl[] and td[] */
3166 /* inflate (decompress) the codes in a deflated (compressed) block.
3167    Return an error code or zero if it all goes ok. */
3168 {
3169   register unsigned e;  /* table entry flag/number of extra bits */
3170   unsigned n, d;        /* length and index for copy */
3171   unsigned w;           /* current window position */
3172   struct huft *t;       /* pointer to table entry */
3173   unsigned ml, md;      /* masks for bl and bd bits */
3174   register ulg b;       /* bit buffer */
3175   register unsigned k;  /* number of bits in bit buffer */
3176 
3177   /* make local copies of globals */
3178   b = gu->bb;                       /* initialize bit buffer */
3179   k = gu->bk;
3180   w = gu->outcnt;                       /* initialize window position */
3181 
3182   /* inflate the coded data */
3183   ml = gu->mask_bits[bl];           /* precompute masks for speed */
3184   md = gu->mask_bits[bd];
3185   for (;;)                      /* do until end of block */
3186   {
3187     NEEDBITS(gu,b,k,(unsigned)bl)
3188     if ((e = (t = tl + ((unsigned)b & ml))->e) > 16)
3189       do {
3190 	if (e == 99) return 1;
3191 	DUMPBITS(b,k,t->b)
3192 	e -= 16;
3193 	NEEDBITS(gu,b,k,e)
3194       } while ((e = (t = t->v.t + ((unsigned)b & gu->mask_bits[e]))->e) > 16);
3195     DUMPBITS(b,k,t->b)
3196     if (e == 16)                /* then it's a literal */
3197     {
3198       gu->window[w++] = (uch)t->v.n;
3199       if (w == WSIZE) {
3200 	gu->outcnt = w;
3201 	if (!flush_window(gu)) return 5;        /* Write error - JTL */
3202 	w = 0;
3203       }
3204     }
3205     else                        /* it's an EOB or a length */
3206     {
3207       /* exit if end of block */
3208       if (e == 15)
3209 	break;
3210 
3211       /* get length of block to copy */
3212       NEEDBITS(gu,b,k,e)
3213       n = t->v.n + ((unsigned)b & gu->mask_bits[e]);
3214       DUMPBITS(b,k,e);
3215 
3216       /* decode distance of block to copy */
3217       NEEDBITS(gu,b,k,(unsigned)bd)
3218       if ((e = (t = td + ((unsigned)b & md))->e) > 16)
3219 	do {
3220 	  if (e == 99) return 1;
3221 	  DUMPBITS(b,k,t->b)
3222 	  e -= 16;
3223 	  NEEDBITS(gu,b,k,e)
3224 	} while ((e = (t = t->v.t + ((unsigned)b & gu->mask_bits[e]))->e) > 16);
3225       DUMPBITS(b,k,t->b)
3226       NEEDBITS(gu,b,k,e)
3227       d = w - t->v.n - ((unsigned)b & gu->mask_bits[e]);
3228       DUMPBITS(b,k,e)
3229 
3230       /* do the copy */
3231       do {
3232 	n -= (e = (e = WSIZE - ((d &= WSIZE-1) > w ? d : w)) > n ? n : e);
3233 	if (w - d >= e)         /* (this test assumes unsigned comparison) */
3234 	{
3235 	  memcpy(gu->window + w, gu->window + d, e);
3236 	  w += e;
3237 	  d += e;
3238 	}
3239 	else                      /* do it slow to avoid memcpy() overlap */
3240 	  do {
3241 	    gu->window[w++] = gu->window[d++];
3242 	  } while (--e);
3243 	if (w == WSIZE)
3244 	{
3245 	  gu->outcnt = w;
3246 	  if (!flush_window(gu)) return 5;      /* Write error. */
3247 	  w = 0;
3248 	}
3249       } while (n);
3250     }
3251   }
3252 
3253   /* restore the globals from the locals */
3254   gu->outcnt = w;                       /* restore global window pointer */
3255   gu->bb = b;                       /* restore global bit buffer */
3256   gu->bk = k;
3257 
3258   /* done */
3259   return 0;
3260 }
3261 
inflate_stored(gu)3262 static int inflate_stored(gu)
3263 GUp gu;
3264 /* "decompress" an inflated type 0 (stored) block. */
3265 {
3266   unsigned n;           /* number of bytes in block */
3267   unsigned w;           /* current window position */
3268   register ulg b;       /* bit buffer */
3269   register unsigned k;  /* number of bits in bit buffer */
3270 
3271   /* make local copies of globals */
3272   b = gu->bb;                       /* initialize bit buffer */
3273   k = gu->bk;
3274   w = gu->outcnt;                       /* initialize window position */
3275 
3276   /* go to byte boundary */
3277   n = k & 7;
3278   DUMPBITS(b,k,n);
3279 
3280   /* get the length and its complement */
3281   NEEDBITS(gu,b,k,16)
3282   n = ((unsigned)b & 0xffff);
3283   DUMPBITS(b,k,16)
3284   NEEDBITS(gu,b,k,16)
3285   if (n != (unsigned)((~b) & 0xffff))
3286     return 1;                   /* error in compressed data */
3287   DUMPBITS(b,k,16)
3288 
3289   /* read and output the compressed data */
3290   while (n--)
3291   {
3292     NEEDBITS(gu,b,k,8)
3293     gu->window[w++] = (uch)b;
3294     if (w == WSIZE)
3295     {
3296       gu->outcnt = w;
3297       if (!flush_window(gu)) return 5;  /* Write error. */
3298       w = 0;
3299     }
3300     DUMPBITS(b,k,8)
3301   }
3302 
3303   /* restore the globals from the locals */
3304   gu->outcnt = w;                       /* restore global window pointer */
3305   gu->bb = b;                       /* restore global bit buffer */
3306   gu->bk = k;
3307   return 0;
3308 }
3309 
inflate_fixed(gu)3310 static int inflate_fixed(gu)
3311 GUp gu;
3312 /* decompress an inflated type 1 (fixed Huffman codes) block.  We should
3313    either replace this with a custom decoder, or at least precompute the
3314    Huffman tables. */
3315 {
3316   int i;                /* temporary variable */
3317   struct huft *tl;      /* literal/length code table */
3318   struct huft *td;      /* distance code table */
3319   int bl;               /* lookup bits for tl */
3320   int bd;               /* lookup bits for td */
3321   unsigned l[288];      /* length list for huft_build */
3322 
3323   /* set up literal table */
3324   for (i = 0; i < 144; i++)
3325     l[i] = 8;
3326   for (; i < 256; i++)
3327     l[i] = 9;
3328   for (; i < 280; i++)
3329     l[i] = 7;
3330   for (; i < 288; i++)          /* make a complete, but wrong code set */
3331     l[i] = 8;
3332   bl = 7;
3333   if ((i = huft_build(gu, l, 288, 257, gu->cplens, gu->cplext, &tl, &bl)) != 0)
3334     return i;
3335 
3336   /* set up distance table */
3337   for (i = 0; i < 30; i++)      /* make an incomplete code set */
3338     l[i] = 5;
3339   bd = 5;
3340   if ((i = huft_build(gu, l, 30, 0, gu->cpdist, gu->cpdext, &td, &bd)) > 1)
3341   {
3342     huft_free(tl);
3343     return i;
3344   }
3345 
3346   /* decompress until an end-of-block code */
3347   if ((i = inflate_codes(gu,tl,td,bl,bd)) != 0) return i;       /* JTL */
3348 
3349   /* free the decoding tables, return */
3350   huft_free (tl);
3351   huft_free (td);
3352   return 0;
3353 }
3354 
inflate_dynamic(gu)3355 static int inflate_dynamic(gu)
3356 GUp gu;
3357 /* decompress an inflated type 2 (dynamic Huffman codes) block. */
3358 {
3359   int i;                /* temporary variables */
3360   unsigned j;
3361   unsigned l;           /* last length */
3362   unsigned m;           /* mask for bit lengths table */
3363   unsigned n;           /* number of lengths to get */
3364   struct huft *tl;      /* literal/length code table */
3365   struct huft *td;      /* distance code table */
3366   int bl;               /* lookup bits for tl */
3367   int bd;               /* lookup bits for td */
3368   unsigned nb;          /* number of bit length codes */
3369   unsigned nl;          /* number of literal/length codes */
3370   unsigned nd;          /* number of distance codes */
3371   unsigned ll[286+30];  /* literal/length and distance code lengths */
3372   register ulg b;       /* bit buffer */
3373   register unsigned k;  /* number of bits in bit buffer */
3374 
3375   /* make local bit buffer */
3376   b = gu->bb;
3377   k = gu->bk;
3378 
3379   /* read in table lengths */
3380   NEEDBITS(gu,b,k,5)
3381   nl = 257 + ((unsigned)b & 0x1f);      /* number of literal/length codes */
3382   DUMPBITS(b,k,5)
3383   NEEDBITS(gu,b,k,5)
3384   nd = 1 + ((unsigned)b & 0x1f);        /* number of distance codes */
3385   DUMPBITS(b,k,5)
3386   NEEDBITS(gu,b,k,4)
3387   nb = 4 + ((unsigned)b & 0xf);         /* number of bit length codes */
3388   DUMPBITS(b,k,4)
3389   if (nl > 286 || nd > 30) return 1;                   /* bad lengths */
3390 
3391   /* read in bit-length-code lengths */
3392   for (j = 0; j < nb; j++)
3393   {
3394     NEEDBITS(gu,b,k,3)
3395     ll[gu->border[j]] = (unsigned)b & 7;
3396     DUMPBITS(b,k,3)
3397   }
3398   for (; j < 19; j++) ll[gu->border[j]] = 0;
3399 
3400   /* build decoding table for trees--single level, 7 bit lookup */
3401   bl = 7;
3402   if ((i = huft_build(gu, ll, 19, 19, NULL, NULL, &tl, &bl)) != 0)
3403   {
3404     if (i == 1) huft_free (tl);
3405     return i;                   /* incomplete code set */
3406   }
3407 
3408   /* read in literal and distance code lengths */
3409   n = nl + nd;
3410   m = gu->mask_bits[bl];
3411   i = l = 0;
3412   while ((unsigned)i < n)
3413   {
3414     NEEDBITS(gu,b,k,(unsigned)bl)
3415     j = (td = tl + ((unsigned)b & m))->b;
3416     DUMPBITS(b,k,j)
3417     j = td->v.n;
3418     if (j < 16)                 /* length of code in bits (0..15) */
3419       ll[i++] = l = j;          /* save last length in l */
3420     else if (j == 16)           /* repeat last length 3 to 6 times */
3421     {
3422       NEEDBITS(gu,b,k,2)
3423       j = 3 + ((unsigned)b & 3);
3424       DUMPBITS(b,k,2)
3425       if ((unsigned)i + j > n)
3426 	return 1;
3427       while (j--)
3428 	ll[i++] = l;
3429     }
3430     else if (j == 17)           /* 3 to 10 zero length codes */
3431     {
3432       NEEDBITS(gu,b,k,3)
3433       j = 3 + ((unsigned)b & 7);
3434       DUMPBITS(b,k,3)
3435       if ((unsigned)i + j > n)
3436 	return 1;
3437       while (j--)
3438 	ll[i++] = 0;
3439       l = 0;
3440     }
3441     else                        /* j == 18: 11 to 138 zero length codes */
3442     {
3443       NEEDBITS(gu,b,k,7)
3444       j = 11 + ((unsigned)b & 0x7f);
3445       DUMPBITS(b,k,7)
3446       if ((unsigned)i + j > n)
3447 	return 1;
3448       while (j--)
3449 	ll[i++] = 0;
3450       l = 0;
3451     }
3452   }
3453 
3454   /* free decoding table for trees */
3455   huft_free (tl);
3456 
3457   /* restore the global bit buffer */
3458   gu->bb = b;
3459   gu->bk = k;
3460 
3461   /* build the decoding tables for literal/length and distance codes */
3462   bl = LBITS;
3463   if ((i = huft_build(gu, ll, nl, 257, gu->cplens, gu->cplext, &tl, &bl)) != 0)
3464   {
3465     if (i == 1) {
3466       /* fprintf(stderr, " incomplete literal tree\n"); */
3467       huft_free (tl);
3468     }
3469     return i;                   /* incomplete code set */
3470   }
3471   bd = DBITS;
3472   if ((i = huft_build(gu, ll + nl, nd, 0, gu->cpdist, gu->cpdext, &td, &bd)) != 0) {
3473     if (i == 1) {
3474       /* fprintf(stderr, " incomplete distance tree\n"); */
3475       huft_free (td);
3476     }
3477     huft_free (tl);
3478     return i;                   /* incomplete code set */
3479   }
3480 
3481 
3482   /* decompress until an end-of-block code */
3483   if ((i = inflate_codes(gu,tl,td,bl,bd)) != 0) return i;       /* JTL */
3484 
3485   /* free the decoding tables, return */
3486   huft_free (tl);
3487   huft_free (td);
3488   return 0;
3489 }
3490 
inflate_block(gu,e)3491 static int inflate_block(gu, e)
3492 GUp gu;
3493 int *e;                 /* last block flag */
3494 /* decompress an inflated block */
3495 {
3496   unsigned t;           /* block type */
3497   register ulg b;       /* bit buffer */
3498   register unsigned k;  /* number of bits in bit buffer */
3499 
3500   /* make local bit buffer */
3501   b = gu->bb;
3502   k = gu->bk;
3503 
3504   /* read in last block bit */
3505   NEEDBITS(gu,b,k,1)
3506   *e = (int)b & 1;
3507   DUMPBITS(b,k,1)
3508 
3509   /* read in block type */
3510   NEEDBITS(gu,b,k,2)
3511   t = (unsigned)b & 3;
3512   DUMPBITS(b,k,2)
3513 
3514   /* restore the global bit buffer */
3515   gu->bb = b;
3516   gu->bk = k;
3517 
3518   /* inflate that block type */
3519   if (t == 2) return inflate_dynamic(gu);
3520   if (t == 0) return inflate_stored(gu);
3521   if (t == 1) return inflate_fixed(gu);
3522 
3523   /* bad block type */
3524   return 2;
3525 }
3526 
3527 
3528 
inflate(gu)3529 static int inflate(gu)
3530 GUp gu;
3531 /* decompress an inflated entry */
3532 {
3533   int e;                /* last block flag */
3534   int r;                /* result code */
3535   unsigned h;           /* maximum struct huft's malloc'ed */
3536 
3537   /* initialize window, bit buffer */
3538   gu->outcnt = 0;
3539   gu->bk = 0;
3540   gu->bb = 0;
3541 
3542   /* decompress until the last block */
3543   h = 0;
3544   do {
3545     gu->hufts = 0;
3546     if ((r = inflate_block(gu,&e)) != 0) return r;
3547     if (gu->hufts > h) h = gu->hufts;
3548   } while (!e);
3549 
3550   /* Undo too much lookahead. The next read will be byte aligned so we
3551    * can discard unused bits in the last meaningful byte.
3552    */
3553   while (gu->bk >= 8) {
3554     gu->bk -= 8;
3555     gu->inptr--;
3556   }
3557 
3558   /* flush out slide */
3559   if (!flush_window(gu)) return 5;      /* Write error. */
3560 
3561   /* return success */
3562   return 0;
3563 }
3564 
3565 /******************************************************************************
3566 * PutByte.
3567 ******************************************************************************/
3568 
PutByte(gz,c)3569 static Logical PutByte (gz, c)
3570 GZp gz;
3571 unsigned c;
3572 {
3573   gz->outbuf[gz->outcnt++] = (uch) c;
3574   if (gz->outcnt == OUTBUFSIZ) {
3575     if (!flush_outbuf(gz)) return FALSE;
3576   }
3577   return TRUE;
3578 }
3579 
3580 /******************************************************************************
3581 * PutShort.
3582 ******************************************************************************/
3583 
PutShort(gz,w)3584 static Logical PutShort (gz, w)
3585 GZp gz;
3586 unsigned w;
3587 {
3588   if (gz->outcnt < OUTBUFSIZ-2) {
3589     gz->outbuf[gz->outcnt++] = (uch) ((ush)(w) & 0xff);
3590     gz->outbuf[gz->outcnt++] = (uch) ((ush)(w) >> 8);
3591   }
3592   else {
3593     if (!PutByte(gz,(unsigned)((ush)(w) & 0xff))) return FALSE;
3594     if (!PutByte(gz,(unsigned)((ush)(w) >> 8))) return FALSE;
3595   }
3596   return TRUE;
3597 }
3598 
3599 /******************************************************************************
3600 * PutLong.
3601 ******************************************************************************/
3602 
PutLong(gz,n)3603 static Logical PutLong (gz, n)
3604 GZp gz;
3605 ulg n;
3606 {
3607   if (!PutShort(gz,(unsigned)((n) & 0xffff))) return FALSE;
3608   if (!PutShort(gz,(unsigned)((n) >> 16))) return FALSE;
3609   return TRUE;
3610 }
3611 
3612 /******************************************************************************
3613 * GetByte.
3614 ******************************************************************************/
3615 
GetByte(gu,byte)3616 static Logical GetByte (gu, byte)
3617 GUp gu;
3618 uch *byte;
3619 {
3620   if (gu->inptr < gu->insize)
3621     *byte = gu->inbuf[gu->inptr++];
3622   else
3623     if (!fill_inbuf(gu,byte)) return FALSE;
3624   return TRUE;
3625 }
3626 
3627 /******************************************************************************
3628 * initCRC.
3629 ******************************************************************************/
3630 
initCRC(crc_32_tab)3631 static void initCRC (crc_32_tab)
3632 ulg crc_32_tab[N_CRC_32_TAB];
3633 {
3634   crc_32_tab[0]= 0x00000000L;
3635   crc_32_tab[1]= 0x77073096L;
3636   crc_32_tab[2]= 0xee0e612cL;
3637   crc_32_tab[3]= 0x990951baL;
3638   crc_32_tab[4]= 0x076dc419L;
3639   crc_32_tab[5]= 0x706af48fL;
3640   crc_32_tab[6]= 0xe963a535L;
3641   crc_32_tab[7]= 0x9e6495a3L;
3642   crc_32_tab[8]= 0x0edb8832L;
3643   crc_32_tab[9]= 0x79dcb8a4L;
3644   crc_32_tab[10]= 0xe0d5e91eL;
3645   crc_32_tab[11]= 0x97d2d988L;
3646   crc_32_tab[12]= 0x09b64c2bL;
3647   crc_32_tab[13]= 0x7eb17cbdL;
3648   crc_32_tab[14]= 0xe7b82d07L;
3649   crc_32_tab[15]= 0x90bf1d91L;
3650   crc_32_tab[16]= 0x1db71064L;
3651   crc_32_tab[17]= 0x6ab020f2L;
3652   crc_32_tab[18]= 0xf3b97148L;
3653   crc_32_tab[19]= 0x84be41deL;
3654   crc_32_tab[20]= 0x1adad47dL;
3655   crc_32_tab[21]= 0x6ddde4ebL;
3656   crc_32_tab[22]= 0xf4d4b551L;
3657   crc_32_tab[23]= 0x83d385c7L;
3658   crc_32_tab[24]= 0x136c9856L;
3659   crc_32_tab[25]= 0x646ba8c0L;
3660   crc_32_tab[26]= 0xfd62f97aL;
3661   crc_32_tab[27]= 0x8a65c9ecL;
3662   crc_32_tab[28]= 0x14015c4fL;
3663   crc_32_tab[29]= 0x63066cd9L;
3664   crc_32_tab[30]= 0xfa0f3d63L;
3665   crc_32_tab[31]= 0x8d080df5L;
3666   crc_32_tab[32]= 0x3b6e20c8L;
3667   crc_32_tab[33]= 0x4c69105eL;
3668   crc_32_tab[34]= 0xd56041e4L;
3669   crc_32_tab[35]= 0xa2677172L;
3670   crc_32_tab[36]= 0x3c03e4d1L;
3671   crc_32_tab[37]= 0x4b04d447L;
3672   crc_32_tab[38]= 0xd20d85fdL;
3673   crc_32_tab[39]= 0xa50ab56bL;
3674   crc_32_tab[40]= 0x35b5a8faL;
3675   crc_32_tab[41]= 0x42b2986cL;
3676   crc_32_tab[42]= 0xdbbbc9d6L;
3677   crc_32_tab[43]= 0xacbcf940L;
3678   crc_32_tab[44]= 0x32d86ce3L;
3679   crc_32_tab[45]= 0x45df5c75L;
3680   crc_32_tab[46]= 0xdcd60dcfL;
3681   crc_32_tab[47]= 0xabd13d59L;
3682   crc_32_tab[48]= 0x26d930acL;
3683   crc_32_tab[49]= 0x51de003aL;
3684   crc_32_tab[50]= 0xc8d75180L;
3685   crc_32_tab[51]= 0xbfd06116L;
3686   crc_32_tab[52]= 0x21b4f4b5L;
3687   crc_32_tab[53]= 0x56b3c423L;
3688   crc_32_tab[54]= 0xcfba9599L;
3689   crc_32_tab[55]= 0xb8bda50fL;
3690   crc_32_tab[56]= 0x2802b89eL;
3691   crc_32_tab[57]= 0x5f058808L;
3692   crc_32_tab[58]= 0xc60cd9b2L;
3693   crc_32_tab[59]= 0xb10be924L;
3694   crc_32_tab[60]= 0x2f6f7c87L;
3695   crc_32_tab[61]= 0x58684c11L;
3696   crc_32_tab[62]= 0xc1611dabL;
3697   crc_32_tab[63]= 0xb6662d3dL;
3698   crc_32_tab[64]= 0x76dc4190L;
3699   crc_32_tab[65]= 0x01db7106L;
3700   crc_32_tab[66]= 0x98d220bcL;
3701   crc_32_tab[67]= 0xefd5102aL;
3702   crc_32_tab[68]= 0x71b18589L;
3703   crc_32_tab[69]= 0x06b6b51fL;
3704   crc_32_tab[70]= 0x9fbfe4a5L;
3705   crc_32_tab[71]= 0xe8b8d433L;
3706   crc_32_tab[72]= 0x7807c9a2L;
3707   crc_32_tab[73]= 0x0f00f934L;
3708   crc_32_tab[74]= 0x9609a88eL;
3709   crc_32_tab[75]= 0xe10e9818L;
3710   crc_32_tab[76]= 0x7f6a0dbbL;
3711   crc_32_tab[77]= 0x086d3d2dL;
3712   crc_32_tab[78]= 0x91646c97L;
3713   crc_32_tab[79]= 0xe6635c01L;
3714   crc_32_tab[80]= 0x6b6b51f4L;
3715   crc_32_tab[81]= 0x1c6c6162L;
3716   crc_32_tab[82]= 0x856530d8L;
3717   crc_32_tab[83]= 0xf262004eL;
3718   crc_32_tab[84]= 0x6c0695edL;
3719   crc_32_tab[85]= 0x1b01a57bL;
3720   crc_32_tab[86]= 0x8208f4c1L;
3721   crc_32_tab[87]= 0xf50fc457L;
3722   crc_32_tab[88]= 0x65b0d9c6L;
3723   crc_32_tab[89]= 0x12b7e950L;
3724   crc_32_tab[90]= 0x8bbeb8eaL;
3725   crc_32_tab[91]= 0xfcb9887cL;
3726   crc_32_tab[92]= 0x62dd1ddfL;
3727   crc_32_tab[93]= 0x15da2d49L;
3728   crc_32_tab[94]= 0x8cd37cf3L;
3729   crc_32_tab[95]= 0xfbd44c65L;
3730   crc_32_tab[96]= 0x4db26158L;
3731   crc_32_tab[97]= 0x3ab551ceL;
3732   crc_32_tab[98]= 0xa3bc0074L;
3733   crc_32_tab[99]= 0xd4bb30e2L;
3734   crc_32_tab[100]= 0x4adfa541L;
3735   crc_32_tab[101]= 0x3dd895d7L;
3736   crc_32_tab[102]= 0xa4d1c46dL;
3737   crc_32_tab[103]= 0xd3d6f4fbL;
3738   crc_32_tab[104]= 0x4369e96aL;
3739   crc_32_tab[105]= 0x346ed9fcL;
3740   crc_32_tab[106]= 0xad678846L;
3741   crc_32_tab[107]= 0xda60b8d0L;
3742   crc_32_tab[108]= 0x44042d73L;
3743   crc_32_tab[109]= 0x33031de5L;
3744   crc_32_tab[110]= 0xaa0a4c5fL;
3745   crc_32_tab[111]= 0xdd0d7cc9L;
3746   crc_32_tab[112]= 0x5005713cL;
3747   crc_32_tab[113]= 0x270241aaL;
3748   crc_32_tab[114]= 0xbe0b1010L;
3749   crc_32_tab[115]= 0xc90c2086L;
3750   crc_32_tab[116]= 0x5768b525L;
3751   crc_32_tab[117]= 0x206f85b3L;
3752   crc_32_tab[118]= 0xb966d409L;
3753   crc_32_tab[119]= 0xce61e49fL;
3754   crc_32_tab[120]= 0x5edef90eL;
3755   crc_32_tab[121]= 0x29d9c998L;
3756   crc_32_tab[122]= 0xb0d09822L;
3757   crc_32_tab[123]= 0xc7d7a8b4L;
3758   crc_32_tab[124]= 0x59b33d17L;
3759   crc_32_tab[125]= 0x2eb40d81L;
3760   crc_32_tab[126]= 0xb7bd5c3bL;
3761   crc_32_tab[127]= 0xc0ba6cadL;
3762   crc_32_tab[128]= 0xedb88320L;
3763   crc_32_tab[129]= 0x9abfb3b6L;
3764   crc_32_tab[130]= 0x03b6e20cL;
3765   crc_32_tab[131]= 0x74b1d29aL;
3766   crc_32_tab[132]= 0xead54739L;
3767   crc_32_tab[133]= 0x9dd277afL;
3768   crc_32_tab[134]= 0x04db2615L;
3769   crc_32_tab[135]= 0x73dc1683L;
3770   crc_32_tab[136]= 0xe3630b12L;
3771   crc_32_tab[137]= 0x94643b84L;
3772   crc_32_tab[138]= 0x0d6d6a3eL;
3773   crc_32_tab[139]= 0x7a6a5aa8L;
3774   crc_32_tab[140]= 0xe40ecf0bL;
3775   crc_32_tab[141]= 0x9309ff9dL;
3776   crc_32_tab[142]= 0x0a00ae27L;
3777   crc_32_tab[143]= 0x7d079eb1L;
3778   crc_32_tab[144]= 0xf00f9344L;
3779   crc_32_tab[145]= 0x8708a3d2L;
3780   crc_32_tab[146]= 0x1e01f268L;
3781   crc_32_tab[147]= 0x6906c2feL;
3782   crc_32_tab[148]= 0xf762575dL;
3783   crc_32_tab[149]= 0x806567cbL;
3784   crc_32_tab[150]= 0x196c3671L;
3785   crc_32_tab[151]= 0x6e6b06e7L;
3786   crc_32_tab[152]= 0xfed41b76L;
3787   crc_32_tab[153]= 0x89d32be0L;
3788   crc_32_tab[154]= 0x10da7a5aL;
3789   crc_32_tab[155]= 0x67dd4accL;
3790   crc_32_tab[156]= 0xf9b9df6fL;
3791   crc_32_tab[157]= 0x8ebeeff9L;
3792   crc_32_tab[158]= 0x17b7be43L;
3793   crc_32_tab[159]= 0x60b08ed5L;
3794   crc_32_tab[160]= 0xd6d6a3e8L;
3795   crc_32_tab[161]= 0xa1d1937eL;
3796   crc_32_tab[162]= 0x38d8c2c4L;
3797   crc_32_tab[163]= 0x4fdff252L;
3798   crc_32_tab[164]= 0xd1bb67f1L;
3799   crc_32_tab[165]= 0xa6bc5767L;
3800   crc_32_tab[166]= 0x3fb506ddL;
3801   crc_32_tab[167]= 0x48b2364bL;
3802   crc_32_tab[168]= 0xd80d2bdaL;
3803   crc_32_tab[169]= 0xaf0a1b4cL;
3804   crc_32_tab[170]= 0x36034af6L;
3805   crc_32_tab[171]= 0x41047a60L;
3806   crc_32_tab[172]= 0xdf60efc3L;
3807   crc_32_tab[173]= 0xa867df55L;
3808   crc_32_tab[174]= 0x316e8eefL;
3809   crc_32_tab[175]= 0x4669be79L;
3810   crc_32_tab[176]= 0xcb61b38cL;
3811   crc_32_tab[177]= 0xbc66831aL;
3812   crc_32_tab[178]= 0x256fd2a0L;
3813   crc_32_tab[179]= 0x5268e236L;
3814   crc_32_tab[180]= 0xcc0c7795L;
3815   crc_32_tab[181]= 0xbb0b4703L;
3816   crc_32_tab[182]= 0x220216b9L;
3817   crc_32_tab[183]= 0x5505262fL;
3818   crc_32_tab[184]= 0xc5ba3bbeL;
3819   crc_32_tab[185]= 0xb2bd0b28L;
3820   crc_32_tab[186]= 0x2bb45a92L;
3821   crc_32_tab[187]= 0x5cb36a04L;
3822   crc_32_tab[188]= 0xc2d7ffa7L;
3823   crc_32_tab[189]= 0xb5d0cf31L;
3824   crc_32_tab[190]= 0x2cd99e8bL;
3825   crc_32_tab[191]= 0x5bdeae1dL;
3826   crc_32_tab[192]= 0x9b64c2b0L;
3827   crc_32_tab[193]= 0xec63f226L;
3828   crc_32_tab[194]= 0x756aa39cL;
3829   crc_32_tab[195]= 0x026d930aL;
3830   crc_32_tab[196]= 0x9c0906a9L;
3831   crc_32_tab[197]= 0xeb0e363fL;
3832   crc_32_tab[198]= 0x72076785L;
3833   crc_32_tab[199]= 0x05005713L;
3834   crc_32_tab[200]= 0x95bf4a82L;
3835   crc_32_tab[201]= 0xe2b87a14L;
3836   crc_32_tab[202]= 0x7bb12baeL;
3837   crc_32_tab[203]= 0x0cb61b38L;
3838   crc_32_tab[204]= 0x92d28e9bL;
3839   crc_32_tab[205]= 0xe5d5be0dL;
3840   crc_32_tab[206]= 0x7cdcefb7L;
3841   crc_32_tab[207]= 0x0bdbdf21L;
3842   crc_32_tab[208]= 0x86d3d2d4L;
3843   crc_32_tab[209]= 0xf1d4e242L;
3844   crc_32_tab[210]= 0x68ddb3f8L;
3845   crc_32_tab[211]= 0x1fda836eL;
3846   crc_32_tab[212]= 0x81be16cdL;
3847   crc_32_tab[213]= 0xf6b9265bL;
3848   crc_32_tab[214]= 0x6fb077e1L;
3849   crc_32_tab[215]= 0x18b74777L;
3850   crc_32_tab[216]= 0x88085ae6L;
3851   crc_32_tab[217]= 0xff0f6a70L;
3852   crc_32_tab[218]= 0x66063bcaL;
3853   crc_32_tab[219]= 0x11010b5cL;
3854   crc_32_tab[220]= 0x8f659effL;
3855   crc_32_tab[221]= 0xf862ae69L;
3856   crc_32_tab[222]= 0x616bffd3L;
3857   crc_32_tab[223]= 0x166ccf45L;
3858   crc_32_tab[224]= 0xa00ae278L;
3859   crc_32_tab[225]= 0xd70dd2eeL;
3860   crc_32_tab[226]= 0x4e048354L;
3861   crc_32_tab[227]= 0x3903b3c2L;
3862   crc_32_tab[228]= 0xa7672661L;
3863   crc_32_tab[229]= 0xd06016f7L;
3864   crc_32_tab[230]= 0x4969474dL;
3865   crc_32_tab[231]= 0x3e6e77dbL;
3866   crc_32_tab[232]= 0xaed16a4aL;
3867   crc_32_tab[233]= 0xd9d65adcL;
3868   crc_32_tab[234]= 0x40df0b66L;
3869   crc_32_tab[235]= 0x37d83bf0L;
3870   crc_32_tab[236]= 0xa9bcae53L;
3871   crc_32_tab[237]= 0xdebb9ec5L;
3872   crc_32_tab[238]= 0x47b2cf7fL;
3873   crc_32_tab[239]= 0x30b5ffe9L;
3874   crc_32_tab[240]= 0xbdbdf21cL;
3875   crc_32_tab[241]= 0xcabac28aL;
3876   crc_32_tab[242]= 0x53b39330L;
3877   crc_32_tab[243]= 0x24b4a3a6L;
3878   crc_32_tab[244]= 0xbad03605L;
3879   crc_32_tab[245]= 0xcdd70693L;
3880   crc_32_tab[246]= 0x54de5729L;
3881   crc_32_tab[247]= 0x23d967bfL;
3882   crc_32_tab[248]= 0xb3667a2eL;
3883   crc_32_tab[249]= 0xc4614ab8L;
3884   crc_32_tab[250]= 0x5d681b02L;
3885   crc_32_tab[251]= 0x2a6f2b94L;
3886   crc_32_tab[252]= 0xb40bbe37L;
3887   crc_32_tab[253]= 0xc30c8ea1L;
3888   crc_32_tab[254]= 0x5a05df1bL;
3889   crc_32_tab[255]= 0x2d02ef8dL;
3890   return;
3891 }
3892 #endif  /* SUPPORT_GZIP */
3893 
3894 /******************************************************************************
3895 * Miscellaneous...most of this could be reimplemented as global constants if
3896 * that were a "safe" thing to do considering that the routines in this file
3897 * are part of a shareable library.
3898 ******************************************************************************/
3899 
3900 #if 0
3901 config configuration_table[10] = {
3902 /* good lazy nice chain */
3903   {0,    0,  0,    0},  /* 0 */   /* store only */
3904   {4,    4,  8,    4},  /* 1 */   /* maximum speed, no lazy matches */
3905   {4,    5, 16,    8},  /* 2 */
3906   {4,    6, 32,   32},  /* 3 */
3907   {4,    4, 16,   16},  /* 4 */   /* lazy matches */
3908   {8,   16, 32,   32},  /* 5 */
3909   {8,   16, 128, 128},  /* 6 */
3910   {8,   32, 128, 256},  /* 7 */
3911   {32, 128, 258, 1024}, /* 8 */
3912   {32, 258, 258, 4096}  /* 9 */   /* maximum compression */
3913 };
3914 uch bl_order[BL_CODES] = {
3915   16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15
3916 };
3917 /* Tables for deflate from PKZIP's appnote.txt. */
3918 unsigned border[] = {    /* Order of the bit length code lengths */
3919 	16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15};
3920 ush cplens[] = {         /* Copy lengths for literal codes 257..285 */
3921 	3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,
3922 	35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0};
3923 	/* note: see note #13 above about the 258 in this list. */
3924 ush cplext[] = {         /* Extra bits for literal codes 257..285 */
3925 	0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2,
3926 	3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0, 99, 99}; /* 99==invalid */
3927 ush cpdist[] = {         /* Copy offsets for distance codes 0..29 */
3928 	1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,
3929 	257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,
3930 	8193, 12289, 16385, 24577};
3931 ush cpdext[] = {         /* Extra bits for distance codes */
3932 	0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6,
3933 	7, 7, 8, 8, 9, 9, 10, 10, 11, 11,
3934 	12, 12, 13, 13};
3935 ush mask_bits[] = {
3936     0x0000,
3937     0x0001, 0x0003, 0x0007, 0x000f, 0x001f, 0x003f, 0x007f, 0x00ff,
3938     0x01ff, 0x03ff, 0x07ff, 0x0fff, 0x1fff, 0x3fff, 0x7fff, 0xffff
3939 };
3940 int extra_lbits[LENGTH_CODES] /* extra bits for each length code */
3941    = {0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0};
3942 ct_data dyn_ltree[HEAP_SIZE];
3943 			/* literal and length tree */
3944 ct_data static_ltree[L_CODES+2];
3945 /* The static literal tree. Since the bit lengths are imposed, there is no
3946  * need for the L_CODES extra codes used during heap construction. However
3947  * The codes 286 and 287 are needed to build a canonical tree (see ct_init
3948  * below).
3949  */
3950 tree_desc l_desc = {
3951   dyn_ltree, static_ltree, extra_lbits, LITERALS+1, L_CODES, MAX_BITS, 0
3952 };
3953 int extra_dbits[D_CODES] /* extra bits for each distance code */
3954    = {0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13};
3955 ct_data dyn_dtree[2*D_CODES+1];
3956 			/* distance tree */
3957 ct_data static_dtree[D_CODES];
3958 /* The static distance tree. (Actually a trivial tree since all codes use
3959  * 5 bits.)
3960  */
3961 tree_desc d_desc = {
3962   dyn_dtree, static_dtree, extra_dbits, 0, D_CODES, MAX_BITS, 0
3963 };
3964 int extra_blbits[BL_CODES]/* extra bits for each bit length code */
3965    = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7};
3966 ct_data bl_tree[2*BL_CODES+1];
3967 /* Huffman tree for the bit lengths */
3968 tree_desc bl_desc = {
3969   bl_tree, (ct_data *) NULL, extra_blbits, 0, BL_CODES, MAX_BL_BITS, 0
3970 };
3971 /* ========================================================================
3972  * Table of CRC-32's of all single-byte values (made by makecrc.c)
3973  */
3974 ulg crc_32_tab[] = {
3975   0x00000000L, 0x77073096L, 0xee0e612cL, 0x990951baL, 0x076dc419L,
3976   0x706af48fL, 0xe963a535L, 0x9e6495a3L, 0x0edb8832L, 0x79dcb8a4L,
3977   0xe0d5e91eL, 0x97d2d988L, 0x09b64c2bL, 0x7eb17cbdL, 0xe7b82d07L,
3978   0x90bf1d91L, 0x1db71064L, 0x6ab020f2L, 0xf3b97148L, 0x84be41deL,
3979   0x1adad47dL, 0x6ddde4ebL, 0xf4d4b551L, 0x83d385c7L, 0x136c9856L,
3980   0x646ba8c0L, 0xfd62f97aL, 0x8a65c9ecL, 0x14015c4fL, 0x63066cd9L,
3981   0xfa0f3d63L, 0x8d080df5L, 0x3b6e20c8L, 0x4c69105eL, 0xd56041e4L,
3982   0xa2677172L, 0x3c03e4d1L, 0x4b04d447L, 0xd20d85fdL, 0xa50ab56bL,
3983   0x35b5a8faL, 0x42b2986cL, 0xdbbbc9d6L, 0xacbcf940L, 0x32d86ce3L,
3984   0x45df5c75L, 0xdcd60dcfL, 0xabd13d59L, 0x26d930acL, 0x51de003aL,
3985   0xc8d75180L, 0xbfd06116L, 0x21b4f4b5L, 0x56b3c423L, 0xcfba9599L,
3986   0xb8bda50fL, 0x2802b89eL, 0x5f058808L, 0xc60cd9b2L, 0xb10be924L,
3987   0x2f6f7c87L, 0x58684c11L, 0xc1611dabL, 0xb6662d3dL, 0x76dc4190L,
3988   0x01db7106L, 0x98d220bcL, 0xefd5102aL, 0x71b18589L, 0x06b6b51fL,
3989   0x9fbfe4a5L, 0xe8b8d433L, 0x7807c9a2L, 0x0f00f934L, 0x9609a88eL,
3990   0xe10e9818L, 0x7f6a0dbbL, 0x086d3d2dL, 0x91646c97L, 0xe6635c01L,
3991   0x6b6b51f4L, 0x1c6c6162L, 0x856530d8L, 0xf262004eL, 0x6c0695edL,
3992   0x1b01a57bL, 0x8208f4c1L, 0xf50fc457L, 0x65b0d9c6L, 0x12b7e950L,
3993   0x8bbeb8eaL, 0xfcb9887cL, 0x62dd1ddfL, 0x15da2d49L, 0x8cd37cf3L,
3994   0xfbd44c65L, 0x4db26158L, 0x3ab551ceL, 0xa3bc0074L, 0xd4bb30e2L,
3995   0x4adfa541L, 0x3dd895d7L, 0xa4d1c46dL, 0xd3d6f4fbL, 0x4369e96aL,
3996   0x346ed9fcL, 0xad678846L, 0xda60b8d0L, 0x44042d73L, 0x33031de5L,
3997   0xaa0a4c5fL, 0xdd0d7cc9L, 0x5005713cL, 0x270241aaL, 0xbe0b1010L,
3998   0xc90c2086L, 0x5768b525L, 0x206f85b3L, 0xb966d409L, 0xce61e49fL,
3999   0x5edef90eL, 0x29d9c998L, 0xb0d09822L, 0xc7d7a8b4L, 0x59b33d17L,
4000   0x2eb40d81L, 0xb7bd5c3bL, 0xc0ba6cadL, 0xedb88320L, 0x9abfb3b6L,
4001   0x03b6e20cL, 0x74b1d29aL, 0xead54739L, 0x9dd277afL, 0x04db2615L,
4002   0x73dc1683L, 0xe3630b12L, 0x94643b84L, 0x0d6d6a3eL, 0x7a6a5aa8L,
4003   0xe40ecf0bL, 0x9309ff9dL, 0x0a00ae27L, 0x7d079eb1L, 0xf00f9344L,
4004   0x8708a3d2L, 0x1e01f268L, 0x6906c2feL, 0xf762575dL, 0x806567cbL,
4005   0x196c3671L, 0x6e6b06e7L, 0xfed41b76L, 0x89d32be0L, 0x10da7a5aL,
4006   0x67dd4accL, 0xf9b9df6fL, 0x8ebeeff9L, 0x17b7be43L, 0x60b08ed5L,
4007   0xd6d6a3e8L, 0xa1d1937eL, 0x38d8c2c4L, 0x4fdff252L, 0xd1bb67f1L,
4008   0xa6bc5767L, 0x3fb506ddL, 0x48b2364bL, 0xd80d2bdaL, 0xaf0a1b4cL,
4009   0x36034af6L, 0x41047a60L, 0xdf60efc3L, 0xa867df55L, 0x316e8eefL,
4010   0x4669be79L, 0xcb61b38cL, 0xbc66831aL, 0x256fd2a0L, 0x5268e236L,
4011   0xcc0c7795L, 0xbb0b4703L, 0x220216b9L, 0x5505262fL, 0xc5ba3bbeL,
4012   0xb2bd0b28L, 0x2bb45a92L, 0x5cb36a04L, 0xc2d7ffa7L, 0xb5d0cf31L,
4013   0x2cd99e8bL, 0x5bdeae1dL, 0x9b64c2b0L, 0xec63f226L, 0x756aa39cL,
4014   0x026d930aL, 0x9c0906a9L, 0xeb0e363fL, 0x72076785L, 0x05005713L,
4015   0x95bf4a82L, 0xe2b87a14L, 0x7bb12baeL, 0x0cb61b38L, 0x92d28e9bL,
4016   0xe5d5be0dL, 0x7cdcefb7L, 0x0bdbdf21L, 0x86d3d2d4L, 0xf1d4e242L,
4017   0x68ddb3f8L, 0x1fda836eL, 0x81be16cdL, 0xf6b9265bL, 0x6fb077e1L,
4018   0x18b74777L, 0x88085ae6L, 0xff0f6a70L, 0x66063bcaL, 0x11010b5cL,
4019   0x8f659effL, 0xf862ae69L, 0x616bffd3L, 0x166ccf45L, 0xa00ae278L,
4020   0xd70dd2eeL, 0x4e048354L, 0x3903b3c2L, 0xa7672661L, 0xd06016f7L,
4021   0x4969474dL, 0x3e6e77dbL, 0xaed16a4aL, 0xd9d65adcL, 0x40df0b66L,
4022   0x37d83bf0L, 0xa9bcae53L, 0xdebb9ec5L, 0x47b2cf7fL, 0x30b5ffe9L,
4023   0xbdbdf21cL, 0xcabac28aL, 0x53b39330L, 0x24b4a3a6L, 0xbad03605L,
4024   0xcdd70693L, 0x54de5729L, 0x23d967bfL, 0xb3667a2eL, 0xc4614ab8L,
4025   0x5d681b02L, 0x2a6f2b94L, 0xb40bbe37L, 0xc30c8ea1L, 0x5a05df1bL,
4026   0x2d02ef8dL
4027 };
4028 #endif
4029