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