]> git.ozlabs.org Git - ppp.git/blob - modules/bsd-comp.c
fix null deref and packet length check (off by 1)
[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     /*
496      * Copy the PPP header over, changing the protocol,
497      * and install the 3-byte sequence number.
498      */
499     slen += db->seqno - PPP_HDRLEN + 1;
500     db->seqno = slen;
501     if (wptr) {
502         wptr[0] = rptr[0];      /* assumes the ppp header is */
503         wptr[1] = rptr[1];      /* all in one mblk */
504         wptr[2] = 0;            /* change the protocol */
505         wptr[3] = PPP_COMP;
506         wptr[4] = slen>>16;
507         wptr[5] = slen>>8;
508         wptr[6] = slen;
509         wptr += PPP_HDRLEN + BSD_OVHD;
510     }
511
512     /* start with the protocol byte */
513     ent = rptr[3];
514     rptr += PPP_HDRLEN;
515     slen = mp->b_wptr - rptr;
516     db->in_count += slen + 1;
517     np = mp->b_cont;
518     for (;;) {
519         if (slen <= 0) {
520             if (!np)
521                 break;
522             rptr = np->b_rptr;
523             slen = np->b_wptr - rptr;
524             np = np->b_cont;
525             if (!slen)
526                 continue;   /* handle 0-length buffers */
527             db->in_count += slen;
528         }
529
530         slen--;
531         c = *rptr++;
532         fcode = BSD_KEY(ent, c);
533         hval = BSD_HASH(ent, c, hshift);
534         dictp = &db->dict[hval];
535
536         /* Validate and then check the entry. */
537         if (dictp->codem1 >= max_ent)
538             goto nomatch;
539         if (dictp->f.fcode == fcode) {
540             ent = dictp->codem1+1;
541             continue;   /* found (prefix,suffix) */
542         }
543
544         /* continue probing until a match or invalid entry */
545         disp = (hval == 0) ? 1 : hval;
546         do {
547             hval += disp;
548             if (hval >= db->hsize)
549                 hval -= db->hsize;
550             dictp = &db->dict[hval];
551             if (dictp->codem1 >= max_ent)
552                 goto nomatch;
553         } while (dictp->f.fcode != fcode);
554         ent = dictp->codem1+1;          /* finally found (prefix,suffix) */
555         continue;
556
557     nomatch:
558         OUTPUT(ent);            /* output the prefix */
559
560         /* code -> hashtable */
561         if (max_ent < db->maxmaxcode) {
562             struct bsd_dict *dictp2;
563             /* expand code size if needed */
564             if (max_ent >= MAXCODE(n_bits))
565                 db->n_bits = ++n_bits;
566
567             /* Invalidate old hash table entry using
568              * this code, and then take it over.
569              */
570             dictp2 = &db->dict[max_ent+1];
571             if (db->dict[dictp2->cptr].codem1 == max_ent)
572                 db->dict[dictp2->cptr].codem1 = BADCODEM1;
573             dictp2->cptr = hval;
574             dictp->codem1 = max_ent;
575             dictp->f.fcode = fcode;
576
577             db->max_ent = ++max_ent;
578         }
579         ent = c;
580     }
581
582     OUTPUT(ent);                        /* output the last code */
583     db->bytes_out += olen;
584
585     if (bsd_check(db))
586         OUTPUT(CLEAR);                  /* do not count the CLEAR */
587
588     /* Pad dribble bits of last code with ones.
589      * Do not emit a completely useless byte of ones.
590      */
591     if (bitno != 32)
592         PUTBYTE((accm | (0xff << (bitno-8))) >> 24);
593
594     /* Increase code size if we would have without the packet
595      * boundary and as the decompressor will.
596      */
597     if (max_ent >= MAXCODE(n_bits) && max_ent < db->maxmaxcode)
598         db->n_bits++;
599
600     if (olen + PPP_HDRLEN + BSD_OVHD > maxolen && *mret != NULL) {
601         /* throw away the compressed stuff if it is longer than uncompressed */
602         freemsg(*mret);
603         *mret = NULL;
604     } else if (wptr != NULL) {
605         m->b_wptr = wptr;
606         if (m->b_cont) {
607             freemsg(m->b_cont);
608             m->b_cont = NULL;
609         }
610     }
611
612     return olen + PPP_HDRLEN + BSD_OVHD;
613 #undef OUTPUT
614 #undef PUTBYTE
615 }
616
617
618 /*
619  * Update the "BSD Compress" dictionary on the receiver for
620  * incompressible data by pretending to compress the incoming data.
621  * The protocol is assumed to be < 0x100.
622  */
623 static void
624 bsd_incomp(state, dmsg)
625     void *state;
626     mblk_t *dmsg;
627 {
628     struct bsd_db *db = (struct bsd_db *) state;
629     u_int hshift = db->hshift;
630     u_int max_ent = db->max_ent;
631     u_int n_bits = db->n_bits;
632     struct bsd_dict *dictp;
633     u_long fcode;
634     u_char c;
635     long hval, disp;
636     int slen;
637     u_int bitno = 7;
638     u_char *rptr;
639     u_int ent;
640
641     db->incomp_count++;
642
643     db->seqno++;
644     db->in_count++;             /* count the protocol as 1 byte */
645     rptr = dmsg->b_rptr;
646     ent = rptr[3];              /* get the protocol */
647     rptr += PPP_HDRLEN;
648     for (;;) {
649         slen = dmsg->b_wptr - rptr;
650         if (slen <= 0) {
651             dmsg = dmsg->b_cont;
652             if (!dmsg)
653                 break;
654             rptr = dmsg->b_rptr;
655             continue;           /* skip zero-length buffers */
656         }
657         db->in_count += slen;
658         db->seqno += slen;
659
660         do {
661             c = *rptr++;
662             fcode = BSD_KEY(ent, c);
663             hval = BSD_HASH(ent, c, hshift);
664             dictp = &db->dict[hval];
665
666             /* validate and then check the entry */
667             if (dictp->codem1 >= max_ent)
668                 goto nomatch;
669             if (dictp->f.fcode == fcode) {
670                 ent = dictp->codem1+1;
671                 continue;   /* found (prefix,suffix) */
672             }
673
674             /* continue probing until a match or invalid entry */
675             disp = (hval == 0) ? 1 : hval;
676             do {
677                 hval += disp;
678                 if (hval >= db->hsize)
679                     hval -= db->hsize;
680                 dictp = &db->dict[hval];
681                 if (dictp->codem1 >= max_ent)
682                     goto nomatch;
683             } while (dictp->f.fcode != fcode);
684             ent = dictp->codem1+1;
685             continue;   /* finally found (prefix,suffix) */
686
687         nomatch:                /* output (count) the prefix */
688             bitno += n_bits;
689
690             /* code -> hashtable */
691             if (max_ent < db->maxmaxcode) {
692                 struct bsd_dict *dictp2;
693                 /* expand code size if needed */
694                 if (max_ent >= MAXCODE(n_bits))
695                     db->n_bits = ++n_bits;
696
697                 /* Invalidate previous hash table entry
698                  * assigned this code, and then take it over.
699                  */
700                 dictp2 = &db->dict[max_ent+1];
701                 if (db->dict[dictp2->cptr].codem1 == max_ent)
702                     db->dict[dictp2->cptr].codem1 = BADCODEM1;
703                 dictp2->cptr = hval;
704                 dictp->codem1 = max_ent;
705                 dictp->f.fcode = fcode;
706
707                 db->max_ent = ++max_ent;
708                 db->lens[max_ent] = db->lens[ent]+1;
709             }
710             ent = c;
711         } while (--slen != 0);
712     }
713     bitno += n_bits;            /* output (count) the last code */
714     db->bytes_out += bitno/8;
715     (void)bsd_check(db);
716
717     /* Increase code size if we would have without the packet
718      * boundary and as the decompressor will.
719      */
720     if (max_ent >= MAXCODE(n_bits) && max_ent < db->maxmaxcode)
721         db->n_bits++;
722 }
723
724
725 /*
726  * Decompress "BSD Compress"
727  */
728 static mblk_t *                         /* 0=failed, so zap CCP */
729 bsd_decompress(state, cmsg, hdroff)
730     void *state;
731     mblk_t *cmsg;
732     int hdroff;
733 {
734     struct bsd_db *db = (struct bsd_db *) state;
735     u_int max_ent = db->max_ent;
736     u_long accm = 0;
737     u_int bitno = 32;           /* 1st valid bit in accm */
738     u_int n_bits = db->n_bits;
739     u_int tgtbitno = 32-n_bits; /* bitno when we have a code */
740     struct bsd_dict *dictp;
741     int explen, i, seq, len;
742     u_int incode, oldcode, finchar;
743     u_char *p, *rptr, *wptr;
744     mblk_t *dmsg;
745     int adrs, ctrl;
746     int dlen, space, codelen;
747
748     /*
749      * Get at least the BSD Compress header in the first buffer
750      */
751     rptr = cmsg->b_rptr;
752     if (rptr + PPP_HDRLEN + BSD_OVHD <= cmsg->b_wptr) {
753         if (!pullupmsg(cmsg, PPP_HDRLEN + BSD_OVHD + 1)) {
754             if (db->debug)
755                 printf("bsd_decomp%d: failed to pullup\n", db->unit);
756             return 0;
757         }
758         rptr = cmsg->b_rptr;
759     }
760
761     /*
762      * Save the address/control from the PPP header
763      * and then get the sequence number.
764      */
765     adrs = PPP_ADDRESS(rptr);
766     ctrl = PPP_CONTROL(rptr);
767     rptr += PPP_HDRLEN;
768     seq = (rptr[0] << 16) + (rptr[1] << 8) + rptr[2];
769     rptr += 3;
770     len = cmsg->b_wptr - rptr;
771
772     /*
773      * Check the sequence number and give up if the length is nonsense.
774      * The check is against mru+1 because we compress one byte of protocol.
775      */
776     explen = (seq - db->seqno) & 0xffffff;
777     db->seqno = seq;
778     if (explen > db->mru + 1 || explen < 1) {
779         if (db->debug)
780             printf("bsd_decomp%d: bad length 0x%x\n", db->unit, explen);
781         return 0;
782     }
783
784     /* allocate enough message blocks for the decompressed message */
785     dlen = explen + PPP_HDRLEN - 1 + hdroff;
786     /* XXX assume decompressed packet fits in a single block */
787     dmsg = allocb(dlen, BPRI_HI);
788     if (!dmsg) {
789         /* give up if cannot get an uncompressed buffer */
790         return 0;
791     }
792     wptr = dmsg->b_wptr;
793
794     /* Fill in the ppp header, but not the last byte of the protocol
795        (that comes from the decompressed data). */
796     wptr[0] = adrs;
797     wptr[1] = ctrl;
798     wptr[2] = 0;
799     wptr += PPP_HDRLEN - 1;
800     space = dmsg->b_datap->db_lim - wptr;
801
802     db->bytes_out += len;
803     dlen = explen;
804     oldcode = CLEAR;
805     for (;;) {
806         if (len == 0) {
807             cmsg = cmsg->b_cont;
808             if (!cmsg) {        /* quit at end of message */
809                 if (dlen != 0) {
810                     freemsg(dmsg);
811                     if (db->debug)
812                         printf("bsd_decomp%d: lost %d bytes\n",
813                                db->unit, explen);
814                     return 0;
815                 }
816                 break;
817             }
818             rptr = cmsg->b_rptr;
819             len = cmsg->b_wptr - rptr;
820             db->bytes_out += len;
821             continue;           /* handle 0-length buffers */
822         }
823
824         /* Accumulate bytes until we have a complete code.
825          * Then get the next code, relying on the 32-bit,
826          * unsigned accm to mask the result.
827          */
828         bitno -= 8;
829         accm |= *rptr++ << bitno;
830         --len;
831         if (tgtbitno < bitno)
832             continue;
833         incode = accm >> tgtbitno;
834         accm <<= n_bits;
835         bitno += n_bits;
836
837         if (incode == CLEAR) {
838             /* The dictionary must only be cleared at
839              * the end of a packet.  But there could be an
840              * empty message block at the end.
841              */
842             if (len > 0 || cmsg->b_cont != 0) {
843                 if (cmsg->b_cont)
844                     len += msgdsize(cmsg->b_cont);
845                 if (len > 0) {
846                     freemsg(dmsg);
847                     if (db->debug)
848                         printf("bsd_decomp%d: bad CLEAR\n", db->unit);
849                     return 0;
850                 }
851             }
852             bsd_clear(db);
853             explen = 0;
854             break;
855         }
856
857         /* Special case for KwKwK string. */
858         if (incode > max_ent) {
859             if (incode > max_ent+2 || incode > db->maxmaxcode
860                 || oldcode == CLEAR) {
861                 freemsg(dmsg);
862                 if (db->debug) {
863                     printf("bsd_decomp%d: bad code 0x%x oldcode=0x%x ",
864                            db->unit, incode, oldcode);
865                     printf("max_ent=0x%x dlen=%d seqno=%d\n",
866                            max_ent, dlen, db->seqno);
867                 }
868                 return 0;
869             }
870             finchar = oldcode;
871             --dlen;
872         } else
873             finchar = incode;
874
875         codelen = db->lens[finchar];
876         dlen -= codelen;
877         if (dlen < 0) {
878             freemsg(dmsg);
879             if (db->debug)
880                 printf("bsd_decomp%d: ran out of buffer\n", db->unit);
881             return 0;
882         }
883
884         /* decode code and install in decompressed buffer */
885         space -= codelen;
886         if (space < 0) {
887 #ifdef DEBUG
888             if (cmsg->b_cont)
889                 len += msgdsize(cmsg->b_cont);
890             printf("bsd_decomp%d: overran output by %d with %d bytes left\n",
891                    db->unit, -space, len);
892 #endif
893             freemsg(dmsg);
894             return 0;
895         }
896         p = (wptr += codelen);
897         while (finchar > LAST) {
898             dictp = &db->dict[db->dict[finchar].cptr];
899 #ifdef DEBUG
900             --codelen;
901             if (codelen <= 0) {
902                 freemsg(dmsg);
903                 printf("bsd_decomp%d: fell off end of chain ", db->unit);
904                 printf("0x%x at 0x%x by 0x%x, max_ent=0x%x\n",
905                        incode, finchar, db->dict[finchar].cptr, max_ent);
906                 return 0;
907             }
908             if (dictp->codem1 != finchar-1) {
909                 freemsg(dmsg);
910                 printf("bsd_decomp%d: bad code chain 0x%x finchar=0x%x ",
911                        db->unit, incode, finchar);
912                 printf("oldcode=0x%x cptr=0x%x codem1=0x%x\n", oldcode,
913                        db->dict[finchar].cptr, dictp->codem1);
914                 return 0;
915             }
916 #endif
917             *--p = dictp->f.hs.suffix;
918             finchar = dictp->f.hs.prefix;
919         }
920         *--p = finchar;
921
922 #ifdef DEBUG
923         if (--codelen != 0)
924             printf("bsd_decomp%d: short by %d after code 0x%x, max_ent=0x%x\n",
925                    db->unit, codelen, incode, max_ent);
926 #endif
927
928         if (incode > max_ent) {         /* the KwKwK case again */
929             *wptr++ = finchar;
930             --space;
931         }
932
933         /*
934          * If not first code in a packet, and
935          * if not out of code space, then allocate a new code.
936          *
937          * Keep the hash table correct so it can be used
938          * with uncompressed packets.
939          */
940         if (oldcode != CLEAR && max_ent < db->maxmaxcode) {
941             struct bsd_dict *dictp2;
942             u_long fcode;
943             long hval, disp;
944
945             fcode = BSD_KEY(oldcode,finchar);
946             hval = BSD_HASH(oldcode,finchar,db->hshift);
947             dictp = &db->dict[hval];
948
949             /* look for a free hash table entry */
950             if (dictp->codem1 < max_ent) {
951                 disp = (hval == 0) ? 1 : hval;
952                 do {
953                     hval += disp;
954                     if (hval >= db->hsize)
955                         hval -= db->hsize;
956                     dictp = &db->dict[hval];
957                 } while (dictp->codem1 < max_ent);
958             }
959
960             /* Invalidate previous hash table entry
961              * assigned this code, and then take it over
962              */
963             dictp2 = &db->dict[max_ent+1];
964             if (db->dict[dictp2->cptr].codem1 == max_ent) {
965                 db->dict[dictp2->cptr].codem1 = BADCODEM1;
966             }
967             dictp2->cptr = hval;
968             dictp->codem1 = max_ent;
969             dictp->f.fcode = fcode;
970
971             db->max_ent = ++max_ent;
972             db->lens[max_ent] = db->lens[oldcode]+1;
973
974             /* Expand code size if needed. */
975             if (max_ent >= MAXCODE(n_bits) && max_ent < db->maxmaxcode) {
976                 db->n_bits = ++n_bits;
977                 tgtbitno = 32-n_bits;
978             }
979         }
980         oldcode = incode;
981     }
982     dmsg->b_wptr = wptr;
983
984     /* fail on packets with bad lengths/sequence numbers */
985     if (dlen != 0) {
986         freemsg(dmsg);
987         return 0;
988     }
989
990     /* Keep the checkpoint right so that incompressible packets
991      * clear the dictionary at the right times.
992      */
993     db->in_count += explen;
994     if (bsd_check(db) && db->debug) {
995         printf("bsd_decomp%d: peer should have cleared dictionary\n",
996                db->unit);
997     }
998
999     return dmsg;
1000 }