2 * S-nail - a mail user agent derived from Berkeley Mail.
4 * Copyright (c) 2000-2004 Gunnar Ritter, Freiburg i. Br., Germany.
5 * Copyright (c) 2012 Steffen "Daode" Nurpmeso.
8 * Copyright (c) 1985, 1986, 1992, 1993
9 * The Regents of the University of California. All rights reserved.
11 * This code is derived from software contributed to Berkeley by
12 * Diomidis Spinellis and James A. Woods, derived from original
13 * work by Spencer Thomas and Joseph Orost.
15 * Redistribution and use in source and binary forms, with or without
16 * modification, are permitted provided that the following conditions
18 * 1. Redistributions of source code must retain the above copyright
19 * notice, this list of conditions and the following disclaimer.
20 * 2. Redistributions in binary form must reproduce the above copyright
21 * notice, this list of conditions and the following disclaimer in the
22 * documentation and/or other materials provided with the distribution.
23 * 4. Neither the name of the University nor the names of its contributors
24 * may be used to endorse or promote products derived from this software
25 * without specific prior written permission.
27 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
28 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
29 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
30 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
31 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
32 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
33 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
34 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
35 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
36 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
40 /* from zopen.c 8.1 (Berkeley) 6/27/93 */
41 /* from FreeBSD: /repoman/r/ncvs/src/usr.bin/compress/zopen.c,v
42 * 1.5.6.1 2002/07/16 00:52:08 tjr Exp */
43 /* from FreeBSD: git://git.freebsd.org/freebsd,
44 * master:usr.bin/compress/zopen.c,
45 * (Fix handling of corrupt compress(1)ed data. [11:04], 2011-09-28),
46 * 2902cb5e28a1e38bce859ef1ae14e9d22fe50214. */
49 * lzw.c - File compression ala IEEE Computer, June 1984.
52 * Spencer W. Thomas (decvax!utah-cs!thomas)
53 * Jim McKie (decvax!mcvax!jim)
54 * Steve Davies (decvax!vax135!petsd!peora!srd)
55 * Ken Turkowski (decvax!decwrl!turtlevax!ken)
56 * James A. Woods (decvax!ihnp4!ames!jaw)
57 * Joe Orost (decvax!vax135!petsd!joe)
59 * Cleaned up and converted to library returning I/O streams by
60 * Diomidis Spinellis <dds@doc.ic.ac.uk>.
62 * Adopted for Heirloom mailx by Gunnar Ritter.
67 #if ! defined USE_IMAP && ! defined USE_JUNK
68 typedef int avoid_empty_file_compiler_warning
;
76 /* Minimize differences to FreeBSDs usr.bin/compress/zopen.c */
78 #define u_int unsigned int
80 #define u_short unsigned short
82 #define u_char unsigned char
84 #define BITS 16 /* Default bits. */
85 #define HSIZE 69001 /* 95% occupancy */
87 /* A code_int must be able to hold 2**BITS values of type int, and also -1. */
88 typedef long code_int
;
89 typedef long count_int
;
91 typedef u_char char_type
;
92 static char_type magic_header
[] =
93 {'\037', '\235'}; /* 1F 9D */
95 #define BIT_MASK 0x1f /* Defines for third byte of header. */
96 #define BLOCK_MASK 0x80
99 * Masks 0x40 and 0x20 are free. I think 0x20 should mean that there is
100 * a fourth header byte (for expansion).
102 #define INIT_BITS 9 /* Initial number of bits/code. */
104 #define MAXCODE(n_bits) ((1 << (n_bits)) - 1)
107 FILE *zs_fp
; /* File stream for I/O */
108 char zs_mode
; /* r or w */
110 S_START
, S_MIDDLE
, S_EOF
111 } zs_state
; /* State of computation */
112 u_int zs_n_bits
; /* Number of bits/code. */
113 u_int zs_maxbits
; /* User settable max # bits/code. */
114 code_int zs_maxcode
; /* Maximum code, given n_bits. */
115 code_int zs_maxmaxcode
; /* Should NEVER generate this code. */
116 count_int zs_htab
[HSIZE
];
117 u_short zs_codetab
[HSIZE
];
118 code_int zs_hsize
; /* For dynamic table sizing. */
119 code_int zs_free_ent
; /* First unused entry. */
121 * Block compression parameters -- after all codes are used up,
122 * and compression rate changes, start over.
124 int zs_block_compress
;
127 count_int zs_checkpoint
;
129 long zs_in_count
; /* Length of input. */
130 long zs_bytes_out
; /* Length of compressed output. */
131 long zs_out_count
; /* # of codes output (for debugging). */
132 char_type zs_buf
[BITS
];
137 code_int zs_hsize_reg
;
139 } w
; /* Write parameters */
141 char_type
*zs_stackp
;
143 code_int zs_code
, zs_oldcode
, zs_incode
;
144 int zs_roffset
, zs_size
;
145 char_type zs_gbuf
[BITS
];
146 } r
; /* Read parameters */
150 /* Definitions to retain old variable names */
152 #define zmode zs->zs_mode
153 #define state zs->zs_state
154 #define n_bits zs->zs_n_bits
155 #define maxbits zs->zs_maxbits
156 #define maxcode zs->zs_maxcode
157 #define maxmaxcode zs->zs_maxmaxcode
158 #define htab zs->zs_htab
159 #define codetab zs->zs_codetab
160 #define hsize zs->zs_hsize
161 #define free_ent zs->zs_free_ent
162 #define block_compress zs->zs_block_compress
163 #define clear_flg zs->zs_clear_flg
164 #define ratio zs->zs_ratio
165 #define checkpoint zs->zs_checkpoint
166 #define offset zs->zs_offset
167 #define in_count zs->zs_in_count
168 #define bytes_out zs->zs_bytes_out
169 #define out_count zs->zs_out_count
170 #define buf zs->zs_buf
171 #define fcode zs->u.w.zs_fcode
172 #define hsize_reg zs->u.w.zs_hsize_reg
173 #define ent zs->u.w.zs_ent
174 #define hshift zs->u.w.zs_hshift
175 #define stackp zs->u.r.zs_stackp
176 #define finchar zs->u.r.zs_finchar
177 #define code zs->u.r.zs_code
178 #define oldcode zs->u.r.zs_oldcode
179 #define incode zs->u.r.zs_incode
180 #define roffset zs->u.r.zs_roffset
181 #define size zs->u.r.zs_size
182 #define gbuf zs->u.r.zs_gbuf
185 * To save much memory, we overlay the table used by compress() with those
186 * used by decompress(). The tab_prefix table is the same size and type as
187 * the codetab. The tab_suffix table needs 2**BITS characters. We get this
188 * from the beginning of htab. The output stack uses the rest of htab, and
189 * contains characters. There is plenty of room for any possible stack
190 * (stack used to be 8000 characters).
193 #define htabof(i) htab[i]
194 #define codetabof(i) codetab[i]
196 #define tab_prefixof(i) codetabof(i)
197 #define tab_suffixof(i) ((char_type *)(htab))[i]
198 #define de_stack ((char_type *)&tab_suffixof(1 << BITS))
200 #define CHECK_GAP 10000 /* Ratio check interval. */
203 * the next two codes should not be changed lightly, as they must not
204 * lie within the contiguous general code space.
206 #define FIRST 257 /* First free entry. */
207 #define CLEAR 256 /* Table clear output code. */
209 static int cl_block(struct s_zstate
*);
210 static void cl_hash(struct s_zstate
*, count_int
);
211 static code_int
getcode(struct s_zstate
*);
212 static int output(struct s_zstate
*, code_int
);
215 * Algorithm from "A Technique for High Performance Data Compression",
216 * Terry A. Welch, IEEE Computer Vol 17, No 6 (June 1984), pp 8-19.
219 * Modified Lempel-Ziv method (LZW). Basically finds common
220 * substrings and replaces them with a variable size code. This is
221 * deterministic, and can be done on the fly. Thus, the decompression
222 * procedure needs no input table, but tracks the way the table was built.
228 * Algorithm: use open addressing double hashing (no chaining) on the
229 * prefix code / next character combination. We do a variant of Knuth's
230 * algorithm D (vol. 3, sec. 6.4) along with G. Knott's relatively-prime
231 * secondary probe. Here, the modular division first probe is gives way
232 * to a faster exclusive-or manipulation. Also do block compression with
233 * an adaptive reset, whereby the code table is cleared when the compression
234 * ratio decreases, but after the table fills. The variable-length output
235 * codes are re-sized at this point, and a special CLEAR code is generated
236 * for the decompressor. Late addition: construct the table according to
237 * file size for noticeable speed improvement on small files. Please direct
238 * questions about this implementation to ames!jaw.
241 zwrite(void *cookie
, const char *wbp
, int num
)
256 bp
= (const u_char
*)wbp
;
257 if (state
== S_MIDDLE
)
261 maxmaxcode
= 1L << maxbits
;
262 if (fwrite(magic_header
,
263 sizeof(char), sizeof(magic_header
), fp
) != sizeof(magic_header
))
265 tmp
= (u_char
)((maxbits
) | block_compress
);
266 if (fwrite(&tmp
, sizeof(char), sizeof(tmp
), fp
) != sizeof(tmp
))
270 bytes_out
= 3; /* Includes 3-byte header mojo. */
275 checkpoint
= CHECK_GAP
;
276 maxcode
= MAXCODE(n_bits
= INIT_BITS
);
277 free_ent
= ((block_compress
) ? FIRST
: 256);
283 for (fcode
= (long)hsize
; fcode
< 65536L; fcode
*= 2L)
285 hshift
= 8 - hshift
; /* Set hash code range bound. */
288 cl_hash(zs
, (count_int
)hsize_reg
); /* Clear hash table. */
290 middle
: for (i
= 0; count
--;) {
293 fcode
= (long)(((long)c
<< maxbits
) + ent
);
294 i
= ((c
<< hshift
) ^ ent
); /* Xor hashing. */
296 if (htabof(i
) == fcode
) {
299 } else if ((long)htabof(i
) < 0) /* Empty slot. */
301 disp
= hsize_reg
- i
; /* Secondary hash (after G. Knott). */
304 probe
: if ((i
-= disp
) < 0)
307 if (htabof(i
) == fcode
) {
311 if ((long)htabof(i
) >= 0)
313 nomatch
: if (output(zs
, (code_int
) ent
) == -1)
317 if (free_ent
< maxmaxcode
) {
318 codetabof(i
) = free_ent
++; /* code -> hashtable */
320 } else if ((count_int
)in_count
>=
321 checkpoint
&& block_compress
) {
322 if (cl_block(zs
) == -1)
335 if (zmode
== 'w') { /* Put out the final code. */
336 if (output(zs
, (code_int
) ent
) == -1) {
341 if (output(zs
, (code_int
) - 1) == -1) {
351 * Output the given code.
353 * code: A n_bits-bit integer. If == -1, then EOF. This assumes
354 * that n_bits =< (long)wordsize - 1.
356 * Outputs code to the file.
358 * Chars are 8 bits long.
360 * Maintain a BITS character long buffer (so that 8 codes will
361 * fit in it exactly). Use the VAX insv instruction to insert each
362 * code in turn. When the buffer fills up empty it and start over.
365 static char_type lmask
[9] =
366 {0xff, 0xfe, 0xfc, 0xf8, 0xf0, 0xe0, 0xc0, 0x80, 0x00};
367 static char_type rmask
[9] =
368 {0x00, 0x01, 0x03, 0x07, 0x0f, 0x1f, 0x3f, 0x7f, 0xff};
371 output(struct s_zstate
*zs
, code_int ocode
)
381 /* Get to the first byte. */
385 * Since ocode is always >= 8 bits, only need to mask the first
388 *bp
= (*bp
& rmask
[r_off
]) | ((ocode
<< r_off
) & lmask
[r_off
]);
392 /* Get any 8 bit parts in the middle (<=1 for up to 16 bits). */
402 if (offset
== (n_bits
<< 3)) {
406 if (fwrite(bp
, sizeof(char), bits
, fp
) != bits
)
413 * If the next entry is going to be too big for the ocode size,
414 * then increase it, if possible.
416 if (free_ent
> maxcode
|| (clear_flg
> 0)) {
418 * Write the whole buffer, because the input side won't
419 * discover the size increase until after it has read it.
422 if (fwrite(buf
, 1, n_bits
, fp
) != n_bits
)
429 maxcode
= MAXCODE(n_bits
= INIT_BITS
);
433 if (n_bits
== maxbits
)
434 maxcode
= maxmaxcode
;
436 maxcode
= MAXCODE(n_bits
);
440 /* At EOF, write the rest of the buffer. */
442 offset
= (offset
+ 7) / 8;
443 if (fwrite(buf
, 1, offset
, fp
) != offset
)
453 * Decompress read. This routine adapts to the codes in the file building
454 * the "string" table on-the-fly; requiring no table to be stored in the
455 * compressed file. The tables used herein are shared with those of the
456 * compress() routine. See the definitions above.
459 zread(void *cookie
, char *rbp
, int num
)
463 u_char
*bp
, header
[3];
481 /* Check the magic number */
483 sizeof(char), sizeof(header
), fp
) != sizeof(header
) ||
484 memcmp(header
, magic_header
, sizeof(magic_header
)) != 0) {
487 maxbits
= header
[2]; /* Set -b from file. */
488 block_compress
= maxbits
& BLOCK_MASK
;
490 maxmaxcode
= 1L << maxbits
;
491 if (maxbits
> BITS
|| maxbits
< 12) {
494 /* As above, initialize the first 256 entries in the table. */
495 maxcode
= MAXCODE(n_bits
= INIT_BITS
);
496 for (code
= 255; code
>= 0; code
--) {
497 tab_prefixof(code
) = 0;
498 tab_suffixof(code
) = (char_type
) code
;
500 free_ent
= block_compress
? FIRST
: 256;
502 finchar
= oldcode
= getcode(zs
);
503 if (oldcode
== -1) /* EOF already? */
504 return (0); /* Get out of here */
506 /* First code must be 8 bits = char. */
507 *bp
++ = (u_char
)finchar
;
511 while ((code
= getcode(zs
)) > -1) {
513 if ((code
== CLEAR
) && block_compress
) {
514 for (code
= 255; code
>= 0; code
--)
515 tab_prefixof(code
) = 0;
523 /* Special case for kWkWk string. */
524 if (code
>= free_ent
) {
525 if (code
> free_ent
|| oldcode
== -1) {
532 * The above condition ensures that code < free_ent.
533 * The construction of tab_prefixof in turn guarantees that
534 * each iteration decreases code and therefore stack usage is
535 * bound by 1 << BITS - 256.
538 /* Generate output characters in reverse order. */
539 while (code
>= 256) {
540 *stackp
++ = tab_suffixof(code
);
541 code
= tab_prefixof(code
);
543 *stackp
++ = finchar
= tab_suffixof(code
);
545 /* And put them out in forward order. */
550 } while (stackp
> de_stack
);
552 /* Generate the new entry. */
553 if ((code
= free_ent
) < maxmaxcode
&& oldcode
!= -1) {
554 tab_prefixof(code
) = (u_short
) oldcode
;
555 tab_suffixof(code
) = finchar
;
559 /* Remember previous code. */
563 eof
: return (num
- count
);
567 * Read one code from the standard input. If EOF, return -1.
571 * code or -1 is returned.
574 getcode(struct s_zstate
*zs
)
581 if (clear_flg
> 0 || roffset
>= size
|| free_ent
> maxcode
) {
583 * If the next entry will be too big for the current gcode
584 * size, then we must increase the size. This implies reading
585 * a new buffer full, too.
587 if (free_ent
> maxcode
) {
589 if (n_bits
== maxbits
) /* Won't get any bigger now. */
590 maxcode
= maxmaxcode
;
592 maxcode
= MAXCODE(n_bits
);
595 maxcode
= MAXCODE(n_bits
= INIT_BITS
);
598 size
= fread(gbuf
, 1, n_bits
, fp
);
599 if (size
<= 0) /* End of file. */
602 /* Round size down to integral number of codes. */
603 size
= (size
<< 3) - (n_bits
- 1);
608 /* Get to the first byte. */
612 /* Get first part (low order bits). */
613 gcode
= (*bp
++ >> r_off
);
615 r_off
= 8 - r_off
; /* Now, roffset into gcode word. */
617 /* Get any 8 bit parts in the middle (<=1 for up to 16 bits). */
619 gcode
|= *bp
++ << r_off
;
624 /* High order bits. */
625 gcode
|= (*bp
& rmask
[bits
]) << r_off
;
632 cl_block(struct s_zstate
*zs
) /* Table clear for block compress. */
636 checkpoint
= in_count
+ CHECK_GAP
;
638 if (in_count
> 0x007fffff) { /* Shift will overflow. */
639 rat
= bytes_out
>> 8;
640 if (rat
== 0) /* Don't divide by zero. */
643 rat
= in_count
/ rat
;
645 rat
= (in_count
<< 8) / bytes_out
; /* 8 fractional bits. */
650 cl_hash(zs
, (count_int
) hsize
);
653 if (output(zs
, (code_int
) CLEAR
) == -1)
660 cl_hash(struct s_zstate
*zs
, count_int cl_hsize
) /* Reset code table. */
666 htab_p
= htab
+ cl_hsize
;
668 do { /* Might use Sys V memset(3) here. */
686 } while ((i
-= 16) >= 0);
687 for (i
+= 16; i
> 0; i
--)
698 zs
= scalloc(1, sizeof *zs
);
699 maxbits
= bits
? bits
: BITS
; /* User settable max # bits/code. */
700 maxmaxcode
= 1L << maxbits
; /* Should NEVER generate this code. */
701 hsize
= HSIZE
; /* For dynamic table sizing. */
702 free_ent
= 0; /* First unused entry. */
703 block_compress
= BLOCK_MASK
;
706 checkpoint
= CHECK_GAP
;
707 in_count
= 1; /* Length of input. */
708 out_count
= 0; /* # of codes output (for debugging). */
715 #endif /* ! defined USE_IMAP && ! defined USE_JUNK */