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