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