1/*
2 * Copyright (c) 2000 Apple Computer, Inc. All rights reserved.
3 *
4 * @APPLE_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. Please obtain a copy of the License at
10 * http://www.opensource.apple.com/apsl/ and read it before using this
11 * file.
12 *
13 * The Original Code and all software distributed under the License are
14 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
15 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
16 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
17 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
18 * Please see the License for the specific language governing rights and
19 * limitations under the License.
20 *
21 * @APPLE_LICENSE_HEADER_END@
22 */
23
24/*-
25 * Copyright (c) 1989, 1993, 1994
26 *	The Regents of the University of California.  All rights reserved.
27 *
28 * Redistribution and use in source and binary forms, with or without
29 * modification, are permitted provided that the following conditions
30 * are met:
31 * 1. Redistributions of source code must retain the above copyright
32 *    notice, this list of conditions and the following disclaimer.
33 * 2. Redistributions in binary form must reproduce the above copyright
34 *    notice, this list of conditions and the following disclaimer in the
35 *    documentation and/or other materials provided with the distribution.
36 * 3. All advertising materials mentioning features or use of this software
37 *    must display the following acknowledgement:
38 *	This product includes software developed by the University of
39 *	California, Berkeley and its contributors.
40 * 4. Neither the name of the University nor the names of its contributors
41 *    may be used to endorse or promote products derived from this software
42 *    without specific prior written permission.
43 *
44 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
45 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
46 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
47 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
48 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
49 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
50 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
51 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
52 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
53 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
54 * SUCH DAMAGE.
55 *
56 *	@(#)slcompress.c	8.2 (Berkeley) 4/16/94
57 */
58
59/*
60 * Routines to compress and uncompess tcp packets (for transmission
61 * over low speed serial lines.
62 *
63 * Van Jacobson (van@helios.ee.lbl.gov), Dec 31, 1989:
64 *	- Initial distribution.
65 *
66 */
67
68#include <sys/param.h>
69#include <sys/mbuf.h>
70#include <sys/systm.h>
71
72#include <netinet/in.h>
73#include <netinet/in_systm.h>
74#include <netinet/ip.h>
75#include <netinet/tcp.h>
76
77#include "slcompress.h"
78
79#ifndef SL_NO_STATS
80#define INCR(counter) ++comp->counter;
81#else
82#define INCR(counter)
83#endif
84
85#define BCMP(p1, p2, n) bcmp((char *)(p1), (char *)(p2), (int)(n))
86#define BCOPY(p1, p2, n) bcopy((char *)(p1), (char *)(p2), (int)(n))
87#ifndef KERNEL
88#define ovbcopy bcopy
89#endif
90
91/* Wcast-align fix - cast away alignment warning when buffer is aligned */
92#define ALIGNED_CAST(type)	(type)(void *)
93
94
95void
96sl_compress_init(comp, max_state)
97	struct slcompress *comp;
98	int max_state;
99{
100	register u_int i;
101	register struct cstate *tstate = comp->tstate;
102
103	if (max_state == -1) {
104		max_state = MAX_STATES - 1;
105		bzero((char *)comp, sizeof(*comp));
106	} else {
107		/* Don't reset statistics */
108		bzero((char *)comp->tstate, sizeof(comp->tstate));
109		bzero((char *)comp->rstate, sizeof(comp->rstate));
110	}
111  	for (i = max_state; i > 0; --i) {
112		tstate[i].cs_id = i;
113		tstate[i].cs_next = &tstate[i - 1];
114	}
115	tstate[0].cs_next = &tstate[max_state];
116	tstate[0].cs_id = 0;
117	comp->last_cs = &tstate[0];
118	comp->last_recv = 255;
119	comp->last_xmit = 255;
120	comp->flags = SLF_TOSS;
121}
122
123
124/* ENCODE encodes a number that is known to be non-zero.  ENCODEZ
125 * checks for zero (since zero has to be encoded in the long, 3 byte
126 * form).
127 */
128#define ENCODE(n) { \
129	if ((u_int16_t)(n) >= 256) { \
130		*cp++ = 0; \
131		cp[1] = (n); \
132		cp[0] = (n) >> 8; \
133		cp += 2; \
134	} else { \
135		*cp++ = (n); \
136	} \
137}
138#define ENCODEZ(n) { \
139	if ((u_int16_t)(n) >= 256 || (u_int16_t)(n) == 0) { \
140		*cp++ = 0; \
141		cp[1] = (n); \
142		cp[0] = (n) >> 8; \
143		cp += 2; \
144	} else { \
145		*cp++ = (n); \
146	} \
147}
148
149#define DECODEL(f) { \
150	if (*cp == 0) {\
151		(f) = htonl(ntohl(f) + ((cp[1] << 8) | cp[2])); \
152		cp += 3; \
153	} else { \
154		(f) = htonl(ntohl(f) + (u_int32_t)*cp++); \
155	} \
156}
157
158#define DECODES(f) { \
159	if (*cp == 0) {\
160		(f) = htons(ntohs(f) + ((cp[1] << 8) | cp[2])); \
161		cp += 3; \
162	} else { \
163		(f) = htons(ntohs(f) + (u_int32_t)*cp++); \
164	} \
165}
166
167#define DECODEU(f) { \
168	if (*cp == 0) {\
169		(f) = htons((cp[1] << 8) | cp[2]); \
170		cp += 3; \
171	} else { \
172		(f) = htons((u_int32_t)*cp++); \
173	} \
174}
175
176u_int
177sl_compress_tcp(m, ip, comp, compress_cid)
178	mbuf_t m;
179	register struct ip *ip;
180	struct slcompress *comp;
181	int compress_cid;
182{
183	register struct cstate *cs = comp->last_cs->cs_next;
184	register u_int hlen = ip->ip_hl;
185	register struct tcphdr *oth;
186	register struct tcphdr *th;
187	register u_int deltaS, deltaA;
188	register u_int changes = 0;
189	u_char new_seq[16];
190	register u_char *cp = new_seq;
191
192	/*
193	 * Bail if this is an IP fragment or if the TCP packet isn't
194	 * `compressible' (i.e., ACK isn't set or some other control bit is
195	 * set).  (We assume that the caller has already made sure the
196	 * packet is IP proto TCP).
197	 */
198	if ((ip->ip_off & htons(0x3fff)) || mbuf_len(m) < 40)
199		return (TYPE_IP);
200
201	th = (struct tcphdr *)&((int32_t *)ip)[hlen];
202	if ((th->th_flags & (TH_SYN|TH_FIN|TH_RST|TH_ACK)) != TH_ACK)
203		return (TYPE_IP);
204	/*
205	 * Packet is compressible -- we're going to send either a
206	 * COMPRESSED_TCP or UNCOMPRESSED_TCP packet.  Either way we need
207	 * to locate (or create) the connection state.  Special case the
208	 * most recently used connection since it's most likely to be used
209	 * again & we don't have to do any reordering if it's used.
210	 */
211	INCR(sls_packets)
212	if (ip->ip_src.s_addr != cs->cs_ip.ip_src.s_addr ||
213	    ip->ip_dst.s_addr != cs->cs_ip.ip_dst.s_addr ||
214	    *(int32_t *)th != ((int32_t *)&cs->cs_ip)[cs->cs_ip.ip_hl]) {
215		/*
216		 * Wasn't the first -- search for it.
217		 *
218		 * States are kept in a circularly linked list with
219		 * last_cs pointing to the end of the list.  The
220		 * list is kept in lru order by moving a state to the
221		 * head of the list whenever it is referenced.  Since
222		 * the list is short and, empirically, the connection
223		 * we want is almost always near the front, we locate
224		 * states via linear search.  If we don't find a state
225		 * for the datagram, the oldest state is (re-)used.
226		 */
227		register struct cstate *lcs;
228		register struct cstate *lastcs = comp->last_cs;
229
230		do {
231			lcs = cs; cs = cs->cs_next;
232			INCR(sls_searches)
233			if (ip->ip_src.s_addr == cs->cs_ip.ip_src.s_addr
234			    && ip->ip_dst.s_addr == cs->cs_ip.ip_dst.s_addr
235			    && *(int32_t *)th ==
236			    ((int32_t *)&cs->cs_ip)[cs->cs_ip.ip_hl])
237				goto found;
238		} while (cs != lastcs);
239
240		/*
241		 * Didn't find it -- re-use oldest cstate.  Send an
242		 * uncompressed packet that tells the other side what
243		 * connection number we're using for this conversation.
244		 * Note that since the state list is circular, the oldest
245		 * state points to the newest and we only need to set
246		 * last_cs to update the lru linkage.
247		 */
248		INCR(sls_misses)
249		comp->last_cs = lcs;
250		hlen += th->th_off;
251		hlen <<= 2;
252		if (hlen > mbuf_len(m))
253		    return TYPE_IP;
254		goto uncompressed;
255
256	found:
257		/*
258		 * Found it -- move to the front on the connection list.
259		 */
260		if (cs == lastcs)
261			comp->last_cs = lcs;
262		else {
263			lcs->cs_next = cs->cs_next;
264			cs->cs_next = lastcs->cs_next;
265			lastcs->cs_next = cs;
266		}
267	}
268
269	/*
270	 * Make sure that only what we expect to change changed. The first
271	 * line of the `if' checks the IP protocol version, header length &
272	 * type of service.  The 2nd line checks the "Don't fragment" bit.
273	 * The 3rd line checks the time-to-live and protocol (the protocol
274	 * check is unnecessary but costless).  The 4th line checks the TCP
275	 * header length.  The 5th line checks IP options, if any.  The 6th
276	 * line checks TCP options, if any.  If any of these things are
277	 * different between the previous & current datagram, we send the
278	 * current datagram `uncompressed'.
279	 */
280	oth = (struct tcphdr *)&((int32_t *)&cs->cs_ip)[hlen];
281	deltaS = hlen;
282	hlen += th->th_off;
283	hlen <<= 2;
284	if (hlen > mbuf_len(m))
285	    return TYPE_IP;
286
287	if (((u_int16_t *)ip)[0] != ((u_int16_t *)&cs->cs_ip)[0] ||
288	    ((u_int16_t *)ip)[3] != ((u_int16_t *)&cs->cs_ip)[3] ||
289	    ((u_int16_t *)ip)[4] != ((u_int16_t *)&cs->cs_ip)[4] ||
290	    th->th_off != oth->th_off ||
291	    (deltaS > 5 &&
292	     BCMP(ip + 1, &cs->cs_ip + 1, (deltaS - 5) << 2)) ||
293	    (th->th_off > 5 &&
294	     BCMP(th + 1, oth + 1, (th->th_off - 5) << 2)))
295		goto uncompressed;
296
297	/*
298	 * Figure out which of the changing fields changed.  The
299	 * receiver expects changes in the order: urgent, window,
300	 * ack, seq (the order minimizes the number of temporaries
301	 * needed in this section of code).
302	 */
303	if (th->th_flags & TH_URG) {
304		deltaS = ntohs(th->th_urp);
305		ENCODEZ(deltaS);
306		changes |= NEW_U;
307	} else if (th->th_urp != oth->th_urp)
308		/* argh! URG not set but urp changed -- a sensible
309		 * implementation should never do this but RFC793
310		 * doesn't prohibit the change so we have to deal
311		 * with it. */
312		 goto uncompressed;
313
314	deltaS = (u_int16_t)(ntohs(th->th_win) - ntohs(oth->th_win));
315	if (deltaS) {
316		ENCODE(deltaS);
317		changes |= NEW_W;
318	}
319
320	deltaA = ntohl(th->th_ack) - ntohl(oth->th_ack);
321	if (deltaA) {
322		if (deltaA > 0xffff)
323			goto uncompressed;
324		ENCODE(deltaA);
325		changes |= NEW_A;
326	}
327
328	deltaS = ntohl(th->th_seq) - ntohl(oth->th_seq);
329	if (deltaS) {
330		if (deltaS > 0xffff)
331			goto uncompressed;
332		ENCODE(deltaS);
333		changes |= NEW_S;
334	}
335
336	switch(changes) {
337
338	case 0:
339		/*
340		 * Nothing changed. If this packet contains data and the
341		 * last one didn't, this is probably a data packet following
342		 * an ack (normal on an interactive connection) and we send
343		 * it compressed.  Otherwise it's probably a retransmit,
344		 * retransmitted ack or window probe.  Send it uncompressed
345		 * in case the other side missed the compressed version.
346		 */
347		if (ip->ip_len != cs->cs_ip.ip_len &&
348		    ntohs(cs->cs_ip.ip_len) == hlen)
349			break;
350
351		/* (fall through) */
352
353	case SPECIAL_I:
354	case SPECIAL_D:
355		/*
356		 * actual changes match one of our special case encodings --
357		 * send packet uncompressed.
358		 */
359		goto uncompressed;
360
361	case NEW_S|NEW_A:
362		if (deltaS == deltaA &&
363		    deltaS == ntohs(cs->cs_ip.ip_len) - hlen) {
364			/* special case for echoed terminal traffic */
365			changes = SPECIAL_I;
366			cp = new_seq;
367		}
368		break;
369
370	case NEW_S:
371		if (deltaS == ntohs(cs->cs_ip.ip_len) - hlen) {
372			/* special case for data xfer */
373			changes = SPECIAL_D;
374			cp = new_seq;
375		}
376		break;
377	}
378
379	deltaS = ntohs(ip->ip_id) - ntohs(cs->cs_ip.ip_id);
380	if (deltaS != 1) {
381		ENCODEZ(deltaS);
382		changes |= NEW_I;
383	}
384	if (th->th_flags & TH_PUSH)
385		changes |= TCP_PUSH_BIT;
386	/*
387	 * Grab the cksum before we overwrite it below.  Then update our
388	 * state with this packet's header.
389	 */
390	deltaA = ntohs(th->th_sum);
391	BCOPY(ip, &cs->cs_ip, hlen);
392
393	/*
394	 * We want to use the original packet as our compressed packet.
395	 * (cp - new_seq) is the number of bytes we need for compressed
396	 * sequence numbers.  In addition we need one byte for the change
397	 * mask, one for the connection id and two for the tcp checksum.
398	 * So, (cp - new_seq) + 4 bytes of header are needed.  hlen is how
399	 * many bytes of the original packet to toss so subtract the two to
400	 * get the new packet size.
401	 */
402	deltaS = cp - new_seq;
403	cp = (u_char *)ip;
404	if (compress_cid == 0 || comp->last_xmit != cs->cs_id) {
405		comp->last_xmit = cs->cs_id;
406		hlen -= deltaS + 4;
407		cp += hlen;
408		*cp++ = changes | NEW_C;
409		*cp++ = cs->cs_id;
410	} else {
411		hlen -= deltaS + 3;
412		cp += hlen;
413		*cp++ = changes;
414	}
415	mbuf_setdata(m, mbuf_data(m) + hlen, mbuf_len(m) - hlen);
416	*cp++ = deltaA >> 8;
417	*cp++ = deltaA;
418	BCOPY(new_seq, cp, deltaS);
419	INCR(sls_compressed)
420	return (TYPE_COMPRESSED_TCP);
421
422	/*
423	 * Update connection state cs & send uncompressed packet ('uncompressed'
424	 * means a regular ip/tcp packet but with the 'conversation id' we hope
425	 * to use on future compressed packets in the protocol field).
426	 */
427uncompressed:
428	BCOPY(ip, &cs->cs_ip, hlen);
429	ip->ip_p = cs->cs_id;
430	comp->last_xmit = cs->cs_id;
431	return (TYPE_UNCOMPRESSED_TCP);
432}
433
434
435int
436sl_uncompress_tcp(bufp, len, type, comp)
437	u_char **bufp;
438	int len;
439	u_int type;
440	struct slcompress *comp;
441{
442	u_char *hdr, *cp;
443	int hlen, vjlen;
444
445	cp = bufp? *bufp: NULL;
446	vjlen = sl_uncompress_tcp_core(cp, len, len, type, comp, &hdr, (uint32_t *)&hlen);
447	if (vjlen < 0)
448		return (0);	/* error */
449	if (vjlen == 0)
450		return (len);	/* was uncompressed already */
451
452	cp += vjlen;
453	len -= vjlen;
454
455	/*
456	 * At this point, cp points to the first byte of data in the
457	 * packet.  If we're not aligned on a 4-byte boundary, copy the
458	 * data down so the ip & tcp headers will be aligned.  Then back up
459	 * cp by the tcp/ip header length to make room for the reconstructed
460	 * header (we assume the packet we were handed has enough space to
461	 * prepend 128 bytes of header).
462	 */
463        // Start APPLE
464//        if ((intptr_t)cp & 3) {
465 //               if (len > 0)
466//                        (void) ovbcopy(cp, (caddr_t)((intptr_t)cp &~ 3), len);
467//                cp = (u_char *)((intptr_t)cp &~ 3);
468//        }
469        if ((uintptr_t)cp & 3) {
470            if (len > 0)
471                    (void) ovbcopy(cp, (caddr_t)((uintptr_t)cp &~ 3), len);
472            cp = (u_char *)((uintptr_t)cp &~ 3);
473        }
474        // End APPLE
475	cp -= hlen;
476	len += hlen;
477	BCOPY(hdr, cp, hlen);
478
479	if (bufp)
480		*bufp = cp;
481	return (len);
482}
483
484/*
485 * Uncompress a packet of total length total_len.  The first buflen
486 * bytes are at buf; this must include the entire (compressed or
487 * uncompressed) TCP/IP header.  This procedure returns the length
488 * of the VJ header, with a pointer to the uncompressed IP header
489 * in *hdrp and its length in *hlenp.
490 */
491int
492sl_uncompress_tcp_core(buf, buflen, total_len, type, comp, hdrp, hlenp)
493	u_char *buf;
494	int buflen, total_len;
495	u_int type;
496	struct slcompress *comp;
497	u_char **hdrp;
498	u_int *hlenp;
499{
500	register u_char *cp;
501	register u_int hlen, changes;
502	register struct tcphdr *th;
503	register struct cstate *cs;
504	register struct ip *ip;
505	register u_int16_t *bp;
506	register u_int vjlen;
507
508	switch (type) {
509
510	case TYPE_UNCOMPRESSED_TCP:
511		ip = (struct ip *)(void*) buf;  // Wcast-align fix (void*) - used only to access 1 byte or less
512		if (ip->ip_p >= MAX_STATES)
513			goto bad;
514		cs = &comp->rstate[comp->last_recv = ip->ip_p];
515		comp->flags &=~ SLF_TOSS;
516		ip->ip_p = IPPROTO_TCP;
517		/*
518		 * Calculate the size of the TCP/IP header and make sure that
519		 * we don't overflow the space we have available for it.
520		 */
521		hlen = ip->ip_hl << 2;
522		if (hlen + sizeof(struct tcphdr) > buflen)
523			goto bad;
524		hlen += ((struct tcphdr *)(void*)&((char *)ip)[hlen])->th_off << 2; // Wcast-align fix (void*) - used for access to 4 bits
525		if (hlen > MAX_HDR || hlen > buflen)
526			goto bad;
527		BCOPY(ip, &cs->cs_ip, hlen);
528		cs->cs_hlen = hlen;
529		INCR(sls_uncompressedin)
530		*hdrp = (u_char *) &cs->cs_ip;
531		*hlenp = hlen;
532		return (0);
533
534	default:
535		goto bad;
536
537	case TYPE_COMPRESSED_TCP:
538		break;
539	}
540	/* We've got a compressed packet. */
541	INCR(sls_compressedin)
542	cp = buf;
543	changes = *cp++;
544	if (changes & NEW_C) {
545		/* Make sure the state index is in range, then grab the state.
546		 * If we have a good state index, clear the 'discard' flag. */
547		if (*cp >= MAX_STATES)
548			goto bad;
549
550		comp->flags &=~ SLF_TOSS;
551		comp->last_recv = *cp++;
552	} else {
553		/* this packet has an implicit state index.  If we've
554		 * had a line error since the last time we got an
555		 * explicit state index, we have to toss the packet. */
556		if (comp->flags & SLF_TOSS) {
557			INCR(sls_tossed)
558			return (-1);
559		}
560	}
561	cs = &comp->rstate[comp->last_recv];
562	hlen = cs->cs_ip.ip_hl << 2;
563	th = ALIGNED_CAST(struct tcphdr *)&((u_char *)&cs->cs_ip)[hlen];
564	th->th_sum = htons((*cp << 8) | cp[1]);
565	cp += 2;
566	if (changes & TCP_PUSH_BIT)
567		th->th_flags |= TH_PUSH;
568	else
569		th->th_flags &=~ TH_PUSH;
570
571	switch (changes & SPECIALS_MASK) {
572	case SPECIAL_I:
573		{
574		register u_int i = ntohs(cs->cs_ip.ip_len) - cs->cs_hlen;
575		th->th_ack = htonl(ntohl(th->th_ack) + i);
576		th->th_seq = htonl(ntohl(th->th_seq) + i);
577		}
578		break;
579
580	case SPECIAL_D:
581		th->th_seq = htonl(ntohl(th->th_seq) + ntohs(cs->cs_ip.ip_len)
582				   - cs->cs_hlen);
583		break;
584
585	default:
586		if (changes & NEW_U) {
587			th->th_flags |= TH_URG;
588			DECODEU(th->th_urp)
589		} else
590			th->th_flags &=~ TH_URG;
591		if (changes & NEW_W)
592			DECODES(th->th_win)
593		if (changes & NEW_A)
594			DECODEL(th->th_ack)
595		if (changes & NEW_S)
596			DECODEL(th->th_seq)
597		break;
598	}
599	if (changes & NEW_I) {
600		DECODES(cs->cs_ip.ip_id)
601	} else
602		cs->cs_ip.ip_id = htons(ntohs(cs->cs_ip.ip_id) + 1);
603
604	/*
605	 * At this point, cp points to the first byte of data in the
606	 * packet.  Fill in the IP total length and update the IP
607	 * header checksum.
608	 */
609	vjlen = cp - buf;
610	buflen -= vjlen;
611	if (buflen < 0)
612		/* we must have dropped some characters (crc should detect
613		 * this but the old slip framing won't) */
614		goto bad;
615
616	total_len += cs->cs_hlen - vjlen;
617	cs->cs_ip.ip_len = htons(total_len);
618
619	/* recompute the ip header checksum */
620	bp = (u_int16_t *) &cs->cs_ip;
621	cs->cs_ip.ip_sum = 0;
622		for (changes = 0; hlen > 0; hlen -= 2)
623			changes += *bp++;
624		changes = (changes & 0xffff) + (changes >> 16);
625		changes = (changes & 0xffff) + (changes >> 16);
626	cs->cs_ip.ip_sum = ~ changes;
627
628	*hdrp = (u_char *) &cs->cs_ip;
629	*hlenp = cs->cs_hlen;
630	return vjlen;
631
632bad:
633	comp->flags |= SLF_TOSS;
634	INCR(sls_errorin)
635	return (-1);
636}
637