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