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