1 /*@ S-nail - a mail user agent derived from Berkeley Mail.
2 *@ LZW file compression.
4 * Copyright (c) 2000-2004 Gunnar Ritter, Freiburg i. Br., Germany.
5 * Copyright (c) 2012 - 2017 Steffen (Daode) Nurpmeso <sdaoden@users.sf.net>.
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) */
48 * lzw.c - File compression ala IEEE Computer, June 1984.
51 * Spencer W. Thomas (decvax!utah-cs!thomas)
52 * Jim McKie (decvax!mcvax!jim)
53 * Steve Davies (decvax!vax135!petsd!peora!srd)
54 * Ken Turkowski (decvax!decwrl!turtlevax!ken)
55 * James A. Woods (decvax!ihnp4!ames!jaw)
56 * Joe Orost (decvax!vax135!petsd!joe)
58 * Cleaned up and converted to library returning I/O streams by
59 * Diomidis Spinellis <dds@doc.ic.ac.uk>.
61 * Adopted for Heirloom mailx by Gunnar Ritter.
64 #define n_FILE obs_lzw
66 #ifndef HAVE_AMALGAMATION
72 /* Minimize differences to FreeBSDs usr.bin/compress/zopen.c */
74 #define u_int unsigned int
76 #define u_short unsigned short
78 #define u_char unsigned char
81 #define BITS 16 /* Default bits. */
82 #define HSIZE 69001 /* 95% occupancy */
84 /* A code_int must be able to hold 2**BITS values of type int, and also -1. */
85 typedef long code_int
;
86 typedef long count_int
;
88 typedef u_char char_type
;
89 static char_type magic_header
[] = {0x1F, 0x9D}; /* \037, \235 */
91 #define BIT_MASK 0x1f /* Defines for third byte of header. */
92 #define BLOCK_MASK 0x80
95 * Masks 0x40 and 0x20 are free. I think 0x20 should mean that there is
96 * a fourth header byte (for expansion).
98 #define INIT_BITS 9 /* Initial number of bits/code. */
100 #define MAXCODE(n_bits) ((1 << (n_bits)) - 1)
103 FILE *zs_fp
; /* File stream for I/O */
104 char zs_mode
; /* r or w */
106 S_START
, S_MIDDLE
, S_EOF
107 } zs_state
; /* State of computation */
108 u_int zs_n_bits
; /* Number of bits/code. */
109 u_int zs_maxbits
; /* User settable max # bits/code. */
110 code_int zs_maxcode
; /* Maximum code, given n_bits. */
111 code_int zs_maxmaxcode
; /* Should NEVER generate this code. */
112 count_int zs_htab
[HSIZE
];
113 u_short zs_codetab
[HSIZE
];
114 code_int zs_hsize
; /* For dynamic table sizing. */
115 code_int zs_free_ent
; /* First unused entry. */
117 * Block compression parameters -- after all codes are used up,
118 * and compression rate changes, start over.
120 int zs_block_compress
;
123 count_int zs_checkpoint
;
125 long zs_in_count
; /* Length of input. */
126 long zs_bytes_out
; /* Length of compressed output. */
127 long zs_out_count
; /* # of codes output (for debugging). */
128 char_type zs_buf
[BITS
];
133 code_int zs_hsize_reg
;
135 } w
; /* Write parameters */
137 char_type
*zs_stackp
;
139 code_int zs_code
, zs_oldcode
, zs_incode
;
140 int zs_roffset
, zs_size
;
141 char_type zs_gbuf
[BITS
];
142 } r
; /* Read parameters */
146 /* Definitions to retain old variable names */
148 #define zmode zs->zs_mode
149 #define state zs->zs_state
150 #define n_bits zs->zs_n_bits
151 #define maxbits zs->zs_maxbits
152 #define maxcode zs->zs_maxcode
153 #define maxmaxcode zs->zs_maxmaxcode
154 #define htab zs->zs_htab
155 #define codetab zs->zs_codetab
156 #define hsize zs->zs_hsize
157 #define free_ent zs->zs_free_ent
158 #define block_compress zs->zs_block_compress
159 #define clear_flg zs->zs_clear_flg
160 #define ratio zs->zs_ratio
161 #define checkpoint zs->zs_checkpoint
162 #define offset zs->zs_offset
163 #define in_count zs->zs_in_count
164 #define bytes_out zs->zs_bytes_out
165 #define out_count zs->zs_out_count
166 #define buf zs->zs_buf
167 #define fcode zs->u.w.zs_fcode
168 #define hsize_reg zs->u.w.zs_hsize_reg
169 #define ent zs->u.w.zs_ent
170 #define hshift zs->u.w.zs_hshift
171 #define stackp zs->u.r.zs_stackp
172 #define finchar zs->u.r.zs_finchar
173 #define code zs->u.r.zs_code
174 #define oldcode zs->u.r.zs_oldcode
175 #define incode zs->u.r.zs_incode
176 #define roffset zs->u.r.zs_roffset
177 #define size zs->u.r.zs_size
178 #define gbuf zs->u.r.zs_gbuf
181 * To save much memory, we overlay the table used by compress() with those
182 * used by decompress(). The tab_prefix table is the same size and type as
183 * the codetab. The tab_suffix table needs 2**BITS characters. We get this
184 * from the beginning of htab. The output stack uses the rest of htab, and
185 * contains characters. There is plenty of room for any possible stack
186 * (stack used to be 8000 characters).
189 #define htabof(i) htab[i]
190 #define codetabof(i) codetab[i]
192 #define tab_prefixof(i) codetabof(i)
193 #define tab_suffixof(i) ((char_type *)(htab))[i]
194 #define de_stack ((char_type *)&tab_suffixof(1 << BITS))
196 #define CHECK_GAP 10000 /* Ratio check interval. */
199 * the next two codes should not be changed lightly, as they must not
200 * lie within the contiguous general code space.
202 #define FIRST 257 /* First free entry. */
203 #define CLEAR 256 /* Table clear output code. */
205 static int cl_block(struct s_zstate
*);
206 static void cl_hash(struct s_zstate
*, count_int
);
207 static code_int
getcode(struct s_zstate
*);
208 static int output(struct s_zstate
*, code_int
);
211 * Algorithm from "A Technique for High Performance Data Compression",
212 * Terry A. Welch, IEEE Computer Vol 17, No 6 (June 1984), pp 8-19.
215 * Modified Lempel-Ziv method (LZW). Basically finds common
216 * substrings and replaces them with a variable size code. This is
217 * deterministic, and can be done on the fly. Thus, the decompression
218 * procedure needs no input table, but tracks the way the table was built.
224 * Algorithm: use open addressing double hashing (no chaining) on the
225 * prefix code / next character combination. We do a variant of Knuth's
226 * algorithm D (vol. 3, sec. 6.4) along with G. Knott's relatively-prime
227 * secondary probe. Here, the modular division first probe is gives way
228 * to a faster exclusive-or manipulation. Also do block compression with
229 * an adaptive reset, whereby the code table is cleared when the compression
230 * ratio decreases, but after the table fills. The variable-length output
231 * codes are re-sized at this point, and a special CLEAR code is generated
232 * for the decompressor. Late addition: construct the table according to
233 * file size for noticeable speed improvement on small files. Please direct
234 * questions about this implementation to ames!jaw.
237 zwrite(void *cookie
, const char *wbp
, int num
)
252 bp
= (const u_char
*)wbp
;
253 if (state
== S_MIDDLE
)
257 maxmaxcode
= 1L << maxbits
;
258 if (fwrite(magic_header
,
259 sizeof(char), sizeof(magic_header
), fp
) != sizeof(magic_header
))
261 tmp
= (u_char
)((maxbits
) | block_compress
);
262 if (fwrite(&tmp
, sizeof(char), sizeof(tmp
), fp
) != sizeof(tmp
))
266 bytes_out
= 3; /* Includes 3-byte header mojo. */
271 checkpoint
= CHECK_GAP
;
272 maxcode
= MAXCODE(n_bits
= INIT_BITS
);
273 free_ent
= ((block_compress
) ? FIRST
: 256);
279 for (fcode
= (long)hsize
; fcode
< 65536L; fcode
*= 2L)
281 hshift
= 8 - hshift
; /* Set hash code range bound. */
284 cl_hash(zs
, (count_int
)hsize_reg
); /* Clear hash table. */
286 middle
: for (i
= 0; count
--;) {
289 fcode
= (long)(((long)c
<< maxbits
) + ent
);
290 i
= ((c
<< hshift
) ^ ent
); /* Xor hashing. */
292 if (htabof(i
) == fcode
) {
295 } else if ((long)htabof(i
) < 0) /* Empty slot. */
297 disp
= hsize_reg
- i
; /* Secondary hash (after G. Knott). */
300 probe
: if ((i
-= disp
) < 0)
303 if (htabof(i
) == fcode
) {
307 if ((long)htabof(i
) >= 0)
309 nomatch
: if (output(zs
, (code_int
) ent
) == -1)
313 if (free_ent
< maxmaxcode
) {
314 codetabof(i
) = free_ent
++; /* code -> hashtable */
316 } else if ((count_int
)in_count
>=
317 checkpoint
&& block_compress
) {
318 if (cl_block(zs
) == -1)
331 if (zmode
== 'w') { /* Put out the final code. */
332 if (output(zs
, (code_int
) ent
) == -1) {
337 if (output(zs
, (code_int
) - 1) == -1) {
347 * Output the given code.
349 * code: A n_bits-bit integer. If == -1, then EOF. This assumes
350 * that n_bits =< (long)wordsize - 1.
352 * Outputs code to the file.
354 * Chars are 8 bits long.
356 * Maintain a BITS character long buffer (so that 8 codes will
357 * fit in it exactly). Use the VAX insv instruction to insert each
358 * code in turn. When the buffer fills up empty it and start over.
361 static char_type lmask
[9] =
362 {0xff, 0xfe, 0xfc, 0xf8, 0xf0, 0xe0, 0xc0, 0x80, 0x00};
363 static char_type rmask
[9] =
364 {0x00, 0x01, 0x03, 0x07, 0x0f, 0x1f, 0x3f, 0x7f, 0xff};
367 output(struct s_zstate
*zs
, code_int ocode
)
377 /* Get to the first byte. */
381 * Since ocode is always >= 8 bits, only need to mask the first
384 *bp
= (*bp
& rmask
[r_off
]) | ((ocode
<< r_off
) & lmask
[r_off
]);
388 /* Get any 8 bit parts in the middle (<=1 for up to 16 bits). */
398 if (offset
== (n_bits
<< 3)) {
402 if (fwrite(bp
, sizeof(char), bits
, fp
) != bits
)
409 * If the next entry is going to be too big for the ocode size,
410 * then increase it, if possible.
412 if (free_ent
> maxcode
|| (clear_flg
> 0)) {
414 * Write the whole buffer, because the input side won't
415 * discover the size increase until after it has read it.
418 if (fwrite(buf
, 1, n_bits
, fp
) != n_bits
)
425 maxcode
= MAXCODE(n_bits
= INIT_BITS
);
429 if (n_bits
== maxbits
)
430 maxcode
= maxmaxcode
;
432 maxcode
= MAXCODE(n_bits
);
436 /* At EOF, write the rest of the buffer. */
438 offset
= (offset
+ 7) / 8;
439 if (fwrite(buf
, 1, offset
, fp
) != offset
)
449 * Decompress read. This routine adapts to the codes in the file building
450 * the "string" table on-the-fly; requiring no table to be stored in the
451 * compressed file. The tables used herein are shared with those of the
452 * compress() routine. See the definitions above.
455 zread(void *cookie
, char *rbp
, int num
)
459 u_char
*bp
, header
[3];
477 /* Check the magic number */
479 sizeof(char), sizeof(header
), fp
) != sizeof(header
) ||
480 memcmp(header
, magic_header
, sizeof(magic_header
)) != 0) {
483 maxbits
= header
[2]; /* Set -b from file. */
484 block_compress
= maxbits
& BLOCK_MASK
;
486 maxmaxcode
= 1L << maxbits
;
487 if (maxbits
> BITS
|| maxbits
< 12) {
490 /* As above, initialize the first 256 entries in the table. */
491 maxcode
= MAXCODE(n_bits
= INIT_BITS
);
492 for (code
= 255; code
>= 0; code
--) {
493 tab_prefixof(code
) = 0;
494 tab_suffixof(code
) = (char_type
) code
;
496 free_ent
= block_compress
? FIRST
: 256;
498 finchar
= oldcode
= getcode(zs
);
499 if (oldcode
== -1) /* EOF already? */
500 return (0); /* Get out of here */
502 /* First code must be 8 bits = char. */
503 *bp
++ = (u_char
)finchar
;
507 while ((code
= getcode(zs
)) > -1) {
509 if ((code
== CLEAR
) && block_compress
) {
510 for (code
= 255; code
>= 0; code
--)
511 tab_prefixof(code
) = 0;
519 /* Special case for kWkWk string. */
520 if (code
>= free_ent
) {
521 if (code
> free_ent
|| oldcode
== -1) {
528 * The above condition ensures that code < free_ent.
529 * The construction of tab_prefixof in turn guarantees that
530 * each iteration decreases code and therefore stack usage is
531 * bound by 1 << BITS - 256.
534 /* Generate output characters in reverse order. */
535 while (code
>= 256) {
536 *stackp
++ = tab_suffixof(code
);
537 code
= tab_prefixof(code
);
539 *stackp
++ = finchar
= tab_suffixof(code
);
541 /* And put them out in forward order. */
546 } while (stackp
> de_stack
);
548 /* Generate the new entry. */
549 if ((code
= free_ent
) < maxmaxcode
&& oldcode
!= -1) {
550 tab_prefixof(code
) = (u_short
) oldcode
;
551 tab_suffixof(code
) = finchar
;
555 /* Remember previous code. */
559 eof
: return (num
- count
);
563 * Read one code from the standard input. If EOF, return -1.
567 * code or -1 is returned.
570 getcode(struct s_zstate
*zs
)
577 if (clear_flg
> 0 || roffset
>= size
|| free_ent
> maxcode
) {
579 * If the next entry will be too big for the current gcode
580 * size, then we must increase the size. This implies reading
581 * a new buffer full, too.
583 if (free_ent
> maxcode
) {
585 if (n_bits
== maxbits
) /* Won't get any bigger now. */
586 maxcode
= maxmaxcode
;
588 maxcode
= MAXCODE(n_bits
);
591 maxcode
= MAXCODE(n_bits
= INIT_BITS
);
594 size
= fread(gbuf
, 1, n_bits
, fp
);
595 if (size
<= 0) /* End of file. */
598 /* Round size down to integral number of codes. */
599 size
= (size
<< 3) - (n_bits
- 1);
604 /* Get to the first byte. */
608 /* Get first part (low order bits). */
609 gcode
= (*bp
++ >> r_off
);
611 r_off
= 8 - r_off
; /* Now, roffset into gcode word. */
613 /* Get any 8 bit parts in the middle (<=1 for up to 16 bits). */
615 gcode
|= *bp
++ << r_off
;
620 /* High order bits. */
621 gcode
|= (*bp
& rmask
[bits
]) << r_off
;
628 cl_block(struct s_zstate
*zs
) /* Table clear for block compress. */
632 checkpoint
= in_count
+ CHECK_GAP
;
634 if (in_count
> 0x007fffff) { /* Shift will overflow. */
635 rat
= bytes_out
>> 8;
636 if (rat
== 0) /* Don't divide by zero. */
639 rat
= in_count
/ rat
;
641 rat
= (in_count
<< 8) / bytes_out
; /* 8 fractional bits. */
646 cl_hash(zs
, (count_int
) hsize
);
649 if (output(zs
, (code_int
) CLEAR
) == -1)
656 cl_hash(struct s_zstate
*zs
, count_int cl_hsize
) /* Reset code table. */
662 htab_p
= htab
+ cl_hsize
;
664 do { /* Might use Sys V memset(3) here. */
682 } while ((i
-= 16) >= 0);
683 for (i
+= 16; i
> 0; i
--)
694 zs
= scalloc(1, sizeof *zs
);
695 maxbits
= bits
? bits
: BITS
; /* User settable max # bits/code. */
696 maxmaxcode
= 1L << maxbits
; /* Should NEVER generate this code. */
697 hsize
= HSIZE
; /* For dynamic table sizing. */
698 free_ent
= 0; /* First unused entry. */
699 block_compress
= BLOCK_MASK
;
702 checkpoint
= CHECK_GAP
;
703 in_count
= 1; /* Length of input. */
704 out_count
= 0; /* # of codes output (for debugging). */
733 #undef block_compress
754 #endif /* ndef HAVE_IMAP */