]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/net/bsd_comp.c
This commit was generated by cvs2svn to compensate for changes in r75937,
[FreeBSD/FreeBSD.git] / sys / net / 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  * $FreeBSD$
44  */
45
46 #include <sys/param.h>
47 #include <sys/systm.h>
48 #include <sys/malloc.h>
49 #include <sys/mbuf.h>
50 #include <net/ppp_defs.h>
51
52 #define PACKETPTR       struct mbuf *
53 #include <net/ppp_comp.h>
54
55 /*
56  * PPP "BSD compress" compression
57  *  The differences between this compression and the classic BSD LZW
58  *  source are obvious from the requirement that the classic code worked
59  *  with files while this handles arbitrarily long streams that
60  *  are broken into packets.  They are:
61  *
62  *      When the code size expands, a block of junk is not emitted by
63  *          the compressor and not expected by the decompressor.
64  *
65  *      New codes are not necessarily assigned every time an old
66  *          code is output by the compressor.  This is because a packet
67  *          end forces a code to be emitted, but does not imply that a
68  *          new sequence has been seen.
69  *
70  *      The compression ratio is checked at the first end of a packet
71  *          after the appropriate gap.  Besides simplifying and speeding
72  *          things up, this makes it more likely that the transmitter
73  *          and receiver will agree when the dictionary is cleared when
74  *          compression is not going well.
75  */
76
77 /*
78  * A dictionary for doing BSD compress.
79  */
80 struct bsd_db {
81     int     totlen;                     /* length of this structure */
82     u_int   hsize;                      /* size of the hash table */
83     u_char  hshift;                     /* used in hash function */
84     u_char  n_bits;                     /* current bits/code */
85     u_char  maxbits;
86     u_char  debug;
87     u_char  unit;
88     u_int16_t seqno;                    /* sequence # of next packet */
89     u_int   hdrlen;                     /* header length to preallocate */
90     u_int   mru;
91     u_int   maxmaxcode;                 /* largest valid code */
92     u_int   max_ent;                    /* largest code in use */
93     u_int   in_count;                   /* uncompressed bytes, aged */
94     u_int   bytes_out;                  /* compressed bytes, aged */
95     u_int   ratio;                      /* recent compression ratio */
96     u_int   checkpoint;                 /* when to next check the ratio */
97     u_int   clear_count;                /* times dictionary cleared */
98     u_int   incomp_count;               /* incompressible packets */
99     u_int   incomp_bytes;               /* incompressible bytes */
100     u_int   uncomp_count;               /* uncompressed packets */
101     u_int   uncomp_bytes;               /* uncompressed bytes */
102     u_int   comp_count;                 /* compressed packets */
103     u_int   comp_bytes;                 /* compressed bytes */
104     u_int16_t *lens;                    /* array of lengths of codes */
105     struct bsd_dict {
106         union {                         /* hash value */
107             u_int32_t   fcode;
108             struct {
109 #if BYTE_ORDER == LITTLE_ENDIAN
110                 u_int16_t prefix;       /* preceding code */
111                 u_char  suffix;         /* last character of new code */
112                 u_char  pad;
113 #else
114                 u_char  pad;
115                 u_char  suffix;         /* last character of new code */
116                 u_int16_t prefix;       /* preceding code */
117 #endif
118             } hs;
119         } f;
120         u_int16_t codem1;               /* output of hash table -1 */
121         u_int16_t cptr;                 /* map code to hash table entry */
122     } dict[1];
123 };
124
125 #define BSD_OVHD        2               /* BSD compress overhead/packet */
126 #define BSD_INIT_BITS   BSD_MIN_BITS
127
128 static void     bsd_clear __P((struct bsd_db *db));
129 static int      bsd_check __P((struct bsd_db *db));
130 static void     *bsd_alloc __P((u_char *options, int opt_len, int decomp));
131 static int      bsd_init __P((struct bsd_db *db, u_char *options, int opt_len,
132                               int unit, int hdrlen, int mru, int debug,
133                               int decomp));
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  * the next two codes should not be changed lightly, as they must not
171  * lie within the contiguous general code space.
172  */
173 #define CLEAR   256                     /* table clear output code */
174 #define FIRST   257                     /* first free entry */
175 #define LAST    255
176
177 #define MAXCODE(b)      ((1 << (b)) - 1)
178 #define BADCODEM1       MAXCODE(BSD_MAX_BITS)
179
180 #define BSD_HASH(prefix,suffix,hshift)  ((((u_int32_t)(suffix)) << (hshift)) \
181                                          ^ (u_int32_t)(prefix))
182 #define BSD_KEY(prefix,suffix)          ((((u_int32_t)(suffix)) << 16) \
183                                          + (u_int32_t)(prefix))
184
185 #define CHECK_GAP       10000           /* Ratio check interval */
186
187 #define RATIO_SCALE_LOG 8
188 #define RATIO_SCALE     (1<<RATIO_SCALE_LOG)
189 #define RATIO_MAX       (0x7fffffff>>RATIO_SCALE_LOG)
190
191 /*
192  * clear the dictionary
193  */
194 static void
195 bsd_clear(db)
196     struct bsd_db *db;
197 {
198     db->clear_count++;
199     db->max_ent = FIRST-1;
200     db->n_bits = BSD_INIT_BITS;
201     db->ratio = 0;
202     db->bytes_out = 0;
203     db->in_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     u_char *rptr, *wptr;
484     u_char *cp_end;
485     int olen;
486     struct mbuf *m;
487
488 #define PUTBYTE(v) {                                    \
489     ++olen;                                             \
490     if (wptr) {                                         \
491         *wptr++ = (v);                                  \
492         if (wptr >= cp_end) {                           \
493             m->m_len = wptr - mtod(m, u_char *);        \
494             MGET(m->m_next, M_DONTWAIT, MT_DATA);       \
495             m = m->m_next;                              \
496             if (m) {                                    \
497                 m->m_len = 0;                           \
498                 if (maxolen - olen > MLEN)              \
499                     MCLGET(m, M_DONTWAIT);              \
500                 wptr = mtod(m, u_char *);               \
501                 cp_end = wptr + M_TRAILINGSPACE(m);     \
502             } else                                      \
503                 wptr = NULL;                            \
504         }                                               \
505     }                                                   \
506 }
507
508 #define OUTPUT(ent) {                                   \
509     bitno -= n_bits;                                    \
510     accm |= ((ent) << bitno);                           \
511     do {                                                \
512         PUTBYTE(accm >> 24);                            \
513         accm <<= 8;                                     \
514         bitno += 8;                                     \
515     } while (bitno <= 24);                              \
516 }
517
518     /*
519      * If the protocol is not in the range we're interested in,
520      * just return without compressing the packet.  If it is,
521      * the protocol becomes the first byte to compress.
522      */
523     rptr = mtod(mp, u_char *);
524     ent = PPP_PROTOCOL(rptr);
525     if (ent < 0x21 || ent > 0xf9) {
526         *mret = NULL;
527         return slen;
528     }
529
530     /* Don't generate compressed packets which are larger than
531        the uncompressed packet. */
532     if (maxolen > slen)
533         maxolen = slen;
534
535     /* Allocate one mbuf to start with. */
536     MGET(m, M_DONTWAIT, MT_DATA);
537     *mret = m;
538     if (m != NULL) {
539         m->m_len = 0;
540         if (maxolen + db->hdrlen > MLEN)
541             MCLGET(m, M_DONTWAIT);
542         m->m_data += db->hdrlen;
543         wptr = mtod(m, u_char *);
544         cp_end = wptr + M_TRAILINGSPACE(m);
545     } else
546         wptr = cp_end = NULL;
547
548     /*
549      * Copy the PPP header over, changing the protocol,
550      * and install the 2-byte packet sequence number.
551      */
552     if (wptr) {
553         *wptr++ = PPP_ADDRESS(rptr);    /* assumes the ppp header is */
554         *wptr++ = PPP_CONTROL(rptr);    /* all in one mbuf */
555         *wptr++ = 0;                    /* change the protocol */
556         *wptr++ = PPP_COMP;
557         *wptr++ = db->seqno >> 8;
558         *wptr++ = db->seqno;
559     }
560     ++db->seqno;
561
562     olen = 0;
563     rptr += PPP_HDRLEN;
564     slen = mp->m_len - PPP_HDRLEN;
565     ilen = slen + 1;
566     for (;;) {
567         if (slen <= 0) {
568             mp = mp->m_next;
569             if (!mp)
570                 break;
571             rptr = mtod(mp, u_char *);
572             slen = mp->m_len;
573             if (!slen)
574                 continue;   /* handle 0-length buffers */
575             ilen += slen;
576         }
577
578         slen--;
579         c = *rptr++;
580         fcode = BSD_KEY(ent, c);
581         hval = BSD_HASH(ent, c, hshift);
582         dictp = &db->dict[hval];
583
584         /* Validate and then check the entry. */
585         if (dictp->codem1 >= max_ent)
586             goto nomatch;
587         if (dictp->f.fcode == fcode) {
588             ent = dictp->codem1+1;
589             continue;   /* found (prefix,suffix) */
590         }
591
592         /* continue probing until a match or invalid entry */
593         disp = (hval == 0) ? 1 : hval;
594         do {
595             hval += disp;
596             if (hval >= db->hsize)
597                 hval -= db->hsize;
598             dictp = &db->dict[hval];
599             if (dictp->codem1 >= max_ent)
600                 goto nomatch;
601         } while (dictp->f.fcode != fcode);
602         ent = dictp->codem1 + 1;        /* finally found (prefix,suffix) */
603         continue;
604
605     nomatch:
606         OUTPUT(ent);            /* output the prefix */
607
608         /* code -> hashtable */
609         if (max_ent < db->maxmaxcode) {
610             struct bsd_dict *dictp2;
611             /* expand code size if needed */
612             if (max_ent >= MAXCODE(n_bits))
613                 db->n_bits = ++n_bits;
614
615             /* Invalidate old hash table entry using
616              * this code, and then take it over.
617              */
618             dictp2 = &db->dict[max_ent+1];
619             if (db->dict[dictp2->cptr].codem1 == max_ent)
620                 db->dict[dictp2->cptr].codem1 = BADCODEM1;
621             dictp2->cptr = hval;
622             dictp->codem1 = max_ent;
623             dictp->f.fcode = fcode;
624
625             db->max_ent = ++max_ent;
626         }
627         ent = c;
628     }
629
630     OUTPUT(ent);                /* output the last code */
631     db->bytes_out += olen;
632     db->in_count += ilen;
633     if (bitno < 32)
634         ++db->bytes_out;        /* count complete bytes */
635
636     if (bsd_check(db))
637         OUTPUT(CLEAR);          /* do not count the CLEAR */
638
639     /*
640      * Pad dribble bits of last code with ones.
641      * Do not emit a completely useless byte of ones.
642      */
643     if (bitno != 32)
644         PUTBYTE((accm | (0xff << (bitno-8))) >> 24);
645
646     if (m != NULL) {
647         m->m_len = wptr - mtod(m, u_char *);
648         m->m_next = NULL;
649     }
650
651     /*
652      * Increase code size if we would have without the packet
653      * boundary and as the decompressor will.
654      */
655     if (max_ent >= MAXCODE(n_bits) && max_ent < db->maxmaxcode)
656         db->n_bits++;
657
658     db->uncomp_bytes += ilen;
659     ++db->uncomp_count;
660     if (olen + PPP_HDRLEN + BSD_OVHD > maxolen) {
661         /* throw away the compressed stuff if it is longer than uncompressed */
662         if (*mret != NULL) {
663             m_freem(*mret);
664             *mret = NULL;
665         }
666         ++db->incomp_count;
667         db->incomp_bytes += ilen;
668     } else {
669         ++db->comp_count;
670         db->comp_bytes += olen + BSD_OVHD;
671     }
672
673     return olen + PPP_HDRLEN + BSD_OVHD;
674 #undef OUTPUT
675 #undef PUTBYTE
676 }
677
678
679 /*
680  * Update the "BSD Compress" dictionary on the receiver for
681  * incompressible data by pretending to compress the incoming data.
682  */
683 static void
684 bsd_incomp(state, dmsg)
685     void *state;
686     struct mbuf *dmsg;
687 {
688     struct bsd_db *db = (struct bsd_db *) state;
689     u_int hshift = db->hshift;
690     u_int max_ent = db->max_ent;
691     u_int n_bits = db->n_bits;
692     struct bsd_dict *dictp;
693     u_int32_t fcode;
694     u_char c;
695     u_int32_t hval, disp;
696     int slen, ilen;
697     u_int bitno = 7;
698     u_char *rptr;
699     u_int ent;
700
701     /*
702      * If the protocol is not in the range we're interested in,
703      * just return without looking at the packet.  If it is,
704      * the protocol becomes the first byte to "compress".
705      */
706     rptr = mtod(dmsg, u_char *);
707     ent = PPP_PROTOCOL(rptr);
708     if (ent < 0x21 || ent > 0xf9)
709         return;
710
711     db->seqno++;
712     ilen = 1;           /* count the protocol as 1 byte */
713     rptr += PPP_HDRLEN;
714     slen = dmsg->m_len - PPP_HDRLEN;
715     for (;;) {
716         if (slen <= 0) {
717             dmsg = dmsg->m_next;
718             if (!dmsg)
719                 break;
720             rptr = mtod(dmsg, u_char *);
721             slen = dmsg->m_len;
722             continue;
723         }
724         ilen += slen;
725
726         do {
727             c = *rptr++;
728             fcode = BSD_KEY(ent, c);
729             hval = BSD_HASH(ent, c, hshift);
730             dictp = &db->dict[hval];
731
732             /* validate and then check the entry */
733             if (dictp->codem1 >= max_ent)
734                 goto nomatch;
735             if (dictp->f.fcode == fcode) {
736                 ent = dictp->codem1+1;
737                 continue;   /* found (prefix,suffix) */
738             }
739
740             /* continue probing until a match or invalid entry */
741             disp = (hval == 0) ? 1 : hval;
742             do {
743                 hval += disp;
744                 if (hval >= db->hsize)
745                     hval -= db->hsize;
746                 dictp = &db->dict[hval];
747                 if (dictp->codem1 >= max_ent)
748                     goto nomatch;
749             } while (dictp->f.fcode != fcode);
750             ent = dictp->codem1+1;
751             continue;   /* finally found (prefix,suffix) */
752
753         nomatch:                /* output (count) the prefix */
754             bitno += n_bits;
755
756             /* code -> hashtable */
757             if (max_ent < db->maxmaxcode) {
758                 struct bsd_dict *dictp2;
759                 /* expand code size if needed */
760                 if (max_ent >= MAXCODE(n_bits))
761                     db->n_bits = ++n_bits;
762
763                 /* Invalidate previous hash table entry
764                  * assigned this code, and then take it over.
765                  */
766                 dictp2 = &db->dict[max_ent+1];
767                 if (db->dict[dictp2->cptr].codem1 == max_ent)
768                     db->dict[dictp2->cptr].codem1 = BADCODEM1;
769                 dictp2->cptr = hval;
770                 dictp->codem1 = max_ent;
771                 dictp->f.fcode = fcode;
772
773                 db->max_ent = ++max_ent;
774                 db->lens[max_ent] = db->lens[ent]+1;
775             }
776             ent = c;
777         } while (--slen != 0);
778     }
779     bitno += n_bits;            /* output (count) the last code */
780     db->bytes_out += bitno/8;
781     db->in_count += ilen;
782     (void)bsd_check(db);
783
784     ++db->incomp_count;
785     db->incomp_bytes += ilen;
786     ++db->uncomp_count;
787     db->uncomp_bytes += ilen;
788
789     /* Increase code size if we would have without the packet
790      * boundary and as the decompressor will.
791      */
792     if (max_ent >= MAXCODE(n_bits) && max_ent < db->maxmaxcode)
793         db->n_bits++;
794 }
795
796
797 /*
798  * Decompress "BSD Compress".
799  *
800  * Because of patent problems, we return DECOMP_ERROR for errors
801  * found by inspecting the input data and for system problems, but
802  * DECOMP_FATALERROR for any errors which could possibly be said to
803  * be being detected "after" decompression.  For DECOMP_ERROR,
804  * we can issue a CCP reset-request; for DECOMP_FATALERROR, we may be
805  * infringing a patent of Motorola's if we do, so we take CCP down
806  * instead.
807  *
808  * Given that the frame has the correct sequence number and a good FCS,
809  * errors such as invalid codes in the input most likely indicate a
810  * bug, so we return DECOMP_FATALERROR for them in order to turn off
811  * compression, even though they are detected by inspecting the input.
812  */
813 int
814 bsd_decompress(state, cmp, dmpp)
815     void *state;
816     struct mbuf *cmp, **dmpp;
817 {
818     struct bsd_db *db = (struct bsd_db *) state;
819     u_int max_ent = db->max_ent;
820     u_int32_t accm = 0;
821     u_int bitno = 32;           /* 1st valid bit in accm */
822     u_int n_bits = db->n_bits;
823     u_int tgtbitno = 32-n_bits; /* bitno when we have a code */
824     struct bsd_dict *dictp;
825     int explen, i, seq, len;
826     u_int incode, oldcode, finchar;
827     u_char *p, *rptr, *wptr;
828     struct mbuf *m, *dmp, *mret;
829     int adrs, ctrl, ilen;
830     int space, codelen, extra;
831
832     /*
833      * Save the address/control from the PPP header
834      * and then get the sequence number.
835      */
836     *dmpp = NULL;
837     rptr = mtod(cmp, u_char *);
838     adrs = PPP_ADDRESS(rptr);
839     ctrl = PPP_CONTROL(rptr);
840     rptr += PPP_HDRLEN;
841     len = cmp->m_len - PPP_HDRLEN;
842     seq = 0;
843     for (i = 0; i < 2; ++i) {
844         while (len <= 0) {
845             cmp = cmp->m_next;
846             if (cmp == NULL)
847                 return DECOMP_ERROR;
848             rptr = mtod(cmp, u_char *);
849             len = cmp->m_len;
850         }
851         seq = (seq << 8) + *rptr++;
852         --len;
853     }
854
855     /*
856      * Check the sequence number and give up if it differs from
857      * the value we're expecting.
858      */
859     if (seq != db->seqno) {
860         if (db->debug)
861             printf("bsd_decomp%d: bad sequence # %d, expected %d\n",
862                    db->unit, seq, db->seqno - 1);
863         return DECOMP_ERROR;
864     }
865     ++db->seqno;
866
867     /*
868      * Allocate one mbuf to start with.
869      */
870     MGETHDR(dmp, M_DONTWAIT, MT_DATA);
871     if (dmp == NULL)
872         return DECOMP_ERROR;
873     mret = dmp;
874     dmp->m_len = 0;
875     dmp->m_next = NULL;
876     MCLGET(dmp, M_DONTWAIT);
877     dmp->m_data += db->hdrlen;
878     wptr = mtod(dmp, u_char *);
879     space = M_TRAILINGSPACE(dmp) - PPP_HDRLEN + 1;
880
881     /*
882      * Fill in the ppp header, but not the last byte of the protocol
883      * (that comes from the decompressed data).
884      */
885     wptr[0] = adrs;
886     wptr[1] = ctrl;
887     wptr[2] = 0;
888     wptr += PPP_HDRLEN - 1;
889
890     ilen = len;
891     oldcode = CLEAR;
892     explen = 0;
893     for (;;) {
894         if (len == 0) {
895             cmp = cmp->m_next;
896             if (!cmp)           /* quit at end of message */
897                 break;
898             rptr = mtod(cmp, u_char *);
899             len = cmp->m_len;
900             ilen += len;
901             continue;           /* handle 0-length buffers */
902         }
903
904         /*
905          * Accumulate bytes until we have a complete code.
906          * Then get the next code, relying on the 32-bit,
907          * unsigned accm to mask the result.
908          */
909         bitno -= 8;
910         accm |= *rptr++ << bitno;
911         --len;
912         if (tgtbitno < bitno)
913             continue;
914         incode = accm >> tgtbitno;
915         accm <<= n_bits;
916         bitno += n_bits;
917
918         if (incode == CLEAR) {
919             /*
920              * The dictionary must only be cleared at
921              * the end of a packet.  But there could be an
922              * empty mbuf at the end.
923              */
924             if (len > 0 || cmp->m_next != NULL) {
925                 while ((cmp = cmp->m_next) != NULL)
926                     len += cmp->m_len;
927                 if (len > 0) {
928                     m_freem(mret);
929                     if (db->debug)
930                         printf("bsd_decomp%d: bad CLEAR\n", db->unit);
931                     return DECOMP_FATALERROR;   /* probably a bug */
932                 }
933             }
934             bsd_clear(db);
935             explen = ilen = 0;
936             break;
937         }
938
939         if (incode > max_ent + 2 || incode > db->maxmaxcode
940             || (incode > max_ent && oldcode == CLEAR)) {
941             m_freem(mret);
942             if (db->debug) {
943                 printf("bsd_decomp%d: bad code 0x%x oldcode=0x%x ",
944                        db->unit, incode, oldcode);
945                 printf("max_ent=0x%x explen=%d seqno=%d\n",
946                        max_ent, explen, db->seqno);
947             }
948             return DECOMP_FATALERROR;   /* probably a bug */
949         }
950
951         /* Special case for KwKwK string. */
952         if (incode > max_ent) {
953             finchar = oldcode;
954             extra = 1;
955         } else {
956             finchar = incode;
957             extra = 0;
958         }
959
960         codelen = db->lens[finchar];
961         explen += codelen + extra;
962         if (explen > db->mru + 1) {
963             m_freem(mret);
964             if (db->debug) {
965                 printf("bsd_decomp%d: ran out of mru\n", db->unit);
966 #ifdef DEBUG
967                 while ((cmp = cmp->m_next) != NULL)
968                     len += cmp->m_len;
969                 printf("  len=%d, finchar=0x%x, codelen=%d, explen=%d\n",
970                        len, finchar, codelen, explen);
971 #endif
972             }
973             return DECOMP_FATALERROR;
974         }
975
976         /*
977          * For simplicity, the decoded characters go in a single mbuf,
978          * so we allocate a single extra cluster mbuf if necessary.
979          */
980         if ((space -= codelen + extra) < 0) {
981             dmp->m_len = wptr - mtod(dmp, u_char *);
982             MGET(m, M_DONTWAIT, MT_DATA);
983             if (m == NULL) {
984                 m_freem(mret);
985                 return DECOMP_ERROR;
986             }
987             m->m_len = 0;
988             m->m_next = NULL;
989             dmp->m_next = m;
990             MCLGET(m, M_DONTWAIT);
991             space = M_TRAILINGSPACE(m) - (codelen + extra);
992             if (space < 0) {
993                 /* now that's what I call *compression*. */
994                 m_freem(mret);
995                 return DECOMP_ERROR;
996             }
997             dmp = m;
998             wptr = mtod(dmp, u_char *);
999         }
1000
1001         /*
1002          * Decode this code and install it in the decompressed buffer.
1003          */
1004         p = (wptr += codelen);
1005         while (finchar > LAST) {
1006             dictp = &db->dict[db->dict[finchar].cptr];
1007 #ifdef DEBUG
1008             if (--codelen <= 0 || dictp->codem1 != finchar-1)
1009                 goto bad;
1010 #endif
1011             *--p = dictp->f.hs.suffix;
1012             finchar = dictp->f.hs.prefix;
1013         }
1014         *--p = finchar;
1015
1016 #ifdef DEBUG
1017         if (--codelen != 0)
1018             printf("bsd_decomp%d: short by %d after code 0x%x, max_ent=0x%x\n",
1019                    db->unit, codelen, incode, max_ent);
1020 #endif
1021
1022         if (extra)              /* the KwKwK case again */
1023             *wptr++ = finchar;
1024
1025         /*
1026          * If not first code in a packet, and
1027          * if not out of code space, then allocate a new code.
1028          *
1029          * Keep the hash table correct so it can be used
1030          * with uncompressed packets.
1031          */
1032         if (oldcode != CLEAR && max_ent < db->maxmaxcode) {
1033             struct bsd_dict *dictp2;
1034             u_int32_t fcode;
1035             u_int32_t hval, disp;
1036
1037             fcode = BSD_KEY(oldcode,finchar);
1038             hval = BSD_HASH(oldcode,finchar,db->hshift);
1039             dictp = &db->dict[hval];
1040
1041             /* look for a free hash table entry */
1042             if (dictp->codem1 < max_ent) {
1043                 disp = (hval == 0) ? 1 : hval;
1044                 do {
1045                     hval += disp;
1046                     if (hval >= db->hsize)
1047                         hval -= db->hsize;
1048                     dictp = &db->dict[hval];
1049                 } while (dictp->codem1 < max_ent);
1050             }
1051
1052             /*
1053              * Invalidate previous hash table entry
1054              * assigned this code, and then take it over
1055              */
1056             dictp2 = &db->dict[max_ent+1];
1057             if (db->dict[dictp2->cptr].codem1 == max_ent) {
1058                 db->dict[dictp2->cptr].codem1 = BADCODEM1;
1059             }
1060             dictp2->cptr = hval;
1061             dictp->codem1 = max_ent;
1062             dictp->f.fcode = fcode;
1063
1064             db->max_ent = ++max_ent;
1065             db->lens[max_ent] = db->lens[oldcode]+1;
1066
1067             /* Expand code size if needed. */
1068             if (max_ent >= MAXCODE(n_bits) && max_ent < db->maxmaxcode) {
1069                 db->n_bits = ++n_bits;
1070                 tgtbitno = 32-n_bits;
1071             }
1072         }
1073         oldcode = incode;
1074     }
1075     dmp->m_len = wptr - mtod(dmp, u_char *);
1076
1077     /*
1078      * Keep the checkpoint right so that incompressible packets
1079      * clear the dictionary at the right times.
1080      */
1081     db->bytes_out += ilen;
1082     db->in_count += explen;
1083     if (bsd_check(db) && db->debug) {
1084         printf("bsd_decomp%d: peer should have cleared dictionary\n",
1085                db->unit);
1086     }
1087
1088     ++db->comp_count;
1089     db->comp_bytes += ilen + BSD_OVHD;
1090     ++db->uncomp_count;
1091     db->uncomp_bytes += explen;
1092
1093     *dmpp = mret;
1094     return DECOMP_OK;
1095
1096 #ifdef DEBUG
1097  bad:
1098     if (codelen <= 0) {
1099         printf("bsd_decomp%d: fell off end of chain ", db->unit);
1100         printf("0x%x at 0x%x by 0x%x, max_ent=0x%x\n",
1101                incode, finchar, db->dict[finchar].cptr, max_ent);
1102     } else if (dictp->codem1 != finchar-1) {
1103         printf("bsd_decomp%d: bad code chain 0x%x finchar=0x%x ",
1104                db->unit, incode, finchar);
1105         printf("oldcode=0x%x cptr=0x%x codem1=0x%x\n", oldcode,
1106                db->dict[finchar].cptr, dictp->codem1);
1107     }
1108     m_freem(mret);
1109     return DECOMP_FATALERROR;
1110 #endif /* DEBUG */
1111 }