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