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