1 /* Because this code is derived from the 4.3BSD compress source:
4 * Copyright (c) 1985, 1986 The Regents of the University of California.
7 * This code is derived from software contributed to Berkeley by
8 * James A. Woods, derived from original work by Spencer Thomas
11 * Redistribution and use in source and binary forms, with or without
12 * modification, are permitted provided that the following conditions
14 * 1. Redistributions of source code must retain the above copyright
15 * notice, this list of conditions and the following disclaimer.
16 * 2. Redistributions in binary form must reproduce the above copyright
17 * notice, this list of conditions and the following disclaimer in the
18 * documentation and/or other materials provided with the distribution.
19 * 3. All advertising materials mentioning features or use of this software
20 * must display the following acknowledgement:
21 * This product includes software developed by the University of
22 * California, Berkeley and its contributors.
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
41 * $Id: bsd-comp.c,v 1.4 2004/01/17 05:47:55 carlsonj Exp $
44 #include <sys/types.h>
55 * PPP "BSD compress" compression
56 * The differences between this compression and the classic BSD LZW
57 * source are obvious from the requirement that the classic code worked
58 * with files while this handles arbitrarily long streams that
59 * are broken into packets. They are:
61 * When the code size expands, a block of junk is not emitted by
62 * the compressor and not expected by the decompressor.
64 * New codes are not necessarily assigned every time an old
65 * code is output by the compressor. This is because a packet
66 * end forces a code to be emitted, but does not imply that a
67 * new sequence has been seen.
69 * The compression ratio is checked at the first end of a packet
70 * after the appropriate gap. Besides simplifying and speeding
71 * things up, this makes it more likely that the transmitter
72 * and receiver will agree when the dictionary is cleared when
73 * compression is not going well.
77 * A dictionary for doing BSD compress.
80 int totlen; /* length of this structure */
81 u_int hsize; /* size of the hash table */
82 u_char hshift; /* used in hash function */
83 u_char n_bits; /* current bits/code */
87 u_short seqno; /* sequence number of next packet */
88 u_int hdrlen; /* header length to preallocate */
90 u_int maxmaxcode; /* largest valid code */
91 u_int max_ent; /* largest code in use */
92 u_int in_count; /* uncompressed bytes, aged */
93 u_int bytes_out; /* compressed bytes, aged */
94 u_int ratio; /* recent compression ratio */
95 u_int checkpoint; /* when to next check the ratio */
96 u_int clear_count; /* times dictionary cleared */
97 u_int incomp_count; /* incompressible packets */
98 u_int incomp_bytes; /* incompressible bytes */
99 u_int uncomp_count; /* uncompressed packets */
100 u_int uncomp_bytes; /* uncompressed bytes */
101 u_int comp_count; /* compressed packets */
102 u_int comp_bytes; /* compressed bytes */
103 u_short *lens; /* array of lengths of codes */
105 union { /* hash value */
108 #ifdef BSD_LITTLE_ENDIAN
109 u_short prefix; /* preceding code */
110 u_char suffix; /* last character of new code */
114 u_char suffix; /* last character of new code */
115 u_short prefix; /* preceding code */
119 u_short codem1; /* output of hash table -1 */
120 u_short cptr; /* map code to hash table entry */
124 #define BSD_OVHD 2 /* BSD compress overhead/packet */
125 #define BSD_INIT_BITS BSD_MIN_BITS
127 static void *bsd_decomp_alloc(u_char *options, int opt_len);
128 static void bsd_free(void *state);
129 static int bsd_decomp_init(void *state, u_char *options, int opt_len,
130 int unit, int hdrlen, int mru, int debug);
131 static void bsd_incomp(void *state, u_char *dmsg, int len);
132 static int bsd_decompress(void *state, u_char *cmp, int inlen,
133 u_char *dmp, int *outlen);
134 static void bsd_reset(void *state);
135 static void bsd_comp_stats(void *state, struct compstat *stats);
138 * Exported procedures.
140 struct compressor ppp_bsd_compress = {
141 CI_BSD_COMPRESS, /* compress_proto */
142 bsd_decomp_alloc, /* decomp_alloc */
143 bsd_free, /* decomp_free */
144 bsd_decomp_init, /* decomp_init */
145 bsd_reset, /* decomp_reset */
146 bsd_decompress, /* decompress */
147 bsd_incomp, /* incomp */
148 bsd_comp_stats, /* decomp_stat */
152 * the next two codes should not be changed lightly, as they must not
153 * lie within the contiguous general code space.
155 #define CLEAR 256 /* table clear output code */
156 #define FIRST 257 /* first free entry */
159 #define MAXCODE(b) ((1 << (b)) - 1)
160 #define BADCODEM1 MAXCODE(BSD_MAX_BITS)
162 #define BSD_HASH(prefix,suffix,hshift) ((((u_int32_t)(suffix)) << (hshift)) \
163 ^ (u_int32_t)(prefix))
164 #define BSD_KEY(prefix,suffix) ((((u_int32_t)(suffix)) << 16) \
165 + (u_int32_t)(prefix))
167 #define CHECK_GAP 10000 /* Ratio check interval */
169 #define RATIO_SCALE_LOG 8
170 #define RATIO_SCALE (1<<RATIO_SCALE_LOG)
171 #define RATIO_MAX (0x7fffffff>>RATIO_SCALE_LOG)
174 * clear the dictionary
177 bsd_clear(struct bsd_db *db)
180 db->max_ent = FIRST-1;
181 db->n_bits = BSD_INIT_BITS;
185 db->checkpoint = CHECK_GAP;
189 * If the dictionary is full, then see if it is time to reset it.
191 * Compute the compression ratio using fixed-point arithmetic
192 * with 8 fractional bits.
194 * Since we have an infinite stream instead of a single file,
195 * watch only the local compression ratio.
197 * Since both peers must reset the dictionary at the same time even in
198 * the absence of CLEAR codes (while packets are incompressible), they
199 * must compute the same ratio.
201 static int /* 1=output CLEAR */
202 bsd_check(struct bsd_db *db)
206 if (db->in_count >= db->checkpoint) {
207 /* age the ratio by limiting the size of the counts */
208 if (db->in_count >= RATIO_MAX
209 || db->bytes_out >= RATIO_MAX) {
210 db->in_count -= db->in_count/4;
211 db->bytes_out -= db->bytes_out/4;
214 db->checkpoint = db->in_count + CHECK_GAP;
216 if (db->max_ent >= db->maxmaxcode) {
217 /* Reset the dictionary only if the ratio is worse,
218 * or if it looks as if it has been poisoned
219 * by incompressible data.
221 * This does not overflow, because
222 * db->in_count <= RATIO_MAX.
224 new_ratio = db->in_count << RATIO_SCALE_LOG;
225 if (db->bytes_out != 0)
226 new_ratio /= db->bytes_out;
228 if (new_ratio < db->ratio || new_ratio < 1 * RATIO_SCALE) {
232 db->ratio = new_ratio;
242 bsd_comp_stats(void *state, struct compstat *stats)
244 struct bsd_db *db = (struct bsd_db *) state;
247 stats->unc_bytes = db->uncomp_bytes;
248 stats->unc_packets = db->uncomp_count;
249 stats->comp_bytes = db->comp_bytes;
250 stats->comp_packets = db->comp_count;
251 stats->inc_bytes = db->incomp_bytes;
252 stats->inc_packets = db->incomp_count;
254 u_int ratio = db->in_count;
256 if (ratio <= 0x7fffff)
261 stats->ratio = ratio / out;
265 * Reset state, as on a CCP ResetReq.
268 bsd_reset(void *state)
270 struct bsd_db *db = (struct bsd_db *) state;
278 * Allocate space for a (de) compressor.
281 bsd_alloc(u_char *options, int opt_len, int decomp)
284 u_int newlen, hsize, hshift, maxmaxcode;
287 if (opt_len != 3 || options[0] != CI_BSD_COMPRESS || options[1] != 3
288 || BSD_VERSION(options[2]) != BSD_CURRENT_VERSION)
291 bits = BSD_NBITS(options[2]);
293 case 9: /* needs 82152 for both directions */
294 case 10: /* needs 84144 */
295 case 11: /* needs 88240 */
296 case 12: /* needs 96432 */
300 case 13: /* needs 176784 */
304 case 14: /* needs 353744 */
308 case 15: /* needs 691440 */
312 case 16: /* needs 1366160--far too much, */
313 /* hsize = 69001; */ /* and 69001 is too big for cptr */
314 /* hshift = 8; */ /* in struct bsd_db */
320 maxmaxcode = MAXCODE(bits);
321 newlen = sizeof(*db) + (hsize-1) * (sizeof(db->dict[0]));
322 db = (struct bsd_db *) malloc(newlen);
325 memset(db, 0, sizeof(*db) - sizeof(db->dict));
330 db->lens = (u_short *) malloc((maxmaxcode+1) * sizeof(db->lens[0]));
340 db->maxmaxcode = maxmaxcode;
347 bsd_free(void *state)
349 struct bsd_db *db = (struct bsd_db *) state;
357 bsd_decomp_alloc(u_char *options, int opt_len)
359 return bsd_alloc(options, opt_len, 1);
363 * Initialize the database.
366 bsd_init(struct bsd_db *db, u_char *options, int opt_len, int unit,
367 int hdrlen, int mru, int debug, int decomp)
371 if (opt_len < CILEN_BSD_COMPRESS
372 || options[0] != CI_BSD_COMPRESS || options[1] != CILEN_BSD_COMPRESS
373 || BSD_VERSION(options[2]) != BSD_CURRENT_VERSION
374 || BSD_NBITS(options[2]) != db->maxbits
375 || (decomp && db->lens == NULL))
385 db->dict[--i].codem1 = BADCODEM1;
386 db->dict[i].cptr = 0;
401 bsd_decomp_init(void *state, u_char *options, int opt_len,
402 int unit, int hdrlen, int mru, int debug)
404 return bsd_init((struct bsd_db *) state, options, opt_len,
405 unit, hdrlen, mru, debug, 1);
410 * Update the "BSD Compress" dictionary on the receiver for
411 * incompressible data by pretending to compress the incoming data.
414 bsd_incomp(void *state, u_char *dmsg, int mlen)
416 struct bsd_db *db = (struct bsd_db *) state;
417 u_int hshift = db->hshift;
418 u_int max_ent = db->max_ent;
419 u_int n_bits = db->n_bits;
420 struct bsd_dict *dictp;
430 ent = rptr[0]; /* get the protocol */
436 if ((ent & 1) == 0 || ent < 0x21 || ent > 0xf9)
440 ilen = 1; /* count the protocol as 1 byte */
442 slen = dmsg + mlen - rptr;
444 for (; slen > 0; --slen) {
446 fcode = BSD_KEY(ent, c);
447 hval = BSD_HASH(ent, c, hshift);
448 dictp = &db->dict[hval];
450 /* validate and then check the entry */
451 if (dictp->codem1 >= max_ent)
453 if (dictp->f.fcode == fcode) {
454 ent = dictp->codem1+1;
455 continue; /* found (prefix,suffix) */
458 /* continue probing until a match or invalid entry */
459 disp = (hval == 0) ? 1 : hval;
462 if (hval >= db->hsize)
464 dictp = &db->dict[hval];
465 if (dictp->codem1 >= max_ent)
467 } while (dictp->f.fcode != fcode);
468 ent = dictp->codem1+1;
469 continue; /* finally found (prefix,suffix) */
471 nomatch: /* output (count) the prefix */
474 /* code -> hashtable */
475 if (max_ent < db->maxmaxcode) {
476 struct bsd_dict *dictp2;
477 /* expand code size if needed */
478 if (max_ent >= MAXCODE(n_bits))
479 db->n_bits = ++n_bits;
481 /* Invalidate previous hash table entry
482 * assigned this code, and then take it over.
484 dictp2 = &db->dict[max_ent+1];
485 if (db->dict[dictp2->cptr].codem1 == max_ent)
486 db->dict[dictp2->cptr].codem1 = BADCODEM1;
488 dictp->codem1 = max_ent;
489 dictp->f.fcode = fcode;
491 db->max_ent = ++max_ent;
492 db->lens[max_ent] = db->lens[ent]+1;
496 bitno += n_bits; /* output (count) the last code */
497 db->bytes_out += bitno/8;
498 db->in_count += ilen;
502 db->incomp_bytes += ilen;
504 db->uncomp_bytes += ilen;
506 /* Increase code size if we would have without the packet
507 * boundary and as the decompressor will.
509 if (max_ent >= MAXCODE(n_bits) && max_ent < db->maxmaxcode)
515 * Decompress "BSD Compress"
517 * Because of patent problems, we return DECOMP_ERROR for errors
518 * found by inspecting the input data and for system problems, but
519 * DECOMP_FATALERROR for any errors which could possibly be said to
520 * be being detected "after" decompression. For DECOMP_ERROR,
521 * we can issue a CCP reset-request; for DECOMP_FATALERROR, we may be
522 * infringing a patent of Motorola's if we do, so we take CCP down
525 * Given that the frame has the correct sequence number and a good FCS,
526 * errors such as invalid codes in the input most likely indicate a
527 * bug, so we return DECOMP_FATALERROR for them in order to turn off
528 * compression, even though they are detected by inspecting the input.
531 bsd_decompress(void *state, u_char *cmsg, int inlen, u_char *dmp, int *outlenp)
533 struct bsd_db *db = (struct bsd_db *) state;
534 u_int max_ent = db->max_ent;
536 u_int bitno = 32; /* 1st valid bit in accm */
537 u_int n_bits = db->n_bits;
538 u_int tgtbitno = 32-n_bits; /* bitno when we have a code */
539 struct bsd_dict *dictp;
540 int explen, seq, len;
541 u_int incode, oldcode, finchar;
542 u_char *p, *rptr, *wptr;
549 ++rptr; /* skip protocol (assumed 0xfd) */
550 seq = (rptr[0] << 8) + rptr[1];
552 ilen = len = cmsg + inlen - rptr;
555 * Check the sequence number and give up if it is not what we expect.
557 if (seq != db->seqno++) {
559 printf("bsd_decomp%d: bad sequence # %d, expected %d\n",
560 db->unit, seq, db->seqno - 1);
564 wptr = dmp + db->hdrlen;
570 * Accumulate bytes until we have a complete code.
571 * Then get the next code, relying on the 32-bit,
572 * unsigned accm to mask the result.
575 accm |= *rptr++ << bitno;
577 if (tgtbitno < bitno)
579 incode = accm >> tgtbitno;
583 if (incode == CLEAR) {
585 * The dictionary must only be cleared at
586 * the end of a packet. But there could be an
587 * empty message block at the end.
591 printf("bsd_decomp%d: bad CLEAR\n", db->unit);
592 return DECOMP_FATALERROR;
599 if (incode > max_ent + 2 || incode > db->maxmaxcode
600 || (incode > max_ent && oldcode == CLEAR)) {
602 printf("bsd_decomp%d: bad code 0x%x oldcode=0x%x ",
603 db->unit, incode, oldcode);
604 printf("max_ent=0x%x seqno=%d\n",
607 return DECOMP_FATALERROR; /* probably a bug */
610 /* Special case for KwKwK string. */
611 if (incode > max_ent) {
619 codelen = db->lens[finchar];
620 explen += codelen + extra;
621 if (explen > db->mru + 1) {
623 printf("bsd_decomp%d: ran out of mru\n", db->unit);
624 return DECOMP_FATALERROR;
628 * Decode this code and install it in the decompressed buffer.
630 p = (wptr += codelen);
631 while (finchar > LAST) {
632 dictp = &db->dict[db->dict[finchar].cptr];
636 printf("bsd_decomp%d: fell off end of chain ", db->unit);
637 printf("0x%x at 0x%x by 0x%x, max_ent=0x%x\n",
638 incode, finchar, db->dict[finchar].cptr, max_ent);
639 return DECOMP_FATALERROR;
641 if (dictp->codem1 != finchar-1) {
642 printf("bsd_decomp%d: bad code chain 0x%x finchar=0x%x ",
643 db->unit, incode, finchar);
644 printf("oldcode=0x%x cptr=0x%x codem1=0x%x\n", oldcode,
645 db->dict[finchar].cptr, dictp->codem1);
646 return DECOMP_FATALERROR;
649 *--p = dictp->f.hs.suffix;
650 finchar = dictp->f.hs.prefix;
656 printf("bsd_decomp%d: short by %d after code 0x%x, max_ent=0x%x\n",
657 db->unit, codelen, incode, max_ent);
660 if (extra) /* the KwKwK case again */
664 * If not first code in a packet, and
665 * if not out of code space, then allocate a new code.
667 * Keep the hash table correct so it can be used
668 * with uncompressed packets.
670 if (oldcode != CLEAR && max_ent < db->maxmaxcode) {
671 struct bsd_dict *dictp2;
675 fcode = BSD_KEY(oldcode,finchar);
676 hval = BSD_HASH(oldcode,finchar,db->hshift);
677 dictp = &db->dict[hval];
679 /* look for a free hash table entry */
680 if (dictp->codem1 < max_ent) {
681 disp = (hval == 0) ? 1 : hval;
684 if (hval >= db->hsize)
686 dictp = &db->dict[hval];
687 } while (dictp->codem1 < max_ent);
691 * Invalidate previous hash table entry
692 * assigned this code, and then take it over
694 dictp2 = &db->dict[max_ent+1];
695 if (db->dict[dictp2->cptr].codem1 == max_ent) {
696 db->dict[dictp2->cptr].codem1 = BADCODEM1;
699 dictp->codem1 = max_ent;
700 dictp->f.fcode = fcode;
702 db->max_ent = ++max_ent;
703 db->lens[max_ent] = db->lens[oldcode]+1;
705 /* Expand code size if needed. */
706 if (max_ent >= MAXCODE(n_bits) && max_ent < db->maxmaxcode) {
707 db->n_bits = ++n_bits;
708 tgtbitno = 32-n_bits;
713 *outlenp = wptr - (dmp + db->hdrlen);
716 * Keep the checkpoint right so that incompressible packets
717 * clear the dictionary at the right times.
719 db->bytes_out += ilen;
720 db->in_count += explen;
721 if (bsd_check(db) && db->debug) {
722 printf("bsd_decomp%d: peer should have cleared dictionary\n",
727 db->comp_bytes += ilen + BSD_OVHD;
729 db->uncomp_bytes += explen;
733 #endif /* DO_BSD_COMPRESS */