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;
253 stats->ratio = db->in_count;
255 if (stats->ratio <= 0x7fffff)
264 * Reset state, as on a CCP ResetReq.
267 bsd_reset(void *state)
269 struct bsd_db *db = (struct bsd_db *) state;
277 * Allocate space for a (de) compressor.
280 bsd_alloc(u_char *options, int opt_len, int decomp)
283 u_int newlen, hsize, hshift, maxmaxcode;
286 if (opt_len != 3 || options[0] != CI_BSD_COMPRESS || options[1] != 3
287 || BSD_VERSION(options[2]) != BSD_CURRENT_VERSION)
290 bits = BSD_NBITS(options[2]);
292 case 9: /* needs 82152 for both directions */
293 case 10: /* needs 84144 */
294 case 11: /* needs 88240 */
295 case 12: /* needs 96432 */
299 case 13: /* needs 176784 */
303 case 14: /* needs 353744 */
307 case 15: /* needs 691440 */
311 case 16: /* needs 1366160--far too much, */
312 /* hsize = 69001; */ /* and 69001 is too big for cptr */
313 /* hshift = 8; */ /* in struct bsd_db */
319 maxmaxcode = MAXCODE(bits);
320 newlen = sizeof(*db) + (hsize-1) * (sizeof(db->dict[0]));
321 db = (struct bsd_db *) malloc(newlen);
324 memset(db, 0, sizeof(*db) - sizeof(db->dict));
329 db->lens = (u_short *) malloc((maxmaxcode+1) * sizeof(db->lens[0]));
339 db->maxmaxcode = maxmaxcode;
346 bsd_free(void *state)
348 struct bsd_db *db = (struct bsd_db *) state;
356 bsd_decomp_alloc(u_char *options, int opt_len)
358 return bsd_alloc(options, opt_len, 1);
362 * Initialize the database.
365 bsd_init(struct bsd_db *db, u_char *options, int opt_len, int unit,
366 int hdrlen, int mru, int debug, int decomp)
370 if (opt_len < CILEN_BSD_COMPRESS
371 || options[0] != CI_BSD_COMPRESS || options[1] != CILEN_BSD_COMPRESS
372 || BSD_VERSION(options[2]) != BSD_CURRENT_VERSION
373 || BSD_NBITS(options[2]) != db->maxbits
374 || (decomp && db->lens == NULL))
384 db->dict[--i].codem1 = BADCODEM1;
385 db->dict[i].cptr = 0;
400 bsd_decomp_init(void *state, u_char *options, int opt_len,
401 int unit, int hdrlen, int mru, int debug)
403 return bsd_init((struct bsd_db *) state, options, opt_len,
404 unit, hdrlen, mru, debug, 1);
409 * Update the "BSD Compress" dictionary on the receiver for
410 * incompressible data by pretending to compress the incoming data.
413 bsd_incomp(void *state, u_char *dmsg, int mlen)
415 struct bsd_db *db = (struct bsd_db *) state;
416 u_int hshift = db->hshift;
417 u_int max_ent = db->max_ent;
418 u_int n_bits = db->n_bits;
419 struct bsd_dict *dictp;
429 ent = rptr[0]; /* get the protocol */
435 if ((ent & 1) == 0 || ent < 0x21 || ent > 0xf9)
439 ilen = 1; /* count the protocol as 1 byte */
441 slen = dmsg + mlen - rptr;
443 for (; slen > 0; --slen) {
445 fcode = BSD_KEY(ent, c);
446 hval = BSD_HASH(ent, c, hshift);
447 dictp = &db->dict[hval];
449 /* validate and then check the entry */
450 if (dictp->codem1 >= max_ent)
452 if (dictp->f.fcode == fcode) {
453 ent = dictp->codem1+1;
454 continue; /* found (prefix,suffix) */
457 /* continue probing until a match or invalid entry */
458 disp = (hval == 0) ? 1 : hval;
461 if (hval >= db->hsize)
463 dictp = &db->dict[hval];
464 if (dictp->codem1 >= max_ent)
466 } while (dictp->f.fcode != fcode);
467 ent = dictp->codem1+1;
468 continue; /* finally found (prefix,suffix) */
470 nomatch: /* output (count) the prefix */
473 /* code -> hashtable */
474 if (max_ent < db->maxmaxcode) {
475 struct bsd_dict *dictp2;
476 /* expand code size if needed */
477 if (max_ent >= MAXCODE(n_bits))
478 db->n_bits = ++n_bits;
480 /* Invalidate previous hash table entry
481 * assigned this code, and then take it over.
483 dictp2 = &db->dict[max_ent+1];
484 if (db->dict[dictp2->cptr].codem1 == max_ent)
485 db->dict[dictp2->cptr].codem1 = BADCODEM1;
487 dictp->codem1 = max_ent;
488 dictp->f.fcode = fcode;
490 db->max_ent = ++max_ent;
491 db->lens[max_ent] = db->lens[ent]+1;
495 bitno += n_bits; /* output (count) the last code */
496 db->bytes_out += bitno/8;
497 db->in_count += ilen;
501 db->incomp_bytes += ilen;
503 db->uncomp_bytes += ilen;
505 /* Increase code size if we would have without the packet
506 * boundary and as the decompressor will.
508 if (max_ent >= MAXCODE(n_bits) && max_ent < db->maxmaxcode)
514 * Decompress "BSD Compress"
516 * Because of patent problems, we return DECOMP_ERROR for errors
517 * found by inspecting the input data and for system problems, but
518 * DECOMP_FATALERROR for any errors which could possibly be said to
519 * be being detected "after" decompression. For DECOMP_ERROR,
520 * we can issue a CCP reset-request; for DECOMP_FATALERROR, we may be
521 * infringing a patent of Motorola's if we do, so we take CCP down
524 * Given that the frame has the correct sequence number and a good FCS,
525 * errors such as invalid codes in the input most likely indicate a
526 * bug, so we return DECOMP_FATALERROR for them in order to turn off
527 * compression, even though they are detected by inspecting the input.
530 bsd_decompress(void *state, u_char *cmsg, int inlen, u_char *dmp, int *outlenp)
532 struct bsd_db *db = (struct bsd_db *) state;
533 u_int max_ent = db->max_ent;
535 u_int bitno = 32; /* 1st valid bit in accm */
536 u_int n_bits = db->n_bits;
537 u_int tgtbitno = 32-n_bits; /* bitno when we have a code */
538 struct bsd_dict *dictp;
539 int explen, seq, len;
540 u_int incode, oldcode, finchar;
541 u_char *p, *rptr, *wptr;
548 ++rptr; /* skip protocol (assumed 0xfd) */
549 seq = (rptr[0] << 8) + rptr[1];
551 ilen = len = cmsg + inlen - rptr;
554 * Check the sequence number and give up if it is not what we expect.
556 if (seq != db->seqno++) {
558 printf("bsd_decomp%d: bad sequence # %d, expected %d\n",
559 db->unit, seq, db->seqno - 1);
563 wptr = dmp + db->hdrlen;
569 * Accumulate bytes until we have a complete code.
570 * Then get the next code, relying on the 32-bit,
571 * unsigned accm to mask the result.
574 accm |= *rptr++ << bitno;
576 if (tgtbitno < bitno)
578 incode = accm >> tgtbitno;
582 if (incode == CLEAR) {
584 * The dictionary must only be cleared at
585 * the end of a packet. But there could be an
586 * empty message block at the end.
590 printf("bsd_decomp%d: bad CLEAR\n", db->unit);
591 return DECOMP_FATALERROR;
598 if (incode > max_ent + 2 || incode > db->maxmaxcode
599 || (incode > max_ent && oldcode == CLEAR)) {
601 printf("bsd_decomp%d: bad code 0x%x oldcode=0x%x ",
602 db->unit, incode, oldcode);
603 printf("max_ent=0x%x seqno=%d\n",
606 return DECOMP_FATALERROR; /* probably a bug */
609 /* Special case for KwKwK string. */
610 if (incode > max_ent) {
618 codelen = db->lens[finchar];
619 explen += codelen + extra;
620 if (explen > db->mru + 1) {
622 printf("bsd_decomp%d: ran out of mru\n", db->unit);
623 return DECOMP_FATALERROR;
627 * Decode this code and install it in the decompressed buffer.
629 p = (wptr += codelen);
630 while (finchar > LAST) {
631 dictp = &db->dict[db->dict[finchar].cptr];
635 printf("bsd_decomp%d: fell off end of chain ", db->unit);
636 printf("0x%x at 0x%x by 0x%x, max_ent=0x%x\n",
637 incode, finchar, db->dict[finchar].cptr, max_ent);
638 return DECOMP_FATALERROR;
640 if (dictp->codem1 != finchar-1) {
641 printf("bsd_decomp%d: bad code chain 0x%x finchar=0x%x ",
642 db->unit, incode, finchar);
643 printf("oldcode=0x%x cptr=0x%x codem1=0x%x\n", oldcode,
644 db->dict[finchar].cptr, dictp->codem1);
645 return DECOMP_FATALERROR;
648 *--p = dictp->f.hs.suffix;
649 finchar = dictp->f.hs.prefix;
655 printf("bsd_decomp%d: short by %d after code 0x%x, max_ent=0x%x\n",
656 db->unit, codelen, incode, max_ent);
659 if (extra) /* the KwKwK case again */
663 * If not first code in a packet, and
664 * if not out of code space, then allocate a new code.
666 * Keep the hash table correct so it can be used
667 * with uncompressed packets.
669 if (oldcode != CLEAR && max_ent < db->maxmaxcode) {
670 struct bsd_dict *dictp2;
674 fcode = BSD_KEY(oldcode,finchar);
675 hval = BSD_HASH(oldcode,finchar,db->hshift);
676 dictp = &db->dict[hval];
678 /* look for a free hash table entry */
679 if (dictp->codem1 < max_ent) {
680 disp = (hval == 0) ? 1 : hval;
683 if (hval >= db->hsize)
685 dictp = &db->dict[hval];
686 } while (dictp->codem1 < max_ent);
690 * Invalidate previous hash table entry
691 * assigned this code, and then take it over
693 dictp2 = &db->dict[max_ent+1];
694 if (db->dict[dictp2->cptr].codem1 == max_ent) {
695 db->dict[dictp2->cptr].codem1 = BADCODEM1;
698 dictp->codem1 = max_ent;
699 dictp->f.fcode = fcode;
701 db->max_ent = ++max_ent;
702 db->lens[max_ent] = db->lens[oldcode]+1;
704 /* Expand code size if needed. */
705 if (max_ent >= MAXCODE(n_bits) && max_ent < db->maxmaxcode) {
706 db->n_bits = ++n_bits;
707 tgtbitno = 32-n_bits;
712 *outlenp = wptr - (dmp + db->hdrlen);
715 * Keep the checkpoint right so that incompressible packets
716 * clear the dictionary at the right times.
718 db->bytes_out += ilen;
719 db->in_count += explen;
720 if (bsd_check(db) && db->debug) {
721 printf("bsd_decomp%d: peer should have cleared dictionary\n",
726 db->comp_bytes += ilen + BSD_OVHD;
728 db->uncomp_bytes += explen;
732 #endif /* DO_BSD_COMPRESS */