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