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