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