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