slcompress.c revision 102413
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 * $FreeBSD: head/usr.sbin/ppp/slcompress.c 102413 2002-08-25 13:30:43Z charnier $
21 *
22 *	Van Jacobson (van@helios.ee.lbl.gov), Dec 31, 1989:
23 *	- Initial distribution.
24 */
25
26#include <sys/param.h>
27#include <netinet/in_systm.h>
28#include <netinet/in.h>
29#include <netinet/tcp.h>
30#include <netinet/ip.h>
31#include <sys/socket.h>
32#include <sys/un.h>
33
34#include <stdio.h>
35#include <string.h>
36#include <termios.h>
37
38#include "layer.h"
39#include "defs.h"
40#include "command.h"
41#include "mbuf.h"
42#include "log.h"
43#include "slcompress.h"
44#include "descriptor.h"
45#include "prompt.h"
46#include "timer.h"
47#include "fsm.h"
48#include "throughput.h"
49#include "iplist.h"
50#include "lqr.h"
51#include "hdlc.h"
52#include "ncpaddr.h"
53#include "ipcp.h"
54#include "filter.h"
55#include "lcp.h"
56#include "ccp.h"
57#include "link.h"
58#include "mp.h"
59#ifndef NORADIUS
60#include "radius.h"
61#endif
62#include "ipv6cp.h"
63#include "ncp.h"
64#include "bundle.h"
65
66void
67sl_compress_init(struct slcompress *comp, int max_state)
68{
69  register u_int i;
70  register struct cstate *tstate = comp->tstate;
71
72  memset(comp, '\0', sizeof *comp);
73  for (i = max_state; i > 0; --i) {
74    tstate[i].cs_id = i;
75    tstate[i].cs_next = &tstate[i - 1];
76  }
77  tstate[0].cs_next = &tstate[max_state];
78  tstate[0].cs_id = 0;
79  comp->last_cs = &tstate[0];
80  comp->last_recv = 255;
81  comp->last_xmit = 255;
82  comp->flags = SLF_TOSS;
83}
84
85
86/* ENCODE encodes a number that is known to be non-zero.  ENCODEZ
87 * checks for zero (since zero has to be encoded in the 32-bit, 3 byte
88 * form).
89 */
90#define ENCODE(n) { \
91	if ((u_short)(n) >= 256) { \
92		*cp++ = 0; \
93		cp[1] = (n); \
94		cp[0] = (n) >> 8; \
95		cp += 2; \
96	} else { \
97		*cp++ = (n); \
98	} \
99}
100#define ENCODEZ(n) { \
101	if ((u_short)(n) >= 256 || (u_short)(n) == 0) { \
102		*cp++ = 0; \
103		cp[1] = (n); \
104		cp[0] = (n) >> 8; \
105		cp += 2; \
106	} else { \
107		*cp++ = (n); \
108	} \
109}
110
111#define DECODEL(f) { \
112	if (*cp == 0) {\
113		(f) = htonl(ntohl(f) + ((cp[1] << 8) | cp[2])); \
114		cp += 3; \
115	} else { \
116		(f) = htonl(ntohl(f) + (u_int32_t)*cp++); \
117	} \
118}
119
120#define DECODES(f) { \
121	if (*cp == 0) {\
122		(f) = htons(ntohs(f) + ((cp[1] << 8) | cp[2])); \
123		cp += 3; \
124	} else { \
125		(f) = htons(ntohs(f) + (u_int32_t)*cp++); \
126	} \
127}
128
129#define DECODEU(f) { \
130	if (*cp == 0) {\
131		(f) = htons((cp[1] << 8) | cp[2]); \
132		cp += 3; \
133	} else { \
134		(f) = htons((u_int32_t)*cp++); \
135	} \
136}
137
138
139u_char
140sl_compress_tcp(struct mbuf * m,
141		struct ip * ip,
142		struct slcompress *comp,
143                struct slstat *slstat,
144		int compress_cid)
145{
146  register struct cstate *cs = comp->last_cs->cs_next;
147  register u_int hlen = ip->ip_hl;
148  register struct tcphdr *oth;
149  register struct tcphdr *th;
150  register u_int deltaS, deltaA;
151  register u_int changes = 0;
152  u_char new_seq[16];
153  register u_char *cp = new_seq;
154
155  /*
156   * Bail if this is an IP fragment or if the TCP packet isn't `compressible'
157   * (i.e., ACK isn't set or some other control bit is set).  (We assume that
158   * the caller has already made sure the packet is IP proto TCP).
159   */
160  if ((ip->ip_off & htons(0x3fff)) || m->m_len < 40) {
161    log_Printf(LogDEBUG, "??? 1 ip_off = %x, m_len = %lu\n",
162	      ip->ip_off, (unsigned long)m->m_len);
163    log_DumpBp(LogDEBUG, "", m);
164    return (TYPE_IP);
165  }
166  th = (struct tcphdr *) & ((int *) ip)[hlen];
167  if ((th->th_flags & (TH_SYN | TH_FIN | TH_RST | TH_ACK)) != TH_ACK) {
168    log_Printf(LogDEBUG, "??? 2 th_flags = %x\n", th->th_flags);
169    log_DumpBp(LogDEBUG, "", m);
170    return (TYPE_IP);
171  }
172
173  /*
174   * Packet is compressible -- we're going to send either a COMPRESSED_TCP or
175   * UNCOMPRESSED_TCP packet.  Either way we need to locate (or create) the
176   * connection state.  Special case the most recently used connection since
177   * it's most likely to be used again & we don't have to do any reordering
178   * if it's used.
179   */
180  slstat->sls_packets++;
181  if (ip->ip_src.s_addr != cs->cs_ip.ip_src.s_addr ||
182      ip->ip_dst.s_addr != cs->cs_ip.ip_dst.s_addr ||
183      *(int *) th != ((int *) &cs->cs_ip)[cs->cs_ip.ip_hl]) {
184
185    /*
186     * Wasn't the first -- search for it.
187     *
188     * States are kept in a circularly linked list with last_cs pointing to the
189     * end of the list.  The list is kept in lru order by moving a state to
190     * the head of the list whenever it is referenced.  Since the list is
191     * short and, empirically, the connection we want is almost always near
192     * the front, we locate states via linear search.  If we don't find a
193     * state for the datagram, the oldest state is (re-)used.
194     */
195    register struct cstate *lcs;
196    register struct cstate *lastcs = comp->last_cs;
197
198    do {
199      lcs = cs;
200      cs = cs->cs_next;
201      slstat->sls_searches++;
202      if (ip->ip_src.s_addr == cs->cs_ip.ip_src.s_addr
203	  && ip->ip_dst.s_addr == cs->cs_ip.ip_dst.s_addr
204	  && *(int *) th == ((int *) &cs->cs_ip)[cs->cs_ip.ip_hl])
205	goto found;
206    } while (cs != lastcs);
207
208    /*
209     * Didn't find it -- re-use oldest cstate.  Send an uncompressed packet
210     * that tells the other side what connection number we're using for this
211     * conversation. Note that since the state list is circular, the oldest
212     * state points to the newest and we only need to set last_cs to update
213     * the lru linkage.
214     */
215    slstat->sls_misses++;
216      comp->last_cs = lcs;
217#define	THOFFSET(th)	(th->th_off)
218    hlen += th->th_off;
219    hlen <<= 2;
220    if (hlen > m->m_len)
221      return (TYPE_IP);
222    goto uncompressed;
223
224found:
225
226    /*
227     * Found it -- move to the front on the connection list.
228     */
229    if (cs == lastcs)
230      comp->last_cs = lcs;
231    else {
232      lcs->cs_next = cs->cs_next;
233      cs->cs_next = lastcs->cs_next;
234      lastcs->cs_next = cs;
235    }
236  }
237
238  /*
239   * Make sure that only what we expect to change changed. The first line of
240   * the `if' checks the IP protocol version, header length & type of
241   * service.  The 2nd line checks the "Don't fragment" bit. The 3rd line
242   * checks the time-to-live and protocol (the protocol check is unnecessary
243   * but costless).  The 4th line checks the TCP header length.  The 5th line
244   * checks IP options, if any.  The 6th line checks TCP options, if any.  If
245   * any of these things are different between the previous & current
246   * datagram, we send the current datagram `uncompressed'.
247   */
248  oth = (struct tcphdr *) & ((int *) &cs->cs_ip)[hlen];
249  deltaS = hlen;
250  hlen += th->th_off;
251  hlen <<= 2;
252  if (hlen > m->m_len)
253    return (TYPE_IP);
254
255  if (((u_short *) ip)[0] != ((u_short *) & cs->cs_ip)[0] ||
256      ((u_short *) ip)[3] != ((u_short *) & cs->cs_ip)[3] ||
257      ((u_short *) ip)[4] != ((u_short *) & cs->cs_ip)[4] ||
258      THOFFSET(th) != THOFFSET(oth) ||
259      (deltaS > 5 &&
260       memcmp(ip + 1, &cs->cs_ip + 1, (deltaS - 5) << 2)) ||
261      (THOFFSET(th) > 5 &&
262       memcmp(th + 1, oth + 1, (THOFFSET(th) - 5) << 2))) {
263    goto uncompressed;
264  }
265
266  /*
267   * Figure out which of the changing fields changed.  The receiver expects
268   * changes in the order: urgent, window, ack, seq (the order minimizes the
269   * number of temporaries needed in this section of code).
270   */
271  if (th->th_flags & TH_URG) {
272    deltaS = ntohs(th->th_urp);
273    ENCODEZ(deltaS);
274    changes |= NEW_U;
275  } else if (th->th_urp != oth->th_urp) {
276
277    /*
278     * argh! URG not set but urp changed -- a sensible implementation should
279     * never do this but RFC793 doesn't prohibit the change so we have to
280     * deal with it.
281     */
282    goto uncompressed;
283  }
284  deltaS = (u_short) (ntohs(th->th_win) - ntohs(oth->th_win));
285  if (deltaS) {
286    ENCODE(deltaS);
287    changes |= NEW_W;
288  }
289  deltaA = ntohl(th->th_ack) - ntohl(oth->th_ack);
290  if (deltaA) {
291    if (deltaA > 0xffff) {
292      goto uncompressed;
293    }
294    ENCODE(deltaA);
295    changes |= NEW_A;
296  }
297  deltaS = ntohl(th->th_seq) - ntohl(oth->th_seq);
298  if (deltaS) {
299    if (deltaS > 0xffff) {
300      goto uncompressed;
301    }
302    ENCODE(deltaS);
303    changes |= NEW_S;
304  }
305  switch (changes) {
306
307  case 0:
308
309    /*
310     * Nothing changed. If this packet contains data and the last one didn't,
311     * this is probably a data packet following an ack (normal on an
312     * interactive connection) and we send it compressed.  Otherwise it's
313     * probably a retransmit, retransmitted ack or window probe.  Send it
314     * uncompressed in case the other side missed the compressed version.
315     */
316    if (ip->ip_len != cs->cs_ip.ip_len &&
317	ntohs(cs->cs_ip.ip_len) == hlen)
318      break;
319
320    /* FALLTHROUGH */
321
322  case SPECIAL_I:
323  case SPECIAL_D:
324
325    /*
326     * actual changes match one of our special case encodings -- send packet
327     * uncompressed.
328     */
329    goto uncompressed;
330
331  case NEW_S | NEW_A:
332    if (deltaS == deltaA &&
333	deltaS == ntohs(cs->cs_ip.ip_len) - hlen) {
334      /* special case for echoed terminal traffic */
335      changes = SPECIAL_I;
336      cp = new_seq;
337    }
338    break;
339
340  case NEW_S:
341    if (deltaS == ntohs(cs->cs_ip.ip_len) - hlen) {
342      /* special case for data xfer */
343      changes = SPECIAL_D;
344      cp = new_seq;
345    }
346    break;
347  }
348
349  deltaS = ntohs(ip->ip_id) - ntohs(cs->cs_ip.ip_id);
350  if (deltaS != 1) {
351    ENCODEZ(deltaS);
352    changes |= NEW_I;
353  }
354  if (th->th_flags & TH_PUSH)
355    changes |= TCP_PUSH_BIT;
356
357  /*
358   * Grab the cksum before we overwrite it below.  Then update our state with
359   * this packet's header.
360   */
361  deltaA = ntohs(th->th_sum);
362  memcpy(&cs->cs_ip, ip, hlen);
363
364  /*
365   * We want to use the original packet as our compressed packet. (cp -
366   * new_seq) is the number of bytes we need for compressed sequence numbers.
367   * In addition we need one byte for the change mask, one for the connection
368   * id and two for the tcp checksum. So, (cp - new_seq) + 4 bytes of header
369   * are needed.  hlen is how many bytes of the original packet to toss so
370   * subtract the two to get the new packet size.
371   */
372  deltaS = cp - new_seq;
373  cp = (u_char *) ip;
374
375  /*
376   * Since fastq traffic can jump ahead of the background traffic, we don't
377   * know what order packets will go on the line.  In this case, we always
378   * send a "new" connection id so the receiver state stays synchronized.
379   */
380  if (comp->last_xmit == cs->cs_id && compress_cid) {
381    hlen -= deltaS + 3;
382    cp += hlen;
383    *cp++ = changes;
384  } else {
385    comp->last_xmit = cs->cs_id;
386    hlen -= deltaS + 4;
387    cp += hlen;
388    *cp++ = changes | NEW_C;
389    *cp++ = cs->cs_id;
390  }
391  m->m_len -= hlen;
392  m->m_offset += hlen;
393  *cp++ = deltaA >> 8;
394  *cp++ = deltaA;
395  memcpy(cp, new_seq, deltaS);
396  slstat->sls_compressed++;
397  return (TYPE_COMPRESSED_TCP);
398
399  /*
400   * Update connection state cs & send uncompressed packet ('uncompressed'
401   * means a regular ip/tcp packet but with the 'conversation id' we hope to
402   * use on future compressed packets in the protocol field).
403   */
404uncompressed:
405  memcpy(&cs->cs_ip, ip, hlen);
406  ip->ip_p = cs->cs_id;
407  comp->last_xmit = cs->cs_id;
408  return (TYPE_UNCOMPRESSED_TCP);
409}
410
411
412int
413sl_uncompress_tcp(u_char ** bufp, int len, u_int type, struct slcompress *comp,
414                  struct slstat *slstat, int max_state)
415{
416  register u_char *cp;
417  register u_int hlen, changes;
418  register struct tcphdr *th;
419  register struct cstate *cs;
420  register struct ip *ip;
421  u_short *bp;
422
423  switch (type) {
424
425  case TYPE_UNCOMPRESSED_TCP:
426    ip = (struct ip *) * bufp;
427    if (ip->ip_p > max_state)
428      goto bad;
429    cs = &comp->rstate[comp->last_recv = ip->ip_p];
430    comp->flags &= ~SLF_TOSS;
431    ip->ip_p = IPPROTO_TCP;
432
433    /*
434     * Calculate the size of the TCP/IP header and make sure that we don't
435     * overflow the space we have available for it.
436     */
437    hlen = ip->ip_hl << 2;
438    if (hlen + sizeof(struct tcphdr) > len)
439      goto bad;
440    th = (struct tcphdr *) & ((char *) ip)[hlen];
441    hlen += THOFFSET(th) << 2;
442    if (hlen > MAX_HDR)
443      goto bad;
444    memcpy(&cs->cs_ip, ip, hlen);
445    cs->cs_hlen = hlen;
446    slstat->sls_uncompressedin++;
447    return (len);
448
449  default:
450    goto bad;
451
452  case TYPE_COMPRESSED_TCP:
453    break;
454  }
455
456  /* We've got a compressed packet. */
457  slstat->sls_compressedin++;
458  cp = *bufp;
459  changes = *cp++;
460  log_Printf(LogDEBUG, "compressed: changes = %02x\n", changes);
461
462  if (changes & NEW_C) {
463    /*
464     * Make sure the state index is in range, then grab the state. If we have
465     * a good state index, clear the 'discard' flag.
466     */
467    if (*cp > max_state || comp->last_recv == 255)
468      goto bad;
469
470    comp->flags &= ~SLF_TOSS;
471    comp->last_recv = *cp++;
472  } else {
473    /*
474     * this packet has an implicit state index.  If we've had a line error
475     * since the last time we got an explicit state index, we have to toss
476     * the packet.
477     */
478    if (comp->flags & SLF_TOSS) {
479      slstat->sls_tossed++;
480      return (0);
481    }
482  }
483  cs = &comp->rstate[comp->last_recv];
484  hlen = cs->cs_ip.ip_hl << 2;
485  th = (struct tcphdr *) & ((u_char *) & cs->cs_ip)[hlen];
486  th->th_sum = htons((*cp << 8) | cp[1]);
487  cp += 2;
488  if (changes & TCP_PUSH_BIT)
489    th->th_flags |= TH_PUSH;
490  else
491    th->th_flags &= ~TH_PUSH;
492
493  switch (changes & SPECIALS_MASK) {
494  case SPECIAL_I:
495    {
496      register u_int i = ntohs(cs->cs_ip.ip_len) - cs->cs_hlen;
497
498      th->th_ack = htonl(ntohl(th->th_ack) + i);
499      th->th_seq = htonl(ntohl(th->th_seq) + i);
500    }
501    break;
502
503  case SPECIAL_D:
504    th->th_seq = htonl(ntohl(th->th_seq) + ntohs(cs->cs_ip.ip_len)
505		       - cs->cs_hlen);
506    break;
507
508  default:
509    if (changes & NEW_U) {
510      th->th_flags |= TH_URG;
511      DECODEU(th->th_urp)
512    } else
513      th->th_flags &= ~TH_URG;
514    if (changes & NEW_W)
515      DECODES(th->th_win)
516	if (changes & NEW_A)
517	DECODEL(th->th_ack)
518	  if (changes & NEW_S) {
519	  log_Printf(LogDEBUG, "NEW_S: %02x, %02x, %02x\n",
520		    *cp, cp[1], cp[2]);
521	  DECODEL(th->th_seq)
522	}
523    break;
524  }
525  if (changes & NEW_I) {
526    DECODES(cs->cs_ip.ip_id)
527  } else
528    cs->cs_ip.ip_id = htons(ntohs(cs->cs_ip.ip_id) + 1);
529
530  log_Printf(LogDEBUG, "Uncompress: id = %04x, seq = %08lx\n",
531	    cs->cs_ip.ip_id, (u_long)ntohl(th->th_seq));
532
533  /*
534   * At this point, cp points to the first byte of data in the packet.
535   * Back up cp by the tcp/ip header length to make room for the
536   * reconstructed header (we assume the packet we were handed has enough
537   * space to prepend 128 bytes of header).  Adjust the length to account
538   * for the new header & fill in the IP total length.
539   */
540  len -= (cp - *bufp);
541  if (len < 0)
542    /*
543     * we must have dropped some characters (crc should detect this but the
544     * old slip framing won't)
545     */
546    goto bad;
547
548  *bufp = cp - cs->cs_hlen;
549  len += cs->cs_hlen;
550  cs->cs_ip.ip_len = htons(len);
551
552  /* recompute the ip header checksum */
553  cs->cs_ip.ip_sum = 0;
554  bp = (u_short *)&cs->cs_ip;
555  for (changes = 0; hlen > 0; hlen -= 2)
556    changes += *bp++;
557  changes = (changes & 0xffff) + (changes >> 16);
558  changes = (changes & 0xffff) + (changes >> 16);
559  cs->cs_ip.ip_sum = ~changes;
560
561  /* And copy the result into our buffer */
562  memcpy(*bufp, &cs->cs_ip, cs->cs_hlen);
563
564  return (len);
565bad:
566  comp->flags |= SLF_TOSS;
567  slstat->sls_errorin++;
568  return (0);
569}
570
571int
572sl_Show(struct cmdargs const *arg)
573{
574  prompt_Printf(arg->prompt, "VJ compression statistics:\n");
575  prompt_Printf(arg->prompt, "  Out:  %d (compress) / %d (total)",
576	        arg->bundle->ncp.ipcp.vj.slstat.sls_compressed,
577                arg->bundle->ncp.ipcp.vj.slstat.sls_packets);
578  prompt_Printf(arg->prompt, "  %d (miss) / %d (search)\n",
579	        arg->bundle->ncp.ipcp.vj.slstat.sls_misses,
580                arg->bundle->ncp.ipcp.vj.slstat.sls_searches);
581  prompt_Printf(arg->prompt, "  In:  %d (compress), %d (uncompress)",
582	        arg->bundle->ncp.ipcp.vj.slstat.sls_compressedin,
583                arg->bundle->ncp.ipcp.vj.slstat.sls_uncompressedin);
584  prompt_Printf(arg->prompt, "  %d (error),  %d (tossed)\n",
585	        arg->bundle->ncp.ipcp.vj.slstat.sls_errorin,
586                arg->bundle->ncp.ipcp.vj.slstat.sls_tossed);
587  return 0;
588}
589