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