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