tcp_input.c revision 1.90 1 /* $NetBSD: tcp_input.c,v 1.90 1999/08/11 03:02:18 thorpej Exp $ */
2
3 /*
4 %%% portions-copyright-nrl-95
5 Portions of this software are Copyright 1995-1998 by Randall Atkinson,
6 Ronald Lee, Daniel McDonald, Bao Phan, and Chris Winters. All Rights
7 Reserved. All rights under this copyright have been assigned to the US
8 Naval Research Laboratory (NRL). The NRL Copyright Notice and License
9 Agreement Version 1.1 (January 17, 1995) applies to these portions of the
10 software.
11 You should have received a copy of the license with this software. If you
12 didn't get a copy, you may request one from <license (at) ipv6.nrl.navy.mil>.
13
14 */
15
16 /*
17 * Copyright (C) 1995, 1996, 1997, and 1998 WIDE Project.
18 * All rights reserved.
19 *
20 * Redistribution and use in source and binary forms, with or without
21 * modification, are permitted provided that the following conditions
22 * are met:
23 * 1. Redistributions of source code must retain the above copyright
24 * notice, this list of conditions and the following disclaimer.
25 * 2. Redistributions in binary form must reproduce the above copyright
26 * notice, this list of conditions and the following disclaimer in the
27 * documentation and/or other materials provided with the distribution.
28 * 3. Neither the name of the project nor the names of its contributors
29 * may be used to endorse or promote products derived from this software
30 * without specific prior written permission.
31 *
32 * THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND
33 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
34 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
35 * ARE DISCLAIMED. IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE
36 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
37 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
38 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
39 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
40 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
41 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
42 * SUCH DAMAGE.
43 */
44
45 /*-
46 * Copyright (c) 1997, 1998, 1999 The NetBSD Foundation, Inc.
47 * All rights reserved.
48 *
49 * This code is derived from software contributed to The NetBSD Foundation
50 * by Jason R. Thorpe and Kevin M. Lahey of the Numerical Aerospace Simulation
51 * Facility, NASA Ames Research Center.
52 *
53 * Redistribution and use in source and binary forms, with or without
54 * modification, are permitted provided that the following conditions
55 * are met:
56 * 1. Redistributions of source code must retain the above copyright
57 * notice, this list of conditions and the following disclaimer.
58 * 2. Redistributions in binary form must reproduce the above copyright
59 * notice, this list of conditions and the following disclaimer in the
60 * documentation and/or other materials provided with the distribution.
61 * 3. All advertising materials mentioning features or use of this software
62 * must display the following acknowledgement:
63 * This product includes software developed by the NetBSD
64 * Foundation, Inc. and its contributors.
65 * 4. Neither the name of The NetBSD Foundation nor the names of its
66 * contributors may be used to endorse or promote products derived
67 * from this software without specific prior written permission.
68 *
69 * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
70 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
71 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
72 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
73 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
74 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
75 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
76 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
77 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
78 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
79 * POSSIBILITY OF SUCH DAMAGE.
80 */
81
82 /*
83 * Copyright (c) 1982, 1986, 1988, 1990, 1993, 1994, 1995
84 * The Regents of the University of California. All rights reserved.
85 *
86 * Redistribution and use in source and binary forms, with or without
87 * modification, are permitted provided that the following conditions
88 * are met:
89 * 1. Redistributions of source code must retain the above copyright
90 * notice, this list of conditions and the following disclaimer.
91 * 2. Redistributions in binary form must reproduce the above copyright
92 * notice, this list of conditions and the following disclaimer in the
93 * documentation and/or other materials provided with the distribution.
94 * 3. All advertising materials mentioning features or use of this software
95 * must display the following acknowledgement:
96 * This product includes software developed by the University of
97 * California, Berkeley and its contributors.
98 * 4. Neither the name of the University nor the names of its contributors
99 * may be used to endorse or promote products derived from this software
100 * without specific prior written permission.
101 *
102 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
103 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
104 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
105 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
106 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
107 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
108 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
109 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
110 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
111 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
112 * SUCH DAMAGE.
113 *
114 * @(#)tcp_input.c 8.12 (Berkeley) 5/24/95
115 */
116
117 /*
118 * TODO list for SYN cache stuff:
119 *
120 * Find room for a "state" field, which is needed to keep a
121 * compressed state for TIME_WAIT TCBs. It's been noted already
122 * that this is fairly important for very high-volume web and
123 * mail servers, which use a large number of short-lived
124 * connections.
125 */
126
127 #include "opt_inet.h"
128 #include "opt_ipsec.h"
129
130 #include <sys/param.h>
131 #include <sys/systm.h>
132 #include <sys/malloc.h>
133 #include <sys/mbuf.h>
134 #include <sys/protosw.h>
135 #include <sys/socket.h>
136 #include <sys/socketvar.h>
137 #include <sys/errno.h>
138 #include <sys/syslog.h>
139 #include <sys/pool.h>
140 #include <sys/domain.h>
141
142 #include <net/if.h>
143 #include <net/route.h>
144 #include <net/if_types.h>
145
146 #include <netinet/in.h>
147 #include <netinet/in_systm.h>
148 #include <netinet/ip.h>
149 #include <netinet/in_pcb.h>
150 #include <netinet/ip_var.h>
151
152 #ifdef INET6
153 #ifndef INET
154 #include <netinet/in.h>
155 #endif
156 #include <netinet/ip6.h>
157 #include <netinet6/in6_pcb.h>
158 #include <netinet6/ip6_var.h>
159 #include <netinet6/in6_var.h>
160 #include <netinet/icmp6.h>
161 #endif
162
163 #include <netinet/tcp.h>
164 #include <netinet/tcp_fsm.h>
165 #include <netinet/tcp_seq.h>
166 #include <netinet/tcp_timer.h>
167 #include <netinet/tcp_var.h>
168 #include <netinet/tcpip.h>
169 #include <netinet/tcp_debug.h>
170
171 #include <machine/stdarg.h>
172
173 #ifdef IPSEC
174 #include <netinet6/ipsec.h>
175 #include <netkey/key.h>
176 #include <netkey/key_debug.h>
177 #endif /*IPSEC*/
178 #ifdef INET6
179 #include "faith.h"
180 #endif
181
182 int tcprexmtthresh = 3;
183 int tcp_log_refused;
184
185 #define TCP_PAWS_IDLE (24 * 24 * 60 * 60 * PR_SLOWHZ)
186
187 /* for modulo comparisons of timestamps */
188 #define TSTMP_LT(a,b) ((int)((a)-(b)) < 0)
189 #define TSTMP_GEQ(a,b) ((int)((a)-(b)) >= 0)
190
191 /*
192 * Macro to compute ACK transmission behavior. Delay the ACK unless
193 * we have already delayed an ACK (must send an ACK every two segments).
194 * We also ACK immediately if we received a PUSH and the ACK-on-PUSH
195 * option is enabled.
196 */
197 #define TCP_SETUP_ACK(tp, th) \
198 do { \
199 if ((tp)->t_flags & TF_DELACK || \
200 (tcp_ack_on_push && (th)->th_flags & TH_PUSH)) \
201 tp->t_flags |= TF_ACKNOW; \
202 else \
203 TCP_SET_DELACK(tp); \
204 } while (0)
205
206 int
207 tcp_reass(tp, th, m, tlen)
208 register struct tcpcb *tp;
209 register struct tcphdr *th;
210 struct mbuf *m;
211 int *tlen;
212 {
213 register struct ipqent *p, *q, *nq, *tiqe = NULL;
214 struct socket *so = NULL;
215 int pkt_flags;
216 tcp_seq pkt_seq;
217 unsigned pkt_len;
218 u_long rcvpartdupbyte = 0;
219 u_long rcvoobyte;
220
221 if (tp->t_inpcb)
222 so = tp->t_inpcb->inp_socket;
223 #ifdef INET6
224 else if (tp->t_in6pcb)
225 so = tp->t_in6pcb->in6p_socket;
226 #endif
227
228 TCP_REASS_LOCK_CHECK(tp);
229
230 /*
231 * Call with th==0 after become established to
232 * force pre-ESTABLISHED data up to user socket.
233 */
234 if (th == 0)
235 goto present;
236
237 rcvoobyte = *tlen;
238 /*
239 * Copy these to local variables because the tcpiphdr
240 * gets munged while we are collapsing mbufs.
241 */
242 pkt_seq = th->th_seq;
243 pkt_len = *tlen;
244 pkt_flags = th->th_flags;
245 /*
246 * Find a segment which begins after this one does.
247 */
248 for (p = NULL, q = tp->segq.lh_first; q != NULL; q = nq) {
249 nq = q->ipqe_q.le_next;
250 /*
251 * If the received segment is just right after this
252 * fragment, merge the two together and then check
253 * for further overlaps.
254 */
255 if (q->ipqe_seq + q->ipqe_len == pkt_seq) {
256 #ifdef TCPREASS_DEBUG
257 printf("tcp_reass[%p]: concat %u:%u(%u) to %u:%u(%u)\n",
258 tp, pkt_seq, pkt_seq + pkt_len, pkt_len,
259 q->ipqe_seq, q->ipqe_seq + q->ipqe_len, q->ipqe_len);
260 #endif
261 pkt_len += q->ipqe_len;
262 pkt_flags |= q->ipqe_flags;
263 pkt_seq = q->ipqe_seq;
264 m_cat(q->ipqe_m, m);
265 m = q->ipqe_m;
266 goto free_ipqe;
267 }
268 /*
269 * If the received segment is completely past this
270 * fragment, we need to go the next fragment.
271 */
272 if (SEQ_LT(q->ipqe_seq + q->ipqe_len, pkt_seq)) {
273 p = q;
274 continue;
275 }
276 /*
277 * If the fragment is past the received segment,
278 * it (or any following) can't be concatenated.
279 */
280 if (SEQ_GT(q->ipqe_seq, pkt_seq + pkt_len))
281 break;
282 /*
283 * We've received all the data in this segment before.
284 * mark it as a duplicate and return.
285 */
286 if (SEQ_LEQ(q->ipqe_seq, pkt_seq) &&
287 SEQ_GEQ(q->ipqe_seq + q->ipqe_len, pkt_seq + pkt_len)) {
288 tcpstat.tcps_rcvduppack++;
289 tcpstat.tcps_rcvdupbyte += pkt_len;
290 m_freem(m);
291 if (tiqe != NULL)
292 pool_put(&ipqent_pool, tiqe);
293 return (0);
294 }
295 /*
296 * Received segment completely overlaps this fragment
297 * so we drop the fragment (this keeps the temporal
298 * ordering of segments correct).
299 */
300 if (SEQ_GEQ(q->ipqe_seq, pkt_seq) &&
301 SEQ_LEQ(q->ipqe_seq + q->ipqe_len, pkt_seq + pkt_len)) {
302 rcvpartdupbyte += q->ipqe_len;
303 m_freem(q->ipqe_m);
304 goto free_ipqe;
305 }
306 /*
307 * RX'ed segment extends past the end of the
308 * fragment. Drop the overlapping bytes. Then
309 * merge the fragment and segment then treat as
310 * a longer received packet.
311 */
312 if (SEQ_LT(q->ipqe_seq, pkt_seq)
313 && SEQ_GT(q->ipqe_seq + q->ipqe_len, pkt_seq)) {
314 int overlap = q->ipqe_seq + q->ipqe_len - pkt_seq;
315 #ifdef TCPREASS_DEBUG
316 printf("tcp_reass[%p]: trim starting %d bytes of %u:%u(%u)\n",
317 tp, overlap,
318 pkt_seq, pkt_seq + pkt_len, pkt_len);
319 #endif
320 m_adj(m, overlap);
321 rcvpartdupbyte += overlap;
322 m_cat(q->ipqe_m, m);
323 m = q->ipqe_m;
324 pkt_seq = q->ipqe_seq;
325 pkt_len += q->ipqe_len - overlap;
326 rcvoobyte -= overlap;
327 goto free_ipqe;
328 }
329 /*
330 * RX'ed segment extends past the front of the
331 * fragment. Drop the overlapping bytes on the
332 * received packet. The packet will then be
333 * contatentated with this fragment a bit later.
334 */
335 if (SEQ_GT(q->ipqe_seq, pkt_seq)
336 && SEQ_LT(q->ipqe_seq, pkt_seq + pkt_len)) {
337 int overlap = pkt_seq + pkt_len - q->ipqe_seq;
338 #ifdef TCPREASS_DEBUG
339 printf("tcp_reass[%p]: trim trailing %d bytes of %u:%u(%u)\n",
340 tp, overlap,
341 pkt_seq, pkt_seq + pkt_len, pkt_len);
342 #endif
343 m_adj(m, -overlap);
344 pkt_len -= overlap;
345 rcvpartdupbyte += overlap;
346 rcvoobyte -= overlap;
347 }
348 /*
349 * If the received segment immediates precedes this
350 * fragment then tack the fragment onto this segment
351 * and reinsert the data.
352 */
353 if (q->ipqe_seq == pkt_seq + pkt_len) {
354 #ifdef TCPREASS_DEBUG
355 printf("tcp_reass[%p]: append %u:%u(%u) to %u:%u(%u)\n",
356 tp, q->ipqe_seq, q->ipqe_seq + q->ipqe_len, q->ipqe_len,
357 pkt_seq, pkt_seq + pkt_len, pkt_len);
358 #endif
359 pkt_len += q->ipqe_len;
360 pkt_flags |= q->ipqe_flags;
361 m_cat(m, q->ipqe_m);
362 LIST_REMOVE(q, ipqe_q);
363 LIST_REMOVE(q, ipqe_timeq);
364 if (tiqe == NULL) {
365 tiqe = q;
366 } else {
367 pool_put(&ipqent_pool, q);
368 }
369 break;
370 }
371 /*
372 * If the fragment is before the segment, remember it.
373 * When this loop is terminated, p will contain the
374 * pointer to fragment that is right before the received
375 * segment.
376 */
377 if (SEQ_LEQ(q->ipqe_seq, pkt_seq))
378 p = q;
379
380 continue;
381
382 /*
383 * This is a common operation. It also will allow
384 * to save doing a malloc/free in most instances.
385 */
386 free_ipqe:
387 LIST_REMOVE(q, ipqe_q);
388 LIST_REMOVE(q, ipqe_timeq);
389 if (tiqe == NULL) {
390 tiqe = q;
391 } else {
392 pool_put(&ipqent_pool, q);
393 }
394 }
395
396 /*
397 * Allocate a new queue entry since the received segment did not
398 * collapse onto any other out-of-order block; thus we are allocating
399 * a new block. If it had collapsed, tiqe would not be NULL and
400 * we would be reusing it.
401 * XXX If we can't, just drop the packet. XXX
402 */
403 if (tiqe == NULL) {
404 tiqe = pool_get(&ipqent_pool, PR_NOWAIT);
405 if (tiqe == NULL) {
406 tcpstat.tcps_rcvmemdrop++;
407 m_freem(m);
408 return (0);
409 }
410 }
411
412 /*
413 * Update the counters.
414 */
415 tcpstat.tcps_rcvoopack++;
416 tcpstat.tcps_rcvoobyte += rcvoobyte;
417 if (rcvpartdupbyte) {
418 tcpstat.tcps_rcvpartduppack++;
419 tcpstat.tcps_rcvpartdupbyte += rcvpartdupbyte;
420 }
421
422 /*
423 * Insert the new fragment queue entry into both queues.
424 */
425 tiqe->ipqe_m = m;
426 tiqe->ipqe_seq = pkt_seq;
427 tiqe->ipqe_len = pkt_len;
428 tiqe->ipqe_flags = pkt_flags;
429 if (p == NULL) {
430 LIST_INSERT_HEAD(&tp->segq, tiqe, ipqe_q);
431 #ifdef TCPREASS_DEBUG
432 if (tiqe->ipqe_seq != tp->rcv_nxt)
433 printf("tcp_reass[%p]: insert %u:%u(%u) at front\n",
434 tp, pkt_seq, pkt_seq + pkt_len, pkt_len);
435 #endif
436 } else {
437 LIST_INSERT_AFTER(p, tiqe, ipqe_q);
438 #ifdef TCPREASS_DEBUG
439 printf("tcp_reass[%p]: insert %u:%u(%u) after %u:%u(%u)\n",
440 tp, pkt_seq, pkt_seq + pkt_len, pkt_len,
441 p->ipqe_seq, p->ipqe_seq + p->ipqe_len, p->ipqe_len);
442 #endif
443 }
444
445 LIST_INSERT_HEAD(&tp->timeq, tiqe, ipqe_timeq);
446
447 present:
448 /*
449 * Present data to user, advancing rcv_nxt through
450 * completed sequence space.
451 */
452 if (TCPS_HAVEESTABLISHED(tp->t_state) == 0)
453 return (0);
454 q = tp->segq.lh_first;
455 if (q == NULL || q->ipqe_seq != tp->rcv_nxt)
456 return (0);
457 if (tp->t_state == TCPS_SYN_RECEIVED && q->ipqe_len)
458 return (0);
459
460 tp->rcv_nxt += q->ipqe_len;
461 pkt_flags = q->ipqe_flags & TH_FIN;
462
463 LIST_REMOVE(q, ipqe_q);
464 LIST_REMOVE(q, ipqe_timeq);
465 if (so->so_state & SS_CANTRCVMORE)
466 m_freem(q->ipqe_m);
467 else
468 sbappend(&so->so_rcv, q->ipqe_m);
469 pool_put(&ipqent_pool, q);
470 sorwakeup(so);
471 return (pkt_flags);
472 }
473
474 #if defined(INET6) && !defined(TCP6)
475 int
476 tcp6_input(mp, offp, proto)
477 struct mbuf **mp;
478 int *offp, proto;
479 {
480 struct mbuf *m = *mp;
481
482 #if defined(NFAITH) && 0 < NFAITH
483 if (m->m_pkthdr.rcvif) {
484 if (m->m_pkthdr.rcvif->if_type == IFT_FAITH) {
485 /* XXX send icmp6 host/port unreach? */
486 m_freem(m);
487 return IPPROTO_DONE;
488 }
489 }
490 #endif
491
492 /*
493 * draft-itojun-ipv6-tcp-to-anycast
494 * better place to put this in?
495 */
496 if (m->m_flags & M_ANYCAST6) {
497 if (m->m_len >= sizeof(struct ip6_hdr)) {
498 struct ip6_hdr *ip6 = mtod(m, struct ip6_hdr *);
499 icmp6_error(m, ICMP6_DST_UNREACH,
500 ICMP6_DST_UNREACH_ADDR,
501 (caddr_t)&ip6->ip6_dst - (caddr_t)ip6);
502 } else
503 m_freem(m);
504 return IPPROTO_DONE;
505 }
506
507 tcp_input(m, *offp, proto);
508 return IPPROTO_DONE;
509 }
510 #endif
511
512 /*
513 * TCP input routine, follows pages 65-76 of the
514 * protocol specification dated September, 1981 very closely.
515 */
516 void
517 #if __STDC__
518 tcp_input(struct mbuf *m, ...)
519 #else
520 tcp_input(m, va_alist)
521 register struct mbuf *m;
522 #endif
523 {
524 int proto;
525 register struct tcphdr *th;
526 struct ip *ip;
527 register struct inpcb *inp;
528 #ifdef INET6
529 struct ip6_hdr *ip6;
530 register struct in6pcb *in6p;
531 #endif
532 caddr_t optp = NULL;
533 int optlen = 0;
534 int len, tlen, toff, hdroptlen = 0;
535 register struct tcpcb *tp = 0;
536 register int tiflags;
537 struct socket *so = NULL;
538 int todrop, acked, ourfinisacked, needoutput = 0;
539 short ostate = 0;
540 int iss = 0;
541 u_long tiwin;
542 struct tcp_opt_info opti;
543 int off, iphlen;
544 va_list ap;
545 int af; /* af on the wire */
546 struct mbuf *tcp_saveti = NULL;
547
548 va_start(ap, m);
549 toff = va_arg(ap, int);
550 proto = va_arg(ap, int);
551 va_end(ap);
552
553 tcpstat.tcps_rcvtotal++;
554
555 bzero(&opti, sizeof(opti));
556 opti.ts_present = 0;
557 opti.maxseg = 0;
558
559 /*
560 * Get IP and TCP header together in first mbuf.
561 * Note: IP leaves IP header in first mbuf.
562 */
563 ip = mtod(m, struct ip *);
564 #ifdef INET6
565 ip6 = NULL;
566 #endif
567 switch (ip->ip_v) {
568 case 4:
569 af = AF_INET;
570 iphlen = sizeof(struct ip);
571 /* would like to get rid of this... */
572 if (toff > sizeof (struct ip)) {
573 ip_stripoptions(m, (struct mbuf *)0);
574 toff = sizeof(struct ip);
575 }
576 if (m->m_len < toff + sizeof (struct tcphdr)) {
577 if ((m = m_pullup(m, toff + sizeof (struct tcphdr))) == 0) {
578 tcpstat.tcps_rcvshort++;
579 return;
580 }
581 }
582 ip = mtod(m, struct ip *);
583 th = (struct tcphdr *)(mtod(m, caddr_t) + toff);
584
585 /*
586 * Checksum extended TCP header and data.
587 */
588 len = ip->ip_len;
589 tlen = len - toff;
590 {
591 struct ipovly *ipov;
592 ipov = (struct ipovly *)ip;
593 bzero(ipov->ih_x1, sizeof ipov->ih_x1);
594 ipov->ih_len = htons(tlen);
595 }
596 if (in_cksum(m, len) != 0) {
597 tcpstat.tcps_rcvbadsum++;
598 goto drop;
599 }
600 break;
601 #ifdef INET6
602 case 6:
603 ip = NULL;
604 iphlen = sizeof(struct ip6_hdr);
605 af = AF_INET6;
606 if (m->m_len < toff + sizeof(struct tcphdr)) {
607 m = m_pullup(m, toff + sizeof(struct tcphdr)); /*XXX*/
608 if (m == NULL) {
609 tcpstat.tcps_rcvshort++;
610 return;
611 }
612 }
613 ip6 = mtod(m, struct ip6_hdr *);
614 th = (struct tcphdr *)(mtod(m, caddr_t) + toff);
615
616 /*
617 * Checksum extended TCP header and data.
618 */
619 len = m->m_pkthdr.len;
620 tlen = len - toff;
621 if (in6_cksum(m, IPPROTO_TCP, toff, tlen)) {
622 tcpstat.tcps_rcvbadsum++;
623 goto drop;
624 }
625 break;
626 #endif
627 default:
628 m_freem(m);
629 return;
630 }
631
632 /*
633 * Check that TCP offset makes sense,
634 * pull out TCP options and adjust length. XXX
635 */
636 off = th->th_off << 2;
637 if (off < sizeof (struct tcphdr) || off > tlen) {
638 tcpstat.tcps_rcvbadoff++;
639 goto drop;
640 }
641 tlen -= off;
642
643 /*
644 * tcp_input() has been modified to use tlen to mean the TCP data
645 * length throughout the function. Other functions can use
646 * m->m_pkthdr.len as the basis for calculating the TCP data length.
647 * rja
648 */
649
650 if (off > sizeof (struct tcphdr)) {
651 if (m->m_len < toff + off) {
652 if ((m = m_pullup(m, toff + off)) == 0) {
653 tcpstat.tcps_rcvshort++;
654 return;
655 }
656 switch (af) {
657 case AF_INET:
658 ip = mtod(m, struct ip *);
659 break;
660 #ifdef INET6
661 case AF_INET6:
662 ip6 = mtod(m, struct ip6_hdr *);
663 break;
664 #endif
665 }
666 th = (struct tcphdr *)(mtod(m, caddr_t) + toff);
667 }
668 optlen = off - sizeof (struct tcphdr);
669 optp = mtod(m, caddr_t) + toff + sizeof (struct tcphdr);
670 /*
671 * Do quick retrieval of timestamp options ("options
672 * prediction?"). If timestamp is the only option and it's
673 * formatted as recommended in RFC 1323 appendix A, we
674 * quickly get the values now and not bother calling
675 * tcp_dooptions(), etc.
676 */
677 if ((optlen == TCPOLEN_TSTAMP_APPA ||
678 (optlen > TCPOLEN_TSTAMP_APPA &&
679 optp[TCPOLEN_TSTAMP_APPA] == TCPOPT_EOL)) &&
680 *(u_int32_t *)optp == htonl(TCPOPT_TSTAMP_HDR) &&
681 (th->th_flags & TH_SYN) == 0) {
682 opti.ts_present = 1;
683 opti.ts_val = ntohl(*(u_int32_t *)(optp + 4));
684 opti.ts_ecr = ntohl(*(u_int32_t *)(optp + 8));
685 optp = NULL; /* we've parsed the options */
686 }
687 }
688 tiflags = th->th_flags;
689
690 /*
691 * Convert TCP protocol specific fields to host format.
692 */
693 NTOHL(th->th_seq);
694 NTOHL(th->th_ack);
695 NTOHS(th->th_win);
696 NTOHS(th->th_urp);
697
698 /*
699 * Locate pcb for segment.
700 */
701 findpcb:
702 inp = NULL;
703 #ifdef INET6
704 in6p = NULL;
705 #endif
706 switch (af) {
707 case AF_INET:
708 inp = in_pcblookup_connect(&tcbtable, ip->ip_src, th->th_sport,
709 ip->ip_dst, th->th_dport);
710 if (inp == 0) {
711 ++tcpstat.tcps_pcbhashmiss;
712 inp = in_pcblookup_bind(&tcbtable, ip->ip_dst, th->th_dport);
713 }
714 #if defined(INET6) && !defined(TCP6)
715 if (inp == 0) {
716 struct in6_addr s, d;
717
718 /* mapped addr case */
719 bzero(&s, sizeof(s));
720 s.s6_addr16[5] = htons(0xffff);
721 bcopy(&ip->ip_src, &s.s6_addr32[3], sizeof(ip->ip_src));
722 bzero(&d, sizeof(d));
723 d.s6_addr16[5] = htons(0xffff);
724 bcopy(&ip->ip_dst, &d.s6_addr32[3], sizeof(ip->ip_dst));
725 in6p = in6_pcblookup_connect(&tcb6, &s, th->th_sport,
726 &d, th->th_dport, 0);
727 if (in6p == 0) {
728 ++tcpstat.tcps_pcbhashmiss;
729 in6p = in6_pcblookup_bind(&tcb6, &d,
730 th->th_dport, 0);
731 }
732 }
733 #endif
734 #ifndef INET6
735 if (inp == 0)
736 #else
737 if (inp == 0 && in6p == 0)
738 #endif
739 {
740 ++tcpstat.tcps_noport;
741 if (tcp_log_refused && (tiflags & TH_SYN)) {
742 #ifndef INET6
743 char src[4*sizeof "123"];
744 char dst[4*sizeof "123"];
745 #else
746 char src[INET6_ADDRSTRLEN];
747 char dst[INET6_ADDRSTRLEN];
748 #endif
749 if (ip) {
750 strcpy(src, inet_ntoa(ip->ip_dst));
751 strcpy(dst, inet_ntoa(ip->ip_dst));
752 }
753 #ifdef INET6
754 else if (ip6) {
755 strcpy(src, ip6_sprintf(&ip6->ip6_dst));
756 strcpy(dst, ip6_sprintf(&ip6->ip6_src));
757 }
758 #endif
759 else {
760 strcpy(src, "(unknown)");
761 strcpy(dst, "(unknown)");
762 }
763 log(LOG_INFO,
764 "Connection attempt to TCP %s:%d from %s:%d\n",
765 src, ntohs(th->th_dport),
766 dst, ntohs(th->th_sport));
767 }
768 goto dropwithreset;
769 }
770 #ifdef IPSEC
771 if (inp && ipsec4_in_reject(m, inp)) {
772 ipsecstat.in_polvio++;
773 goto drop;
774 }
775 #ifdef INET6
776 else if (in6p && ipsec4_in_reject_so(m, in6p->in6p_socket)) {
777 ipsecstat.in_polvio++;
778 goto drop;
779 }
780 #endif
781 #endif /*IPSEC*/
782 break;
783 #if defined(INET6) && !defined(TCP6)
784 case AF_INET6:
785 {
786 int faith;
787
788 #if defined(NFAITH) && NFAITH > 0
789 if (m->m_pkthdr.rcvif
790 && m->m_pkthdr.rcvif->if_type == IFT_FAITH) {
791 faith = 1;
792 } else
793 faith = 0;
794 #else
795 faith = 0;
796 #endif
797 in6p = in6_pcblookup_connect(&tcb6, &ip6->ip6_src, th->th_sport,
798 &ip6->ip6_dst, th->th_dport, faith);
799 if (in6p == NULL) {
800 ++tcpstat.tcps_pcbhashmiss;
801 in6p = in6_pcblookup_bind(&tcb6, &ip6->ip6_dst,
802 th->th_dport, faith);
803 }
804 if (in6p == NULL) {
805 ++tcpstat.tcps_noport;
806 goto dropwithreset;
807 }
808 #ifdef IPSEC
809 if (ipsec6_in_reject(m, in6p)) {
810 ipsec6stat.in_polvio++;
811 goto drop;
812 }
813 #endif /*IPSEC*/
814 break;
815 }
816 #endif
817 }
818
819 /*
820 * If the state is CLOSED (i.e., TCB does not exist) then
821 * all data in the incoming segment is discarded.
822 * If the TCB exists but is in CLOSED state, it is embryonic,
823 * but should either do a listen or a connect soon.
824 */
825 tp = NULL;
826 so = NULL;
827 if (inp) {
828 tp = intotcpcb(inp);
829 so = inp->inp_socket;
830 }
831 #ifdef INET6
832 else if (in6p) {
833 tp = in6totcpcb(in6p);
834 so = in6p->in6p_socket;
835 }
836 #endif
837 if (tp == 0) {
838 goto dropwithreset;
839 }
840 if (tp->t_state == TCPS_CLOSED)
841 goto drop;
842
843 /* Unscale the window into a 32-bit value. */
844 if ((tiflags & TH_SYN) == 0)
845 tiwin = th->th_win << tp->snd_scale;
846 else
847 tiwin = th->th_win;
848
849 #ifdef INET6
850 /* save packet options if user wanted */
851 if (in6p && (in6p->in6p_flags & IN6P_CONTROLOPTS)) {
852 if (in6p->in6p_options) {
853 m_freem(in6p->in6p_options);
854 in6p->in6p_options = 0;
855 }
856 ip6_savecontrol(in6p, &in6p->in6p_options, ip6, m);
857 }
858 #endif
859
860 if (so->so_options & (SO_DEBUG|SO_ACCEPTCONN)) {
861 union syn_cache_sa src;
862 union syn_cache_sa dst;
863
864 bzero(&src, sizeof(src));
865 bzero(&dst, sizeof(dst));
866 switch (af) {
867 case AF_INET:
868 src.sin.sin_len = sizeof(struct sockaddr_in);
869 src.sin.sin_family = AF_INET;
870 src.sin.sin_addr = ip->ip_src;
871 src.sin.sin_port = th->th_sport;
872
873 dst.sin.sin_len = sizeof(struct sockaddr_in);
874 dst.sin.sin_family = AF_INET;
875 dst.sin.sin_addr = ip->ip_dst;
876 dst.sin.sin_port = th->th_dport;
877 break;
878 #ifdef INET6
879 case AF_INET6:
880 src.sin6.sin6_len = sizeof(struct sockaddr_in6);
881 src.sin6.sin6_family = AF_INET6;
882 src.sin6.sin6_addr = ip6->ip6_src;
883 src.sin6.sin6_port = th->th_sport;
884
885 dst.sin6.sin6_len = sizeof(struct sockaddr_in6);
886 dst.sin6.sin6_family = AF_INET6;
887 dst.sin6.sin6_addr = ip6->ip6_dst;
888 dst.sin6.sin6_port = th->th_dport;
889 break;
890 #endif /* INET6 */
891 default:
892 goto badsyn; /*sanity*/
893 }
894
895 if (so->so_options & SO_DEBUG) {
896 ostate = tp->t_state;
897 tcp_saveti = m_copym(m, 0, iphlen, M_DONTWAIT);
898 if (M_TRAILINGSPACE(tcp_saveti) < sizeof(struct tcphdr)) {
899 m_freem(tcp_saveti);
900 tcp_saveti = NULL;
901 } else {
902 tcp_saveti->m_len += sizeof(struct tcphdr);
903 bcopy(th, mtod(tcp_saveti, caddr_t) + iphlen,
904 sizeof(struct tcphdr));
905 }
906 if (tcp_saveti) {
907 /*
908 * need to recover version # field, which was
909 * overwritten on ip_cksum computation.
910 */
911 struct ip *sip;
912 sip = mtod(tcp_saveti, struct ip *);
913 switch (af) {
914 case AF_INET:
915 sip->ip_v = 4;
916 break;
917 #ifdef INET6
918 case AF_INET6:
919 sip->ip_v = 6;
920 break;
921 #endif
922 }
923 }
924 }
925 if (so->so_options & SO_ACCEPTCONN) {
926 if ((tiflags & (TH_RST|TH_ACK|TH_SYN)) != TH_SYN) {
927 if (tiflags & TH_RST) {
928 syn_cache_reset(&src.sa, &dst.sa, th);
929 } else if ((tiflags & (TH_ACK|TH_SYN)) ==
930 (TH_ACK|TH_SYN)) {
931 /*
932 * Received a SYN,ACK. This should
933 * never happen while we are in
934 * LISTEN. Send an RST.
935 */
936 goto badsyn;
937 } else if (tiflags & TH_ACK) {
938 so = syn_cache_get(&src.sa, &dst.sa,
939 th, toff, tlen, so, m);
940 if (so == NULL) {
941 /*
942 * We don't have a SYN for
943 * this ACK; send an RST.
944 */
945 goto badsyn;
946 } else if (so ==
947 (struct socket *)(-1)) {
948 /*
949 * We were unable to create
950 * the connection. If the
951 * 3-way handshake was
952 * completed, and RST has
953 * been sent to the peer.
954 * Since the mbuf might be
955 * in use for the reply,
956 * do not free it.
957 */
958 m = NULL;
959 } else {
960 /*
961 * We have created a
962 * full-blown connection.
963 */
964 tp = NULL;
965 inp = NULL;
966 #ifdef INET6
967 in6p = NULL;
968 #endif
969 switch (so->so_proto->pr_domain->dom_family) {
970 case AF_INET:
971 inp = sotoinpcb(so);
972 tp = intotcpcb(inp);
973 break;
974 #ifdef INET6
975 case AF_INET6:
976 in6p = sotoin6pcb(so);
977 tp = in6totcpcb(in6p);
978 break;
979 #endif
980 }
981 if (tp == NULL)
982 goto badsyn; /*XXX*/
983 tiwin <<= tp->snd_scale;
984 goto after_listen;
985 }
986 } else {
987 /*
988 * None of RST, SYN or ACK was set.
989 * This is an invalid packet for a
990 * TCB in LISTEN state. Send a RST.
991 */
992 goto badsyn;
993 }
994 } else {
995 /*
996 * Received a SYN.
997 */
998
999 /*
1000 * LISTEN socket received a SYN
1001 * from itself? This can't possibly
1002 * be valid; drop the packet.
1003 */
1004 if (th->th_sport == th->th_dport) {
1005 int i;
1006
1007 switch (af) {
1008 case AF_INET:
1009 i = in_hosteq(ip->ip_src, ip->ip_dst);
1010 break;
1011 #ifdef INET6
1012 case AF_INET6:
1013 i = IN6_ARE_ADDR_EQUAL(&ip6->ip6_src, &ip6->ip6_dst);
1014 break;
1015 #endif
1016 default:
1017 i = 1;
1018 }
1019 if (i) {
1020 tcpstat.tcps_badsyn++;
1021 goto drop;
1022 }
1023 }
1024
1025 /*
1026 * SYN looks ok; create compressed TCP
1027 * state for it.
1028 */
1029 if (so->so_qlen <= so->so_qlimit &&
1030 syn_cache_add(&src.sa, &dst.sa, th, tlen,
1031 so, m, optp, optlen, &opti))
1032 m = NULL;
1033 }
1034 goto drop;
1035 }
1036 }
1037
1038 after_listen:
1039 #ifdef DIAGNOSTIC
1040 /*
1041 * Should not happen now that all embryonic connections
1042 * are handled with compressed state.
1043 */
1044 if (tp->t_state == TCPS_LISTEN)
1045 panic("tcp_input: TCPS_LISTEN");
1046 #endif
1047
1048 /*
1049 * Segment received on connection.
1050 * Reset idle time and keep-alive timer.
1051 */
1052 tp->t_idle = 0;
1053 if (TCPS_HAVEESTABLISHED(tp->t_state))
1054 TCP_TIMER_ARM(tp, TCPT_KEEP, tcp_keepidle);
1055
1056 /*
1057 * Process options.
1058 */
1059 if (optp)
1060 tcp_dooptions(tp, optp, optlen, th, &opti);
1061
1062 /*
1063 * Header prediction: check for the two common cases
1064 * of a uni-directional data xfer. If the packet has
1065 * no control flags, is in-sequence, the window didn't
1066 * change and we're not retransmitting, it's a
1067 * candidate. If the length is zero and the ack moved
1068 * forward, we're the sender side of the xfer. Just
1069 * free the data acked & wake any higher level process
1070 * that was blocked waiting for space. If the length
1071 * is non-zero and the ack didn't move, we're the
1072 * receiver side. If we're getting packets in-order
1073 * (the reassembly queue is empty), add the data to
1074 * the socket buffer and note that we need a delayed ack.
1075 */
1076 if (tp->t_state == TCPS_ESTABLISHED &&
1077 (tiflags & (TH_SYN|TH_FIN|TH_RST|TH_URG|TH_ACK)) == TH_ACK &&
1078 (!opti.ts_present || TSTMP_GEQ(opti.ts_val, tp->ts_recent)) &&
1079 th->th_seq == tp->rcv_nxt &&
1080 tiwin && tiwin == tp->snd_wnd &&
1081 tp->snd_nxt == tp->snd_max) {
1082
1083 /*
1084 * If last ACK falls within this segment's sequence numbers,
1085 * record the timestamp.
1086 */
1087 if (opti.ts_present &&
1088 SEQ_LEQ(th->th_seq, tp->last_ack_sent) &&
1089 SEQ_LT(tp->last_ack_sent, th->th_seq + tlen)) {
1090 tp->ts_recent_age = tcp_now;
1091 tp->ts_recent = opti.ts_val;
1092 }
1093
1094 if (tlen == 0) {
1095 if (SEQ_GT(th->th_ack, tp->snd_una) &&
1096 SEQ_LEQ(th->th_ack, tp->snd_max) &&
1097 tp->snd_cwnd >= tp->snd_wnd &&
1098 tp->t_dupacks < tcprexmtthresh) {
1099 /*
1100 * this is a pure ack for outstanding data.
1101 */
1102 ++tcpstat.tcps_predack;
1103 if (opti.ts_present && opti.ts_ecr)
1104 tcp_xmit_timer(tp,
1105 tcp_now - opti.ts_ecr + 1);
1106 else if (tp->t_rtt &&
1107 SEQ_GT(th->th_ack, tp->t_rtseq))
1108 tcp_xmit_timer(tp, tp->t_rtt);
1109 acked = th->th_ack - tp->snd_una;
1110 tcpstat.tcps_rcvackpack++;
1111 tcpstat.tcps_rcvackbyte += acked;
1112 sbdrop(&so->so_snd, acked);
1113 tp->snd_una = th->th_ack;
1114 m_freem(m);
1115
1116 /*
1117 * If all outstanding data are acked, stop
1118 * retransmit timer, otherwise restart timer
1119 * using current (possibly backed-off) value.
1120 * If process is waiting for space,
1121 * wakeup/selwakeup/signal. If data
1122 * are ready to send, let tcp_output
1123 * decide between more output or persist.
1124 */
1125 if (tp->snd_una == tp->snd_max)
1126 TCP_TIMER_DISARM(tp, TCPT_REXMT);
1127 else if (TCP_TIMER_ISARMED(tp,
1128 TCPT_PERSIST) == 0)
1129 TCP_TIMER_ARM(tp, TCPT_REXMT,
1130 tp->t_rxtcur);
1131
1132 sowwakeup(so);
1133 if (so->so_snd.sb_cc)
1134 (void) tcp_output(tp);
1135 if (tcp_saveti)
1136 m_freem(tcp_saveti);
1137 return;
1138 }
1139 } else if (th->th_ack == tp->snd_una &&
1140 tp->segq.lh_first == NULL &&
1141 tlen <= sbspace(&so->so_rcv)) {
1142 /*
1143 * this is a pure, in-sequence data packet
1144 * with nothing on the reassembly queue and
1145 * we have enough buffer space to take it.
1146 */
1147 ++tcpstat.tcps_preddat;
1148 tp->rcv_nxt += tlen;
1149 tcpstat.tcps_rcvpack++;
1150 tcpstat.tcps_rcvbyte += tlen;
1151 /*
1152 * Drop TCP, IP headers and TCP options then add data
1153 * to socket buffer.
1154 */
1155 m->m_data += toff + off;
1156 m->m_len -= (toff + off);
1157 sbappend(&so->so_rcv, m);
1158 sorwakeup(so);
1159 TCP_SETUP_ACK(tp, th);
1160 if (tp->t_flags & TF_ACKNOW)
1161 (void) tcp_output(tp);
1162 if (tcp_saveti)
1163 m_freem(tcp_saveti);
1164 return;
1165 }
1166 }
1167
1168 /*
1169 * Drop TCP, IP headers and TCP options.
1170 */
1171 hdroptlen = toff + off;
1172 m->m_data += hdroptlen;
1173 m->m_len -= hdroptlen;
1174
1175 /*
1176 * Calculate amount of space in receive window,
1177 * and then do TCP input processing.
1178 * Receive window is amount of space in rcv queue,
1179 * but not less than advertised window.
1180 */
1181 { int win;
1182
1183 win = sbspace(&so->so_rcv);
1184 if (win < 0)
1185 win = 0;
1186 tp->rcv_wnd = imax(win, (int)(tp->rcv_adv - tp->rcv_nxt));
1187 }
1188
1189 switch (tp->t_state) {
1190
1191 /*
1192 * If the state is SYN_SENT:
1193 * if seg contains an ACK, but not for our SYN, drop the input.
1194 * if seg contains a RST, then drop the connection.
1195 * if seg does not contain SYN, then drop it.
1196 * Otherwise this is an acceptable SYN segment
1197 * initialize tp->rcv_nxt and tp->irs
1198 * if seg contains ack then advance tp->snd_una
1199 * if SYN has been acked change to ESTABLISHED else SYN_RCVD state
1200 * arrange for segment to be acked (eventually)
1201 * continue processing rest of data/controls, beginning with URG
1202 */
1203 case TCPS_SYN_SENT:
1204 if ((tiflags & TH_ACK) &&
1205 (SEQ_LEQ(th->th_ack, tp->iss) ||
1206 SEQ_GT(th->th_ack, tp->snd_max)))
1207 goto dropwithreset;
1208 if (tiflags & TH_RST) {
1209 if (tiflags & TH_ACK)
1210 tp = tcp_drop(tp, ECONNREFUSED);
1211 goto drop;
1212 }
1213 if ((tiflags & TH_SYN) == 0)
1214 goto drop;
1215 if (tiflags & TH_ACK) {
1216 tp->snd_una = th->th_ack;
1217 if (SEQ_LT(tp->snd_nxt, tp->snd_una))
1218 tp->snd_nxt = tp->snd_una;
1219 }
1220 TCP_TIMER_DISARM(tp, TCPT_REXMT);
1221 tp->irs = th->th_seq;
1222 tcp_rcvseqinit(tp);
1223 tp->t_flags |= TF_ACKNOW;
1224 tcp_mss_from_peer(tp, opti.maxseg);
1225
1226 /*
1227 * Initialize the initial congestion window. If we
1228 * had to retransmit the SYN, we must initialize cwnd
1229 * to 1 segment (i.e. the Loss Window).
1230 */
1231 if (tp->t_flags & TF_SYN_REXMT)
1232 tp->snd_cwnd = tp->t_peermss;
1233 else
1234 tp->snd_cwnd = TCP_INITIAL_WINDOW(tcp_init_win,
1235 tp->t_peermss);
1236
1237 tcp_rmx_rtt(tp);
1238 if (tiflags & TH_ACK && SEQ_GT(tp->snd_una, tp->iss)) {
1239 tcpstat.tcps_connects++;
1240 soisconnected(so);
1241 tcp_established(tp);
1242 /* Do window scaling on this connection? */
1243 if ((tp->t_flags & (TF_RCVD_SCALE|TF_REQ_SCALE)) ==
1244 (TF_RCVD_SCALE|TF_REQ_SCALE)) {
1245 tp->snd_scale = tp->requested_s_scale;
1246 tp->rcv_scale = tp->request_r_scale;
1247 }
1248 TCP_REASS_LOCK(tp);
1249 (void) tcp_reass(tp, NULL, (struct mbuf *)0, &tlen);
1250 TCP_REASS_UNLOCK(tp);
1251 /*
1252 * if we didn't have to retransmit the SYN,
1253 * use its rtt as our initial srtt & rtt var.
1254 */
1255 if (tp->t_rtt)
1256 tcp_xmit_timer(tp, tp->t_rtt);
1257 } else
1258 tp->t_state = TCPS_SYN_RECEIVED;
1259
1260 /*
1261 * Advance th->th_seq to correspond to first data byte.
1262 * If data, trim to stay within window,
1263 * dropping FIN if necessary.
1264 */
1265 th->th_seq++;
1266 if (tlen > tp->rcv_wnd) {
1267 todrop = tlen - tp->rcv_wnd;
1268 m_adj(m, -todrop);
1269 tlen = tp->rcv_wnd;
1270 tiflags &= ~TH_FIN;
1271 tcpstat.tcps_rcvpackafterwin++;
1272 tcpstat.tcps_rcvbyteafterwin += todrop;
1273 }
1274 tp->snd_wl1 = th->th_seq - 1;
1275 tp->rcv_up = th->th_seq;
1276 goto step6;
1277
1278 /*
1279 * If the state is SYN_RECEIVED:
1280 * If seg contains an ACK, but not for our SYN, drop the input
1281 * and generate an RST. See page 36, rfc793
1282 */
1283 case TCPS_SYN_RECEIVED:
1284 if ((tiflags & TH_ACK) &&
1285 (SEQ_LEQ(th->th_ack, tp->iss) ||
1286 SEQ_GT(th->th_ack, tp->snd_max)))
1287 goto dropwithreset;
1288 break;
1289 }
1290
1291 /*
1292 * States other than LISTEN or SYN_SENT.
1293 * First check timestamp, if present.
1294 * Then check that at least some bytes of segment are within
1295 * receive window. If segment begins before rcv_nxt,
1296 * drop leading data (and SYN); if nothing left, just ack.
1297 *
1298 * RFC 1323 PAWS: If we have a timestamp reply on this segment
1299 * and it's less than ts_recent, drop it.
1300 */
1301 if (opti.ts_present && (tiflags & TH_RST) == 0 && tp->ts_recent &&
1302 TSTMP_LT(opti.ts_val, tp->ts_recent)) {
1303
1304 /* Check to see if ts_recent is over 24 days old. */
1305 if ((int)(tcp_now - tp->ts_recent_age) > TCP_PAWS_IDLE) {
1306 /*
1307 * Invalidate ts_recent. If this segment updates
1308 * ts_recent, the age will be reset later and ts_recent
1309 * will get a valid value. If it does not, setting
1310 * ts_recent to zero will at least satisfy the
1311 * requirement that zero be placed in the timestamp
1312 * echo reply when ts_recent isn't valid. The
1313 * age isn't reset until we get a valid ts_recent
1314 * because we don't want out-of-order segments to be
1315 * dropped when ts_recent is old.
1316 */
1317 tp->ts_recent = 0;
1318 } else {
1319 tcpstat.tcps_rcvduppack++;
1320 tcpstat.tcps_rcvdupbyte += tlen;
1321 tcpstat.tcps_pawsdrop++;
1322 goto dropafterack;
1323 }
1324 }
1325
1326 todrop = tp->rcv_nxt - th->th_seq;
1327 if (todrop > 0) {
1328 if (tiflags & TH_SYN) {
1329 tiflags &= ~TH_SYN;
1330 th->th_seq++;
1331 if (th->th_urp > 1)
1332 th->th_urp--;
1333 else {
1334 tiflags &= ~TH_URG;
1335 th->th_urp = 0;
1336 }
1337 todrop--;
1338 }
1339 if (todrop > tlen ||
1340 (todrop == tlen && (tiflags & TH_FIN) == 0)) {
1341 /*
1342 * Any valid FIN must be to the left of the window.
1343 * At this point the FIN must be a duplicate or
1344 * out of sequence; drop it.
1345 */
1346 tiflags &= ~TH_FIN;
1347 /*
1348 * Send an ACK to resynchronize and drop any data.
1349 * But keep on processing for RST or ACK.
1350 */
1351 tp->t_flags |= TF_ACKNOW;
1352 todrop = tlen;
1353 tcpstat.tcps_rcvdupbyte += todrop;
1354 tcpstat.tcps_rcvduppack++;
1355 } else {
1356 tcpstat.tcps_rcvpartduppack++;
1357 tcpstat.tcps_rcvpartdupbyte += todrop;
1358 }
1359 m_adj(m, todrop);
1360 th->th_seq += todrop;
1361 tlen -= todrop;
1362 if (th->th_urp > todrop)
1363 th->th_urp -= todrop;
1364 else {
1365 tiflags &= ~TH_URG;
1366 th->th_urp = 0;
1367 }
1368 }
1369
1370 /*
1371 * If new data are received on a connection after the
1372 * user processes are gone, then RST the other end.
1373 */
1374 if ((so->so_state & SS_NOFDREF) &&
1375 tp->t_state > TCPS_CLOSE_WAIT && tlen) {
1376 tp = tcp_close(tp);
1377 tcpstat.tcps_rcvafterclose++;
1378 goto dropwithreset;
1379 }
1380
1381 /*
1382 * If segment ends after window, drop trailing data
1383 * (and PUSH and FIN); if nothing left, just ACK.
1384 */
1385 todrop = (th->th_seq + tlen) - (tp->rcv_nxt+tp->rcv_wnd);
1386 if (todrop > 0) {
1387 tcpstat.tcps_rcvpackafterwin++;
1388 if (todrop >= tlen) {
1389 tcpstat.tcps_rcvbyteafterwin += tlen;
1390 /*
1391 * If a new connection request is received
1392 * while in TIME_WAIT, drop the old connection
1393 * and start over if the sequence numbers
1394 * are above the previous ones.
1395 */
1396 if (tiflags & TH_SYN &&
1397 tp->t_state == TCPS_TIME_WAIT &&
1398 SEQ_GT(th->th_seq, tp->rcv_nxt)) {
1399 iss = tcp_new_iss(tp, sizeof(struct tcpcb),
1400 tp->snd_nxt);
1401 tp = tcp_close(tp);
1402 /*
1403 * We have already advanced the mbuf
1404 * pointers past the IP+TCP headers and
1405 * options. Restore those pointers before
1406 * attempting to use the TCP header again.
1407 */
1408 m->m_data -= hdroptlen;
1409 m->m_len += hdroptlen;
1410 hdroptlen = 0;
1411 goto findpcb;
1412 }
1413 /*
1414 * If window is closed can only take segments at
1415 * window edge, and have to drop data and PUSH from
1416 * incoming segments. Continue processing, but
1417 * remember to ack. Otherwise, drop segment
1418 * and ack.
1419 */
1420 if (tp->rcv_wnd == 0 && th->th_seq == tp->rcv_nxt) {
1421 tp->t_flags |= TF_ACKNOW;
1422 tcpstat.tcps_rcvwinprobe++;
1423 } else
1424 goto dropafterack;
1425 } else
1426 tcpstat.tcps_rcvbyteafterwin += todrop;
1427 m_adj(m, -todrop);
1428 tlen -= todrop;
1429 tiflags &= ~(TH_PUSH|TH_FIN);
1430 }
1431
1432 /*
1433 * If last ACK falls within this segment's sequence numbers,
1434 * and the timestamp is newer, record it.
1435 */
1436 if (opti.ts_present && TSTMP_GEQ(opti.ts_val, tp->ts_recent) &&
1437 SEQ_LEQ(th->th_seq, tp->last_ack_sent) &&
1438 SEQ_LT(tp->last_ack_sent, th->th_seq + tlen +
1439 ((tiflags & (TH_SYN|TH_FIN)) != 0))) {
1440 tp->ts_recent_age = tcp_now;
1441 tp->ts_recent = opti.ts_val;
1442 }
1443
1444 /*
1445 * If the RST bit is set examine the state:
1446 * SYN_RECEIVED STATE:
1447 * If passive open, return to LISTEN state.
1448 * If active open, inform user that connection was refused.
1449 * ESTABLISHED, FIN_WAIT_1, FIN_WAIT2, CLOSE_WAIT STATES:
1450 * Inform user that connection was reset, and close tcb.
1451 * CLOSING, LAST_ACK, TIME_WAIT STATES
1452 * Close the tcb.
1453 */
1454 if (tiflags&TH_RST) switch (tp->t_state) {
1455
1456 case TCPS_SYN_RECEIVED:
1457 so->so_error = ECONNREFUSED;
1458 goto close;
1459
1460 case TCPS_ESTABLISHED:
1461 case TCPS_FIN_WAIT_1:
1462 case TCPS_FIN_WAIT_2:
1463 case TCPS_CLOSE_WAIT:
1464 so->so_error = ECONNRESET;
1465 close:
1466 tp->t_state = TCPS_CLOSED;
1467 tcpstat.tcps_drops++;
1468 tp = tcp_close(tp);
1469 goto drop;
1470
1471 case TCPS_CLOSING:
1472 case TCPS_LAST_ACK:
1473 case TCPS_TIME_WAIT:
1474 tp = tcp_close(tp);
1475 goto drop;
1476 }
1477
1478 /*
1479 * If a SYN is in the window, then this is an
1480 * error and we send an RST and drop the connection.
1481 */
1482 if (tiflags & TH_SYN) {
1483 tp = tcp_drop(tp, ECONNRESET);
1484 goto dropwithreset;
1485 }
1486
1487 /*
1488 * If the ACK bit is off we drop the segment and return.
1489 */
1490 if ((tiflags & TH_ACK) == 0) {
1491 if (tp->t_flags & TF_ACKNOW)
1492 goto dropafterack;
1493 else
1494 goto drop;
1495 }
1496
1497 /*
1498 * Ack processing.
1499 */
1500 switch (tp->t_state) {
1501
1502 /*
1503 * In SYN_RECEIVED state if the ack ACKs our SYN then enter
1504 * ESTABLISHED state and continue processing, otherwise
1505 * send an RST.
1506 */
1507 case TCPS_SYN_RECEIVED:
1508 if (SEQ_GT(tp->snd_una, th->th_ack) ||
1509 SEQ_GT(th->th_ack, tp->snd_max))
1510 goto dropwithreset;
1511 tcpstat.tcps_connects++;
1512 soisconnected(so);
1513 tcp_established(tp);
1514 /* Do window scaling? */
1515 if ((tp->t_flags & (TF_RCVD_SCALE|TF_REQ_SCALE)) ==
1516 (TF_RCVD_SCALE|TF_REQ_SCALE)) {
1517 tp->snd_scale = tp->requested_s_scale;
1518 tp->rcv_scale = tp->request_r_scale;
1519 }
1520 TCP_REASS_LOCK(tp);
1521 (void) tcp_reass(tp, NULL, (struct mbuf *)0, &tlen);
1522 TCP_REASS_UNLOCK(tp);
1523 tp->snd_wl1 = th->th_seq - 1;
1524 /* fall into ... */
1525
1526 /*
1527 * In ESTABLISHED state: drop duplicate ACKs; ACK out of range
1528 * ACKs. If the ack is in the range
1529 * tp->snd_una < th->th_ack <= tp->snd_max
1530 * then advance tp->snd_una to th->th_ack and drop
1531 * data from the retransmission queue. If this ACK reflects
1532 * more up to date window information we update our window information.
1533 */
1534 case TCPS_ESTABLISHED:
1535 case TCPS_FIN_WAIT_1:
1536 case TCPS_FIN_WAIT_2:
1537 case TCPS_CLOSE_WAIT:
1538 case TCPS_CLOSING:
1539 case TCPS_LAST_ACK:
1540 case TCPS_TIME_WAIT:
1541
1542 if (SEQ_LEQ(th->th_ack, tp->snd_una)) {
1543 if (tlen == 0 && tiwin == tp->snd_wnd) {
1544 tcpstat.tcps_rcvdupack++;
1545 /*
1546 * If we have outstanding data (other than
1547 * a window probe), this is a completely
1548 * duplicate ack (ie, window info didn't
1549 * change), the ack is the biggest we've
1550 * seen and we've seen exactly our rexmt
1551 * threshhold of them, assume a packet
1552 * has been dropped and retransmit it.
1553 * Kludge snd_nxt & the congestion
1554 * window so we send only this one
1555 * packet.
1556 *
1557 * We know we're losing at the current
1558 * window size so do congestion avoidance
1559 * (set ssthresh to half the current window
1560 * and pull our congestion window back to
1561 * the new ssthresh).
1562 *
1563 * Dup acks mean that packets have left the
1564 * network (they're now cached at the receiver)
1565 * so bump cwnd by the amount in the receiver
1566 * to keep a constant cwnd packets in the
1567 * network.
1568 */
1569 if (TCP_TIMER_ISARMED(tp, TCPT_REXMT) == 0 ||
1570 th->th_ack != tp->snd_una)
1571 tp->t_dupacks = 0;
1572 else if (++tp->t_dupacks == tcprexmtthresh) {
1573 tcp_seq onxt = tp->snd_nxt;
1574 u_int win =
1575 min(tp->snd_wnd, tp->snd_cwnd) /
1576 2 / tp->t_segsz;
1577 if (SEQ_LT(th->th_ack, tp->snd_recover)) {
1578 /*
1579 * False fast retransmit after
1580 * timeout. Do not cut window.
1581 */
1582 tp->snd_cwnd += tp->t_segsz;
1583 tp->t_dupacks = 0;
1584 (void) tcp_output(tp);
1585 goto drop;
1586 }
1587
1588 if (win < 2)
1589 win = 2;
1590 tp->snd_ssthresh = win * tp->t_segsz;
1591 tp->snd_recover = tp->snd_max;
1592 TCP_TIMER_DISARM(tp, TCPT_REXMT);
1593 tp->t_rtt = 0;
1594 tp->snd_nxt = th->th_ack;
1595 tp->snd_cwnd = tp->t_segsz;
1596 (void) tcp_output(tp);
1597 tp->snd_cwnd = tp->snd_ssthresh +
1598 tp->t_segsz * tp->t_dupacks;
1599 if (SEQ_GT(onxt, tp->snd_nxt))
1600 tp->snd_nxt = onxt;
1601 goto drop;
1602 } else if (tp->t_dupacks > tcprexmtthresh) {
1603 tp->snd_cwnd += tp->t_segsz;
1604 (void) tcp_output(tp);
1605 goto drop;
1606 }
1607 } else
1608 tp->t_dupacks = 0;
1609 break;
1610 }
1611 /*
1612 * If the congestion window was inflated to account
1613 * for the other side's cached packets, retract it.
1614 */
1615 if (!tcp_do_newreno) {
1616 if (tp->t_dupacks >= tcprexmtthresh &&
1617 tp->snd_cwnd > tp->snd_ssthresh)
1618 tp->snd_cwnd = tp->snd_ssthresh;
1619 tp->t_dupacks = 0;
1620 } else if (tp->t_dupacks >= tcprexmtthresh
1621 && !tcp_newreno(tp, th)) {
1622 tp->snd_cwnd = tp->snd_ssthresh;
1623 /*
1624 * Window inflation should have left us with approx.
1625 * snd_ssthresh outstanding data. But in case we
1626 * would be inclined to send a burst, better to do
1627 * it via the slow start mechanism.
1628 */
1629 if (SEQ_SUB(tp->snd_max, th->th_ack) < tp->snd_ssthresh)
1630 tp->snd_cwnd = SEQ_SUB(tp->snd_max, th->th_ack)
1631 + tp->t_segsz;
1632 tp->t_dupacks = 0;
1633 }
1634 if (SEQ_GT(th->th_ack, tp->snd_max)) {
1635 tcpstat.tcps_rcvacktoomuch++;
1636 goto dropafterack;
1637 }
1638 acked = th->th_ack - tp->snd_una;
1639 tcpstat.tcps_rcvackpack++;
1640 tcpstat.tcps_rcvackbyte += acked;
1641
1642 /*
1643 * If we have a timestamp reply, update smoothed
1644 * round trip time. If no timestamp is present but
1645 * transmit timer is running and timed sequence
1646 * number was acked, update smoothed round trip time.
1647 * Since we now have an rtt measurement, cancel the
1648 * timer backoff (cf., Phil Karn's retransmit alg.).
1649 * Recompute the initial retransmit timer.
1650 */
1651 if (opti.ts_present && opti.ts_ecr)
1652 tcp_xmit_timer(tp, tcp_now - opti.ts_ecr + 1);
1653 else if (tp->t_rtt && SEQ_GT(th->th_ack, tp->t_rtseq))
1654 tcp_xmit_timer(tp,tp->t_rtt);
1655
1656 /*
1657 * If all outstanding data is acked, stop retransmit
1658 * timer and remember to restart (more output or persist).
1659 * If there is more data to be acked, restart retransmit
1660 * timer, using current (possibly backed-off) value.
1661 */
1662 if (th->th_ack == tp->snd_max) {
1663 TCP_TIMER_DISARM(tp, TCPT_REXMT);
1664 needoutput = 1;
1665 } else if (TCP_TIMER_ISARMED(tp, TCPT_PERSIST) == 0)
1666 TCP_TIMER_ARM(tp, TCPT_REXMT, tp->t_rxtcur);
1667 /*
1668 * When new data is acked, open the congestion window.
1669 * If the window gives us less than ssthresh packets
1670 * in flight, open exponentially (segsz per packet).
1671 * Otherwise open linearly: segsz per window
1672 * (segsz^2 / cwnd per packet), plus a constant
1673 * fraction of a packet (segsz/8) to help larger windows
1674 * open quickly enough.
1675 */
1676 {
1677 register u_int cw = tp->snd_cwnd;
1678 register u_int incr = tp->t_segsz;
1679
1680 if (cw > tp->snd_ssthresh)
1681 incr = incr * incr / cw;
1682 if (!tcp_do_newreno || SEQ_GEQ(th->th_ack, tp->snd_recover))
1683 tp->snd_cwnd = min(cw + incr,TCP_MAXWIN<<tp->snd_scale);
1684 }
1685 if (acked > so->so_snd.sb_cc) {
1686 tp->snd_wnd -= so->so_snd.sb_cc;
1687 sbdrop(&so->so_snd, (int)so->so_snd.sb_cc);
1688 ourfinisacked = 1;
1689 } else {
1690 sbdrop(&so->so_snd, acked);
1691 tp->snd_wnd -= acked;
1692 ourfinisacked = 0;
1693 }
1694 sowwakeup(so);
1695 tp->snd_una = th->th_ack;
1696 if (SEQ_LT(tp->snd_nxt, tp->snd_una))
1697 tp->snd_nxt = tp->snd_una;
1698
1699 switch (tp->t_state) {
1700
1701 /*
1702 * In FIN_WAIT_1 STATE in addition to the processing
1703 * for the ESTABLISHED state if our FIN is now acknowledged
1704 * then enter FIN_WAIT_2.
1705 */
1706 case TCPS_FIN_WAIT_1:
1707 if (ourfinisacked) {
1708 /*
1709 * If we can't receive any more
1710 * data, then closing user can proceed.
1711 * Starting the timer is contrary to the
1712 * specification, but if we don't get a FIN
1713 * we'll hang forever.
1714 */
1715 if (so->so_state & SS_CANTRCVMORE) {
1716 soisdisconnected(so);
1717 if (tcp_maxidle > 0)
1718 TCP_TIMER_ARM(tp, TCPT_2MSL,
1719 tcp_maxidle);
1720 }
1721 tp->t_state = TCPS_FIN_WAIT_2;
1722 }
1723 break;
1724
1725 /*
1726 * In CLOSING STATE in addition to the processing for
1727 * the ESTABLISHED state if the ACK acknowledges our FIN
1728 * then enter the TIME-WAIT state, otherwise ignore
1729 * the segment.
1730 */
1731 case TCPS_CLOSING:
1732 if (ourfinisacked) {
1733 tp->t_state = TCPS_TIME_WAIT;
1734 tcp_canceltimers(tp);
1735 TCP_TIMER_ARM(tp, TCPT_2MSL, 2 * TCPTV_MSL);
1736 soisdisconnected(so);
1737 }
1738 break;
1739
1740 /*
1741 * In LAST_ACK, we may still be waiting for data to drain
1742 * and/or to be acked, as well as for the ack of our FIN.
1743 * If our FIN is now acknowledged, delete the TCB,
1744 * enter the closed state and return.
1745 */
1746 case TCPS_LAST_ACK:
1747 if (ourfinisacked) {
1748 tp = tcp_close(tp);
1749 goto drop;
1750 }
1751 break;
1752
1753 /*
1754 * In TIME_WAIT state the only thing that should arrive
1755 * is a retransmission of the remote FIN. Acknowledge
1756 * it and restart the finack timer.
1757 */
1758 case TCPS_TIME_WAIT:
1759 TCP_TIMER_ARM(tp, TCPT_2MSL, 2 * TCPTV_MSL);
1760 goto dropafterack;
1761 }
1762 }
1763
1764 step6:
1765 /*
1766 * Update window information.
1767 * Don't look at window if no ACK: TAC's send garbage on first SYN.
1768 */
1769 if ((tiflags & TH_ACK) && (SEQ_LT(tp->snd_wl1, th->th_seq) ||
1770 (tp->snd_wl1 == th->th_seq && SEQ_LT(tp->snd_wl2, th->th_ack)) ||
1771 (tp->snd_wl2 == th->th_ack && tiwin > tp->snd_wnd))) {
1772 /* keep track of pure window updates */
1773 if (tlen == 0 &&
1774 tp->snd_wl2 == th->th_ack && tiwin > tp->snd_wnd)
1775 tcpstat.tcps_rcvwinupd++;
1776 tp->snd_wnd = tiwin;
1777 tp->snd_wl1 = th->th_seq;
1778 tp->snd_wl2 = th->th_ack;
1779 if (tp->snd_wnd > tp->max_sndwnd)
1780 tp->max_sndwnd = tp->snd_wnd;
1781 needoutput = 1;
1782 }
1783
1784 /*
1785 * Process segments with URG.
1786 */
1787 if ((tiflags & TH_URG) && th->th_urp &&
1788 TCPS_HAVERCVDFIN(tp->t_state) == 0) {
1789 /*
1790 * This is a kludge, but if we receive and accept
1791 * random urgent pointers, we'll crash in
1792 * soreceive. It's hard to imagine someone
1793 * actually wanting to send this much urgent data.
1794 */
1795 if (th->th_urp + so->so_rcv.sb_cc > sb_max) {
1796 th->th_urp = 0; /* XXX */
1797 tiflags &= ~TH_URG; /* XXX */
1798 goto dodata; /* XXX */
1799 }
1800 /*
1801 * If this segment advances the known urgent pointer,
1802 * then mark the data stream. This should not happen
1803 * in CLOSE_WAIT, CLOSING, LAST_ACK or TIME_WAIT STATES since
1804 * a FIN has been received from the remote side.
1805 * In these states we ignore the URG.
1806 *
1807 * According to RFC961 (Assigned Protocols),
1808 * the urgent pointer points to the last octet
1809 * of urgent data. We continue, however,
1810 * to consider it to indicate the first octet
1811 * of data past the urgent section as the original
1812 * spec states (in one of two places).
1813 */
1814 if (SEQ_GT(th->th_seq+th->th_urp, tp->rcv_up)) {
1815 tp->rcv_up = th->th_seq + th->th_urp;
1816 so->so_oobmark = so->so_rcv.sb_cc +
1817 (tp->rcv_up - tp->rcv_nxt) - 1;
1818 if (so->so_oobmark == 0)
1819 so->so_state |= SS_RCVATMARK;
1820 sohasoutofband(so);
1821 tp->t_oobflags &= ~(TCPOOB_HAVEDATA | TCPOOB_HADDATA);
1822 }
1823 /*
1824 * Remove out of band data so doesn't get presented to user.
1825 * This can happen independent of advancing the URG pointer,
1826 * but if two URG's are pending at once, some out-of-band
1827 * data may creep in... ick.
1828 */
1829 if (th->th_urp <= (u_int16_t) tlen
1830 #ifdef SO_OOBINLINE
1831 && (so->so_options & SO_OOBINLINE) == 0
1832 #endif
1833 )
1834 tcp_pulloutofband(so, th, m);
1835 } else
1836 /*
1837 * If no out of band data is expected,
1838 * pull receive urgent pointer along
1839 * with the receive window.
1840 */
1841 if (SEQ_GT(tp->rcv_nxt, tp->rcv_up))
1842 tp->rcv_up = tp->rcv_nxt;
1843 dodata: /* XXX */
1844
1845 /*
1846 * Process the segment text, merging it into the TCP sequencing queue,
1847 * and arranging for acknowledgment of receipt if necessary.
1848 * This process logically involves adjusting tp->rcv_wnd as data
1849 * is presented to the user (this happens in tcp_usrreq.c,
1850 * case PRU_RCVD). If a FIN has already been received on this
1851 * connection then we just ignore the text.
1852 */
1853 if ((tlen || (tiflags & TH_FIN)) &&
1854 TCPS_HAVERCVDFIN(tp->t_state) == 0) {
1855 /*
1856 * Insert segment ti into reassembly queue of tcp with
1857 * control block tp. Return TH_FIN if reassembly now includes
1858 * a segment with FIN. The macro form does the common case
1859 * inline (segment is the next to be received on an
1860 * established connection, and the queue is empty),
1861 * avoiding linkage into and removal from the queue and
1862 * repetition of various conversions.
1863 * Set DELACK for segments received in order, but ack
1864 * immediately when segments are out of order
1865 * (so fast retransmit can work).
1866 */
1867 /* NOTE: this was TCP_REASS() macro, but used only once */
1868 TCP_REASS_LOCK(tp);
1869 if (th->th_seq == tp->rcv_nxt &&
1870 tp->segq.lh_first == NULL &&
1871 tp->t_state == TCPS_ESTABLISHED) {
1872 TCP_SETUP_ACK(tp, th);
1873 tp->rcv_nxt += tlen;
1874 tiflags = th->th_flags & TH_FIN;
1875 tcpstat.tcps_rcvpack++;\
1876 tcpstat.tcps_rcvbyte += tlen;\
1877 sbappend(&(so)->so_rcv, m);
1878 sorwakeup(so);
1879 } else {
1880 tiflags = tcp_reass(tp, th, m, &tlen);
1881 tp->t_flags |= TF_ACKNOW;
1882 }
1883 TCP_REASS_UNLOCK(tp);
1884
1885 /*
1886 * Note the amount of data that peer has sent into
1887 * our window, in order to estimate the sender's
1888 * buffer size.
1889 */
1890 len = so->so_rcv.sb_hiwat - (tp->rcv_adv - tp->rcv_nxt);
1891 } else {
1892 m_freem(m);
1893 m = NULL;
1894 tiflags &= ~TH_FIN;
1895 }
1896
1897 /*
1898 * If FIN is received ACK the FIN and let the user know
1899 * that the connection is closing. Ignore a FIN received before
1900 * the connection is fully established.
1901 */
1902 if ((tiflags & TH_FIN) && TCPS_HAVEESTABLISHED(tp->t_state)) {
1903 if (TCPS_HAVERCVDFIN(tp->t_state) == 0) {
1904 socantrcvmore(so);
1905 tp->t_flags |= TF_ACKNOW;
1906 tp->rcv_nxt++;
1907 }
1908 switch (tp->t_state) {
1909
1910 /*
1911 * In ESTABLISHED STATE enter the CLOSE_WAIT state.
1912 */
1913 case TCPS_ESTABLISHED:
1914 tp->t_state = TCPS_CLOSE_WAIT;
1915 break;
1916
1917 /*
1918 * If still in FIN_WAIT_1 STATE FIN has not been acked so
1919 * enter the CLOSING state.
1920 */
1921 case TCPS_FIN_WAIT_1:
1922 tp->t_state = TCPS_CLOSING;
1923 break;
1924
1925 /*
1926 * In FIN_WAIT_2 state enter the TIME_WAIT state,
1927 * starting the time-wait timer, turning off the other
1928 * standard timers.
1929 */
1930 case TCPS_FIN_WAIT_2:
1931 tp->t_state = TCPS_TIME_WAIT;
1932 tcp_canceltimers(tp);
1933 TCP_TIMER_ARM(tp, TCPT_2MSL, 2 * TCPTV_MSL);
1934 soisdisconnected(so);
1935 break;
1936
1937 /*
1938 * In TIME_WAIT state restart the 2 MSL time_wait timer.
1939 */
1940 case TCPS_TIME_WAIT:
1941 TCP_TIMER_ARM(tp, TCPT_2MSL, 2 * TCPTV_MSL);
1942 break;
1943 }
1944 }
1945 if (so->so_options & SO_DEBUG) {
1946 tcp_trace(TA_INPUT, ostate, tp, tcp_saveti, 0);
1947 }
1948
1949 /*
1950 * Return any desired output.
1951 */
1952 if (needoutput || (tp->t_flags & TF_ACKNOW))
1953 (void) tcp_output(tp);
1954 if (tcp_saveti)
1955 m_freem(tcp_saveti);
1956 return;
1957
1958 badsyn:
1959 /*
1960 * Received a bad SYN. Increment counters and dropwithreset.
1961 */
1962 tcpstat.tcps_badsyn++;
1963 tp = NULL;
1964 goto dropwithreset;
1965
1966 dropafterack:
1967 /*
1968 * Generate an ACK dropping incoming segment if it occupies
1969 * sequence space, where the ACK reflects our state.
1970 */
1971 if (tiflags & TH_RST)
1972 goto drop;
1973 m_freem(m);
1974 tp->t_flags |= TF_ACKNOW;
1975 (void) tcp_output(tp);
1976 if (tcp_saveti)
1977 m_freem(tcp_saveti);
1978 return;
1979
1980 dropwithreset:
1981 /*
1982 * Generate a RST, dropping incoming segment.
1983 * Make ACK acceptable to originator of segment.
1984 * Don't bother to respond if destination was broadcast/multicast.
1985 */
1986 if ((tiflags & TH_RST) || m->m_flags & (M_BCAST|M_MCAST))
1987 goto drop;
1988 if (ip && IN_MULTICAST(ip->ip_dst.s_addr))
1989 goto drop;
1990 #ifdef INET6
1991 if (m->m_flags & M_ANYCAST6)
1992 goto drop;
1993 else if (ip6 && IN6_IS_ADDR_MULTICAST(&ip6->ip6_dst))
1994 goto drop;
1995 #endif
1996 /* recover the header if dropped. */
1997 m->m_data -= hdroptlen;
1998 m->m_len += hdroptlen;
1999 {
2000 /*
2001 * need to recover version # field, which was overwritten on
2002 * ip_cksum computation.
2003 */
2004 struct ip *sip;
2005 sip = mtod(m, struct ip *);
2006 switch (af) {
2007 case AF_INET:
2008 sip->ip_v = 4;
2009 break;
2010 #ifdef INET6
2011 case AF_INET6:
2012 sip->ip_v = 6;
2013 break;
2014 #endif
2015 }
2016 }
2017 if (tiflags & TH_ACK)
2018 (void)tcp_respond(tp, m, m, th, (tcp_seq)0, th->th_ack, TH_RST);
2019 else {
2020 if (tiflags & TH_SYN)
2021 tlen++;
2022 (void)tcp_respond(tp, m, m, th, th->th_seq + tlen, (tcp_seq)0,
2023 TH_RST|TH_ACK);
2024 }
2025 if (tcp_saveti)
2026 m_freem(tcp_saveti);
2027 return;
2028
2029 drop:
2030 /*
2031 * Drop space held by incoming segment and return.
2032 */
2033 if (tp) {
2034 if (tp->t_inpcb)
2035 so = tp->t_inpcb->inp_socket;
2036 #ifdef INET6
2037 else if (tp->t_in6pcb)
2038 so = tp->t_in6pcb->in6p_socket;
2039 #endif
2040 else
2041 so = NULL;
2042 if (so && (so->so_options & SO_DEBUG) != 0)
2043 tcp_trace(TA_DROP, ostate, tp, tcp_saveti, 0);
2044 }
2045 if (tcp_saveti)
2046 m_freem(tcp_saveti);
2047 m_freem(m);
2048 return;
2049 }
2050
2051 void
2052 tcp_dooptions(tp, cp, cnt, th, oi)
2053 struct tcpcb *tp;
2054 u_char *cp;
2055 int cnt;
2056 struct tcphdr *th;
2057 struct tcp_opt_info *oi;
2058 {
2059 u_int16_t mss;
2060 int opt, optlen;
2061
2062 for (; cnt > 0; cnt -= optlen, cp += optlen) {
2063 opt = cp[0];
2064 if (opt == TCPOPT_EOL)
2065 break;
2066 if (opt == TCPOPT_NOP)
2067 optlen = 1;
2068 else {
2069 optlen = cp[1];
2070 if (optlen <= 0)
2071 break;
2072 }
2073 switch (opt) {
2074
2075 default:
2076 continue;
2077
2078 case TCPOPT_MAXSEG:
2079 if (optlen != TCPOLEN_MAXSEG)
2080 continue;
2081 if (!(th->th_flags & TH_SYN))
2082 continue;
2083 bcopy(cp + 2, &mss, sizeof(mss));
2084 oi->maxseg = ntohs(mss);
2085 break;
2086
2087 case TCPOPT_WINDOW:
2088 if (optlen != TCPOLEN_WINDOW)
2089 continue;
2090 if (!(th->th_flags & TH_SYN))
2091 continue;
2092 tp->t_flags |= TF_RCVD_SCALE;
2093 tp->requested_s_scale = cp[2];
2094 if (tp->requested_s_scale > TCP_MAX_WINSHIFT) {
2095 #if 0 /*XXX*/
2096 char *p;
2097
2098 if (ip)
2099 p = ntohl(ip->ip_src);
2100 #ifdef INET6
2101 else if (ip6)
2102 p = ip6_sprintf(&ip6->ip6_src);
2103 #endif
2104 else
2105 p = "(unknown)";
2106 log(LOG_ERR, "TCP: invalid wscale %d from %s, "
2107 "assuming %d\n",
2108 tp->requested_s_scale, p,
2109 TCP_MAX_WINSHIFT);
2110 #else
2111 log(LOG_ERR, "TCP: invalid wscale %d, "
2112 "assuming %d\n",
2113 tp->requested_s_scale,
2114 TCP_MAX_WINSHIFT);
2115 #endif
2116 tp->requested_s_scale = TCP_MAX_WINSHIFT;
2117 }
2118 break;
2119
2120 case TCPOPT_TIMESTAMP:
2121 if (optlen != TCPOLEN_TIMESTAMP)
2122 continue;
2123 oi->ts_present = 1;
2124 bcopy(cp + 2, &oi->ts_val, sizeof(oi->ts_val));
2125 NTOHL(oi->ts_val);
2126 bcopy(cp + 6, &oi->ts_ecr, sizeof(oi->ts_ecr));
2127 NTOHL(oi->ts_ecr);
2128
2129 /*
2130 * A timestamp received in a SYN makes
2131 * it ok to send timestamp requests and replies.
2132 */
2133 if (th->th_flags & TH_SYN) {
2134 tp->t_flags |= TF_RCVD_TSTMP;
2135 tp->ts_recent = oi->ts_val;
2136 tp->ts_recent_age = tcp_now;
2137 }
2138 break;
2139 case TCPOPT_SACK_PERMITTED:
2140 if (optlen != TCPOLEN_SACK_PERMITTED)
2141 continue;
2142 if (!(th->th_flags & TH_SYN))
2143 continue;
2144 tp->t_flags &= ~TF_CANT_TXSACK;
2145 break;
2146
2147 case TCPOPT_SACK:
2148 if (tp->t_flags & TF_IGNR_RXSACK)
2149 continue;
2150 if (optlen % 8 != 2 || optlen < 10)
2151 continue;
2152 cp += 2;
2153 optlen -= 2;
2154 for (; optlen > 0; cp -= 8, optlen -= 8) {
2155 tcp_seq lwe, rwe;
2156 bcopy((char *)cp, (char *) &lwe, sizeof(lwe));
2157 NTOHL(lwe);
2158 bcopy((char *)cp, (char *) &rwe, sizeof(rwe));
2159 NTOHL(rwe);
2160 /* tcp_mark_sacked(tp, lwe, rwe); */
2161 }
2162 break;
2163 }
2164 }
2165 }
2166
2167 /*
2168 * Pull out of band byte out of a segment so
2169 * it doesn't appear in the user's data queue.
2170 * It is still reflected in the segment length for
2171 * sequencing purposes.
2172 */
2173 void
2174 tcp_pulloutofband(so, th, m)
2175 struct socket *so;
2176 struct tcphdr *th;
2177 register struct mbuf *m;
2178 {
2179 int cnt = th->th_urp - 1;
2180
2181 while (cnt >= 0) {
2182 if (m->m_len > cnt) {
2183 char *cp = mtod(m, caddr_t) + cnt;
2184 struct tcpcb *tp = sototcpcb(so);
2185
2186 tp->t_iobc = *cp;
2187 tp->t_oobflags |= TCPOOB_HAVEDATA;
2188 bcopy(cp+1, cp, (unsigned)(m->m_len - cnt - 1));
2189 m->m_len--;
2190 return;
2191 }
2192 cnt -= m->m_len;
2193 m = m->m_next;
2194 if (m == 0)
2195 break;
2196 }
2197 panic("tcp_pulloutofband");
2198 }
2199
2200 /*
2201 * Collect new round-trip time estimate
2202 * and update averages and current timeout.
2203 */
2204 void
2205 tcp_xmit_timer(tp, rtt)
2206 register struct tcpcb *tp;
2207 short rtt;
2208 {
2209 register short delta;
2210 short rttmin;
2211
2212 tcpstat.tcps_rttupdated++;
2213 --rtt;
2214 if (tp->t_srtt != 0) {
2215 /*
2216 * srtt is stored as fixed point with 3 bits after the
2217 * binary point (i.e., scaled by 8). The following magic
2218 * is equivalent to the smoothing algorithm in rfc793 with
2219 * an alpha of .875 (srtt = rtt/8 + srtt*7/8 in fixed
2220 * point). Adjust rtt to origin 0.
2221 */
2222 delta = (rtt << 2) - (tp->t_srtt >> TCP_RTT_SHIFT);
2223 if ((tp->t_srtt += delta) <= 0)
2224 tp->t_srtt = 1 << 2;
2225 /*
2226 * We accumulate a smoothed rtt variance (actually, a
2227 * smoothed mean difference), then set the retransmit
2228 * timer to smoothed rtt + 4 times the smoothed variance.
2229 * rttvar is stored as fixed point with 2 bits after the
2230 * binary point (scaled by 4). The following is
2231 * equivalent to rfc793 smoothing with an alpha of .75
2232 * (rttvar = rttvar*3/4 + |delta| / 4). This replaces
2233 * rfc793's wired-in beta.
2234 */
2235 if (delta < 0)
2236 delta = -delta;
2237 delta -= (tp->t_rttvar >> TCP_RTTVAR_SHIFT);
2238 if ((tp->t_rttvar += delta) <= 0)
2239 tp->t_rttvar = 1 << 2;
2240 } else {
2241 /*
2242 * No rtt measurement yet - use the unsmoothed rtt.
2243 * Set the variance to half the rtt (so our first
2244 * retransmit happens at 3*rtt).
2245 */
2246 tp->t_srtt = rtt << (TCP_RTT_SHIFT + 2);
2247 tp->t_rttvar = rtt << (TCP_RTTVAR_SHIFT + 2 - 1);
2248 }
2249 tp->t_rtt = 0;
2250 tp->t_rxtshift = 0;
2251
2252 /*
2253 * the retransmit should happen at rtt + 4 * rttvar.
2254 * Because of the way we do the smoothing, srtt and rttvar
2255 * will each average +1/2 tick of bias. When we compute
2256 * the retransmit timer, we want 1/2 tick of rounding and
2257 * 1 extra tick because of +-1/2 tick uncertainty in the
2258 * firing of the timer. The bias will give us exactly the
2259 * 1.5 tick we need. But, because the bias is
2260 * statistical, we have to test that we don't drop below
2261 * the minimum feasible timer (which is 2 ticks).
2262 */
2263 if (tp->t_rttmin > rtt + 2)
2264 rttmin = tp->t_rttmin;
2265 else
2266 rttmin = rtt + 2;
2267 TCPT_RANGESET(tp->t_rxtcur, TCP_REXMTVAL(tp), rttmin, TCPTV_REXMTMAX);
2268
2269 /*
2270 * We received an ack for a packet that wasn't retransmitted;
2271 * it is probably safe to discard any error indications we've
2272 * received recently. This isn't quite right, but close enough
2273 * for now (a route might have failed after we sent a segment,
2274 * and the return path might not be symmetrical).
2275 */
2276 tp->t_softerror = 0;
2277 }
2278
2279 /*
2280 * Checks for partial ack. If partial ack arrives, force the retransmission
2281 * of the next unacknowledged segment, do not clear tp->t_dupacks, and return
2282 * 1. By setting snd_nxt to ti_ack, this forces retransmission timer to
2283 * be started again. If the ack advances at least to tp->snd_recover, return 0.
2284 */
2285 int
2286 tcp_newreno(tp, th)
2287 struct tcpcb *tp;
2288 struct tcphdr *th;
2289 {
2290 if (SEQ_LT(th->th_ack, tp->snd_recover)) {
2291 tcp_seq onxt = tp->snd_nxt;
2292 tcp_seq ouna = tp->snd_una; /* Haven't updated snd_una yet*/
2293 u_long ocwnd = tp->snd_cwnd;
2294 TCP_TIMER_DISARM(tp, TCPT_REXMT);
2295 tp->t_rtt = 0;
2296 tp->snd_nxt = th->th_ack;
2297 tp->snd_cwnd = tp->t_segsz;
2298 tp->snd_una = th->th_ack;
2299 (void) tcp_output(tp);
2300 tp->snd_cwnd = ocwnd;
2301 tp->snd_una = ouna;
2302 if (SEQ_GT(onxt, tp->snd_nxt))
2303 tp->snd_nxt = onxt;
2304 /*
2305 * Partial window deflation. Relies on fact that tp->snd_una
2306 * not updated yet.
2307 */
2308 tp->snd_cwnd -= (th->th_ack - tp->snd_una - tp->t_segsz);
2309 return 1;
2310 }
2311 return 0;
2312 }
2313
2314
2315 /*
2316 * TCP compressed state engine. Currently used to hold compressed
2317 * state for SYN_RECEIVED.
2318 */
2319
2320 u_long syn_cache_count;
2321 u_int32_t syn_hash1, syn_hash2;
2322
2323 #define SYN_HASH(sa, sp, dp) \
2324 ((((sa)->s_addr^syn_hash1)*(((((u_int32_t)(dp))<<16) + \
2325 ((u_int32_t)(sp)))^syn_hash2)))
2326 #ifndef INET6
2327 #define SYN_HASHALL(hash, src, dst) \
2328 do { \
2329 hash = SYN_HASH(&((struct sockaddr_in *)(src))->sin_addr, \
2330 ((struct sockaddr_in *)(src))->sin_port, \
2331 ((struct sockaddr_in *)(dst))->sin_port); \
2332 } while (0)
2333 #else
2334 #define SYN_HASH6(sa, sp, dp) \
2335 ((((sa)->s6_addr32[0] ^ (sa)->s6_addr32[3] ^ syn_hash1) * \
2336 (((((u_int32_t)(dp))<<16) + ((u_int32_t)(sp)))^syn_hash2)) \
2337 & 0x7fffffff)
2338
2339 #define SYN_HASHALL(hash, src, dst) \
2340 do { \
2341 switch ((src)->sa_family) { \
2342 case AF_INET: \
2343 hash = SYN_HASH(&((struct sockaddr_in *)(src))->sin_addr, \
2344 ((struct sockaddr_in *)(src))->sin_port, \
2345 ((struct sockaddr_in *)(dst))->sin_port); \
2346 break; \
2347 case AF_INET6: \
2348 hash = SYN_HASH6(&((struct sockaddr_in6 *)(src))->sin6_addr, \
2349 ((struct sockaddr_in6 *)(src))->sin6_port, \
2350 ((struct sockaddr_in6 *)(dst))->sin6_port); \
2351 break; \
2352 default: \
2353 hash = 0; \
2354 } \
2355 } while (0)
2356 #endif /* INET6 */
2357
2358 #define SYN_CACHE_RM(sc) \
2359 do { \
2360 LIST_REMOVE((sc), sc_bucketq); \
2361 tcp_syn_cache[(sc)->sc_bucketidx].sch_length--; \
2362 TAILQ_REMOVE(&tcp_syn_cache_timeq[(sc)->sc_rxtshift], (sc), sc_timeq); \
2363 syn_cache_count--; \
2364 } while (0)
2365
2366 #define SYN_CACHE_PUT(sc) \
2367 do { \
2368 if ((sc)->sc_ipopts) \
2369 (void) m_free((sc)->sc_ipopts); \
2370 if ((sc)->sc_route4.ro_rt != NULL) \
2371 RTFREE((sc)->sc_route4.ro_rt); \
2372 pool_put(&syn_cache_pool, (sc)); \
2373 } while (0)
2374
2375 struct pool syn_cache_pool;
2376
2377 /*
2378 * We don't estimate RTT with SYNs, so each packet starts with the default
2379 * RTT and each timer queue has a fixed timeout value. This allows us to
2380 * optimize the timer queues somewhat.
2381 */
2382 #define SYN_CACHE_TIMER_ARM(sc) \
2383 do { \
2384 TCPT_RANGESET((sc)->sc_rxtcur, \
2385 TCPTV_SRTTDFLT * tcp_backoff[(sc)->sc_rxtshift], TCPTV_MIN, \
2386 TCPTV_REXMTMAX); \
2387 PRT_SLOW_ARM((sc)->sc_rexmt, (sc)->sc_rxtcur); \
2388 } while (0)
2389
2390 TAILQ_HEAD(, syn_cache) tcp_syn_cache_timeq[TCP_MAXRXTSHIFT + 1];
2391
2392 void
2393 syn_cache_init()
2394 {
2395 int i;
2396
2397 /* Initialize the hash buckets. */
2398 for (i = 0; i < tcp_syn_cache_size; i++)
2399 LIST_INIT(&tcp_syn_cache[i].sch_bucket);
2400
2401 /* Initialize the timer queues. */
2402 for (i = 0; i <= TCP_MAXRXTSHIFT; i++)
2403 TAILQ_INIT(&tcp_syn_cache_timeq[i]);
2404
2405 /* Initialize the syn cache pool. */
2406 pool_init(&syn_cache_pool, sizeof(struct syn_cache), 0, 0, 0,
2407 "synpl", 0, NULL, NULL, M_PCB);
2408 }
2409
2410 void
2411 syn_cache_insert(sc)
2412 struct syn_cache *sc;
2413 {
2414 struct syn_cache_head *scp;
2415 struct syn_cache *sc2;
2416 int s, i;
2417
2418 /*
2419 * If there are no entries in the hash table, reinitialize
2420 * the hash secrets.
2421 */
2422 if (syn_cache_count == 0) {
2423 struct timeval tv;
2424 microtime(&tv);
2425 syn_hash1 = random() ^ (u_long)≻
2426 syn_hash2 = random() ^ tv.tv_usec;
2427 }
2428
2429 SYN_HASHALL(sc->sc_hash, &sc->sc_src.sa, &sc->sc_dst.sa);
2430 sc->sc_bucketidx = sc->sc_hash % tcp_syn_cache_size;
2431 scp = &tcp_syn_cache[sc->sc_bucketidx];
2432
2433 /*
2434 * Make sure that we don't overflow the per-bucket
2435 * limit or the total cache size limit.
2436 */
2437 s = splsoftnet();
2438 if (scp->sch_length >= tcp_syn_bucket_limit) {
2439 tcpstat.tcps_sc_bucketoverflow++;
2440 /*
2441 * The bucket is full. Toss the oldest element in the
2442 * bucket. This will be the entry with our bucket
2443 * index closest to the front of the timer queue with
2444 * the largest timeout value.
2445 *
2446 * Note: This timer queue traversal may be expensive, so
2447 * we hope that this doesn't happen very often. It is
2448 * much more likely that we'll overflow the entire
2449 * cache, which is much easier to handle; see below.
2450 */
2451 for (i = TCP_MAXRXTSHIFT; i >= 0; i--) {
2452 for (sc2 = TAILQ_FIRST(&tcp_syn_cache_timeq[i]);
2453 sc2 != NULL;
2454 sc2 = TAILQ_NEXT(sc2, sc_timeq)) {
2455 if (sc2->sc_bucketidx == sc->sc_bucketidx) {
2456 SYN_CACHE_RM(sc2);
2457 SYN_CACHE_PUT(sc2);
2458 goto insert; /* 2 level break */
2459 }
2460 }
2461 }
2462 #ifdef DIAGNOSTIC
2463 /*
2464 * This should never happen; we should always find an
2465 * entry in our bucket.
2466 */
2467 panic("syn_cache_insert: bucketoverflow: impossible");
2468 #endif
2469 } else if (syn_cache_count >= tcp_syn_cache_limit) {
2470 tcpstat.tcps_sc_overflowed++;
2471 /*
2472 * The cache is full. Toss the oldest entry in the
2473 * entire cache. This is the front entry in the
2474 * first non-empty timer queue with the largest
2475 * timeout value.
2476 */
2477 for (i = TCP_MAXRXTSHIFT; i >= 0; i--) {
2478 sc2 = TAILQ_FIRST(&tcp_syn_cache_timeq[i]);
2479 if (sc2 == NULL)
2480 continue;
2481 SYN_CACHE_RM(sc2);
2482 SYN_CACHE_PUT(sc2);
2483 goto insert; /* symmetry with above */
2484 }
2485 #ifdef DIAGNOSTIC
2486 /*
2487 * This should never happen; we should always find an
2488 * entry in the cache.
2489 */
2490 panic("syn_cache_insert: cache overflow: impossible");
2491 #endif
2492 }
2493
2494 insert:
2495 /*
2496 * Initialize the entry's timer.
2497 */
2498 sc->sc_rxttot = 0;
2499 sc->sc_rxtshift = 0;
2500 SYN_CACHE_TIMER_ARM(sc);
2501 TAILQ_INSERT_TAIL(&tcp_syn_cache_timeq[sc->sc_rxtshift], sc, sc_timeq);
2502
2503 /* Put it into the bucket. */
2504 LIST_INSERT_HEAD(&scp->sch_bucket, sc, sc_bucketq);
2505 scp->sch_length++;
2506 syn_cache_count++;
2507
2508 tcpstat.tcps_sc_added++;
2509 splx(s);
2510 }
2511
2512 /*
2513 * Walk the timer queues, looking for SYN,ACKs that need to be retransmitted.
2514 * If we have retransmitted an entry the maximum number of times, expire
2515 * that entry.
2516 */
2517 void
2518 syn_cache_timer()
2519 {
2520 struct syn_cache *sc, *nsc;
2521 int i, s;
2522
2523 s = splsoftnet();
2524
2525 /*
2526 * First, get all the entries that need to be retransmitted, or
2527 * must be expired due to exceeding the initial keepalive time.
2528 */
2529 for (i = 0; i < TCP_MAXRXTSHIFT; i++) {
2530 for (sc = TAILQ_FIRST(&tcp_syn_cache_timeq[i]);
2531 sc != NULL && PRT_SLOW_ISEXPIRED(sc->sc_rexmt);
2532 sc = nsc) {
2533 nsc = TAILQ_NEXT(sc, sc_timeq);
2534
2535 /*
2536 * Compute the total amount of time this entry has
2537 * been on a queue. If this entry has been on longer
2538 * than the keep alive timer would allow, expire it.
2539 */
2540 sc->sc_rxttot += sc->sc_rxtcur;
2541 if (sc->sc_rxttot >= TCPTV_KEEP_INIT) {
2542 tcpstat.tcps_sc_timed_out++;
2543 SYN_CACHE_RM(sc);
2544 SYN_CACHE_PUT(sc);
2545 continue;
2546 }
2547
2548 tcpstat.tcps_sc_retransmitted++;
2549 (void) syn_cache_respond(sc, NULL);
2550
2551 /* Advance this entry onto the next timer queue. */
2552 TAILQ_REMOVE(&tcp_syn_cache_timeq[i], sc, sc_timeq);
2553 sc->sc_rxtshift = i + 1;
2554 SYN_CACHE_TIMER_ARM(sc);
2555 TAILQ_INSERT_TAIL(&tcp_syn_cache_timeq[sc->sc_rxtshift],
2556 sc, sc_timeq);
2557 }
2558 }
2559
2560 /*
2561 * Now get all the entries that are expired due to too many
2562 * retransmissions.
2563 */
2564 for (sc = TAILQ_FIRST(&tcp_syn_cache_timeq[TCP_MAXRXTSHIFT]);
2565 sc != NULL && PRT_SLOW_ISEXPIRED(sc->sc_rexmt);
2566 sc = nsc) {
2567 nsc = TAILQ_NEXT(sc, sc_timeq);
2568 tcpstat.tcps_sc_timed_out++;
2569 SYN_CACHE_RM(sc);
2570 SYN_CACHE_PUT(sc);
2571 }
2572 splx(s);
2573 }
2574
2575 /*
2576 * Find an entry in the syn cache.
2577 */
2578 struct syn_cache *
2579 syn_cache_lookup(src, dst, headp)
2580 struct sockaddr *src;
2581 struct sockaddr *dst;
2582 struct syn_cache_head **headp;
2583 {
2584 struct syn_cache *sc;
2585 struct syn_cache_head *scp;
2586 u_int32_t hash;
2587 int s;
2588
2589 SYN_HASHALL(hash, src, dst);
2590
2591 scp = &tcp_syn_cache[hash % tcp_syn_cache_size];
2592 *headp = scp;
2593 s = splsoftnet();
2594 for (sc = LIST_FIRST(&scp->sch_bucket); sc != NULL;
2595 sc = LIST_NEXT(sc, sc_bucketq)) {
2596 if (sc->sc_hash != hash)
2597 continue;
2598 if (!bcmp(&sc->sc_src, src, src->sa_len) &&
2599 !bcmp(&sc->sc_dst, dst, dst->sa_len)) {
2600 splx(s);
2601 return (sc);
2602 }
2603 }
2604 splx(s);
2605 return (NULL);
2606 }
2607
2608 /*
2609 * This function gets called when we receive an ACK for a
2610 * socket in the LISTEN state. We look up the connection
2611 * in the syn cache, and if its there, we pull it out of
2612 * the cache and turn it into a full-blown connection in
2613 * the SYN-RECEIVED state.
2614 *
2615 * The return values may not be immediately obvious, and their effects
2616 * can be subtle, so here they are:
2617 *
2618 * NULL SYN was not found in cache; caller should drop the
2619 * packet and send an RST.
2620 *
2621 * -1 We were unable to create the new connection, and are
2622 * aborting it. An ACK,RST is being sent to the peer
2623 * (unless we got screwey sequence numbners; see below),
2624 * because the 3-way handshake has been completed. Caller
2625 * should not free the mbuf, since we may be using it. If
2626 * we are not, we will free it.
2627 *
2628 * Otherwise, the return value is a pointer to the new socket
2629 * associated with the connection.
2630 */
2631 struct socket *
2632 syn_cache_get(src, dst, th, hlen, tlen, so, m)
2633 struct sockaddr *src;
2634 struct sockaddr *dst;
2635 struct tcphdr *th;
2636 unsigned int hlen, tlen;
2637 struct socket *so;
2638 struct mbuf *m;
2639 {
2640 struct syn_cache *sc;
2641 struct syn_cache_head *scp;
2642 register struct inpcb *inp = NULL;
2643 #ifdef INET6
2644 register struct in6pcb *in6p = NULL;
2645 #endif
2646 register struct tcpcb *tp = 0;
2647 struct mbuf *am;
2648 int s;
2649 struct socket *oso;
2650
2651 s = splsoftnet();
2652 if ((sc = syn_cache_lookup(src, dst, &scp)) == NULL) {
2653 splx(s);
2654 return (NULL);
2655 }
2656
2657 /*
2658 * Verify the sequence and ack numbers. Try getting the correct
2659 * response again.
2660 */
2661 if ((th->th_ack != sc->sc_iss + 1) ||
2662 SEQ_LEQ(th->th_seq, sc->sc_irs) ||
2663 SEQ_GT(th->th_seq, sc->sc_irs + 1 + sc->sc_win)) {
2664 (void) syn_cache_respond(sc, m);
2665 splx(s);
2666 return ((struct socket *)(-1));
2667 }
2668
2669 /* Remove this cache entry */
2670 SYN_CACHE_RM(sc);
2671 splx(s);
2672
2673 /*
2674 * Ok, create the full blown connection, and set things up
2675 * as they would have been set up if we had created the
2676 * connection when the SYN arrived. If we can't create
2677 * the connection, abort it.
2678 */
2679 /*
2680 * inp still has the OLD in_pcb stuff, set the
2681 * v6-related flags on the new guy, too. This is
2682 * done particularly for the case where an AF_INET6
2683 * socket is bound only to a port, and a v4 connection
2684 * comes in on that port.
2685 * we also copy the flowinfo from the original pcb
2686 * to the new one.
2687 */
2688 {
2689 struct inpcb *parentinpcb;
2690
2691 parentinpcb = (struct inpcb *)so->so_pcb;
2692
2693 oso = so;
2694 so = sonewconn(so, SS_ISCONNECTED);
2695 if (so == NULL)
2696 goto resetandabort;
2697
2698 switch (so->so_proto->pr_domain->dom_family) {
2699 case AF_INET:
2700 inp = sotoinpcb(so);
2701 break;
2702 #ifdef INET6
2703 case AF_INET6:
2704 in6p = sotoin6pcb(so);
2705 #if 0 /*def INET6*/
2706 inp->inp_flags |= (parentinpcb->inp_flags &
2707 (INP_IPV6 | INP_IPV6_UNDEC | INP_IPV6_MAPPED));
2708 if ((inp->inp_flags & INP_IPV6) &&
2709 !(inp->inp_flags & INP_IPV6_MAPPED)) {
2710 inp->inp_ipv6.ip6_hlim = parentinpcb->inp_ipv6.ip6_hlim;
2711 inp->inp_ipv6.ip6_vfc = parentinpcb->inp_ipv6.ip6_vfc;
2712 }
2713 #endif
2714 break;
2715 #endif
2716 }
2717 }
2718 switch (src->sa_family) {
2719 case AF_INET:
2720 if (inp) {
2721 inp->inp_laddr = ((struct sockaddr_in *)dst)->sin_addr;
2722 inp->inp_lport = ((struct sockaddr_in *)dst)->sin_port;
2723 inp->inp_options = ip_srcroute();
2724 in_pcbstate(inp, INP_BOUND);
2725 if (inp->inp_options == NULL) {
2726 inp->inp_options = sc->sc_ipopts;
2727 sc->sc_ipopts = NULL;
2728 }
2729 }
2730 #ifdef INET6
2731 else if (in6p) {
2732 /* IPv4 packet to AF_INET6 socket */
2733 bzero(&in6p->in6p_laddr, sizeof(in6p->in6p_laddr));
2734 in6p->in6p_laddr.s6_addr16[5] = htons(0xffff);
2735 bcopy(&((struct sockaddr_in *)dst)->sin_addr,
2736 &in6p->in6p_laddr.s6_addr32[3],
2737 sizeof(((struct sockaddr_in *)dst)->sin_addr));
2738 in6p->in6p_lport = ((struct sockaddr_in *)dst)->sin_port;
2739 in6totcpcb(in6p)->t_family = AF_INET;
2740 }
2741 #endif
2742 break;
2743 #ifdef INET6
2744 case AF_INET6:
2745 if (in6p) {
2746 in6p->in6p_laddr = ((struct sockaddr_in6 *)dst)->sin6_addr;
2747 in6p->in6p_lport = ((struct sockaddr_in6 *)dst)->sin6_port;
2748 #if 0
2749 in6p->in6p_flowinfo = ip6->ip6_flow & IPV6_FLOWINFO_MASK;
2750 /*inp->inp_options = ip6_srcroute();*/ /* soon. */
2751 #endif
2752 }
2753 break;
2754 #endif
2755 }
2756 #ifdef INET6
2757 if (in6p && in6totcpcb(in6p)->t_family == AF_INET6 && sotoinpcb(oso)) {
2758 struct in6pcb *oin6p = sotoin6pcb(oso);
2759 /* inherit socket options from the listening socket */
2760 in6p->in6p_flags |= (oin6p->in6p_flags & IN6P_CONTROLOPTS);
2761 if (in6p->in6p_flags & IN6P_CONTROLOPTS) {
2762 m_freem(in6p->in6p_options);
2763 in6p->in6p_options = 0;
2764 }
2765 ip6_savecontrol(in6p, &in6p->in6p_options,
2766 mtod(m, struct ip6_hdr *), m);
2767 }
2768 #endif
2769
2770 #ifdef IPSEC
2771 {
2772 struct secpolicy *sp;
2773 if (inp) {
2774 sp = ipsec_copy_policy(sotoinpcb(oso)->inp_sp);
2775 if (sp) {
2776 key_freesp(inp->inp_sp);
2777 inp->inp_sp = sp;
2778 } else
2779 printf("tcp_input: could not copy policy\n");
2780 }
2781 #ifdef INET6
2782 else if (in6p) {
2783 sp = ipsec_copy_policy(sotoin6pcb(oso)->in6p_sp);
2784 if (sp) {
2785 key_freesp(in6p->in6p_sp);
2786 in6p->in6p_sp = sp;
2787 } else
2788 printf("tcp_input: could not copy policy\n");
2789 }
2790 #endif
2791 }
2792 #endif
2793
2794 /*
2795 * Give the new socket our cached route reference.
2796 */
2797 if (inp)
2798 inp->inp_route = sc->sc_route4; /* struct assignment */
2799 #ifdef INET6
2800 else
2801 in6p->in6p_route = sc->sc_route6;
2802 #endif
2803 sc->sc_route4.ro_rt = NULL;
2804
2805 am = m_get(M_DONTWAIT, MT_SONAME); /* XXX */
2806 if (am == NULL)
2807 goto resetandabort;
2808 am->m_len = src->sa_len;
2809 bcopy(src, mtod(am, caddr_t), src->sa_len);
2810 if (inp) {
2811 if (in_pcbconnect(inp, am)) {
2812 (void) m_free(am);
2813 goto resetandabort;
2814 }
2815 }
2816 #ifdef INET6
2817 else if (in6p) {
2818 if (src->sa_family == AF_INET) {
2819 /* IPv4 packet to AF_INET6 socket */
2820 struct sockaddr_in6 *sin6;
2821 sin6 = mtod(am, struct sockaddr_in6 *);
2822 am->m_len = sizeof(*sin6);
2823 bzero(sin6, sizeof(*sin6));
2824 sin6->sin6_family = AF_INET6;
2825 sin6->sin6_len = sizeof(*sin6);
2826 sin6->sin6_port = ((struct sockaddr_in *)src)->sin_port;
2827 sin6->sin6_addr.s6_addr16[5] = htons(0xffff);
2828 bcopy(&((struct sockaddr_in *)src)->sin_addr,
2829 &sin6->sin6_addr.s6_addr32[3],
2830 sizeof(sin6->sin6_addr.s6_addr32[3]));
2831 }
2832 if (in6_pcbconnect(in6p, am)) {
2833 (void) m_free(am);
2834 goto resetandabort;
2835 }
2836 }
2837 #endif
2838 else {
2839 (void) m_free(am);
2840 goto resetandabort;
2841 }
2842 (void) m_free(am);
2843
2844 if (inp)
2845 tp = intotcpcb(inp);
2846 #ifdef INET6
2847 else if (in6p)
2848 tp = in6totcpcb(in6p);
2849 #endif
2850 else
2851 tp = NULL;
2852 if (sc->sc_request_r_scale != 15) {
2853 tp->requested_s_scale = sc->sc_requested_s_scale;
2854 tp->request_r_scale = sc->sc_request_r_scale;
2855 tp->snd_scale = sc->sc_requested_s_scale;
2856 tp->rcv_scale = sc->sc_request_r_scale;
2857 tp->t_flags |= TF_RCVD_SCALE;
2858 }
2859 if (sc->sc_flags & SCF_TIMESTAMP)
2860 tp->t_flags |= TF_RCVD_TSTMP;
2861
2862 tp->t_template = tcp_template(tp);
2863 if (tp->t_template == 0) {
2864 tp = tcp_drop(tp, ENOBUFS); /* destroys socket */
2865 so = NULL;
2866 m_freem(m);
2867 goto abort;
2868 }
2869
2870 tp->iss = sc->sc_iss;
2871 tp->irs = sc->sc_irs;
2872 tcp_sendseqinit(tp);
2873 tcp_rcvseqinit(tp);
2874 tp->t_state = TCPS_SYN_RECEIVED;
2875 TCP_TIMER_ARM(tp, TCPT_KEEP, TCPTV_KEEP_INIT);
2876 tcpstat.tcps_accepts++;
2877
2878 /* Initialize tp->t_ourmss before we deal with the peer's! */
2879 tp->t_ourmss = sc->sc_ourmaxseg;
2880 tcp_mss_from_peer(tp, sc->sc_peermaxseg);
2881
2882 /*
2883 * Initialize the initial congestion window. If we
2884 * had to retransmit the SYN,ACK, we must initialize cwnd
2885 * to 1 segment (i.e. the Loss Window).
2886 */
2887 if (sc->sc_rxtshift)
2888 tp->snd_cwnd = tp->t_peermss;
2889 else
2890 tp->snd_cwnd = TCP_INITIAL_WINDOW(tcp_init_win, tp->t_peermss);
2891
2892 tcp_rmx_rtt(tp);
2893 tp->snd_wl1 = sc->sc_irs;
2894 tp->rcv_up = sc->sc_irs + 1;
2895
2896 /*
2897 * This is what whould have happened in tcp_ouput() when
2898 * the SYN,ACK was sent.
2899 */
2900 tp->snd_up = tp->snd_una;
2901 tp->snd_max = tp->snd_nxt = tp->iss+1;
2902 TCP_TIMER_ARM(tp, TCPT_REXMT, tp->t_rxtcur);
2903 if (sc->sc_win > 0 && SEQ_GT(tp->rcv_nxt + sc->sc_win, tp->rcv_adv))
2904 tp->rcv_adv = tp->rcv_nxt + sc->sc_win;
2905 tp->last_ack_sent = tp->rcv_nxt;
2906
2907 tcpstat.tcps_sc_completed++;
2908 SYN_CACHE_PUT(sc);
2909 return (so);
2910
2911 resetandabort:
2912 (void) tcp_respond(NULL, m, m, th,
2913 th->th_seq + tlen, (tcp_seq)0, TH_RST|TH_ACK);
2914 abort:
2915 if (so != NULL)
2916 (void) soabort(so);
2917 SYN_CACHE_PUT(sc);
2918 tcpstat.tcps_sc_aborted++;
2919 return ((struct socket *)(-1));
2920 }
2921
2922 /*
2923 * This function is called when we get a RST for a
2924 * non-existant connection, so that we can see if the
2925 * connection is in the syn cache. If it is, zap it.
2926 */
2927
2928 void
2929 syn_cache_reset(src, dst, th)
2930 struct sockaddr *src;
2931 struct sockaddr *dst;
2932 struct tcphdr *th;
2933 {
2934 struct syn_cache *sc;
2935 struct syn_cache_head *scp;
2936 int s = splsoftnet();
2937
2938 if ((sc = syn_cache_lookup(src, dst, &scp)) == NULL) {
2939 splx(s);
2940 return;
2941 }
2942 if (SEQ_LT(th->th_seq, sc->sc_irs) ||
2943 SEQ_GT(th->th_seq, sc->sc_irs+1)) {
2944 splx(s);
2945 return;
2946 }
2947 SYN_CACHE_RM(sc);
2948 splx(s);
2949 tcpstat.tcps_sc_reset++;
2950 SYN_CACHE_PUT(sc);
2951 }
2952
2953 void
2954 syn_cache_unreach(src, dst, th)
2955 struct sockaddr *src;
2956 struct sockaddr *dst;
2957 struct tcphdr *th;
2958 {
2959 struct syn_cache *sc;
2960 struct syn_cache_head *scp;
2961 int s;
2962
2963 s = splsoftnet();
2964 if ((sc = syn_cache_lookup(src, dst, &scp)) == NULL) {
2965 splx(s);
2966 return;
2967 }
2968 /* If the sequence number != sc_iss, then it's a bogus ICMP msg */
2969 if (ntohl (th->th_seq) != sc->sc_iss) {
2970 splx(s);
2971 return;
2972 }
2973
2974 /*
2975 * If we've rertransmitted 3 times and this is our second error,
2976 * we remove the entry. Otherwise, we allow it to continue on.
2977 * This prevents us from incorrectly nuking an entry during a
2978 * spurious network outage.
2979 *
2980 * See tcp_notify().
2981 */
2982 if ((sc->sc_flags & SCF_UNREACH) == 0 || sc->sc_rxtshift < 3) {
2983 sc->sc_flags |= SCF_UNREACH;
2984 splx(s);
2985 return;
2986 }
2987
2988 SYN_CACHE_RM(sc);
2989 splx(s);
2990 tcpstat.tcps_sc_unreach++;
2991 SYN_CACHE_PUT(sc);
2992 }
2993
2994 /*
2995 * Given a LISTEN socket and an inbound SYN request, add
2996 * this to the syn cache, and send back a segment:
2997 * <SEQ=ISS><ACK=RCV_NXT><CTL=SYN,ACK>
2998 * to the source.
2999 *
3000 * IMPORTANT NOTE: We do _NOT_ ACK data that might accompany the SYN.
3001 * Doing so would require that we hold onto the data and deliver it
3002 * to the application. However, if we are the target of a SYN-flood
3003 * DoS attack, an attacker could send data which would eventually
3004 * consume all available buffer space if it were ACKed. By not ACKing
3005 * the data, we avoid this DoS scenario.
3006 */
3007
3008 int
3009 syn_cache_add(src, dst, th, hlen, so, m, optp, optlen, oi)
3010 struct sockaddr *src;
3011 struct sockaddr *dst;
3012 struct tcphdr *th;
3013 unsigned int hlen;
3014 struct socket *so;
3015 struct mbuf *m;
3016 u_char *optp;
3017 int optlen;
3018 struct tcp_opt_info *oi;
3019 {
3020 struct tcpcb tb, *tp;
3021 long win;
3022 struct syn_cache *sc;
3023 struct syn_cache_head *scp;
3024 struct mbuf *ipopts;
3025 #ifdef IPSEC
3026 size_t ipsechdrsiz;
3027 #endif
3028
3029 tp = sototcpcb(so);
3030
3031 /*
3032 * RFC1122 4.2.3.10, p. 104: discard bcast/mcast SYN
3033 * in_broadcast() should never return true on a received
3034 * packet with M_BCAST not set.
3035 */
3036 if (m->m_flags & (M_BCAST|M_MCAST))
3037 return 0;
3038 #ifdef INET6
3039 if (m->m_flags & M_ANYCAST6)
3040 return 0;
3041 #endif
3042
3043 switch (src->sa_family) {
3044 case AF_INET:
3045 if (IN_MULTICAST(((struct sockaddr_in *)src)->sin_addr.s_addr)
3046 || IN_MULTICAST(((struct sockaddr_in *)dst)->sin_addr.s_addr))
3047 return 0;
3048 #ifdef IPSEC
3049 ipsechdrsiz = ipsec4_hdrsiz_tcp(tp);
3050 #endif
3051 break;
3052 #ifdef INET6
3053 case AF_INET6:
3054 if (IN6_IS_ADDR_MULTICAST(&((struct sockaddr_in6 *)src)->sin6_addr)
3055 || IN6_IS_ADDR_MULTICAST(&((struct sockaddr_in6 *)dst)->sin6_addr))
3056 return 0;
3057 #if defined(IPSEC) && !defined(TCP6)
3058 ipsechdrsiz = ipsec6_hdrsiz_tcp(tp);
3059 #endif
3060 break;
3061 #endif
3062 }
3063
3064 /*
3065 * Initialize some local state.
3066 */
3067 win = sbspace(&so->so_rcv);
3068 if (win > TCP_MAXWIN)
3069 win = TCP_MAXWIN;
3070
3071 if (src->sa_family == AF_INET) {
3072 /*
3073 * Remember the IP options, if any.
3074 */
3075 ipopts = ip_srcroute();
3076 } else
3077 ipopts = NULL;
3078
3079 if (optp) {
3080 tb.t_flags = tcp_do_rfc1323 ? (TF_REQ_SCALE|TF_REQ_TSTMP) : 0;
3081 tcp_dooptions(&tb, optp, optlen, th, oi);
3082 } else
3083 tb.t_flags = 0;
3084
3085 /*
3086 * See if we already have an entry for this connection.
3087 * If we do, resend the SYN,ACK. We do not count this
3088 * as a retransmission (XXX though maybe we should).
3089 */
3090 if ((sc = syn_cache_lookup(src, dst, &scp)) != NULL) {
3091 tcpstat.tcps_sc_dupesyn++;
3092 if (ipopts) {
3093 /*
3094 * If we were remembering a previous source route,
3095 * forget it and use the new one we've been given.
3096 */
3097 if (sc->sc_ipopts)
3098 (void) m_free(sc->sc_ipopts);
3099 sc->sc_ipopts = ipopts;
3100 }
3101 sc->sc_timestamp = tb.ts_recent;
3102 if (syn_cache_respond(sc, m) == 0) {
3103 tcpstat.tcps_sndacks++;
3104 tcpstat.tcps_sndtotal++;
3105 }
3106 return (1);
3107 }
3108
3109 sc = pool_get(&syn_cache_pool, PR_NOWAIT);
3110 if (sc == NULL) {
3111 if (ipopts)
3112 (void) m_free(ipopts);
3113 return (0);
3114 }
3115
3116 /*
3117 * Fill in the cache, and put the necessary IP and TCP
3118 * options into the reply.
3119 */
3120 bzero(sc, sizeof(struct syn_cache));
3121 bcopy(src, &sc->sc_src, src->sa_len);
3122 bcopy(dst, &sc->sc_dst, dst->sa_len);
3123 sc->sc_flags = 0;
3124 sc->sc_ipopts = ipopts;
3125 sc->sc_irs = th->th_seq;
3126 sc->sc_iss = tcp_new_iss(sc, sizeof(struct syn_cache), 0);
3127 sc->sc_peermaxseg = oi->maxseg;
3128 sc->sc_ourmaxseg = tcp_mss_to_advertise(m->m_flags & M_PKTHDR ?
3129 m->m_pkthdr.rcvif : NULL);
3130 #ifdef IPSEC
3131 if (ipsechdrsiz < sc->sc_ourmaxseg)
3132 sc->sc_ourmaxseg -= ipsechdrsiz;
3133 #endif
3134 sc->sc_win = win;
3135 sc->sc_timestamp = tb.ts_recent;
3136 if (tcp_do_rfc1323 && (tb.t_flags & TF_RCVD_TSTMP))
3137 sc->sc_flags |= SCF_TIMESTAMP;
3138 if ((tb.t_flags & (TF_RCVD_SCALE|TF_REQ_SCALE)) ==
3139 (TF_RCVD_SCALE|TF_REQ_SCALE)) {
3140 sc->sc_requested_s_scale = tb.requested_s_scale;
3141 sc->sc_request_r_scale = 0;
3142 while (sc->sc_request_r_scale < TCP_MAX_WINSHIFT &&
3143 TCP_MAXWIN << sc->sc_request_r_scale <
3144 so->so_rcv.sb_hiwat)
3145 sc->sc_request_r_scale++;
3146 } else {
3147 sc->sc_requested_s_scale = 15;
3148 sc->sc_request_r_scale = 15;
3149 }
3150 sc->sc_so = so;
3151 if (syn_cache_respond(sc, m) == 0) {
3152 syn_cache_insert(sc);
3153 tcpstat.tcps_sndacks++;
3154 tcpstat.tcps_sndtotal++;
3155 } else {
3156 SYN_CACHE_PUT(sc);
3157 tcpstat.tcps_sc_dropped++;
3158 }
3159 return (1);
3160 }
3161
3162 int
3163 syn_cache_respond(sc, m)
3164 struct syn_cache *sc;
3165 struct mbuf *m;
3166 {
3167 struct route *ro = &sc->sc_route4;
3168 struct rtentry *rt;
3169 u_int8_t *optp;
3170 int optlen, error;
3171 u_int16_t tlen;
3172 struct ip *ip = NULL;
3173 #ifdef INET6
3174 struct ip6_hdr *ip6 = NULL;
3175 #endif
3176 struct tcphdr *th;
3177 u_int hlen;
3178
3179 switch (sc->sc_src.sa.sa_family) {
3180 case AF_INET:
3181 hlen = sizeof(struct ip);
3182 break;
3183 #ifdef INET6
3184 case AF_INET6:
3185 hlen = sizeof(struct ip6_hdr);
3186 break;
3187 #endif
3188 default:
3189 if (m)
3190 m_freem(m);
3191 return EAFNOSUPPORT;
3192 }
3193
3194 /* Compute the size of the TCP options. */
3195 optlen = 4 + (sc->sc_request_r_scale != 15 ? 4 : 0) +
3196 ((sc->sc_flags & SCF_TIMESTAMP) ? TCPOLEN_TSTAMP_APPA : 0);
3197
3198 tlen = hlen + sizeof(struct tcphdr) + optlen;
3199
3200 /*
3201 * Create the IP+TCP header from scratch. Reuse the received mbuf
3202 * if possible.
3203 */
3204 if (m != NULL) {
3205 m_freem(m->m_next);
3206 m->m_next = NULL;
3207 MRESETDATA(m);
3208 } else {
3209 MGETHDR(m, M_DONTWAIT, MT_DATA);
3210 if (m == NULL)
3211 return (ENOBUFS);
3212 }
3213
3214 /* Fixup the mbuf. */
3215 m->m_data += max_linkhdr;
3216 m->m_len = m->m_pkthdr.len = tlen;
3217 #ifdef IPSEC
3218 /* use IPsec policy on listening socket, on SYN ACK */
3219 m->m_pkthdr.rcvif = (struct ifnet *)sc->sc_so;
3220 #else
3221 m->m_pkthdr.rcvif = NULL;
3222 #endif
3223 memset(mtod(m, u_char *), 0, tlen);
3224
3225 switch (sc->sc_src.sa.sa_family) {
3226 case AF_INET:
3227 ip = mtod(m, struct ip *);
3228 ip->ip_dst = sc->sc_src.sin.sin_addr;
3229 ip->ip_src = sc->sc_dst.sin.sin_addr;
3230 ip->ip_p = IPPROTO_TCP;
3231 th = (struct tcphdr *)(ip + 1);
3232 th->th_dport = sc->sc_src.sin.sin_port;
3233 th->th_sport = sc->sc_dst.sin.sin_port;
3234 break;
3235 #ifdef INET6
3236 case AF_INET6:
3237 ip6 = mtod(m, struct ip6_hdr *);
3238 ip6->ip6_dst = sc->sc_src.sin6.sin6_addr;
3239 ip6->ip6_src = sc->sc_dst.sin6.sin6_addr;
3240 ip6->ip6_nxt = IPPROTO_TCP;
3241 /* ip6_plen will be updated in ip6_output() */
3242 th = (struct tcphdr *)(ip6 + 1);
3243 th->th_dport = sc->sc_src.sin6.sin6_port;
3244 th->th_sport = sc->sc_dst.sin6.sin6_port;
3245 break;
3246 #endif
3247 default:
3248 th = NULL;
3249 }
3250
3251 th->th_seq = htonl(sc->sc_iss);
3252 th->th_ack = htonl(sc->sc_irs + 1);
3253 th->th_off = (sizeof(struct tcphdr) + optlen) >> 2;
3254 th->th_flags = TH_SYN|TH_ACK;
3255 th->th_win = htons(sc->sc_win);
3256 /* th_sum already 0 */
3257 /* th_urp already 0 */
3258
3259 /* Tack on the TCP options. */
3260 optp = (u_int8_t *)(th + 1);
3261 *optp++ = TCPOPT_MAXSEG;
3262 *optp++ = 4;
3263 *optp++ = (sc->sc_ourmaxseg >> 8) & 0xff;
3264 *optp++ = sc->sc_ourmaxseg & 0xff;
3265
3266 if (sc->sc_request_r_scale != 15) {
3267 *((u_int32_t *)optp) = htonl(TCPOPT_NOP << 24 |
3268 TCPOPT_WINDOW << 16 | TCPOLEN_WINDOW << 8 |
3269 sc->sc_request_r_scale);
3270 optp += 4;
3271 }
3272
3273 if (sc->sc_flags & SCF_TIMESTAMP) {
3274 u_int32_t *lp = (u_int32_t *)(optp);
3275 /* Form timestamp option as shown in appendix A of RFC 1323. */
3276 *lp++ = htonl(TCPOPT_TSTAMP_HDR);
3277 *lp++ = htonl(tcp_now);
3278 *lp = htonl(sc->sc_timestamp);
3279 optp += TCPOLEN_TSTAMP_APPA;
3280 }
3281
3282 /* Compute the packet's checksum. */
3283 switch (sc->sc_src.sa.sa_family) {
3284 case AF_INET:
3285 ip->ip_len = htons(tlen - hlen);
3286 th->th_sum = 0;
3287 th->th_sum = in_cksum(m, tlen);
3288 break;
3289 #ifdef INET6
3290 case AF_INET6:
3291 ip6->ip6_plen = htons(tlen - hlen);
3292 th->th_sum = 0;
3293 th->th_sum = in6_cksum(m, IPPROTO_TCP, hlen, tlen - hlen);
3294 break;
3295 #endif
3296 }
3297
3298 /*
3299 * Fill in some straggling IP bits. Note the stack expects
3300 * ip_len to be in host order, for convenience.
3301 */
3302 switch (sc->sc_src.sa.sa_family) {
3303 case AF_INET:
3304 ip->ip_len = tlen;
3305 ip->ip_ttl = ip_defttl;
3306 /* XXX tos? */
3307 break;
3308 #ifdef INET6
3309 case AF_INET6:
3310 ip6->ip6_vfc = IPV6_VERSION;
3311 ip6->ip6_plen = htons(tlen - hlen);
3312 ip6->ip6_hlim = ip6_defhlim;
3313 /* XXX flowlabel? */
3314 break;
3315 #endif
3316 }
3317
3318 /*
3319 * If we're doing Path MTU discovery, we need to set DF unless
3320 * the route's MTU is locked. If we don't yet know the route,
3321 * look it up now. We will copy this reference to the inpcb
3322 * when we finish creating the connection.
3323 */
3324 if ((rt = ro->ro_rt) == NULL || (rt->rt_flags & RTF_UP) == 0) {
3325 if (ro->ro_rt != NULL) {
3326 RTFREE(ro->ro_rt);
3327 ro->ro_rt = NULL;
3328 }
3329 bcopy(&sc->sc_src, &ro->ro_dst, sc->sc_src.sa.sa_len);
3330 rtalloc(ro);
3331 if ((rt = ro->ro_rt) == NULL) {
3332 m_freem(m);
3333 switch (sc->sc_src.sa.sa_family) {
3334 case AF_INET:
3335 ipstat.ips_noroute++;
3336 break;
3337 #ifdef INET6
3338 case AF_INET6:
3339 ip6stat.ip6s_noroute++;
3340 break;
3341 #endif
3342 }
3343 return (EHOSTUNREACH);
3344 }
3345 }
3346
3347 switch (sc->sc_src.sa.sa_family) {
3348 case AF_INET:
3349 if (ip_mtudisc != 0 && (rt->rt_rmx.rmx_locks & RTV_MTU) == 0)
3350 ip->ip_off |= IP_DF;
3351
3352 /* ...and send it off! */
3353 error = ip_output(m, sc->sc_ipopts, ro, 0, NULL);
3354 break;
3355 #ifdef INET6
3356 case AF_INET6:
3357 error = ip6_output(m, NULL /*XXX*/, (struct route_in6 *)ro,
3358 0, NULL);
3359 break;
3360 #endif
3361 default:
3362 error = EAFNOSUPPORT;
3363 break;
3364 }
3365 return (error);
3366 }
3367