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