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