1/*
2 * Routines to compress and uncompess tcp packets (for transmission
3 * over low speed serial lines.
4 *
5 * Copyright (c) 1989 Regents of the University of California.
6 * All rights reserved.
7 *
8 * Redistribution and use in source and binary forms are permitted
9 * provided that the above copyright notice and this paragraph are
10 * duplicated in all such forms and that any documentation,
11 * advertising materials, and other materials related to such
12 * distribution and use acknowledge that the software was developed
13 * by the University of California, Berkeley.  The name of the
14 * University may not be used to endorse or promote products derived
15 * from this software without specific prior written permission.
16 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
17 * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
18 * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
19 *
20 *	Van Jacobson (van@helios.ee.lbl.gov), Dec 31, 1989:
21 *	- Initial distribution.
22 *
23 * Modified June 1993 by Paul Mackerras, paulus@cs.anu.edu.au,
24 * so that the entire packet being decompressed doesn't have
25 * to be in contiguous memory (just the compressed header).
26 */
27
28/*
29 * This version is used under SunOS 4.x, Digital UNIX, AIX 4.x,
30 * and SVR4 systems including Solaris 2.
31 *
32 * $Id: vjcompress.c,v 1.11 2004/01/17 05:47:55 carlsonj Exp $
33 */
34
35#include <sys/types.h>
36#include <sys/param.h>
37
38#ifdef SVR4
39#ifndef __GNUC__
40#include <sys/byteorder.h>	/* for ntohl, etc. */
41#else
42/* make sure we don't get the gnu "fixed" one! */
43#include "/usr/include/sys/byteorder.h"
44#endif
45#endif
46
47#ifdef __osf__
48#include <net/net_globals.h>
49#endif
50#include <netinet/in.h>
51
52#ifdef AIX4
53#define _NETINET_IN_SYSTM_H_
54typedef u_long  n_long;
55#else
56#include <netinet/in_systm.h>
57#endif
58
59#ifdef SOL2
60#include <sys/sunddi.h>
61#endif
62
63#include <netinet/ip.h>
64#include <netinet/tcp.h>
65
66#include <net/ppp_defs.h>
67#include <net/vjcompress.h>
68
69#ifndef VJ_NO_STATS
70#define INCR(counter) ++comp->stats.counter
71#else
72#define INCR(counter)
73#endif
74
75#define BCMP(p1, p2, n) bcmp((char *)(p1), (char *)(p2), (int)(n))
76#undef  BCOPY
77#define BCOPY(p1, p2, n) bcopy((char *)(p1), (char *)(p2), (int)(n))
78#ifndef KERNEL
79#define ovbcopy bcopy
80#endif
81
82#ifdef __osf__
83#define getip_hl(base)	(((base).ip_vhl)&0xf)
84#define getth_off(base)	((((base).th_xoff)&0xf0)>>4)
85
86#else
87#define getip_hl(base)	((base).ip_hl)
88#define getth_off(base)	((base).th_off)
89#endif
90
91void
92vj_compress_init(comp, max_state)
93    struct vjcompress *comp;
94    int max_state;
95{
96    register u_int i;
97    register struct cstate *tstate = comp->tstate;
98
99    if (max_state == -1)
100	max_state = MAX_STATES - 1;
101    bzero((char *)comp, sizeof(*comp));
102    for (i = max_state; i > 0; --i) {
103	tstate[i].cs_id = i;
104	tstate[i].cs_next = &tstate[i - 1];
105    }
106    tstate[0].cs_next = &tstate[max_state];
107    tstate[0].cs_id = 0;
108    comp->last_cs = &tstate[0];
109    comp->last_recv = 255;
110    comp->last_xmit = 255;
111    comp->flags = VJF_TOSS;
112}
113
114
115/* ENCODE encodes a number that is known to be non-zero.  ENCODEZ
116 * checks for zero (since zero has to be encoded in the long, 3 byte
117 * form).
118 */
119#define ENCODE(n) { \
120	if ((u_short)(n) >= 256) { \
121		*cp++ = 0; \
122		cp[1] = (n); \
123		cp[0] = (n) >> 8; \
124		cp += 2; \
125	} else { \
126		*cp++ = (n); \
127	} \
128}
129#define ENCODEZ(n) { \
130	if ((u_short)(n) >= 256 || (u_short)(n) == 0) { \
131		*cp++ = 0; \
132		cp[1] = (n); \
133		cp[0] = (n) >> 8; \
134		cp += 2; \
135	} else { \
136		*cp++ = (n); \
137	} \
138}
139
140#define DECODEL(f) { \
141	if (*cp == 0) {\
142		u_int32_t tmp = ntohl(f) + ((cp[1] << 8) | cp[2]); \
143		(f) = htonl(tmp); \
144		cp += 3; \
145	} else { \
146		u_int32_t tmp = ntohl(f) + (u_int32_t)*cp++; \
147		(f) = htonl(tmp); \
148	} \
149}
150
151#define DECODES(f) { \
152	if (*cp == 0) {\
153		u_short tmp = ntohs(f) + ((cp[1] << 8) | cp[2]); \
154		(f) = htons(tmp); \
155		cp += 3; \
156	} else { \
157		u_short tmp = ntohs(f) + (u_int32_t)*cp++; \
158		(f) = htons(tmp); \
159	} \
160}
161
162#define DECODEU(f) { \
163	if (*cp == 0) {\
164		(f) = htons((cp[1] << 8) | cp[2]); \
165		cp += 3; \
166	} else { \
167		(f) = htons((u_int32_t)*cp++); \
168	} \
169}
170
171u_int
172vj_compress_tcp(ip, mlen, comp, compress_cid, vjhdrp)
173    register struct ip *ip;
174    u_int mlen;
175    struct vjcompress *comp;
176    int compress_cid;
177    u_char **vjhdrp;
178{
179    register struct cstate *cs = comp->last_cs->cs_next;
180    register u_int hlen = getip_hl(*ip);
181    register struct tcphdr *oth;
182    register struct tcphdr *th;
183    register u_int deltaS, deltaA;
184    register u_int changes = 0;
185    u_char new_seq[16];
186    register u_char *cp = new_seq;
187
188    /*
189     * Bail if this is an IP fragment or if the TCP packet isn't
190     * `compressible' (i.e., ACK isn't set or some other control bit is
191     * set).  (We assume that the caller has already made sure the
192     * packet is IP proto TCP).
193     */
194    if ((ip->ip_off & htons(0x3fff)) || mlen < 40)
195	return (TYPE_IP);
196
197    th = (struct tcphdr *)&((int *)ip)[hlen];
198    if ((th->th_flags & (TH_SYN|TH_FIN|TH_RST|TH_ACK)) != TH_ACK)
199	return (TYPE_IP);
200    /*
201     * Packet is compressible -- we're going to send either a
202     * COMPRESSED_TCP or UNCOMPRESSED_TCP packet.  Either way we need
203     * to locate (or create) the connection state.  Special case the
204     * most recently used connection since it's most likely to be used
205     * again & we don't have to do any reordering if it's used.
206     */
207    INCR(vjs_packets);
208    if (ip->ip_src.s_addr != cs->cs_ip.ip_src.s_addr ||
209	ip->ip_dst.s_addr != cs->cs_ip.ip_dst.s_addr ||
210	*(int *)th != ((int *)&cs->cs_ip)[getip_hl(cs->cs_ip)]) {
211	/*
212	 * Wasn't the first -- search for it.
213	 *
214	 * States are kept in a circularly linked list with
215	 * last_cs pointing to the end of the list.  The
216	 * list is kept in lru order by moving a state to the
217	 * head of the list whenever it is referenced.  Since
218	 * the list is short and, empirically, the connection
219	 * we want is almost always near the front, we locate
220	 * states via linear search.  If we don't find a state
221	 * for the datagram, the oldest state is (re-)used.
222	 */
223	register struct cstate *lcs;
224	register struct cstate *lastcs = comp->last_cs;
225
226	do {
227	    lcs = cs; cs = cs->cs_next;
228	    INCR(vjs_searches);
229	    if (ip->ip_src.s_addr == cs->cs_ip.ip_src.s_addr
230		&& ip->ip_dst.s_addr == cs->cs_ip.ip_dst.s_addr
231		&& *(int *)th == ((int *)&cs->cs_ip)[getip_hl(cs->cs_ip)])
232		goto found;
233	} while (cs != lastcs);
234
235	/*
236	 * Didn't find it -- re-use oldest cstate.  Send an
237	 * uncompressed packet that tells the other side what
238	 * connection number we're using for this conversation.
239	 * Note that since the state list is circular, the oldest
240	 * state points to the newest and we only need to set
241	 * last_cs to update the lru linkage.
242	 */
243	INCR(vjs_misses);
244	comp->last_cs = lcs;
245	hlen += getth_off(*th);
246	hlen <<= 2;
247	if (hlen > mlen)
248	    return (TYPE_IP);
249	goto uncompressed;
250
251    found:
252	/*
253	 * Found it -- move to the front on the connection list.
254	 */
255	if (cs == lastcs)
256	    comp->last_cs = lcs;
257	else {
258	    lcs->cs_next = cs->cs_next;
259	    cs->cs_next = lastcs->cs_next;
260	    lastcs->cs_next = cs;
261	}
262    }
263
264    /*
265     * Make sure that only what we expect to change changed. The first
266     * line of the `if' checks the IP protocol version, header length &
267     * type of service.  The 2nd line checks the "Don't fragment" bit.
268     * The 3rd line checks the time-to-live and protocol (the protocol
269     * check is unnecessary but costless).  The 4th line checks the TCP
270     * header length.  The 5th line checks IP options, if any.  The 6th
271     * line checks TCP options, if any.  If any of these things are
272     * different between the previous & current datagram, we send the
273     * current datagram `uncompressed'.
274     */
275    oth = (struct tcphdr *)&((int *)&cs->cs_ip)[hlen];
276    deltaS = hlen;
277    hlen += getth_off(*th);
278    hlen <<= 2;
279    if (hlen > mlen)
280	return (TYPE_IP);
281
282    if (((u_short *)ip)[0] != ((u_short *)&cs->cs_ip)[0] ||
283	((u_short *)ip)[3] != ((u_short *)&cs->cs_ip)[3] ||
284	((u_short *)ip)[4] != ((u_short *)&cs->cs_ip)[4] ||
285	getth_off(*th) != getth_off(*oth) ||
286	(deltaS > 5 && BCMP(ip + 1, &cs->cs_ip + 1, (deltaS - 5) << 2)) ||
287	(getth_off(*th) > 5 && BCMP(th + 1, oth + 1, (getth_off(*th) - 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    if ((deltaS = (u_short)(ntohs(th->th_win) - ntohs(oth->th_win))) > 0) {
308	ENCODE(deltaS);
309	changes |= NEW_W;
310    }
311
312    if ((deltaA = ntohl(th->th_ack) - ntohl(oth->th_ack)) > 0) {
313	if (deltaA > 0xffff)
314	    goto uncompressed;
315	ENCODE(deltaA);
316	changes |= NEW_A;
317    }
318
319    if ((deltaS = ntohl(th->th_seq) - ntohl(oth->th_seq)) > 0) {
320	if (deltaS > 0xffff)
321	    goto uncompressed;
322	ENCODE(deltaS);
323	changes |= NEW_S;
324    }
325
326    switch(changes) {
327
328    case 0:
329	/*
330	 * Nothing changed. If this packet contains data and the
331	 * last one didn't, this is probably a data packet following
332	 * an ack (normal on an interactive connection) and we send
333	 * it compressed.  Otherwise it's probably a retransmit,
334	 * retransmitted ack or window probe.  Send it uncompressed
335	 * in case the other side missed the compressed version.
336	 */
337	if (ip->ip_len != cs->cs_ip.ip_len &&
338	    ntohs(cs->cs_ip.ip_len) == hlen)
339	    break;
340
341	/* (fall through) */
342
343    case SPECIAL_I:
344    case SPECIAL_D:
345	/*
346	 * actual changes match one of our special case encodings --
347	 * send packet uncompressed.
348	 */
349	goto uncompressed;
350
351    case NEW_S|NEW_A:
352	if (deltaS == deltaA && deltaS == ntohs(cs->cs_ip.ip_len) - hlen) {
353	    /* special case for echoed terminal traffic */
354	    changes = SPECIAL_I;
355	    cp = new_seq;
356	}
357	break;
358
359    case NEW_S:
360	if (deltaS == ntohs(cs->cs_ip.ip_len) - hlen) {
361	    /* special case for data xfer */
362	    changes = SPECIAL_D;
363	    cp = new_seq;
364	}
365	break;
366    }
367
368    deltaS = ntohs(ip->ip_id) - ntohs(cs->cs_ip.ip_id);
369    if (deltaS != 1) {
370	ENCODEZ(deltaS);
371	changes |= NEW_I;
372    }
373    if (th->th_flags & TH_PUSH)
374	changes |= TCP_PUSH_BIT;
375    /*
376     * Grab the cksum before we overwrite it below.  Then update our
377     * state with this packet's header.
378     */
379    deltaA = ntohs(th->th_sum);
380    BCOPY(ip, &cs->cs_ip, hlen);
381
382    /*
383     * We want to use the original packet as our compressed packet.
384     * (cp - new_seq) is the number of bytes we need for compressed
385     * sequence numbers.  In addition we need one byte for the change
386     * mask, one for the connection id and two for the tcp checksum.
387     * So, (cp - new_seq) + 4 bytes of header are needed.  hlen is how
388     * many bytes of the original packet to toss so subtract the two to
389     * get the new packet size.
390     */
391    deltaS = cp - new_seq;
392    cp = (u_char *)ip;
393    if (compress_cid == 0 || comp->last_xmit != cs->cs_id) {
394	comp->last_xmit = cs->cs_id;
395	hlen -= deltaS + 4;
396	*vjhdrp = (cp += hlen);
397	*cp++ = changes | NEW_C;
398	*cp++ = cs->cs_id;
399    } else {
400	hlen -= deltaS + 3;
401	*vjhdrp = (cp += hlen);
402	*cp++ = changes;
403    }
404    *cp++ = deltaA >> 8;
405    *cp++ = deltaA;
406    BCOPY(new_seq, cp, deltaS);
407    INCR(vjs_compressed);
408    return (TYPE_COMPRESSED_TCP);
409
410    /*
411     * Update connection state cs & send uncompressed packet (that is,
412     * a regular ip/tcp packet but with the 'conversation id' we hope
413     * to use on future compressed packets in the protocol field).
414     */
415 uncompressed:
416    BCOPY(ip, &cs->cs_ip, hlen);
417    ip->ip_p = cs->cs_id;
418    comp->last_xmit = cs->cs_id;
419    return (TYPE_UNCOMPRESSED_TCP);
420}
421
422/*
423 * Called when we may have missed a packet.
424 */
425void
426vj_uncompress_err(comp)
427    struct vjcompress *comp;
428{
429    comp->flags |= VJF_TOSS;
430    INCR(vjs_errorin);
431}
432
433/*
434 * "Uncompress" a packet of type TYPE_UNCOMPRESSED_TCP.
435 */
436int
437vj_uncompress_uncomp(buf, buflen, comp)
438    u_char *buf;
439    int buflen;
440    struct vjcompress *comp;
441{
442    register u_int hlen;
443    register struct cstate *cs;
444    register struct ip *ip;
445
446    ip = (struct ip *) buf;
447    hlen = getip_hl(*ip) << 2;
448    if (ip->ip_p >= MAX_STATES
449	|| hlen + sizeof(struct tcphdr) > buflen
450	|| (hlen += getth_off(*((struct tcphdr *)&((char *)ip)[hlen])) << 2)
451	    > buflen
452	|| hlen > MAX_HDR) {
453	comp->flags |= VJF_TOSS;
454	INCR(vjs_errorin);
455	return (0);
456    }
457    cs = &comp->rstate[comp->last_recv = ip->ip_p];
458    comp->flags &=~ VJF_TOSS;
459    ip->ip_p = IPPROTO_TCP;
460    BCOPY(ip, &cs->cs_ip, hlen);
461    cs->cs_hlen = hlen;
462    INCR(vjs_uncompressedin);
463    return (1);
464}
465
466/*
467 * Uncompress a packet of type TYPE_COMPRESSED_TCP.
468 * The packet starts at buf and is of total length total_len.
469 * The first buflen bytes are at buf; this must include the entire
470 * compressed 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
475vj_uncompress_tcp(buf, buflen, total_len, comp, hdrp, hlenp)
476    u_char *buf;
477    int buflen, total_len;
478    struct vjcompress *comp;
479    u_char **hdrp;
480    u_int *hlenp;
481{
482    register u_char *cp;
483    register u_int hlen, changes;
484    register struct tcphdr *th;
485    register struct cstate *cs;
486    register u_short *bp;
487    register u_int vjlen;
488    register u_int32_t tmp;
489
490    INCR(vjs_compressedin);
491    cp = buf;
492    changes = *cp++;
493    if (changes & NEW_C) {
494	/* Make sure the state index is in range, then grab the state.
495	 * If we have a good state index, clear the 'discard' flag. */
496	if (*cp >= MAX_STATES)
497	    goto bad;
498
499	comp->flags &=~ VJF_TOSS;
500	comp->last_recv = *cp++;
501    } else {
502	/* this packet has an implicit state index.  If we've
503	 * had a line error since the last time we got an
504	 * explicit state index, we have to toss the packet. */
505	if (comp->flags & VJF_TOSS) {
506	    INCR(vjs_tossed);
507	    return (-1);
508	}
509    }
510    cs = &comp->rstate[comp->last_recv];
511    hlen = getip_hl(cs->cs_ip) << 2;
512    th = (struct tcphdr *)&((u_char *)&cs->cs_ip)[hlen];
513    th->th_sum = htons((*cp << 8) | cp[1]);
514    cp += 2;
515    if (changes & TCP_PUSH_BIT)
516	th->th_flags |= TH_PUSH;
517    else
518	th->th_flags &=~ TH_PUSH;
519
520    switch (changes & SPECIALS_MASK) {
521    case SPECIAL_I:
522	{
523	    register u_int32_t i = ntohs(cs->cs_ip.ip_len) - cs->cs_hlen;
524	    /* some compilers can't nest inline assembler.. */
525	    tmp = ntohl(th->th_ack) + i;
526	    th->th_ack = htonl(tmp);
527	    tmp = ntohl(th->th_seq) + i;
528	    th->th_seq = htonl(tmp);
529	}
530	break;
531
532    case SPECIAL_D:
533	/* some compilers can't nest inline assembler.. */
534	tmp = ntohl(th->th_seq) + ntohs(cs->cs_ip.ip_len) - cs->cs_hlen;
535	th->th_seq = htonl(tmp);
536	break;
537
538    default:
539	if (changes & NEW_U) {
540	    th->th_flags |= TH_URG;
541	    DECODEU(th->th_urp);
542	} else
543	    th->th_flags &=~ TH_URG;
544	if (changes & NEW_W)
545	    DECODES(th->th_win);
546	if (changes & NEW_A)
547	    DECODEL(th->th_ack);
548	if (changes & NEW_S)
549	    DECODEL(th->th_seq);
550	break;
551    }
552    if (changes & NEW_I) {
553	DECODES(cs->cs_ip.ip_id);
554    } else {
555	cs->cs_ip.ip_id = ntohs(cs->cs_ip.ip_id) + 1;
556	cs->cs_ip.ip_id = htons(cs->cs_ip.ip_id);
557    }
558
559    /*
560     * At this point, cp points to the first byte of data in the
561     * packet.  Fill in the IP total length and update the IP
562     * header checksum.
563     */
564    vjlen = cp - buf;
565    buflen -= vjlen;
566    if (buflen < 0)
567	/* we must have dropped some characters (crc should detect
568	 * this but the old slip framing won't) */
569	goto bad;
570
571    total_len += cs->cs_hlen - vjlen;
572    cs->cs_ip.ip_len = htons(total_len);
573
574    /* recompute the ip header checksum */
575    bp = (u_short *) &cs->cs_ip;
576    cs->cs_ip.ip_sum = 0;
577    for (changes = 0; hlen > 0; hlen -= 2)
578	changes += *bp++;
579    changes = (changes & 0xffff) + (changes >> 16);
580    changes = (changes & 0xffff) + (changes >> 16);
581    cs->cs_ip.ip_sum = ~ changes;
582
583    *hdrp = (u_char *) &cs->cs_ip;
584    *hlenp = cs->cs_hlen;
585    return vjlen;
586
587 bad:
588    comp->flags |= VJF_TOSS;
589    INCR(vjs_errorin);
590    return (-1);
591}
592