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