]> git.ozlabs.org Git - ppp.git/blob - ultrix/bsd-comp.c
update to 2.2
[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.2 1994/11/28 01:41:29 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 /*
58  * PPP "BSD compress" compression
59  *  The differences between this compression and the classic BSD LZW
60  *  source are obvious from the requirement that the classic code worked
61  *  with files while this handles arbitrarily long streams that
62  *  are broken into packets.  They are:
63  *
64  *      When the code size expands, a block of junk is not emitted by
65  *          the compressor and not expected by the decompressor.
66  *
67  *      New codes are not necessarily assigned every time an old
68  *          code is output by the compressor.  This is because a packet
69  *          end forces a code to be emitted, but does not imply that a
70  *          new sequence has been seen.
71  *
72  *      The compression ratio is checked at the first end of a packet
73  *          after the appropriate gap.  Besides simplifying and speeding
74  *          things up, this makes it more likely that the transmitter
75  *          and receiver will agree when the dictionary is cleared when
76  *          compression is not going well.
77  */
78
79 /*
80  * Macros to extract protocol version and number of bits
81  * from the third byte of the BSD Compress CCP configuration option.
82  */
83 #define BSD_VERSION(x)  ((x) >> 5)
84 #define BSD_NBITS(x)    ((x) & 0x1F)
85
86 #define BSD_CURRENT_VERSION     1
87
88 /*
89  * A dictionary for doing BSD compress.
90  */
91 struct bsd_db {
92     int     totlen;                     /* length of this structure */
93     u_int   hsize;                      /* size of the hash table */
94     u_char  hshift;                     /* used in hash function */
95     u_char  n_bits;                     /* current bits/code */
96     u_char  maxbits;
97     u_char  debug;
98     u_char  unit;
99     u_short seqno;                      /* sequence # of next packet */
100     u_int   mru;
101     u_int   maxmaxcode;                 /* largest valid code */
102     u_int   max_ent;                    /* largest code in use */
103     u_int   in_count;                   /* uncompressed bytes, aged */
104     u_int   bytes_out;                  /* compressed bytes, aged */
105     u_int   ratio;                      /* recent compression ratio */
106     u_int   checkpoint;                 /* when to next check the ratio */
107     u_int   clear_count;                /* times dictionary cleared */
108     u_int   incomp_count;               /* incompressible packets */
109     u_int   incomp_bytes;               /* incompressible bytes */
110     u_int   uncomp_count;               /* uncompressed packets */
111     u_int   uncomp_bytes;               /* uncompressed bytes */
112     u_int   comp_count;                 /* compressed packets */
113     u_int   comp_bytes;                 /* compressed bytes */
114     u_short *lens;                      /* array of lengths of codes */
115     struct bsd_dict {
116         union {                         /* hash value */
117             u_int32_t   fcode;
118             struct {
119 #if BYTE_ORDER == LITTLE_ENDIAN
120                 u_short prefix;         /* preceding code */
121                 u_char  suffix;         /* last character of new code */
122                 u_char  pad;
123 #else
124                 u_char  pad;
125                 u_char  suffix;         /* last character of new code */
126                 u_short prefix;         /* preceding code */
127 #endif
128             } hs;
129         } f;
130         u_short codem1;                 /* output of hash table -1 */
131         u_short cptr;                   /* map code to hash table entry */
132     } dict[1];
133 };
134
135 #define BSD_OVHD        2               /* BSD compress overhead/packet */
136 #define MIN_BSD_BITS    9
137 #define BSD_INIT_BITS   MIN_BSD_BITS
138 #define MAX_BSD_BITS    15
139
140 static void     *bsd_comp_alloc __P((u_char *options, int opt_len));
141 static void     *bsd_decomp_alloc __P((u_char *options, int opt_len));
142 static void     bsd_free __P((void *state));
143 static int      bsd_comp_init __P((void *state, u_char *options, int opt_len,
144                                    int unit, int debug));
145 static int      bsd_decomp_init __P((void *state, u_char *options, int opt_len,
146                                      int unit, int mru, int debug));
147 static int      bsd_compress __P((void *state, struct mbuf **mret,
148                                   struct mbuf *mp, int slen, int maxolen));
149 static void     bsd_incomp __P((void *state, struct mbuf *dmsg));
150 static int      bsd_decompress __P((void *state, struct mbuf *cmp,
151                                     struct mbuf **dmpp));
152 static void     bsd_reset __P((void *state));
153 static void     bsd_comp_stats __P((void *state, struct compstat *stats));
154
155 /*
156  * Procedures exported to if_ppp.c.
157  */
158 struct compressor ppp_bsd_compress = {
159     0x21,                       /* compress_proto */
160     bsd_comp_alloc,             /* comp_alloc */
161     bsd_free,                   /* comp_free */
162     bsd_comp_init,              /* comp_init */
163     bsd_reset,                  /* comp_reset */
164     bsd_compress,               /* compress */
165     bsd_comp_stats,             /* comp_stat */
166     bsd_decomp_alloc,           /* decomp_alloc */
167     bsd_free,                   /* decomp_free */
168     bsd_decomp_init,            /* decomp_init */
169     bsd_reset,                  /* decomp_reset */
170     bsd_decompress,             /* decompress */
171     bsd_incomp,                 /* incomp */
172     bsd_comp_stats,             /* decomp_stat */
173 };
174
175 /*
176  * Some useful mbuf macros not in mbuf.h.
177  */
178 #define M_IS_CLUSTER(m) ((m)->m_off > MMAXOFF)
179
180 #define M_TRAILINGSPACE(m) \
181         ((M_IS_CLUSTER(m) ? (u_int)(m)->m_clptr + M_CLUSTERSZ : MSIZE) \
182          - ((m)->m_off + (m)->m_len))
183
184 /*
185  * the next two codes should not be changed lightly, as they must not
186  * lie within the contiguous general code space.
187  */
188 #define CLEAR   256                     /* table clear output code */
189 #define FIRST   257                     /* first free entry */
190 #define LAST    255
191
192 #define MAXCODE(b)      ((1 << (b)) - 1)
193 #define BADCODEM1       MAXCODE(MAX_BSD_BITS);
194
195 #define BSD_HASH(prefix,suffix,hshift)  ((((u_int32_t)(suffix)) << (hshift)) \
196                                          ^ (u_int32_t)(prefix))
197 #define BSD_KEY(prefix,suffix)          ((((u_int32_t)(suffix)) << 16) \
198                                          + (u_int32_t)(prefix))
199
200 #define CHECK_GAP       10000           /* Ratio check interval */
201
202 #define RATIO_SCALE_LOG 8
203 #define RATIO_SCALE     (1<<RATIO_SCALE_LOG)
204 #define RATIO_MAX       (0x7fffffff>>RATIO_SCALE_LOG)
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->incomp_count = 0;
220     db->checkpoint = CHECK_GAP;
221 }
222
223 /*
224  * If the dictionary is full, then see if it is time to reset it.
225  *
226  * Compute the compression ratio using fixed-point arithmetic
227  * with 8 fractional bits.
228  *
229  * Since we have an infinite stream instead of a single file,
230  * watch only the local compression ratio.
231  *
232  * Since both peers must reset the dictionary at the same time even in
233  * the absence of CLEAR codes (while packets are incompressible), they
234  * must compute the same ratio.
235  */
236 static int                              /* 1=output CLEAR */
237 bsd_check(db)
238     struct bsd_db *db;
239 {
240     u_int new_ratio;
241
242     if (db->in_count >= db->checkpoint) {
243         /* age the ratio by limiting the size of the counts */
244         if (db->in_count >= RATIO_MAX
245             || db->bytes_out >= RATIO_MAX) {
246             db->in_count -= db->in_count/4;
247             db->bytes_out -= db->bytes_out/4;
248         }
249
250         db->checkpoint = db->in_count + CHECK_GAP;
251
252         if (db->max_ent >= db->maxmaxcode) {
253             /* Reset the dictionary only if the ratio is worse,
254              * or if it looks as if it has been poisoned
255              * by incompressible data.
256              *
257              * This does not overflow, because
258              *  db->in_count <= RATIO_MAX.
259              */
260             new_ratio = db->in_count << RATIO_SCALE_LOG;
261             if (db->bytes_out != 0)
262                 new_ratio /= db->bytes_out;
263
264             if (new_ratio < db->ratio || new_ratio < 1 * RATIO_SCALE) {
265                 bsd_clear(db);
266                 return 1;
267             }
268             db->ratio = new_ratio;
269         }
270     }
271     return 0;
272 }
273
274 /*
275  * Return statistics.
276  */
277 static void
278 bsd_comp_stats(state, stats)
279     void *state;
280     struct compstat *stats;
281 {
282     struct bsd_db *db = (struct bsd_db *) state;
283     u_int out;
284
285     stats->unc_bytes = db->uncomp_bytes;
286     stats->unc_packets = db->uncomp_count;
287     stats->comp_bytes = db->comp_bytes;
288     stats->comp_packets = db->comp_count;
289     stats->inc_bytes = db->incomp_bytes;
290     stats->inc_packets = db->incomp_count;
291     stats->ratio = db->in_count;
292     out = db->bytes_out;
293     if (stats->ratio <= 0x7fffff)
294         stats->ratio <<= 8;
295     else
296         out >>= 8;
297     if (out != 0)
298         stats->ratio /= out;
299 }
300
301 /*
302  * Reset state, as on a CCP ResetReq.
303  */
304 static void
305 bsd_reset(state)
306     void *state;
307 {
308     struct bsd_db *db = (struct bsd_db *) state;
309
310     db->seqno = 0;
311     bsd_clear(db);
312     db->clear_count = 0;
313 }
314
315 /*
316  * Allocate space for a (de) compressor.
317  */
318 static void *
319 bsd_alloc(options, opt_len, decomp)
320     u_char *options;
321     int opt_len, decomp;
322 {
323     int bits;
324     u_int newlen, hsize, hshift, maxmaxcode;
325     struct bsd_db *db;
326
327     if (opt_len != 3 || options[0] != 0x21 || options[1] != 3
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, mru, debug, decomp)
418     struct bsd_db *db;
419     u_char *options;
420     int opt_len, unit, mru, debug, decomp;
421 {
422     int i;
423
424     if (opt_len != 3 || options[0] != 0x21 || options[1] != 3
425         || BSD_VERSION(options[2]) != BSD_CURRENT_VERSION
426         || BSD_NBITS(options[2]) != db->maxbits
427         || decomp && db->lens == NULL)
428         return 0;
429
430     if (decomp) {
431         i = LAST+1;
432         while (i != 0)
433             db->lens[--i] = 1;
434     }
435     i = db->hsize;
436     while (i != 0) {
437         db->dict[--i].codem1 = BADCODEM1;
438         db->dict[i].cptr = 0;
439     }
440
441     db->unit = unit;
442     db->mru = mru;
443 #ifndef DEBUG
444     if (debug)
445 #endif
446         db->debug = 1;
447
448     bsd_reset(db);
449
450     return 1;
451 }
452
453 static int
454 bsd_comp_init(state, options, opt_len, unit, debug)
455     void *state;
456     u_char *options;
457     int opt_len, unit, debug;
458 {
459     return bsd_init((struct bsd_db *) state, options, opt_len,
460                     unit, 0, debug, 0);
461 }
462
463 static int
464 bsd_decomp_init(state, options, opt_len, unit, mru, debug)
465     void *state;
466     u_char *options;
467     int opt_len, unit, mru, debug;
468 {
469     return bsd_init((struct bsd_db *) state, options, opt_len,
470                     unit, mru, debug, 1);
471 }
472
473
474 /*
475  * compress a packet
476  *      One change from the BSD compress command is that when the
477  *      code size expands, we do not output a bunch of padding.
478  */
479 static int                              /* new slen */
480 bsd_compress(state, mret, mp, slen, maxolen)
481     void *state;
482     struct mbuf **mret;         /* return compressed mbuf chain here */
483     struct mbuf *mp;            /* from here */
484     int slen;                   /* uncompressed length */
485     int maxolen;                /* max compressed length */
486 {
487     struct bsd_db *db = (struct bsd_db *) state;
488     int hshift = db->hshift;
489     u_int max_ent = db->max_ent;
490     u_int n_bits = db->n_bits;
491     u_int bitno = 32;
492     u_int32_t accm = 0, fcode;
493     struct bsd_dict *dictp;
494     u_char c;
495     int hval, disp, ent, ilen;
496     struct mbuf *np;
497     u_char *rptr, *wptr;
498     u_char *cp_end;
499     int olen;
500     struct mbuf *m, **mnp, *clp;
501         
502 #define PUTBYTE(v) {                                    \
503     ++olen;                                             \
504     if (wptr) {                                         \
505         *wptr++ = (v);                                  \
506         if (wptr >= cp_end) {                           \
507             m->m_len = wptr - mtod(m, u_char *);        \
508             MGET(m->m_next, M_DONTWAIT, MT_DATA);       \
509             m = m->m_next;                              \
510             if (m) {                                    \
511                 if (maxolen - olen > MLEN) {            \
512                     MCLGET(m, clp);                     \
513                 }                                       \
514                 m->m_len = 0;                           \
515                 wptr = mtod(m, u_char *);               \
516                 cp_end = wptr + M_TRAILINGSPACE(m);     \
517             } else                                      \
518                 wptr = NULL;                            \
519         }                                               \
520     }                                                   \
521 }
522
523 #define OUTPUT(ent) {                                   \
524     bitno -= n_bits;                                    \
525     accm |= ((ent) << bitno);                           \
526     do {                                                \
527         PUTBYTE(accm >> 24);                            \
528         accm <<= 8;                                     \
529         bitno += 8;                                     \
530     } while (bitno <= 24);                              \
531 }
532
533     /*
534      * If the protocol is not in the range we're interested in,
535      * just return without compressing the packet.  If it is,
536      * the protocol becomes the first byte to compress.
537      */
538     rptr = mtod(mp, u_char *);
539     ent = PPP_PROTOCOL(rptr);
540     if (ent < 0x21 || ent > 0xf9) {
541         *mret = NULL;
542         return slen;
543     }
544
545     /* Don't generate compressed packets which are larger than
546        the uncompressed packet. */
547     if (maxolen > slen)
548         maxolen = slen;
549
550     /* Allocate one mbuf to start with. */
551     MGET(m, M_DONTWAIT, MT_DATA);
552     *mret = m;
553     if (m != NULL) {
554         if (maxolen > MLEN) {
555             MCLGET(m, clp);
556         }
557         m->m_len = 0;
558         wptr = mtod(m, u_char *);
559         cp_end = wptr + M_TRAILINGSPACE(m);
560     } else
561         wptr = cp_end = NULL;
562
563     /*
564      * Copy the PPP header over, changing the protocol,
565      * and install the 2-byte packet sequence number.
566      */
567     if (wptr) {
568         *wptr++ = PPP_ADDRESS(rptr);    /* assumes the ppp header is */
569         *wptr++ = PPP_CONTROL(rptr);    /* all in one mbuf */
570         *wptr++ = 0;                    /* change the protocol */
571         *wptr++ = PPP_COMP;
572         *wptr++ = db->seqno >> 8;
573         *wptr++ = db->seqno;
574     }
575     ++db->seqno;
576
577     olen = 0;
578     rptr += PPP_HDRLEN;
579     slen = mp->m_len - PPP_HDRLEN;
580     ilen = slen + 1;
581     for (;;) {
582         if (slen <= 0) {
583             mp = mp->m_next;
584             if (!mp)
585                 break;
586             rptr = mtod(mp, u_char *);
587             slen = mp->m_len;
588             if (!slen)
589                 continue;   /* handle 0-length buffers */
590             ilen += slen;
591         }
592
593         slen--;
594         c = *rptr++;
595         fcode = BSD_KEY(ent, c);
596         hval = BSD_HASH(ent, c, hshift);
597         dictp = &db->dict[hval];
598
599         /* Validate and then check the entry. */
600         if (dictp->codem1 >= max_ent)
601             goto nomatch;
602         if (dictp->f.fcode == fcode) {
603             ent = dictp->codem1+1;
604             continue;   /* found (prefix,suffix) */
605         }
606
607         /* continue probing until a match or invalid entry */
608         disp = (hval == 0) ? 1 : hval;
609         do {
610             hval += disp;
611             if (hval >= db->hsize)
612                 hval -= db->hsize;
613             dictp = &db->dict[hval];
614             if (dictp->codem1 >= max_ent)
615                 goto nomatch;
616         } while (dictp->f.fcode != fcode);
617         ent = dictp->codem1 + 1;        /* finally found (prefix,suffix) */
618         continue;
619
620     nomatch:
621         OUTPUT(ent);            /* output the prefix */
622
623         /* code -> hashtable */
624         if (max_ent < db->maxmaxcode) {
625             struct bsd_dict *dictp2;
626             /* expand code size if needed */
627             if (max_ent >= MAXCODE(n_bits))
628                 db->n_bits = ++n_bits;
629
630             /* Invalidate old hash table entry using
631              * this code, and then take it over.
632              */
633             dictp2 = &db->dict[max_ent+1];
634             if (db->dict[dictp2->cptr].codem1 == max_ent)
635                 db->dict[dictp2->cptr].codem1 = BADCODEM1;
636             dictp2->cptr = hval;
637             dictp->codem1 = max_ent;
638             dictp->f.fcode = fcode;
639
640             db->max_ent = ++max_ent;
641         }
642         ent = c;
643     }
644
645     OUTPUT(ent);                /* output the last code */
646     db->bytes_out += olen;
647     db->in_count += ilen;
648     if (bitno < 32)
649         ++db->bytes_out;        /* count complete bytes */
650
651     if (bsd_check(db))
652         OUTPUT(CLEAR);          /* do not count the CLEAR */
653
654     /*
655      * Pad dribble bits of last code with ones.
656      * Do not emit a completely useless byte of ones.
657      */
658     if (bitno != 32)
659         PUTBYTE((accm | (0xff << (bitno-8))) >> 24);
660
661     if (m != NULL) {
662         m->m_len = wptr - mtod(m, u_char *);
663         m->m_next = NULL;
664     }
665
666     /*
667      * Increase code size if we would have without the packet
668      * boundary and as the decompressor will.
669      */
670     if (max_ent >= MAXCODE(n_bits) && max_ent < db->maxmaxcode)
671         db->n_bits++;
672
673     db->uncomp_bytes += ilen;
674     ++db->uncomp_count;
675     if (olen + PPP_HDRLEN + BSD_OVHD > maxolen) {
676         /* throw away the compressed stuff if it is longer than uncompressed */
677         if (*mret != NULL) {
678             m_freem(*mret);
679             *mret = NULL;
680         }
681         ++db->incomp_count;
682         db->incomp_bytes += ilen;
683     } else {
684         ++db->comp_count;
685         db->comp_bytes += olen + BSD_OVHD;
686     }
687
688     return olen + PPP_HDRLEN + BSD_OVHD;
689 #undef OUTPUT
690 #undef PUTBYTE
691 }
692
693
694 /*
695  * Update the "BSD Compress" dictionary on the receiver for
696  * incompressible data by pretending to compress the incoming data.
697  */
698 static void
699 bsd_incomp(state, dmsg)
700     void *state;
701     struct mbuf *dmsg;
702 {
703     struct bsd_db *db = (struct bsd_db *) state;
704     u_int hshift = db->hshift;
705     u_int max_ent = db->max_ent;
706     u_int n_bits = db->n_bits;
707     struct bsd_dict *dictp;
708     u_int32_t fcode;
709     u_char c;
710     long hval, disp;
711     int slen, ilen;
712     u_int bitno = 7;
713     u_char *rptr;
714     u_int ent;
715
716     /*
717      * If the protocol is not in the range we're interested in,
718      * just return without looking at the packet.  If it is,
719      * the protocol becomes the first byte to "compress".
720      */
721     rptr = mtod(dmsg, u_char *);
722     ent = PPP_PROTOCOL(rptr);
723     if (ent < 0x21 || ent > 0xf9)
724         return;
725
726     db->incomp_count++;
727     db->seqno++;
728     ilen = 1;           /* count the protocol as 1 byte */
729     rptr += PPP_HDRLEN;
730     slen = dmsg->m_len - PPP_HDRLEN;
731     for (;;) {
732         if (slen <= 0) {
733             dmsg = dmsg->m_next;
734             if (!dmsg)
735                 break;
736             rptr = mtod(dmsg, u_char *);
737             slen = dmsg->m_len;
738             continue;
739         }
740         ilen += slen;
741
742         do {
743             c = *rptr++;
744             fcode = BSD_KEY(ent, c);
745             hval = BSD_HASH(ent, c, hshift);
746             dictp = &db->dict[hval];
747
748             /* validate and then check the entry */
749             if (dictp->codem1 >= max_ent)
750                 goto nomatch;
751             if (dictp->f.fcode == fcode) {
752                 ent = dictp->codem1+1;
753                 continue;   /* found (prefix,suffix) */
754             }
755
756             /* continue probing until a match or invalid entry */
757             disp = (hval == 0) ? 1 : hval;
758             do {
759                 hval += disp;
760                 if (hval >= db->hsize)
761                     hval -= db->hsize;
762                 dictp = &db->dict[hval];
763                 if (dictp->codem1 >= max_ent)
764                     goto nomatch;
765             } while (dictp->f.fcode != fcode);
766             ent = dictp->codem1+1;
767             continue;   /* finally found (prefix,suffix) */
768
769         nomatch:                /* output (count) the prefix */
770             bitno += n_bits;
771
772             /* code -> hashtable */
773             if (max_ent < db->maxmaxcode) {
774                 struct bsd_dict *dictp2;
775                 /* expand code size if needed */
776                 if (max_ent >= MAXCODE(n_bits))
777                     db->n_bits = ++n_bits;
778
779                 /* Invalidate previous hash table entry
780                  * assigned this code, and then take it over.
781                  */
782                 dictp2 = &db->dict[max_ent+1];
783                 if (db->dict[dictp2->cptr].codem1 == max_ent)
784                     db->dict[dictp2->cptr].codem1 = BADCODEM1;
785                 dictp2->cptr = hval;
786                 dictp->codem1 = max_ent;
787                 dictp->f.fcode = fcode;
788
789                 db->max_ent = ++max_ent;
790                 db->lens[max_ent] = db->lens[ent]+1;
791             }
792             ent = c;
793         } while (--slen != 0);
794     }
795     bitno += n_bits;            /* output (count) the last code */
796     db->bytes_out += bitno/8;
797     db->in_count += ilen;
798     (void)bsd_check(db);
799
800     ++db->incomp_count;
801     db->incomp_bytes += ilen;
802     ++db->uncomp_count;
803     db->uncomp_bytes += ilen;
804
805     /* Increase code size if we would have without the packet
806      * boundary and as the decompressor will.
807      */
808     if (max_ent >= MAXCODE(n_bits) && max_ent < db->maxmaxcode)
809         db->n_bits++;
810 }
811
812
813 /*
814  * Decompress "BSD Compress".
815  *
816  * Because of patent problems, we return DECOMP_ERROR for errors
817  * found by inspecting the input data and for system problems, but
818  * DECOMP_FATALERROR for any errors which could possibly be said to
819  * be being detected "after" decompression.  For DECOMP_ERROR,
820  * we can issue a CCP reset-request; for DECOMP_FATALERROR, we may be
821  * infringing a patent of Motorola's if we do, so we take CCP down
822  * instead.
823  *
824  * Given that the frame has the correct sequence number and a good FCS,
825  * errors such as invalid codes in the input most likely indicate a
826  * bug, so we return DECOMP_FATALERROR for them in order to turn off
827  * compression, even though they are detected by inspecting the input.
828  */
829 static int
830 bsd_decompress(state, cmp, dmpp)
831     void *state;
832     struct mbuf *cmp, **dmpp;
833 {
834     struct bsd_db *db = (struct bsd_db *) state;
835     u_int max_ent = db->max_ent;
836     u_int32_t accm = 0;
837     u_int bitno = 32;           /* 1st valid bit in accm */
838     u_int n_bits = db->n_bits;
839     u_int tgtbitno = 32-n_bits; /* bitno when we have a code */
840     struct bsd_dict *dictp;
841     int explen, i, seq, len;
842     u_int incode, oldcode, finchar;
843     u_char *p, *rptr, *wptr;
844     struct mbuf *m, *dmp, *mret;
845     int adrs, ctrl, ilen;
846     int space, codelen, extra;
847     struct mbuf *last, *clp;
848
849     /*
850      * Save the address/control from the PPP header
851      * and then get the sequence number.
852      */
853     *dmpp = NULL;
854     rptr = mtod(cmp, u_char *);
855     adrs = PPP_ADDRESS(rptr);
856     ctrl = PPP_CONTROL(rptr);
857     rptr += PPP_HDRLEN;
858     len = cmp->m_len - PPP_HDRLEN;
859     seq = 0;
860     for (i = 0; i < 2; ++i) {
861         while (len <= 0) {
862             cmp = cmp->m_next;
863             if (cmp == NULL)
864                 return DECOMP_ERROR;
865             rptr = mtod(cmp, u_char *);
866             len = cmp->m_len;
867         }
868         seq = (seq << 8) + *rptr++;
869         --len;
870     }
871
872     /*
873      * Check the sequence number and give up if it differs from
874      * the value we're expecting.
875      */
876     if (seq != db->seqno++) {
877         if (db->debug)
878             printf("bsd_decomp%d: bad sequence # %d, expected %d\n",
879                    db->unit, seq, db->seqno - 1);
880         return DECOMP_ERROR;
881     }
882
883     /*
884      * Allocate one mbuf to start with.
885      */
886     MGET(dmp, M_DONTWAIT, MT_DATA);
887     if (dmp == NULL)
888         return DECOMP_ERROR;
889     mret = dmp;
890     dmp->m_next = NULL;
891     MCLGET(dmp, clp);
892     dmp->m_len = 0;
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 }