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