]> git.ozlabs.org Git - ppp.git/blob - modules/bsd-comp.c
support AIX4 and OSF1 as well as SunOS 4
[ppp.git] / modules / bsd-comp.c
1 /* Because this code is derived from the 4.3BSD compress source:
2  *
3  *
4  * Copyright (c) 1985, 1986 The Regents of the University of California.
5  * All rights reserved.
6  *
7  * This code is derived from software contributed to Berkeley by
8  * James A. Woods, derived from original work by Spencer Thomas
9  * and Joseph Orost.
10  *
11  * Redistribution and use in source and binary forms, with or without
12  * modification, are permitted provided that the following conditions
13  * are met:
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.
26  *
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
37  * SUCH DAMAGE.
38  */
39
40 /*
41  * This version is for use with STREAMS under SunOS 4.x,
42  * DEC Alpha OSF/1, and AIX 4.x.
43  *
44  * $Id: bsd-comp.c,v 1.8 1994/12/08 00:35:33 paulus Exp $
45  */
46
47 #ifdef __aix4__
48 #include <net/net_globals.h>
49 #endif
50 #include <sys/param.h>
51 #include <sys/types.h>
52 #include <sys/stream.h>
53 #include <sys/socket.h>
54 #include <net/if.h>
55 #include <net/ppp_defs.h>
56 #include <net/ppp_str.h>
57
58 #ifdef sun
59 #include <sys/kmem_alloc.h>
60 #define ALLOCATE(n)     kmem_alloc((n), KMEM_NOSLEEP)
61 #define FREE(p, n)      kmem_free((p), (n))
62 #endif
63
64 #ifdef __osf__
65 #include <kern/kalloc.h>
66 #define ALLOCATE(n)     kalloc((n))
67 #define FREE(p, n)      kfree((p), (n))
68 #endif
69
70 #ifdef __aix4__
71 #define ALLOCATE(n)     xmalloc((n), 0, pinned_heap)
72 #define FREE(p, n)      xmfree((p), pinned_heap)
73 #endif
74
75 #define PACKETPTR       mblk_t *
76 #include <net/ppp-comp.h>
77
78 /*
79  * PPP "BSD compress" compression
80  *  The differences between this compression and the classic BSD LZW
81  *  source are obvious from the requirement that the classic code worked
82  *  with files while this handles arbitrarily long streams that
83  *  are broken into packets.  They are:
84  *
85  *      When the code size expands, a block of junk is not emitted by
86  *          the compressor and not expected by the decompressor.
87  *
88  *      New codes are not necessarily assigned every time an old
89  *          code is output by the compressor.  This is because a packet
90  *          end forces a code to be emitted, but does not imply that a
91  *          new sequence has been seen.
92  *
93  *      The compression ratio is checked at the first end of a packet
94  *          after the appropriate gap.  Besides simplifying and speeding
95  *          things up, this makes it more likely that the transmitter
96  *          and receiver will agree when the dictionary is cleared when
97  *          compression is not going well.
98  */
99
100 /*
101  * Macros to extract protocol version and number of bits
102  * from the third byte of the BSD Compress CCP configuration option.
103  */
104 #define BSD_VERSION(x)  ((x) >> 5)
105 #define BSD_NBITS(x)    ((x) & 0x1F)
106
107 #define BSD_CURRENT_VERSION     1
108
109 /*
110  * A dictionary for doing BSD compress.
111  */
112 struct bsd_db {
113     int     totlen;                     /* length of this structure */
114     u_int   hsize;                      /* size of the hash table */
115     u_char  hshift;                     /* used in hash function */
116     u_char  n_bits;                     /* current bits/code */
117     u_char  maxbits;
118     u_char  debug;
119     u_char  unit;
120     u_short seqno;                      /* sequence number of next packet */
121     u_int   hdrlen;                     /* header length to preallocate */
122     u_int   mru;
123     u_int   maxmaxcode;                 /* largest valid code */
124     u_int   max_ent;                    /* largest code in use */
125     u_int   in_count;                   /* uncompressed bytes, aged */
126     u_int   bytes_out;                  /* compressed bytes, aged */
127     u_int   ratio;                      /* recent compression ratio */
128     u_int   checkpoint;                 /* when to next check the ratio */
129     u_int   clear_count;                /* times dictionary cleared */
130     u_int   incomp_count;               /* incompressible packets */
131     u_int   incomp_bytes;               /* incompressible bytes */
132     u_int   uncomp_count;               /* uncompressed packets */
133     u_int   uncomp_bytes;               /* uncompressed bytes */
134     u_int   comp_count;                 /* compressed packets */
135     u_int   comp_bytes;                 /* compressed bytes */
136     u_short *lens;                      /* array of lengths of codes */
137     struct bsd_dict {
138         union {                         /* hash value */
139             u_int32_t   fcode;
140             struct {
141 #ifdef BSD_LITTLE_ENDIAN
142                 u_short prefix;         /* preceding code */
143                 u_char  suffix;         /* last character of new code */
144                 u_char  pad;
145 #else
146                 u_char  pad;
147                 u_char  suffix;         /* last character of new code */
148                 u_short prefix;         /* preceding code */
149 #endif
150             } hs;
151         } f;
152         u_short codem1;                 /* output of hash table -1 */
153         u_short cptr;                   /* map code to hash table entry */
154     } dict[1];
155 };
156
157 #define BSD_OVHD        2               /* BSD compress overhead/packet */
158 #define MIN_BSD_BITS    9
159 #define BSD_INIT_BITS   MIN_BSD_BITS
160 #define MAX_BSD_BITS    15
161
162 static void     *bsd_comp_alloc __P((u_char *options, int opt_len));
163 static void     *bsd_decomp_alloc __P((u_char *options, int opt_len));
164 static void     bsd_free __P((void *state));
165 static int      bsd_comp_init __P((void *state, u_char *options, int opt_len,
166                                    int unit, int debug));
167 static int      bsd_decomp_init __P((void *state, u_char *options, int opt_len,
168                                      int unit, int hdrlen, int mru, int debug));
169 static int      bsd_compress __P((void *state, mblk_t **mret,
170                                   mblk_t *mp, int slen, int maxolen));
171 static void     bsd_incomp __P((void *state, mblk_t *dmsg));
172 static int      bsd_decompress __P((void *state, mblk_t *cmp, mblk_t **dmpp));
173 static void     bsd_reset __P((void *state));
174 static void     bsd_comp_stats __P((void *state, struct compstat *stats));
175
176 /*
177  * Procedures exported to ppp_comp.c.
178  */
179 struct compressor ppp_bsd_compress = {
180     0x21,                       /* compress_proto */
181     bsd_comp_alloc,             /* comp_alloc */
182     bsd_free,                   /* comp_free */
183     bsd_comp_init,              /* comp_init */
184     bsd_reset,                  /* comp_reset */
185     bsd_compress,               /* compress */
186     bsd_comp_stats,             /* comp_stat */
187     bsd_decomp_alloc,           /* decomp_alloc */
188     bsd_free,                   /* decomp_free */
189     bsd_decomp_init,            /* decomp_init */
190     bsd_reset,                  /* decomp_reset */
191     bsd_decompress,             /* decompress */
192     bsd_incomp,                 /* incomp */
193     bsd_comp_stats,             /* decomp_stat */
194 };
195
196 /*
197  * the next two codes should not be changed lightly, as they must not
198  * lie within the contiguous general code space.
199  */
200 #define CLEAR   256                     /* table clear output code */
201 #define FIRST   257                     /* first free entry */
202 #define LAST    255
203
204 #define MAXCODE(b)      ((1 << (b)) - 1)
205 #define BADCODEM1       MAXCODE(MAX_BSD_BITS);
206
207 #define BSD_HASH(prefix,suffix,hshift)  ((((u_int32_t)(suffix)) << (hshift)) \
208                                          ^ (u_int32_t)(prefix))
209 #define BSD_KEY(prefix,suffix)          ((((u_int32_t)(suffix)) << 16) \
210                                          + (u_int32_t)(prefix))
211
212 #define CHECK_GAP       10000           /* Ratio check interval */
213
214 #define RATIO_SCALE_LOG 8
215 #define RATIO_SCALE     (1<<RATIO_SCALE_LOG)
216 #define RATIO_MAX       (0x7fffffff>>RATIO_SCALE_LOG)
217
218 #define DECOMP_CHUNK    256
219
220 /*
221  * clear the dictionary
222  */
223 static void
224 bsd_clear(db)
225     struct bsd_db *db;
226 {
227     db->clear_count++;
228     db->max_ent = FIRST-1;
229     db->n_bits = BSD_INIT_BITS;
230     db->ratio = 0;
231     db->bytes_out = 0;
232     db->in_count = 0;
233     db->incomp_count = 0;
234     db->checkpoint = CHECK_GAP;
235 }
236
237 /*
238  * If the dictionary is full, then see if it is time to reset it.
239  *
240  * Compute the compression ratio using fixed-point arithmetic
241  * with 8 fractional bits.
242  *
243  * Since we have an infinite stream instead of a single file,
244  * watch only the local compression ratio.
245  *
246  * Since both peers must reset the dictionary at the same time even in
247  * the absence of CLEAR codes (while packets are incompressible), they
248  * must compute the same ratio.
249  */
250 static int                              /* 1=output CLEAR */
251 bsd_check(db)
252     struct bsd_db *db;
253 {
254     u_int new_ratio;
255
256     if (db->in_count >= db->checkpoint) {
257         /* age the ratio by limiting the size of the counts */
258         if (db->in_count >= RATIO_MAX
259             || db->bytes_out >= RATIO_MAX) {
260             db->in_count -= db->in_count/4;
261             db->bytes_out -= db->bytes_out/4;
262         }
263
264         db->checkpoint = db->in_count + CHECK_GAP;
265
266         if (db->max_ent >= db->maxmaxcode) {
267             /* Reset the dictionary only if the ratio is worse,
268              * or if it looks as if it has been poisoned
269              * by incompressible data.
270              *
271              * This does not overflow, because
272              *  db->in_count <= RATIO_MAX.
273              */
274             new_ratio = db->in_count << RATIO_SCALE_LOG;
275             if (db->bytes_out != 0)
276                 new_ratio /= db->bytes_out;
277
278             if (new_ratio < db->ratio || new_ratio < 1 * RATIO_SCALE) {
279                 bsd_clear(db);
280                 return 1;
281             }
282             db->ratio = new_ratio;
283         }
284     }
285     return 0;
286 }
287
288 /*
289  * Return statistics.
290  */
291 static void
292 bsd_comp_stats(state, stats)
293     void *state;
294     struct compstat *stats;
295 {
296     struct bsd_db *db = (struct bsd_db *) state;
297     u_int out;
298
299     stats->unc_bytes = db->uncomp_bytes;
300     stats->unc_packets = db->uncomp_count;
301     stats->comp_bytes = db->comp_bytes;
302     stats->comp_packets = db->comp_count;
303     stats->inc_bytes = db->incomp_bytes;
304     stats->inc_packets = db->incomp_count;
305     stats->ratio = db->in_count;
306     out = db->bytes_out;
307     if (stats->ratio <= 0x7fffff)
308         stats->ratio <<= 8;
309     else
310         out >>= 8;
311     if (out != 0)
312         stats->ratio /= out;
313 }
314
315 /*
316  * Reset state, as on a CCP ResetReq.
317  */
318 static void
319 bsd_reset(state)
320     void *state;
321 {
322     struct bsd_db *db = (struct bsd_db *) state;
323
324     db->seqno = 0;
325     bsd_clear(db);
326     db->clear_count = 0;
327 }
328
329 /*
330  * Allocate space for a (de) compressor.
331  */
332 static void *
333 bsd_alloc(options, opt_len, decomp)
334     u_char *options;
335     int opt_len, decomp;
336 {
337     int bits;
338     u_int newlen, hsize, hshift, maxmaxcode;
339     struct bsd_db *db;
340
341     if (opt_len != 3 || options[0] != 0x21 || options[1] != 3
342         || BSD_VERSION(options[2]) != BSD_CURRENT_VERSION)
343         return NULL;
344     bits = BSD_NBITS(options[2]);
345     switch (bits) {
346     case 9:                     /* needs 82152 for both directions */
347     case 10:                    /* needs 84144 */
348     case 11:                    /* needs 88240 */
349     case 12:                    /* needs 96432 */
350         hsize = 5003;
351         hshift = 4;
352         break;
353     case 13:                    /* needs 176784 */
354         hsize = 9001;
355         hshift = 5;
356         break;
357     case 14:                    /* needs 353744 */
358         hsize = 18013;
359         hshift = 6;
360         break;
361     case 15:                    /* needs 691440 */
362         hsize = 35023;
363         hshift = 7;
364         break;
365     case 16:                    /* needs 1366160--far too much, */
366         /* hsize = 69001; */    /* and 69001 is too big for cptr */
367         /* hshift = 8; */       /* in struct bsd_db */
368         /* break; */
369     default:
370         return NULL;
371     }
372
373     maxmaxcode = MAXCODE(bits);
374     newlen = sizeof(*db) + (hsize-1) * (sizeof(db->dict[0]));
375     db = (struct bsd_db *) ALLOCATE(newlen);
376     if (!db)
377         return NULL;
378     bzero(db, sizeof(*db) - sizeof(db->dict));
379
380     if (!decomp) {
381         db->lens = NULL;
382     } else {
383         db->lens = (u_short *) ALLOCATE((maxmaxcode+1) * sizeof(db->lens[0]));
384         if (!db->lens) {
385             FREE(db, newlen);
386             return NULL;
387         }
388     }
389
390     db->totlen = newlen;
391     db->hsize = hsize;
392     db->hshift = hshift;
393     db->maxmaxcode = maxmaxcode;
394     db->maxbits = bits;
395
396     return (void *) db;
397 }
398
399 static void
400 bsd_free(state)
401     void *state;
402 {
403     struct bsd_db *db = (struct bsd_db *) state;
404
405     if (db->lens)
406         FREE(db->lens, (db->maxmaxcode+1) * sizeof(db->lens[0]));
407     FREE(db, db->totlen);
408 }
409
410 static void *
411 bsd_comp_alloc(options, opt_len)
412     u_char *options;
413     int opt_len;
414 {
415     return bsd_alloc(options, opt_len, 0);
416 }
417
418 static void *
419 bsd_decomp_alloc(options, opt_len)
420     u_char *options;
421     int opt_len;
422 {
423     return bsd_alloc(options, opt_len, 1);
424 }
425
426 /*
427  * Initialize the database.
428  */
429 static int
430 bsd_init(db, options, opt_len, unit, hdrlen, mru, debug, decomp)
431     struct bsd_db *db;
432     u_char *options;
433     int opt_len, unit, hdrlen, mru, debug, decomp;
434 {
435     int i;
436
437     if (opt_len != 3 || options[0] != 0x21 || options[1] != 3
438         || BSD_VERSION(options[2]) != BSD_CURRENT_VERSION
439         || BSD_NBITS(options[2]) != db->maxbits
440         || decomp && db->lens == NULL)
441         return 0;
442
443     if (decomp) {
444         i = LAST+1;
445         while (i != 0)
446             db->lens[--i] = 1;
447     }
448     i = db->hsize;
449     while (i != 0) {
450         db->dict[--i].codem1 = BADCODEM1;
451         db->dict[i].cptr = 0;
452     }
453
454     db->unit = unit;
455     db->hdrlen = hdrlen;
456     db->mru = mru;
457     if (debug)
458         db->debug = 1;
459
460     bsd_reset(db);
461
462     return 1;
463 }
464
465 static int
466 bsd_comp_init(state, options, opt_len, unit, debug)
467     void *state;
468     u_char *options;
469     int opt_len, unit, debug;
470 {
471     return bsd_init((struct bsd_db *) state, options, opt_len,
472                     unit, 0, 0, debug, 0);
473 }
474
475 static int
476 bsd_decomp_init(state, options, opt_len, unit, hdrlen, mru, debug)
477     void *state;
478     u_char *options;
479     int opt_len, unit, hdrlen, mru, debug;
480 {
481     return bsd_init((struct bsd_db *) state, options, opt_len,
482                     unit, hdrlen, mru, debug, 1);
483 }
484
485
486 /*
487  * compress a packet
488  *      One change from the BSD compress command is that when the
489  *      code size expands, we do not output a bunch of padding.
490  */
491 static int                      /* new slen */
492 bsd_compress(state, mretp, mp, slen, maxolen)
493     void *state;
494     mblk_t **mretp;             /* return compressed mbuf chain here */
495     mblk_t *mp;                 /* from here */
496     int slen;                   /* uncompressed length */
497     int maxolen;                /* max compressed length */
498 {
499     struct bsd_db *db = (struct bsd_db *) state;
500     int hshift = db->hshift;
501     u_int max_ent = db->max_ent;
502     u_int n_bits = db->n_bits;
503     u_int bitno = 32;
504     u_int32_t accm = 0, fcode;
505     struct bsd_dict *dictp;
506     u_char c;
507     int hval, disp, ent, ilen;
508     mblk_t *np, *mret;
509     u_char *rptr, *wptr;
510     u_char *cp_end;
511     int olen;
512     mblk_t *m, **mnp;
513
514 #define PUTBYTE(v) {                                    \
515     if (wptr) {                                         \
516         *wptr++ = (v);                                  \
517         if (wptr >= cp_end) {                           \
518             m->b_wptr = wptr;                           \
519             m = m->b_cont;                              \
520             if (m) {                                    \
521                 wptr = m->b_wptr;                       \
522                 cp_end = m->b_datap->db_lim;            \
523             } else                                      \
524                 wptr = NULL;                            \
525         }                                               \
526     }                                                   \
527     ++olen;                                             \
528 }
529
530 #define OUTPUT(ent) {                                   \
531     bitno -= n_bits;                                    \
532     accm |= ((ent) << bitno);                           \
533     do {                                                \
534         PUTBYTE(accm >> 24);                            \
535         accm <<= 8;                                     \
536         bitno += 8;                                     \
537     } while (bitno <= 24);                              \
538 }
539
540     /*
541      * First get the protocol and check that we're
542      * interested in this packet.
543      */
544     *mretp = NULL;
545     rptr = mp->b_rptr;
546     if (rptr + PPP_HDRLEN > mp->b_wptr) {
547         if (!pullupmsg(mp, PPP_HDRLEN))
548             return 0;
549         rptr = mp->b_rptr;
550     }
551     ent = PPP_PROTOCOL(rptr);           /* get the protocol */
552     if (ent < 0x21 || ent > 0xf9)
553         return 0;
554
555     /* Don't generate compressed packets which are larger than
556        the uncompressed packet. */
557     if (maxolen > slen)
558         maxolen = slen;
559
560     /* Allocate enough message blocks to give maxolen total space. */
561     mnp = &mret;
562     for (olen = maxolen; olen > 0; ) {
563         m = allocb((olen < 4096? olen: 4096), BPRI_MED);
564         *mnp = m;
565         if (m == NULL) {
566             if (mret != NULL) {
567                 freemsg(mret);
568                 mnp = &mret;
569             }
570             break;
571         }
572         mnp = &m->b_cont;
573         olen -= m->b_datap->db_lim - m->b_wptr;
574     }
575     *mnp = NULL;
576
577     if ((m = mret) != NULL) {
578         wptr = m->b_wptr;
579         cp_end = m->b_datap->db_lim;
580     } else
581         wptr = cp_end = NULL;
582     olen = 0;
583
584     /*
585      * Copy the PPP header over, changing the protocol,
586      * and install the 2-byte sequence number.
587      */
588     if (wptr) {
589         wptr[0] = PPP_ADDRESS(rptr);
590         wptr[1] = PPP_CONTROL(rptr);
591         wptr[2] = 0;            /* change the protocol */
592         wptr[3] = PPP_COMP;
593         wptr[4] = db->seqno >> 8;
594         wptr[5] = db->seqno;
595         wptr += PPP_HDRLEN + BSD_OVHD;
596     }
597     ++db->seqno;
598     rptr += PPP_HDRLEN;
599
600     slen = mp->b_wptr - rptr;
601     ilen = slen + 1;
602     np = mp->b_cont;
603     for (;;) {
604         if (slen <= 0) {
605             if (!np)
606                 break;
607             rptr = np->b_rptr;
608             slen = np->b_wptr - rptr;
609             np = np->b_cont;
610             if (!slen)
611                 continue;   /* handle 0-length buffers */
612             ilen += slen;
613         }
614
615         slen--;
616         c = *rptr++;
617         fcode = BSD_KEY(ent, c);
618         hval = BSD_HASH(ent, c, hshift);
619         dictp = &db->dict[hval];
620
621         /* Validate and then check the entry. */
622         if (dictp->codem1 >= max_ent)
623             goto nomatch;
624         if (dictp->f.fcode == fcode) {
625             ent = dictp->codem1+1;
626             continue;   /* found (prefix,suffix) */
627         }
628
629         /* continue probing until a match or invalid entry */
630         disp = (hval == 0) ? 1 : hval;
631         do {
632             hval += disp;
633             if (hval >= db->hsize)
634                 hval -= db->hsize;
635             dictp = &db->dict[hval];
636             if (dictp->codem1 >= max_ent)
637                 goto nomatch;
638         } while (dictp->f.fcode != fcode);
639         ent = dictp->codem1 + 1;        /* finally found (prefix,suffix) */
640         continue;
641
642     nomatch:
643         OUTPUT(ent);            /* output the prefix */
644
645         /* code -> hashtable */
646         if (max_ent < db->maxmaxcode) {
647             struct bsd_dict *dictp2;
648             /* expand code size if needed */
649             if (max_ent >= MAXCODE(n_bits))
650                 db->n_bits = ++n_bits;
651
652             /* Invalidate old hash table entry using
653              * this code, and then take it over.
654              */
655             dictp2 = &db->dict[max_ent+1];
656             if (db->dict[dictp2->cptr].codem1 == max_ent)
657                 db->dict[dictp2->cptr].codem1 = BADCODEM1;
658             dictp2->cptr = hval;
659             dictp->codem1 = max_ent;
660             dictp->f.fcode = fcode;
661
662             db->max_ent = ++max_ent;
663         }
664         ent = c;
665     }
666
667     OUTPUT(ent);                /* output the last code */
668     db->bytes_out += olen;
669     db->in_count += ilen;
670     if (bitno < 32)
671         ++db->bytes_out;        /* count complete bytes */
672
673     if (bsd_check(db))
674         OUTPUT(CLEAR);          /* do not count the CLEAR */
675
676     /*
677      * Pad dribble bits of last code with ones.
678      * Do not emit a completely useless byte of ones.
679      */
680     if (bitno != 32)
681         PUTBYTE((accm | (0xff << (bitno-8))) >> 24);
682
683     /*
684      * Increase code size if we would have without the packet
685      * boundary and as the decompressor will.
686      */
687     if (max_ent >= MAXCODE(n_bits) && max_ent < db->maxmaxcode)
688         db->n_bits++;
689
690     db->uncomp_bytes += ilen;
691     ++db->uncomp_count;
692     if (olen + PPP_HDRLEN + BSD_OVHD > maxolen && mret != NULL) {
693         /* throw away the compressed stuff if it is longer than uncompressed */
694         freemsg(mret);
695         mret = NULL;
696         ++db->incomp_count;
697         db->incomp_bytes += ilen;
698     } else if (wptr != NULL) {
699         m->b_wptr = wptr;
700         if (m->b_cont) {
701             freemsg(m->b_cont);
702             m->b_cont = NULL;
703         }
704         ++db->comp_count;
705         db->comp_bytes += olen + BSD_OVHD;
706     }
707
708     *mretp = mret;
709     return olen + PPP_HDRLEN + BSD_OVHD;
710 #undef OUTPUT
711 #undef PUTBYTE
712 }
713
714
715 /*
716  * Update the "BSD Compress" dictionary on the receiver for
717  * incompressible data by pretending to compress the incoming data.
718  */
719 static void
720 bsd_incomp(state, dmsg)
721     void *state;
722     mblk_t *dmsg;
723 {
724     struct bsd_db *db = (struct bsd_db *) state;
725     u_int hshift = db->hshift;
726     u_int max_ent = db->max_ent;
727     u_int n_bits = db->n_bits;
728     struct bsd_dict *dictp;
729     u_int32_t fcode;
730     u_char c;
731     long hval, disp;
732     int slen, ilen;
733     u_int bitno = 7;
734     u_char *rptr;
735     u_int ent;
736
737     rptr = dmsg->b_rptr;
738     if (rptr + PPP_HDRLEN > dmsg->b_wptr) {
739         if (!pullupmsg(dmsg, PPP_HDRLEN))
740             return;
741         rptr = dmsg->b_rptr;
742     }
743     ent = PPP_PROTOCOL(rptr);           /* get the protocol */
744     if (ent < 0x21 || ent > 0xf9)
745         return;
746
747     db->incomp_count++;
748     db->seqno++;
749     ilen = 1;           /* count the protocol as 1 byte */
750     rptr += PPP_HDRLEN;
751     for (;;) {
752         slen = dmsg->b_wptr - rptr;
753         if (slen <= 0) {
754             dmsg = dmsg->b_cont;
755             if (!dmsg)
756                 break;
757             rptr = dmsg->b_rptr;
758             continue;           /* skip zero-length buffers */
759         }
760         ilen += slen;
761
762         do {
763             c = *rptr++;
764             fcode = BSD_KEY(ent, c);
765             hval = BSD_HASH(ent, c, hshift);
766             dictp = &db->dict[hval];
767
768             /* validate and then check the entry */
769             if (dictp->codem1 >= max_ent)
770                 goto nomatch;
771             if (dictp->f.fcode == fcode) {
772                 ent = dictp->codem1+1;
773                 continue;   /* found (prefix,suffix) */
774             }
775
776             /* continue probing until a match or invalid entry */
777             disp = (hval == 0) ? 1 : hval;
778             do {
779                 hval += disp;
780                 if (hval >= db->hsize)
781                     hval -= db->hsize;
782                 dictp = &db->dict[hval];
783                 if (dictp->codem1 >= max_ent)
784                     goto nomatch;
785             } while (dictp->f.fcode != fcode);
786             ent = dictp->codem1+1;
787             continue;   /* finally found (prefix,suffix) */
788
789         nomatch:                /* output (count) the prefix */
790             bitno += n_bits;
791
792             /* code -> hashtable */
793             if (max_ent < db->maxmaxcode) {
794                 struct bsd_dict *dictp2;
795                 /* expand code size if needed */
796                 if (max_ent >= MAXCODE(n_bits))
797                     db->n_bits = ++n_bits;
798
799                 /* Invalidate previous hash table entry
800                  * assigned this code, and then take it over.
801                  */
802                 dictp2 = &db->dict[max_ent+1];
803                 if (db->dict[dictp2->cptr].codem1 == max_ent)
804                     db->dict[dictp2->cptr].codem1 = BADCODEM1;
805                 dictp2->cptr = hval;
806                 dictp->codem1 = max_ent;
807                 dictp->f.fcode = fcode;
808
809                 db->max_ent = ++max_ent;
810                 db->lens[max_ent] = db->lens[ent]+1;
811             }
812             ent = c;
813         } while (--slen != 0);
814     }
815     bitno += n_bits;            /* output (count) the last code */
816     db->bytes_out += bitno/8;
817     db->in_count += ilen;
818     (void)bsd_check(db);
819
820     ++db->incomp_count;
821     db->incomp_bytes += ilen;
822     ++db->uncomp_count;
823     db->uncomp_bytes += ilen;
824
825     /* Increase code size if we would have without the packet
826      * boundary and as the decompressor will.
827      */
828     if (max_ent >= MAXCODE(n_bits) && max_ent < db->maxmaxcode)
829         db->n_bits++;
830 }
831
832
833 /*
834  * Decompress "BSD Compress"
835  *
836  * Because of patent problems, we return DECOMP_ERROR for errors
837  * found by inspecting the input data and for system problems, but
838  * DECOMP_FATALERROR for any errors which could possibly be said to
839  * be being detected "after" decompression.  For DECOMP_ERROR,
840  * we can issue a CCP reset-request; for DECOMP_FATALERROR, we may be
841  * infringing a patent of Motorola's if we do, so we take CCP down
842  * instead.
843  *
844  * Given that the frame has the correct sequence number and a good FCS,
845  * errors such as invalid codes in the input most likely indicate a
846  * bug, so we return DECOMP_FATALERROR for them in order to turn off
847  * compression, even though they are detected by inspecting the input.
848  */
849 static int
850 bsd_decompress(state, cmsg, dmpp)
851     void *state;
852     mblk_t *cmsg, **dmpp;
853 {
854     struct bsd_db *db = (struct bsd_db *) state;
855     u_int max_ent = db->max_ent;
856     u_int32_t accm = 0;
857     u_int bitno = 32;           /* 1st valid bit in accm */
858     u_int n_bits = db->n_bits;
859     u_int tgtbitno = 32-n_bits; /* bitno when we have a code */
860     struct bsd_dict *dictp;
861     int explen, i, seq, len;
862     u_int incode, oldcode, finchar;
863     u_char *p, *rptr, *wptr;
864     mblk_t *dmsg, *mret;
865     int adrs, ctrl, ilen;
866     int dlen, space, codelen, extra;
867
868     /*
869      * Get at least the BSD Compress header in the first buffer
870      */
871     rptr = cmsg->b_rptr;
872     if (rptr + PPP_HDRLEN + BSD_OVHD >= cmsg->b_wptr) {
873         if (!pullupmsg(cmsg, PPP_HDRLEN + BSD_OVHD + 1)) {
874             if (db->debug)
875                 printf("bsd_decomp%d: failed to pullup\n", db->unit);
876             return DECOMP_ERROR;
877         }
878         rptr = cmsg->b_rptr;
879     }
880
881     /*
882      * Save the address/control from the PPP header
883      * and then get the sequence number.
884      */
885     adrs = PPP_ADDRESS(rptr);
886     ctrl = PPP_CONTROL(rptr);
887     rptr += PPP_HDRLEN;
888     seq = (rptr[0] << 8) + rptr[1];
889     rptr += BSD_OVHD;
890     ilen = len = cmsg->b_wptr - rptr;
891
892     /*
893      * Check the sequence number and give up if it is not what we expect.
894      */
895     if (seq != db->seqno++) {
896         if (db->debug)
897             printf("bsd_decomp%d: bad sequence # %d, expected %d\n",
898                    db->unit, seq, db->seqno - 1);
899         return DECOMP_ERROR;
900     }
901
902     /*
903      * Allocate one message block to start with.
904      */
905     if ((dmsg = allocb(DECOMP_CHUNK + db->hdrlen, BPRI_MED)) == NULL)
906         return DECOMP_ERROR;
907     mret = dmsg;
908     dmsg->b_wptr += db->hdrlen;
909     dmsg->b_rptr = wptr = dmsg->b_wptr;
910
911     /* Fill in the ppp header, but not the last byte of the protocol
912        (that comes from the decompressed data). */
913     wptr[0] = adrs;
914     wptr[1] = ctrl;
915     wptr[2] = 0;
916     wptr += PPP_HDRLEN - 1;
917     space = dmsg->b_datap->db_lim - wptr;
918
919     oldcode = CLEAR;
920     explen = 0;
921     for (;;) {
922         if (len == 0) {
923             cmsg = cmsg->b_cont;
924             if (!cmsg)          /* quit at end of message */
925                 break;
926             rptr = cmsg->b_rptr;
927             len = cmsg->b_wptr - rptr;
928             ilen += len;
929             continue;           /* handle 0-length buffers */
930         }
931
932         /*
933          * Accumulate bytes until we have a complete code.
934          * Then get the next code, relying on the 32-bit,
935          * unsigned accm to mask the result.
936          */
937         bitno -= 8;
938         accm |= *rptr++ << bitno;
939         --len;
940         if (tgtbitno < bitno)
941             continue;
942         incode = accm >> tgtbitno;
943         accm <<= n_bits;
944         bitno += n_bits;
945
946         if (incode == CLEAR) {
947             /*
948              * The dictionary must only be cleared at
949              * the end of a packet.  But there could be an
950              * empty message block at the end.
951              */
952             if (len > 0 || cmsg->b_cont != 0) {
953                 if (cmsg->b_cont)
954                     len += msgdsize(cmsg->b_cont);
955                 if (len > 0) {
956                     freemsg(dmsg);
957                     if (db->debug)
958                         printf("bsd_decomp%d: bad CLEAR\n", db->unit);
959                     return DECOMP_FATALERROR;
960                 }
961             }
962             bsd_clear(db);
963             explen = ilen = 0;
964             break;
965         }
966
967         if (incode > max_ent + 2 || incode > db->maxmaxcode
968             || incode > max_ent && oldcode == CLEAR) {
969             freemsg(dmsg);
970             if (db->debug) {
971                 printf("bsd_decomp%d: bad code 0x%x oldcode=0x%x ",
972                        db->unit, incode, oldcode);
973                 printf("max_ent=0x%x dlen=%d seqno=%d\n",
974                        max_ent, dlen, db->seqno);
975             }
976             return DECOMP_FATALERROR;   /* probably a bug */
977         }
978
979         /* Special case for KwKwK string. */
980         if (incode > max_ent) {
981             finchar = oldcode;
982             extra = 1;
983         } else {
984             finchar = incode;
985             extra = 0;
986         }
987
988         codelen = db->lens[finchar];
989         explen += codelen + extra;
990         if (explen > db->mru + 1) {
991             freemsg(dmsg);
992             if (db->debug)
993                 printf("bsd_decomp%d: ran out of mru\n", db->unit);
994             return DECOMP_FATALERROR;
995         }
996
997         /*
998          * Decode this code and install it in the decompressed buffer.
999          */
1000         space -= codelen + extra;
1001         if (space < 0) {
1002             /* Allocate another message block. */
1003             dmsg->b_wptr = wptr;
1004             dlen = codelen + extra;
1005             if (dlen < DECOMP_CHUNK)
1006                 dlen = DECOMP_CHUNK;
1007             if ((dmsg->b_cont = allocb(dlen, BPRI_MED)) == NULL) {
1008                 freemsg(dmsg);
1009                 return DECOMP_ERROR;
1010             }
1011             dmsg = dmsg->b_cont;
1012             wptr = dmsg->b_wptr;
1013             space = dmsg->b_datap->db_lim - wptr - codelen - extra;
1014         }
1015         p = (wptr += codelen);
1016         while (finchar > LAST) {
1017             dictp = &db->dict[db->dict[finchar].cptr];
1018 #ifdef DEBUG
1019             --codelen;
1020             if (codelen <= 0) {
1021                 freemsg(dmsg);
1022                 printf("bsd_decomp%d: fell off end of chain ", db->unit);
1023                 printf("0x%x at 0x%x by 0x%x, max_ent=0x%x\n",
1024                        incode, finchar, db->dict[finchar].cptr, max_ent);
1025                 return DECOMP_FATALERROR;
1026             }
1027             if (dictp->codem1 != finchar-1) {
1028                 freemsg(dmsg);
1029                 printf("bsd_decomp%d: bad code chain 0x%x finchar=0x%x ",
1030                        db->unit, incode, finchar);
1031                 printf("oldcode=0x%x cptr=0x%x codem1=0x%x\n", oldcode,
1032                        db->dict[finchar].cptr, dictp->codem1);
1033                 return DECOMP_FATALERROR;
1034             }
1035 #endif
1036             *--p = dictp->f.hs.suffix;
1037             finchar = dictp->f.hs.prefix;
1038         }
1039         *--p = finchar;
1040
1041 #ifdef DEBUG
1042         if (--codelen != 0)
1043             printf("bsd_decomp%d: short by %d after code 0x%x, max_ent=0x%x\n",
1044                    db->unit, codelen, incode, max_ent);
1045 #endif
1046
1047         if (extra)              /* the KwKwK case again */
1048             *wptr++ = finchar;
1049
1050         /*
1051          * If not first code in a packet, and
1052          * if not out of code space, then allocate a new code.
1053          *
1054          * Keep the hash table correct so it can be used
1055          * with uncompressed packets.
1056          */
1057         if (oldcode != CLEAR && max_ent < db->maxmaxcode) {
1058             struct bsd_dict *dictp2;
1059             u_int32_t fcode;
1060             int hval, disp;
1061
1062             fcode = BSD_KEY(oldcode,finchar);
1063             hval = BSD_HASH(oldcode,finchar,db->hshift);
1064             dictp = &db->dict[hval];
1065
1066             /* look for a free hash table entry */
1067             if (dictp->codem1 < max_ent) {
1068                 disp = (hval == 0) ? 1 : hval;
1069                 do {
1070                     hval += disp;
1071                     if (hval >= db->hsize)
1072                         hval -= db->hsize;
1073                     dictp = &db->dict[hval];
1074                 } while (dictp->codem1 < max_ent);
1075             }
1076
1077             /*
1078              * Invalidate previous hash table entry
1079              * assigned this code, and then take it over
1080              */
1081             dictp2 = &db->dict[max_ent+1];
1082             if (db->dict[dictp2->cptr].codem1 == max_ent) {
1083                 db->dict[dictp2->cptr].codem1 = BADCODEM1;
1084             }
1085             dictp2->cptr = hval;
1086             dictp->codem1 = max_ent;
1087             dictp->f.fcode = fcode;
1088
1089             db->max_ent = ++max_ent;
1090             db->lens[max_ent] = db->lens[oldcode]+1;
1091
1092             /* Expand code size if needed. */
1093             if (max_ent >= MAXCODE(n_bits) && max_ent < db->maxmaxcode) {
1094                 db->n_bits = ++n_bits;
1095                 tgtbitno = 32-n_bits;
1096             }
1097         }
1098         oldcode = incode;
1099     }
1100     dmsg->b_wptr = wptr;
1101
1102     /*
1103      * Keep the checkpoint right so that incompressible packets
1104      * clear the dictionary at the right times.
1105      */
1106     db->bytes_out += ilen;
1107     db->in_count += explen;
1108     if (bsd_check(db) && db->debug) {
1109         printf("bsd_decomp%d: peer should have cleared dictionary\n",
1110                db->unit);
1111     }
1112
1113     ++db->comp_count;
1114     db->comp_bytes += ilen + BSD_OVHD;
1115     ++db->uncomp_count;
1116     db->uncomp_bytes += explen;
1117
1118     *dmpp = mret;
1119     return DECOMP_OK;
1120 }