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