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