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