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