xref: /netbsd-src/sys/netinet/tcp_input.c (revision d48f14661dda8638fee055ba15d35bdfb29b9fa8)
1 /*	$NetBSD: tcp_input.c,v 1.243 2006/06/07 22:34:01 kardel Exp $	*/
2 
3 /*
4  * Copyright (C) 1995, 1996, 1997, and 1998 WIDE Project.
5  * All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  * 3. Neither the name of the project nor the names of its contributors
16  *    may be used to endorse or promote products derived from this software
17  *    without specific prior written permission.
18  *
19  * THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND
20  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
22  * ARE DISCLAIMED.  IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE
23  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
25  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
26  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
27  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
28  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
29  * SUCH DAMAGE.
30  */
31 
32 /*
33  *      @(#)COPYRIGHT   1.1 (NRL) 17 January 1995
34  *
35  * NRL grants permission for redistribution and use in source and binary
36  * forms, with or without modification, of the software and documentation
37  * created at NRL provided that the following conditions are met:
38  *
39  * 1. Redistributions of source code must retain the above copyright
40  *    notice, this list of conditions and the following disclaimer.
41  * 2. Redistributions in binary form must reproduce the above copyright
42  *    notice, this list of conditions and the following disclaimer in the
43  *    documentation and/or other materials provided with the distribution.
44  * 3. All advertising materials mentioning features or use of this software
45  *    must display the following acknowledgements:
46  *      This product includes software developed by the University of
47  *      California, Berkeley and its contributors.
48  *      This product includes software developed at the Information
49  *      Technology Division, US Naval Research Laboratory.
50  * 4. Neither the name of the NRL nor the names of its contributors
51  *    may be used to endorse or promote products derived from this software
52  *    without specific prior written permission.
53  *
54  * THE SOFTWARE PROVIDED BY NRL IS PROVIDED BY NRL AND CONTRIBUTORS ``AS
55  * IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
56  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
57  * PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL NRL OR
58  * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
59  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
60  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
61  * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
62  * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
63  * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
64  * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
65  *
66  * The views and conclusions contained in the software and documentation
67  * are those of the authors and should not be interpreted as representing
68  * official policies, either expressed or implied, of the US Naval
69  * Research Laboratory (NRL).
70  */
71 
72 /*-
73  * Copyright (c) 1997, 1998, 1999, 2001, 2005 The NetBSD Foundation, Inc.
74  * All rights reserved.
75  *
76  * This code is derived from software contributed to The NetBSD Foundation
77  * by Jason R. Thorpe and Kevin M. Lahey of the Numerical Aerospace Simulation
78  * Facility, NASA Ames Research Center.
79  * This code is derived from software contributed to The NetBSD Foundation
80  * by Charles M. Hannum.
81  *
82  * Redistribution and use in source and binary forms, with or without
83  * modification, are permitted provided that the following conditions
84  * are met:
85  * 1. Redistributions of source code must retain the above copyright
86  *    notice, this list of conditions and the following disclaimer.
87  * 2. Redistributions in binary form must reproduce the above copyright
88  *    notice, this list of conditions and the following disclaimer in the
89  *    documentation and/or other materials provided with the distribution.
90  * 3. All advertising materials mentioning features or use of this software
91  *    must display the following acknowledgement:
92  *	This product includes software developed by the NetBSD
93  *	Foundation, Inc. and its contributors.
94  * 4. Neither the name of The NetBSD Foundation nor the names of its
95  *    contributors may be used to endorse or promote products derived
96  *    from this software without specific prior written permission.
97  *
98  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
99  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
100  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
101  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
102  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
103  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
104  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
105  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
106  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
107  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
108  * POSSIBILITY OF SUCH DAMAGE.
109  */
110 
111 /*
112  * Copyright (c) 1982, 1986, 1988, 1990, 1993, 1994, 1995
113  *	The Regents of the University of California.  All rights reserved.
114  *
115  * Redistribution and use in source and binary forms, with or without
116  * modification, are permitted provided that the following conditions
117  * are met:
118  * 1. Redistributions of source code must retain the above copyright
119  *    notice, this list of conditions and the following disclaimer.
120  * 2. Redistributions in binary form must reproduce the above copyright
121  *    notice, this list of conditions and the following disclaimer in the
122  *    documentation and/or other materials provided with the distribution.
123  * 3. Neither the name of the University nor the names of its contributors
124  *    may be used to endorse or promote products derived from this software
125  *    without specific prior written permission.
126  *
127  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
128  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
129  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
130  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
131  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
132  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
133  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
134  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
135  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
136  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
137  * SUCH DAMAGE.
138  *
139  *	@(#)tcp_input.c	8.12 (Berkeley) 5/24/95
140  */
141 
142 /*
143  *	TODO list for SYN cache stuff:
144  *
145  *	Find room for a "state" field, which is needed to keep a
146  *	compressed state for TIME_WAIT TCBs.  It's been noted already
147  *	that this is fairly important for very high-volume web and
148  *	mail servers, which use a large number of short-lived
149  *	connections.
150  */
151 
152 #include <sys/cdefs.h>
153 __KERNEL_RCSID(0, "$NetBSD: tcp_input.c,v 1.243 2006/06/07 22:34:01 kardel Exp $");
154 
155 #include "opt_inet.h"
156 #include "opt_ipsec.h"
157 #include "opt_inet_csum.h"
158 #include "opt_tcp_debug.h"
159 
160 #include <sys/param.h>
161 #include <sys/systm.h>
162 #include <sys/malloc.h>
163 #include <sys/mbuf.h>
164 #include <sys/protosw.h>
165 #include <sys/socket.h>
166 #include <sys/socketvar.h>
167 #include <sys/errno.h>
168 #include <sys/syslog.h>
169 #include <sys/pool.h>
170 #include <sys/domain.h>
171 #include <sys/kernel.h>
172 #ifdef TCP_SIGNATURE
173 #include <sys/md5.h>
174 #endif
175 
176 #include <net/if.h>
177 #include <net/route.h>
178 #include <net/if_types.h>
179 
180 #include <netinet/in.h>
181 #include <netinet/in_systm.h>
182 #include <netinet/ip.h>
183 #include <netinet/in_pcb.h>
184 #include <netinet/in_var.h>
185 #include <netinet/ip_var.h>
186 #include <netinet/in_offload.h>
187 
188 #ifdef INET6
189 #ifndef INET
190 #include <netinet/in.h>
191 #endif
192 #include <netinet/ip6.h>
193 #include <netinet6/ip6_var.h>
194 #include <netinet6/in6_pcb.h>
195 #include <netinet6/ip6_var.h>
196 #include <netinet6/in6_var.h>
197 #include <netinet/icmp6.h>
198 #include <netinet6/nd6.h>
199 #ifdef TCP_SIGNATURE
200 #include <netinet6/scope6_var.h>
201 #endif
202 #endif
203 
204 #ifndef INET6
205 /* always need ip6.h for IP6_EXTHDR_GET */
206 #include <netinet/ip6.h>
207 #endif
208 
209 #include <netinet/tcp.h>
210 #include <netinet/tcp_fsm.h>
211 #include <netinet/tcp_seq.h>
212 #include <netinet/tcp_timer.h>
213 #include <netinet/tcp_var.h>
214 #include <netinet/tcpip.h>
215 #include <netinet/tcp_debug.h>
216 
217 #include <machine/stdarg.h>
218 
219 #ifdef IPSEC
220 #include <netinet6/ipsec.h>
221 #include <netkey/key.h>
222 #endif /*IPSEC*/
223 #ifdef INET6
224 #include "faith.h"
225 #if defined(NFAITH) && NFAITH > 0
226 #include <net/if_faith.h>
227 #endif
228 #endif	/* IPSEC */
229 
230 #ifdef FAST_IPSEC
231 #include <netipsec/ipsec.h>
232 #include <netipsec/ipsec_var.h>			/* XXX ipsecstat namespace */
233 #include <netipsec/key.h>
234 #ifdef INET6
235 #include <netipsec/ipsec6.h>
236 #endif
237 #endif	/* FAST_IPSEC*/
238 
239 int	tcprexmtthresh = 3;
240 int	tcp_log_refused;
241 
242 static int tcp_rst_ppslim_count = 0;
243 static struct timeval tcp_rst_ppslim_last;
244 static int tcp_ackdrop_ppslim_count = 0;
245 static struct timeval tcp_ackdrop_ppslim_last;
246 
247 #define TCP_PAWS_IDLE	(24U * 24 * 60 * 60 * PR_SLOWHZ)
248 
249 /* for modulo comparisons of timestamps */
250 #define TSTMP_LT(a,b)	((int)((a)-(b)) < 0)
251 #define TSTMP_GEQ(a,b)	((int)((a)-(b)) >= 0)
252 
253 /*
254  * Neighbor Discovery, Neighbor Unreachability Detection Upper layer hint.
255  */
256 #ifdef INET6
257 #define ND6_HINT(tp) \
258 do { \
259 	if (tp && tp->t_in6pcb && tp->t_family == AF_INET6 && \
260 	    tp->t_in6pcb->in6p_route.ro_rt) { \
261 		nd6_nud_hint(tp->t_in6pcb->in6p_route.ro_rt, NULL, 0); \
262 	} \
263 } while (/*CONSTCOND*/ 0)
264 #else
265 #define ND6_HINT(tp)
266 #endif
267 
268 /*
269  * Macro to compute ACK transmission behavior.  Delay the ACK unless
270  * we have already delayed an ACK (must send an ACK every two segments).
271  * We also ACK immediately if we received a PUSH and the ACK-on-PUSH
272  * option is enabled.
273  */
274 #define	TCP_SETUP_ACK(tp, th) \
275 do { \
276 	if ((tp)->t_flags & TF_DELACK || \
277 	    (tcp_ack_on_push && (th)->th_flags & TH_PUSH)) \
278 		tp->t_flags |= TF_ACKNOW; \
279 	else \
280 		TCP_SET_DELACK(tp); \
281 } while (/*CONSTCOND*/ 0)
282 
283 #define ICMP_CHECK(tp, th, acked) \
284 do { \
285 	/* \
286 	 * If we had a pending ICMP message that \
287 	 * refers to data that have just been  \
288 	 * acknowledged, disregard the recorded ICMP \
289 	 * message. \
290 	 */ \
291 	if (((tp)->t_flags & TF_PMTUD_PEND) && \
292 	    SEQ_GT((th)->th_ack, (tp)->t_pmtud_th_seq)) \
293 		(tp)->t_flags &= ~TF_PMTUD_PEND; \
294 \
295 	/* \
296 	 * Keep track of the largest chunk of data \
297 	 * acknowledged since last PMTU update \
298 	 */ \
299 	if ((tp)->t_pmtud_mss_acked < (acked)) \
300 		(tp)->t_pmtud_mss_acked = (acked); \
301 } while (/*CONSTCOND*/ 0)
302 
303 /*
304  * Convert TCP protocol fields to host order for easier processing.
305  */
306 #define	TCP_FIELDS_TO_HOST(th)						\
307 do {									\
308 	NTOHL((th)->th_seq);						\
309 	NTOHL((th)->th_ack);						\
310 	NTOHS((th)->th_win);						\
311 	NTOHS((th)->th_urp);						\
312 } while (/*CONSTCOND*/ 0)
313 
314 /*
315  * ... and reverse the above.
316  */
317 #define	TCP_FIELDS_TO_NET(th)						\
318 do {									\
319 	HTONL((th)->th_seq);						\
320 	HTONL((th)->th_ack);						\
321 	HTONS((th)->th_win);						\
322 	HTONS((th)->th_urp);						\
323 } while (/*CONSTCOND*/ 0)
324 
325 #ifdef TCP_CSUM_COUNTERS
326 #include <sys/device.h>
327 
328 #if defined(INET)
329 extern struct evcnt tcp_hwcsum_ok;
330 extern struct evcnt tcp_hwcsum_bad;
331 extern struct evcnt tcp_hwcsum_data;
332 extern struct evcnt tcp_swcsum;
333 #endif /* defined(INET) */
334 #if defined(INET6)
335 extern struct evcnt tcp6_hwcsum_ok;
336 extern struct evcnt tcp6_hwcsum_bad;
337 extern struct evcnt tcp6_hwcsum_data;
338 extern struct evcnt tcp6_swcsum;
339 #endif /* defined(INET6) */
340 
341 #define	TCP_CSUM_COUNTER_INCR(ev)	(ev)->ev_count++
342 
343 #else
344 
345 #define	TCP_CSUM_COUNTER_INCR(ev)	/* nothing */
346 
347 #endif /* TCP_CSUM_COUNTERS */
348 
349 #ifdef TCP_REASS_COUNTERS
350 #include <sys/device.h>
351 
352 extern struct evcnt tcp_reass_;
353 extern struct evcnt tcp_reass_empty;
354 extern struct evcnt tcp_reass_iteration[8];
355 extern struct evcnt tcp_reass_prependfirst;
356 extern struct evcnt tcp_reass_prepend;
357 extern struct evcnt tcp_reass_insert;
358 extern struct evcnt tcp_reass_inserttail;
359 extern struct evcnt tcp_reass_append;
360 extern struct evcnt tcp_reass_appendtail;
361 extern struct evcnt tcp_reass_overlaptail;
362 extern struct evcnt tcp_reass_overlapfront;
363 extern struct evcnt tcp_reass_segdup;
364 extern struct evcnt tcp_reass_fragdup;
365 
366 #define	TCP_REASS_COUNTER_INCR(ev)	(ev)->ev_count++
367 
368 #else
369 
370 #define	TCP_REASS_COUNTER_INCR(ev)	/* nothing */
371 
372 #endif /* TCP_REASS_COUNTERS */
373 
374 #ifdef INET
375 static void tcp4_log_refused(const struct ip *, const struct tcphdr *);
376 #endif
377 #ifdef INET6
378 static void tcp6_log_refused(const struct ip6_hdr *, const struct tcphdr *);
379 #endif
380 
381 #define	TRAVERSE(x) while ((x)->m_next) (x) = (x)->m_next
382 
383 POOL_INIT(tcpipqent_pool, sizeof(struct ipqent), 0, 0, 0, "tcpipqepl", NULL);
384 
385 struct ipqent *
386 tcpipqent_alloc()
387 {
388 	struct ipqent *ipqe;
389 	int s;
390 
391 	s = splvm();
392 	ipqe = pool_get(&tcpipqent_pool, PR_NOWAIT);
393 	splx(s);
394 
395 	return ipqe;
396 }
397 
398 void
399 tcpipqent_free(struct ipqent *ipqe)
400 {
401 	int s;
402 
403 	s = splvm();
404 	pool_put(&tcpipqent_pool, ipqe);
405 	splx(s);
406 }
407 
408 int
409 tcp_reass(struct tcpcb *tp, struct tcphdr *th, struct mbuf *m, int *tlen)
410 {
411 	struct ipqent *p, *q, *nq, *tiqe = NULL;
412 	struct socket *so = NULL;
413 	int pkt_flags;
414 	tcp_seq pkt_seq;
415 	unsigned pkt_len;
416 	u_long rcvpartdupbyte = 0;
417 	u_long rcvoobyte;
418 #ifdef TCP_REASS_COUNTERS
419 	u_int count = 0;
420 #endif
421 
422 	if (tp->t_inpcb)
423 		so = tp->t_inpcb->inp_socket;
424 #ifdef INET6
425 	else if (tp->t_in6pcb)
426 		so = tp->t_in6pcb->in6p_socket;
427 #endif
428 
429 	TCP_REASS_LOCK_CHECK(tp);
430 
431 	/*
432 	 * Call with th==0 after become established to
433 	 * force pre-ESTABLISHED data up to user socket.
434 	 */
435 	if (th == 0)
436 		goto present;
437 
438 	rcvoobyte = *tlen;
439 	/*
440 	 * Copy these to local variables because the tcpiphdr
441 	 * gets munged while we are collapsing mbufs.
442 	 */
443 	pkt_seq = th->th_seq;
444 	pkt_len = *tlen;
445 	pkt_flags = th->th_flags;
446 
447 	TCP_REASS_COUNTER_INCR(&tcp_reass_);
448 
449 	if ((p = TAILQ_LAST(&tp->segq, ipqehead)) != NULL) {
450 		/*
451 		 * When we miss a packet, the vast majority of time we get
452 		 * packets that follow it in order.  So optimize for that.
453 		 */
454 		if (pkt_seq == p->ipqe_seq + p->ipqe_len) {
455 			p->ipqe_len += pkt_len;
456 			p->ipqe_flags |= pkt_flags;
457 			m_cat(p->ipre_mlast, m);
458 			TRAVERSE(p->ipre_mlast);
459 			m = NULL;
460 			tiqe = p;
461 			TAILQ_REMOVE(&tp->timeq, p, ipqe_timeq);
462 			TCP_REASS_COUNTER_INCR(&tcp_reass_appendtail);
463 			goto skip_replacement;
464 		}
465 		/*
466 		 * While we're here, if the pkt is completely beyond
467 		 * anything we have, just insert it at the tail.
468 		 */
469 		if (SEQ_GT(pkt_seq, p->ipqe_seq + p->ipqe_len)) {
470 			TCP_REASS_COUNTER_INCR(&tcp_reass_inserttail);
471 			goto insert_it;
472 		}
473 	}
474 
475 	q = TAILQ_FIRST(&tp->segq);
476 
477 	if (q != NULL) {
478 		/*
479 		 * If this segment immediately precedes the first out-of-order
480 		 * block, simply slap the segment in front of it and (mostly)
481 		 * skip the complicated logic.
482 		 */
483 		if (pkt_seq + pkt_len == q->ipqe_seq) {
484 			q->ipqe_seq = pkt_seq;
485 			q->ipqe_len += pkt_len;
486 			q->ipqe_flags |= pkt_flags;
487 			m_cat(m, q->ipqe_m);
488 			q->ipqe_m = m;
489 			q->ipre_mlast = m; /* last mbuf may have changed */
490 			TRAVERSE(q->ipre_mlast);
491 			tiqe = q;
492 			TAILQ_REMOVE(&tp->timeq, q, ipqe_timeq);
493 			TCP_REASS_COUNTER_INCR(&tcp_reass_prependfirst);
494 			goto skip_replacement;
495 		}
496 	} else {
497 		TCP_REASS_COUNTER_INCR(&tcp_reass_empty);
498 	}
499 
500 	/*
501 	 * Find a segment which begins after this one does.
502 	 */
503 	for (p = NULL; q != NULL; q = nq) {
504 		nq = TAILQ_NEXT(q, ipqe_q);
505 #ifdef TCP_REASS_COUNTERS
506 		count++;
507 #endif
508 		/*
509 		 * If the received segment is just right after this
510 		 * fragment, merge the two together and then check
511 		 * for further overlaps.
512 		 */
513 		if (q->ipqe_seq + q->ipqe_len == pkt_seq) {
514 #ifdef TCPREASS_DEBUG
515 			printf("tcp_reass[%p]: concat %u:%u(%u) to %u:%u(%u)\n",
516 			       tp, pkt_seq, pkt_seq + pkt_len, pkt_len,
517 			       q->ipqe_seq, q->ipqe_seq + q->ipqe_len, q->ipqe_len);
518 #endif
519 			pkt_len += q->ipqe_len;
520 			pkt_flags |= q->ipqe_flags;
521 			pkt_seq = q->ipqe_seq;
522 			m_cat(q->ipre_mlast, m);
523 			TRAVERSE(q->ipre_mlast);
524 			m = q->ipqe_m;
525 			TCP_REASS_COUNTER_INCR(&tcp_reass_append);
526 			goto free_ipqe;
527 		}
528 		/*
529 		 * If the received segment is completely past this
530 		 * fragment, we need to go the next fragment.
531 		 */
532 		if (SEQ_LT(q->ipqe_seq + q->ipqe_len, pkt_seq)) {
533 			p = q;
534 			continue;
535 		}
536 		/*
537 		 * If the fragment is past the received segment,
538 		 * it (or any following) can't be concatenated.
539 		 */
540 		if (SEQ_GT(q->ipqe_seq, pkt_seq + pkt_len)) {
541 			TCP_REASS_COUNTER_INCR(&tcp_reass_insert);
542 			break;
543 		}
544 
545 		/*
546 		 * We've received all the data in this segment before.
547 		 * mark it as a duplicate and return.
548 		 */
549 		if (SEQ_LEQ(q->ipqe_seq, pkt_seq) &&
550 		    SEQ_GEQ(q->ipqe_seq + q->ipqe_len, pkt_seq + pkt_len)) {
551 			tcpstat.tcps_rcvduppack++;
552 			tcpstat.tcps_rcvdupbyte += pkt_len;
553 			tcp_new_dsack(tp, pkt_seq, pkt_len);
554 			m_freem(m);
555 			if (tiqe != NULL) {
556 				tcpipqent_free(tiqe);
557 			}
558 			TCP_REASS_COUNTER_INCR(&tcp_reass_segdup);
559 			return (0);
560 		}
561 		/*
562 		 * Received segment completely overlaps this fragment
563 		 * so we drop the fragment (this keeps the temporal
564 		 * ordering of segments correct).
565 		 */
566 		if (SEQ_GEQ(q->ipqe_seq, pkt_seq) &&
567 		    SEQ_LEQ(q->ipqe_seq + q->ipqe_len, pkt_seq + pkt_len)) {
568 			rcvpartdupbyte += q->ipqe_len;
569 			m_freem(q->ipqe_m);
570 			TCP_REASS_COUNTER_INCR(&tcp_reass_fragdup);
571 			goto free_ipqe;
572 		}
573 		/*
574 		 * RX'ed segment extends past the end of the
575 		 * fragment.  Drop the overlapping bytes.  Then
576 		 * merge the fragment and segment then treat as
577 		 * a longer received packet.
578 		 */
579 		if (SEQ_LT(q->ipqe_seq, pkt_seq) &&
580 		    SEQ_GT(q->ipqe_seq + q->ipqe_len, pkt_seq))  {
581 			int overlap = q->ipqe_seq + q->ipqe_len - pkt_seq;
582 #ifdef TCPREASS_DEBUG
583 			printf("tcp_reass[%p]: trim starting %d bytes of %u:%u(%u)\n",
584 			       tp, overlap,
585 			       pkt_seq, pkt_seq + pkt_len, pkt_len);
586 #endif
587 			m_adj(m, overlap);
588 			rcvpartdupbyte += overlap;
589 			m_cat(q->ipre_mlast, m);
590 			TRAVERSE(q->ipre_mlast);
591 			m = q->ipqe_m;
592 			pkt_seq = q->ipqe_seq;
593 			pkt_len += q->ipqe_len - overlap;
594 			rcvoobyte -= overlap;
595 			TCP_REASS_COUNTER_INCR(&tcp_reass_overlaptail);
596 			goto free_ipqe;
597 		}
598 		/*
599 		 * RX'ed segment extends past the front of the
600 		 * fragment.  Drop the overlapping bytes on the
601 		 * received packet.  The packet will then be
602 		 * contatentated with this fragment a bit later.
603 		 */
604 		if (SEQ_GT(q->ipqe_seq, pkt_seq) &&
605 		    SEQ_LT(q->ipqe_seq, pkt_seq + pkt_len))  {
606 			int overlap = pkt_seq + pkt_len - q->ipqe_seq;
607 #ifdef TCPREASS_DEBUG
608 			printf("tcp_reass[%p]: trim trailing %d bytes of %u:%u(%u)\n",
609 			       tp, overlap,
610 			       pkt_seq, pkt_seq + pkt_len, pkt_len);
611 #endif
612 			m_adj(m, -overlap);
613 			pkt_len -= overlap;
614 			rcvpartdupbyte += overlap;
615 			TCP_REASS_COUNTER_INCR(&tcp_reass_overlapfront);
616 			rcvoobyte -= overlap;
617 		}
618 		/*
619 		 * If the received segment immediates precedes this
620 		 * fragment then tack the fragment onto this segment
621 		 * and reinsert the data.
622 		 */
623 		if (q->ipqe_seq == pkt_seq + pkt_len) {
624 #ifdef TCPREASS_DEBUG
625 			printf("tcp_reass[%p]: append %u:%u(%u) to %u:%u(%u)\n",
626 			       tp, q->ipqe_seq, q->ipqe_seq + q->ipqe_len, q->ipqe_len,
627 			       pkt_seq, pkt_seq + pkt_len, pkt_len);
628 #endif
629 			pkt_len += q->ipqe_len;
630 			pkt_flags |= q->ipqe_flags;
631 			m_cat(m, q->ipqe_m);
632 			TAILQ_REMOVE(&tp->segq, q, ipqe_q);
633 			TAILQ_REMOVE(&tp->timeq, q, ipqe_timeq);
634 			tp->t_segqlen--;
635 			KASSERT(tp->t_segqlen >= 0);
636 			KASSERT(tp->t_segqlen != 0 ||
637 			    (TAILQ_EMPTY(&tp->segq) &&
638 			    TAILQ_EMPTY(&tp->timeq)));
639 			if (tiqe == NULL) {
640 				tiqe = q;
641 			} else {
642 				tcpipqent_free(q);
643 			}
644 			TCP_REASS_COUNTER_INCR(&tcp_reass_prepend);
645 			break;
646 		}
647 		/*
648 		 * If the fragment is before the segment, remember it.
649 		 * When this loop is terminated, p will contain the
650 		 * pointer to fragment that is right before the received
651 		 * segment.
652 		 */
653 		if (SEQ_LEQ(q->ipqe_seq, pkt_seq))
654 			p = q;
655 
656 		continue;
657 
658 		/*
659 		 * This is a common operation.  It also will allow
660 		 * to save doing a malloc/free in most instances.
661 		 */
662 	  free_ipqe:
663 		TAILQ_REMOVE(&tp->segq, q, ipqe_q);
664 		TAILQ_REMOVE(&tp->timeq, q, ipqe_timeq);
665 		tp->t_segqlen--;
666 		KASSERT(tp->t_segqlen >= 0);
667 		KASSERT(tp->t_segqlen != 0 ||
668 		    (TAILQ_EMPTY(&tp->segq) && TAILQ_EMPTY(&tp->timeq)));
669 		if (tiqe == NULL) {
670 			tiqe = q;
671 		} else {
672 			tcpipqent_free(q);
673 		}
674 	}
675 
676 #ifdef TCP_REASS_COUNTERS
677 	if (count > 7)
678 		TCP_REASS_COUNTER_INCR(&tcp_reass_iteration[0]);
679 	else if (count > 0)
680 		TCP_REASS_COUNTER_INCR(&tcp_reass_iteration[count]);
681 #endif
682 
683     insert_it:
684 
685 	/*
686 	 * Allocate a new queue entry since the received segment did not
687 	 * collapse onto any other out-of-order block; thus we are allocating
688 	 * a new block.  If it had collapsed, tiqe would not be NULL and
689 	 * we would be reusing it.
690 	 * XXX If we can't, just drop the packet.  XXX
691 	 */
692 	if (tiqe == NULL) {
693 		tiqe = tcpipqent_alloc();
694 		if (tiqe == NULL) {
695 			tcpstat.tcps_rcvmemdrop++;
696 			m_freem(m);
697 			return (0);
698 		}
699 	}
700 
701 	/*
702 	 * Update the counters.
703 	 */
704 	tcpstat.tcps_rcvoopack++;
705 	tcpstat.tcps_rcvoobyte += rcvoobyte;
706 	if (rcvpartdupbyte) {
707 	    tcpstat.tcps_rcvpartduppack++;
708 	    tcpstat.tcps_rcvpartdupbyte += rcvpartdupbyte;
709 	}
710 
711 	/*
712 	 * Insert the new fragment queue entry into both queues.
713 	 */
714 	tiqe->ipqe_m = m;
715 	tiqe->ipre_mlast = m;
716 	tiqe->ipqe_seq = pkt_seq;
717 	tiqe->ipqe_len = pkt_len;
718 	tiqe->ipqe_flags = pkt_flags;
719 	if (p == NULL) {
720 		TAILQ_INSERT_HEAD(&tp->segq, tiqe, ipqe_q);
721 #ifdef TCPREASS_DEBUG
722 		if (tiqe->ipqe_seq != tp->rcv_nxt)
723 			printf("tcp_reass[%p]: insert %u:%u(%u) at front\n",
724 			       tp, pkt_seq, pkt_seq + pkt_len, pkt_len);
725 #endif
726 	} else {
727 		TAILQ_INSERT_AFTER(&tp->segq, p, tiqe, ipqe_q);
728 #ifdef TCPREASS_DEBUG
729 		printf("tcp_reass[%p]: insert %u:%u(%u) after %u:%u(%u)\n",
730 		       tp, pkt_seq, pkt_seq + pkt_len, pkt_len,
731 		       p->ipqe_seq, p->ipqe_seq + p->ipqe_len, p->ipqe_len);
732 #endif
733 	}
734 	tp->t_segqlen++;
735 
736 skip_replacement:
737 
738 	TAILQ_INSERT_HEAD(&tp->timeq, tiqe, ipqe_timeq);
739 
740 present:
741 	/*
742 	 * Present data to user, advancing rcv_nxt through
743 	 * completed sequence space.
744 	 */
745 	if (TCPS_HAVEESTABLISHED(tp->t_state) == 0)
746 		return (0);
747 	q = TAILQ_FIRST(&tp->segq);
748 	if (q == NULL || q->ipqe_seq != tp->rcv_nxt)
749 		return (0);
750 	if (tp->t_state == TCPS_SYN_RECEIVED && q->ipqe_len)
751 		return (0);
752 
753 	tp->rcv_nxt += q->ipqe_len;
754 	pkt_flags = q->ipqe_flags & TH_FIN;
755 	ND6_HINT(tp);
756 
757 	TAILQ_REMOVE(&tp->segq, q, ipqe_q);
758 	TAILQ_REMOVE(&tp->timeq, q, ipqe_timeq);
759 	tp->t_segqlen--;
760 	KASSERT(tp->t_segqlen >= 0);
761 	KASSERT(tp->t_segqlen != 0 ||
762 	    (TAILQ_EMPTY(&tp->segq) && TAILQ_EMPTY(&tp->timeq)));
763 	if (so->so_state & SS_CANTRCVMORE)
764 		m_freem(q->ipqe_m);
765 	else
766 		sbappendstream(&so->so_rcv, q->ipqe_m);
767 	tcpipqent_free(q);
768 	sorwakeup(so);
769 	return (pkt_flags);
770 }
771 
772 #ifdef INET6
773 int
774 tcp6_input(struct mbuf **mp, int *offp, int proto)
775 {
776 	struct mbuf *m = *mp;
777 
778 	/*
779 	 * draft-itojun-ipv6-tcp-to-anycast
780 	 * better place to put this in?
781 	 */
782 	if (m->m_flags & M_ANYCAST6) {
783 		struct ip6_hdr *ip6;
784 		if (m->m_len < sizeof(struct ip6_hdr)) {
785 			if ((m = m_pullup(m, sizeof(struct ip6_hdr))) == NULL) {
786 				tcpstat.tcps_rcvshort++;
787 				return IPPROTO_DONE;
788 			}
789 		}
790 		ip6 = mtod(m, struct ip6_hdr *);
791 		icmp6_error(m, ICMP6_DST_UNREACH, ICMP6_DST_UNREACH_ADDR,
792 		    (caddr_t)&ip6->ip6_dst - (caddr_t)ip6);
793 		return IPPROTO_DONE;
794 	}
795 
796 	tcp_input(m, *offp, proto);
797 	return IPPROTO_DONE;
798 }
799 #endif
800 
801 #ifdef INET
802 static void
803 tcp4_log_refused(const struct ip *ip, const struct tcphdr *th)
804 {
805 	char src[4*sizeof "123"];
806 	char dst[4*sizeof "123"];
807 
808 	if (ip) {
809 		strlcpy(src, inet_ntoa(ip->ip_src), sizeof(src));
810 		strlcpy(dst, inet_ntoa(ip->ip_dst), sizeof(dst));
811 	}
812 	else {
813 		strlcpy(src, "(unknown)", sizeof(src));
814 		strlcpy(dst, "(unknown)", sizeof(dst));
815 	}
816 	log(LOG_INFO,
817 	    "Connection attempt to TCP %s:%d from %s:%d\n",
818 	    dst, ntohs(th->th_dport),
819 	    src, ntohs(th->th_sport));
820 }
821 #endif
822 
823 #ifdef INET6
824 static void
825 tcp6_log_refused(const struct ip6_hdr *ip6, const struct tcphdr *th)
826 {
827 	char src[INET6_ADDRSTRLEN];
828 	char dst[INET6_ADDRSTRLEN];
829 
830 	if (ip6) {
831 		strlcpy(src, ip6_sprintf(&ip6->ip6_src), sizeof(src));
832 		strlcpy(dst, ip6_sprintf(&ip6->ip6_dst), sizeof(dst));
833 	}
834 	else {
835 		strlcpy(src, "(unknown v6)", sizeof(src));
836 		strlcpy(dst, "(unknown v6)", sizeof(dst));
837 	}
838 	log(LOG_INFO,
839 	    "Connection attempt to TCP [%s]:%d from [%s]:%d\n",
840 	    dst, ntohs(th->th_dport),
841 	    src, ntohs(th->th_sport));
842 }
843 #endif
844 
845 /*
846  * Checksum extended TCP header and data.
847  */
848 int
849 tcp_input_checksum(int af, struct mbuf *m, const struct tcphdr *th, int toff,
850     int off, int tlen)
851 {
852 
853 	/*
854 	 * XXX it's better to record and check if this mbuf is
855 	 * already checked.
856 	 */
857 
858 	switch (af) {
859 #ifdef INET
860 	case AF_INET:
861 		switch (m->m_pkthdr.csum_flags &
862 			((m->m_pkthdr.rcvif->if_csum_flags_rx & M_CSUM_TCPv4) |
863 			 M_CSUM_TCP_UDP_BAD | M_CSUM_DATA)) {
864 		case M_CSUM_TCPv4|M_CSUM_TCP_UDP_BAD:
865 			TCP_CSUM_COUNTER_INCR(&tcp_hwcsum_bad);
866 			goto badcsum;
867 
868 		case M_CSUM_TCPv4|M_CSUM_DATA: {
869 			u_int32_t hw_csum = m->m_pkthdr.csum_data;
870 
871 			TCP_CSUM_COUNTER_INCR(&tcp_hwcsum_data);
872 			if (m->m_pkthdr.csum_flags & M_CSUM_NO_PSEUDOHDR) {
873 				const struct ip *ip =
874 				    mtod(m, const struct ip *);
875 
876 				hw_csum = in_cksum_phdr(ip->ip_src.s_addr,
877 				    ip->ip_dst.s_addr,
878 				    htons(hw_csum + tlen + off + IPPROTO_TCP));
879 			}
880 			if ((hw_csum ^ 0xffff) != 0)
881 				goto badcsum;
882 			break;
883 		}
884 
885 		case M_CSUM_TCPv4:
886 			/* Checksum was okay. */
887 			TCP_CSUM_COUNTER_INCR(&tcp_hwcsum_ok);
888 			break;
889 
890 		default:
891 			/*
892 			 * Must compute it ourselves.  Maybe skip checksum
893 			 * on loopback interfaces.
894 			 */
895 			if (__predict_true(!(m->m_pkthdr.rcvif->if_flags &
896 					     IFF_LOOPBACK) ||
897 					   tcp_do_loopback_cksum)) {
898 				TCP_CSUM_COUNTER_INCR(&tcp_swcsum);
899 				if (in4_cksum(m, IPPROTO_TCP, toff,
900 					      tlen + off) != 0)
901 					goto badcsum;
902 			}
903 			break;
904 		}
905 		break;
906 #endif /* INET4 */
907 
908 #ifdef INET6
909 	case AF_INET6:
910 		switch (m->m_pkthdr.csum_flags &
911 			((m->m_pkthdr.rcvif->if_csum_flags_rx & M_CSUM_TCPv6) |
912 			 M_CSUM_TCP_UDP_BAD | M_CSUM_DATA)) {
913 		case M_CSUM_TCPv6|M_CSUM_TCP_UDP_BAD:
914 			TCP_CSUM_COUNTER_INCR(&tcp6_hwcsum_bad);
915 			goto badcsum;
916 
917 #if 0 /* notyet */
918 		case M_CSUM_TCPv6|M_CSUM_DATA:
919 #endif
920 
921 		case M_CSUM_TCPv6:
922 			/* Checksum was okay. */
923 			TCP_CSUM_COUNTER_INCR(&tcp6_hwcsum_ok);
924 			break;
925 
926 		default:
927 			/*
928 			 * Must compute it ourselves.  Maybe skip checksum
929 			 * on loopback interfaces.
930 			 */
931 			if (__predict_true((m->m_flags & M_LOOP) == 0 ||
932 			    tcp_do_loopback_cksum)) {
933 				TCP_CSUM_COUNTER_INCR(&tcp6_swcsum);
934 				if (in6_cksum(m, IPPROTO_TCP, toff,
935 				    tlen + off) != 0)
936 					goto badcsum;
937 			}
938 		}
939 		break;
940 #endif /* INET6 */
941 	}
942 
943 	return 0;
944 
945 badcsum:
946 	tcpstat.tcps_rcvbadsum++;
947 	return -1;
948 }
949 
950 /*
951  * TCP input routine, follows pages 65-76 of RFC 793 very closely.
952  */
953 void
954 tcp_input(struct mbuf *m, ...)
955 {
956 	struct tcphdr *th;
957 	struct ip *ip;
958 	struct inpcb *inp;
959 #ifdef INET6
960 	struct ip6_hdr *ip6;
961 	struct in6pcb *in6p;
962 #endif
963 	u_int8_t *optp = NULL;
964 	int optlen = 0;
965 	int len, tlen, toff, hdroptlen = 0;
966 	struct tcpcb *tp = 0;
967 	int tiflags;
968 	struct socket *so = NULL;
969 	int todrop, dupseg, acked, ourfinisacked, needoutput = 0;
970 #ifdef TCP_DEBUG
971 	short ostate = 0;
972 #endif
973 	u_long tiwin;
974 	struct tcp_opt_info opti;
975 	int off, iphlen;
976 	va_list ap;
977 	int af;		/* af on the wire */
978 	struct mbuf *tcp_saveti = NULL;
979 	uint32_t ts_rtt;
980 
981 	MCLAIM(m, &tcp_rx_mowner);
982 	va_start(ap, m);
983 	toff = va_arg(ap, int);
984 	(void)va_arg(ap, int);		/* ignore value, advance ap */
985 	va_end(ap);
986 
987 	tcpstat.tcps_rcvtotal++;
988 
989 	bzero(&opti, sizeof(opti));
990 	opti.ts_present = 0;
991 	opti.maxseg = 0;
992 
993 	/*
994 	 * RFC1122 4.2.3.10, p. 104: discard bcast/mcast SYN.
995 	 *
996 	 * TCP is, by definition, unicast, so we reject all
997 	 * multicast outright.
998 	 *
999 	 * Note, there are additional src/dst address checks in
1000 	 * the AF-specific code below.
1001 	 */
1002 	if (m->m_flags & (M_BCAST|M_MCAST)) {
1003 		/* XXX stat */
1004 		goto drop;
1005 	}
1006 #ifdef INET6
1007 	if (m->m_flags & M_ANYCAST6) {
1008 		/* XXX stat */
1009 		goto drop;
1010 	}
1011 #endif
1012 
1013 	/*
1014 	 * Get IP and TCP header.
1015 	 * Note: IP leaves IP header in first mbuf.
1016 	 */
1017 	ip = mtod(m, struct ip *);
1018 #ifdef INET6
1019 	ip6 = NULL;
1020 #endif
1021 	switch (ip->ip_v) {
1022 #ifdef INET
1023 	case 4:
1024 		af = AF_INET;
1025 		iphlen = sizeof(struct ip);
1026 		ip = mtod(m, struct ip *);
1027 		IP6_EXTHDR_GET(th, struct tcphdr *, m, toff,
1028 			sizeof(struct tcphdr));
1029 		if (th == NULL) {
1030 			tcpstat.tcps_rcvshort++;
1031 			return;
1032 		}
1033 		/* We do the checksum after PCB lookup... */
1034 		len = ntohs(ip->ip_len);
1035 		tlen = len - toff;
1036 		break;
1037 #endif
1038 #ifdef INET6
1039 	case 6:
1040 		ip = NULL;
1041 		iphlen = sizeof(struct ip6_hdr);
1042 		af = AF_INET6;
1043 		ip6 = mtod(m, struct ip6_hdr *);
1044 		IP6_EXTHDR_GET(th, struct tcphdr *, m, toff,
1045 			sizeof(struct tcphdr));
1046 		if (th == NULL) {
1047 			tcpstat.tcps_rcvshort++;
1048 			return;
1049 		}
1050 
1051 		/* Be proactive about malicious use of IPv4 mapped address */
1052 		if (IN6_IS_ADDR_V4MAPPED(&ip6->ip6_src) ||
1053 		    IN6_IS_ADDR_V4MAPPED(&ip6->ip6_dst)) {
1054 			/* XXX stat */
1055 			goto drop;
1056 		}
1057 
1058 		/*
1059 		 * Be proactive about unspecified IPv6 address in source.
1060 		 * As we use all-zero to indicate unbounded/unconnected pcb,
1061 		 * unspecified IPv6 address can be used to confuse us.
1062 		 *
1063 		 * Note that packets with unspecified IPv6 destination is
1064 		 * already dropped in ip6_input.
1065 		 */
1066 		if (IN6_IS_ADDR_UNSPECIFIED(&ip6->ip6_src)) {
1067 			/* XXX stat */
1068 			goto drop;
1069 		}
1070 
1071 		/*
1072 		 * Make sure destination address is not multicast.
1073 		 * Source address checked in ip6_input().
1074 		 */
1075 		if (IN6_IS_ADDR_MULTICAST(&ip6->ip6_dst)) {
1076 			/* XXX stat */
1077 			goto drop;
1078 		}
1079 
1080 		/* We do the checksum after PCB lookup... */
1081 		len = m->m_pkthdr.len;
1082 		tlen = len - toff;
1083 		break;
1084 #endif
1085 	default:
1086 		m_freem(m);
1087 		return;
1088 	}
1089 
1090 	KASSERT(TCP_HDR_ALIGNED_P(th));
1091 
1092 	/*
1093 	 * Check that TCP offset makes sense,
1094 	 * pull out TCP options and adjust length.		XXX
1095 	 */
1096 	off = th->th_off << 2;
1097 	if (off < sizeof (struct tcphdr) || off > tlen) {
1098 		tcpstat.tcps_rcvbadoff++;
1099 		goto drop;
1100 	}
1101 	tlen -= off;
1102 
1103 	/*
1104 	 * tcp_input() has been modified to use tlen to mean the TCP data
1105 	 * length throughout the function.  Other functions can use
1106 	 * m->m_pkthdr.len as the basis for calculating the TCP data length.
1107 	 * rja
1108 	 */
1109 
1110 	if (off > sizeof (struct tcphdr)) {
1111 		IP6_EXTHDR_GET(th, struct tcphdr *, m, toff, off);
1112 		if (th == NULL) {
1113 			tcpstat.tcps_rcvshort++;
1114 			return;
1115 		}
1116 		/*
1117 		 * NOTE: ip/ip6 will not be affected by m_pulldown()
1118 		 * (as they're before toff) and we don't need to update those.
1119 		 */
1120 		KASSERT(TCP_HDR_ALIGNED_P(th));
1121 		optlen = off - sizeof (struct tcphdr);
1122 		optp = ((u_int8_t *)th) + sizeof(struct tcphdr);
1123 		/*
1124 		 * Do quick retrieval of timestamp options ("options
1125 		 * prediction?").  If timestamp is the only option and it's
1126 		 * formatted as recommended in RFC 1323 appendix A, we
1127 		 * quickly get the values now and not bother calling
1128 		 * tcp_dooptions(), etc.
1129 		 */
1130 		if ((optlen == TCPOLEN_TSTAMP_APPA ||
1131 		     (optlen > TCPOLEN_TSTAMP_APPA &&
1132 			optp[TCPOLEN_TSTAMP_APPA] == TCPOPT_EOL)) &&
1133 		     *(u_int32_t *)optp == htonl(TCPOPT_TSTAMP_HDR) &&
1134 		     (th->th_flags & TH_SYN) == 0) {
1135 			opti.ts_present = 1;
1136 			opti.ts_val = ntohl(*(u_int32_t *)(optp + 4));
1137 			opti.ts_ecr = ntohl(*(u_int32_t *)(optp + 8));
1138 			optp = NULL;	/* we've parsed the options */
1139 		}
1140 	}
1141 	tiflags = th->th_flags;
1142 
1143 	/*
1144 	 * Locate pcb for segment.
1145 	 */
1146 findpcb:
1147 	inp = NULL;
1148 #ifdef INET6
1149 	in6p = NULL;
1150 #endif
1151 	switch (af) {
1152 #ifdef INET
1153 	case AF_INET:
1154 		inp = in_pcblookup_connect(&tcbtable, ip->ip_src, th->th_sport,
1155 		    ip->ip_dst, th->th_dport);
1156 		if (inp == 0) {
1157 			++tcpstat.tcps_pcbhashmiss;
1158 			inp = in_pcblookup_bind(&tcbtable, ip->ip_dst, th->th_dport);
1159 		}
1160 #ifdef INET6
1161 		if (inp == 0) {
1162 			struct in6_addr s, d;
1163 
1164 			/* mapped addr case */
1165 			bzero(&s, sizeof(s));
1166 			s.s6_addr16[5] = htons(0xffff);
1167 			bcopy(&ip->ip_src, &s.s6_addr32[3], sizeof(ip->ip_src));
1168 			bzero(&d, sizeof(d));
1169 			d.s6_addr16[5] = htons(0xffff);
1170 			bcopy(&ip->ip_dst, &d.s6_addr32[3], sizeof(ip->ip_dst));
1171 			in6p = in6_pcblookup_connect(&tcbtable, &s,
1172 			    th->th_sport, &d, th->th_dport, 0);
1173 			if (in6p == 0) {
1174 				++tcpstat.tcps_pcbhashmiss;
1175 				in6p = in6_pcblookup_bind(&tcbtable, &d,
1176 				    th->th_dport, 0);
1177 			}
1178 		}
1179 #endif
1180 #ifndef INET6
1181 		if (inp == 0)
1182 #else
1183 		if (inp == 0 && in6p == 0)
1184 #endif
1185 		{
1186 			++tcpstat.tcps_noport;
1187 			if (tcp_log_refused &&
1188 			    (tiflags & (TH_RST|TH_ACK|TH_SYN)) == TH_SYN) {
1189 				tcp4_log_refused(ip, th);
1190 			}
1191 			TCP_FIELDS_TO_HOST(th);
1192 			goto dropwithreset_ratelim;
1193 		}
1194 #if defined(IPSEC) || defined(FAST_IPSEC)
1195 		if (inp && (inp->inp_socket->so_options & SO_ACCEPTCONN) == 0 &&
1196 		    ipsec4_in_reject(m, inp)) {
1197 			ipsecstat.in_polvio++;
1198 			goto drop;
1199 		}
1200 #ifdef INET6
1201 		else if (in6p &&
1202 		    (in6p->in6p_socket->so_options & SO_ACCEPTCONN) == 0 &&
1203 		    ipsec4_in_reject_so(m, in6p->in6p_socket)) {
1204 			ipsecstat.in_polvio++;
1205 			goto drop;
1206 		}
1207 #endif
1208 #endif /*IPSEC*/
1209 		break;
1210 #endif /*INET*/
1211 #ifdef INET6
1212 	case AF_INET6:
1213 	    {
1214 		int faith;
1215 
1216 #if defined(NFAITH) && NFAITH > 0
1217 		faith = faithprefix(&ip6->ip6_dst);
1218 #else
1219 		faith = 0;
1220 #endif
1221 		in6p = in6_pcblookup_connect(&tcbtable, &ip6->ip6_src,
1222 		    th->th_sport, &ip6->ip6_dst, th->th_dport, faith);
1223 		if (in6p == NULL) {
1224 			++tcpstat.tcps_pcbhashmiss;
1225 			in6p = in6_pcblookup_bind(&tcbtable, &ip6->ip6_dst,
1226 				th->th_dport, faith);
1227 		}
1228 		if (in6p == NULL) {
1229 			++tcpstat.tcps_noport;
1230 			if (tcp_log_refused &&
1231 			    (tiflags & (TH_RST|TH_ACK|TH_SYN)) == TH_SYN) {
1232 				tcp6_log_refused(ip6, th);
1233 			}
1234 			TCP_FIELDS_TO_HOST(th);
1235 			goto dropwithreset_ratelim;
1236 		}
1237 #if defined(IPSEC) || defined(FAST_IPSEC)
1238 		if ((in6p->in6p_socket->so_options & SO_ACCEPTCONN) == 0 &&
1239 		    ipsec6_in_reject(m, in6p)) {
1240 			ipsec6stat.in_polvio++;
1241 			goto drop;
1242 		}
1243 #endif /*IPSEC*/
1244 		break;
1245 	    }
1246 #endif
1247 	}
1248 
1249 	/*
1250 	 * If the state is CLOSED (i.e., TCB does not exist) then
1251 	 * all data in the incoming segment is discarded.
1252 	 * If the TCB exists but is in CLOSED state, it is embryonic,
1253 	 * but should either do a listen or a connect soon.
1254 	 */
1255 	tp = NULL;
1256 	so = NULL;
1257 	if (inp) {
1258 		tp = intotcpcb(inp);
1259 		so = inp->inp_socket;
1260 	}
1261 #ifdef INET6
1262 	else if (in6p) {
1263 		tp = in6totcpcb(in6p);
1264 		so = in6p->in6p_socket;
1265 	}
1266 #endif
1267 	if (tp == 0) {
1268 		TCP_FIELDS_TO_HOST(th);
1269 		goto dropwithreset_ratelim;
1270 	}
1271 	if (tp->t_state == TCPS_CLOSED)
1272 		goto drop;
1273 
1274 	/*
1275 	 * Checksum extended TCP header and data.
1276 	 */
1277 	if (tcp_input_checksum(af, m, th, toff, off, tlen))
1278 		goto badcsum;
1279 
1280 	TCP_FIELDS_TO_HOST(th);
1281 
1282 	/* Unscale the window into a 32-bit value. */
1283 	if ((tiflags & TH_SYN) == 0)
1284 		tiwin = th->th_win << tp->snd_scale;
1285 	else
1286 		tiwin = th->th_win;
1287 
1288 #ifdef INET6
1289 	/* save packet options if user wanted */
1290 	if (in6p && (in6p->in6p_flags & IN6P_CONTROLOPTS)) {
1291 		if (in6p->in6p_options) {
1292 			m_freem(in6p->in6p_options);
1293 			in6p->in6p_options = 0;
1294 		}
1295 		KASSERT(ip6 != NULL);
1296 		ip6_savecontrol(in6p, &in6p->in6p_options, ip6, m);
1297 	}
1298 #endif
1299 
1300 	if (so->so_options & (SO_DEBUG|SO_ACCEPTCONN)) {
1301 		union syn_cache_sa src;
1302 		union syn_cache_sa dst;
1303 
1304 		bzero(&src, sizeof(src));
1305 		bzero(&dst, sizeof(dst));
1306 		switch (af) {
1307 #ifdef INET
1308 		case AF_INET:
1309 			src.sin.sin_len = sizeof(struct sockaddr_in);
1310 			src.sin.sin_family = AF_INET;
1311 			src.sin.sin_addr = ip->ip_src;
1312 			src.sin.sin_port = th->th_sport;
1313 
1314 			dst.sin.sin_len = sizeof(struct sockaddr_in);
1315 			dst.sin.sin_family = AF_INET;
1316 			dst.sin.sin_addr = ip->ip_dst;
1317 			dst.sin.sin_port = th->th_dport;
1318 			break;
1319 #endif
1320 #ifdef INET6
1321 		case AF_INET6:
1322 			src.sin6.sin6_len = sizeof(struct sockaddr_in6);
1323 			src.sin6.sin6_family = AF_INET6;
1324 			src.sin6.sin6_addr = ip6->ip6_src;
1325 			src.sin6.sin6_port = th->th_sport;
1326 
1327 			dst.sin6.sin6_len = sizeof(struct sockaddr_in6);
1328 			dst.sin6.sin6_family = AF_INET6;
1329 			dst.sin6.sin6_addr = ip6->ip6_dst;
1330 			dst.sin6.sin6_port = th->th_dport;
1331 			break;
1332 #endif /* INET6 */
1333 		default:
1334 			goto badsyn;	/*sanity*/
1335 		}
1336 
1337 		if (so->so_options & SO_DEBUG) {
1338 #ifdef TCP_DEBUG
1339 			ostate = tp->t_state;
1340 #endif
1341 
1342 			tcp_saveti = NULL;
1343 			if (iphlen + sizeof(struct tcphdr) > MHLEN)
1344 				goto nosave;
1345 
1346 			if (m->m_len > iphlen && (m->m_flags & M_EXT) == 0) {
1347 				tcp_saveti = m_copym(m, 0, iphlen, M_DONTWAIT);
1348 				if (!tcp_saveti)
1349 					goto nosave;
1350 			} else {
1351 				MGETHDR(tcp_saveti, M_DONTWAIT, MT_HEADER);
1352 				if (!tcp_saveti)
1353 					goto nosave;
1354 				MCLAIM(m, &tcp_mowner);
1355 				tcp_saveti->m_len = iphlen;
1356 				m_copydata(m, 0, iphlen,
1357 				    mtod(tcp_saveti, caddr_t));
1358 			}
1359 
1360 			if (M_TRAILINGSPACE(tcp_saveti) < sizeof(struct tcphdr)) {
1361 				m_freem(tcp_saveti);
1362 				tcp_saveti = NULL;
1363 			} else {
1364 				tcp_saveti->m_len += sizeof(struct tcphdr);
1365 				bcopy(th, mtod(tcp_saveti, caddr_t) + iphlen,
1366 				    sizeof(struct tcphdr));
1367 			}
1368 	nosave:;
1369 		}
1370 		if (so->so_options & SO_ACCEPTCONN) {
1371 			if ((tiflags & (TH_RST|TH_ACK|TH_SYN)) != TH_SYN) {
1372 				if (tiflags & TH_RST) {
1373 					syn_cache_reset(&src.sa, &dst.sa, th);
1374 				} else if ((tiflags & (TH_ACK|TH_SYN)) ==
1375 				    (TH_ACK|TH_SYN)) {
1376 					/*
1377 					 * Received a SYN,ACK.  This should
1378 					 * never happen while we are in
1379 					 * LISTEN.  Send an RST.
1380 					 */
1381 					goto badsyn;
1382 				} else if (tiflags & TH_ACK) {
1383 					so = syn_cache_get(&src.sa, &dst.sa,
1384 						th, toff, tlen, so, m);
1385 					if (so == NULL) {
1386 						/*
1387 						 * We don't have a SYN for
1388 						 * this ACK; send an RST.
1389 						 */
1390 						goto badsyn;
1391 					} else if (so ==
1392 					    (struct socket *)(-1)) {
1393 						/*
1394 						 * We were unable to create
1395 						 * the connection.  If the
1396 						 * 3-way handshake was
1397 						 * completed, and RST has
1398 						 * been sent to the peer.
1399 						 * Since the mbuf might be
1400 						 * in use for the reply,
1401 						 * do not free it.
1402 						 */
1403 						m = NULL;
1404 					} else {
1405 						/*
1406 						 * We have created a
1407 						 * full-blown connection.
1408 						 */
1409 						tp = NULL;
1410 						inp = NULL;
1411 #ifdef INET6
1412 						in6p = NULL;
1413 #endif
1414 						switch (so->so_proto->pr_domain->dom_family) {
1415 #ifdef INET
1416 						case AF_INET:
1417 							inp = sotoinpcb(so);
1418 							tp = intotcpcb(inp);
1419 							break;
1420 #endif
1421 #ifdef INET6
1422 						case AF_INET6:
1423 							in6p = sotoin6pcb(so);
1424 							tp = in6totcpcb(in6p);
1425 							break;
1426 #endif
1427 						}
1428 						if (tp == NULL)
1429 							goto badsyn;	/*XXX*/
1430 						tiwin <<= tp->snd_scale;
1431 						goto after_listen;
1432 					}
1433 				} else {
1434 					/*
1435 					 * None of RST, SYN or ACK was set.
1436 					 * This is an invalid packet for a
1437 					 * TCB in LISTEN state.  Send a RST.
1438 					 */
1439 					goto badsyn;
1440 				}
1441 			} else {
1442 				/*
1443 				 * Received a SYN.
1444 				 */
1445 
1446 #ifdef INET6
1447 				/*
1448 				 * If deprecated address is forbidden, we do
1449 				 * not accept SYN to deprecated interface
1450 				 * address to prevent any new inbound
1451 				 * connection from getting established.
1452 				 * When we do not accept SYN, we send a TCP
1453 				 * RST, with deprecated source address (instead
1454 				 * of dropping it).  We compromise it as it is
1455 				 * much better for peer to send a RST, and
1456 				 * RST will be the final packet for the
1457 				 * exchange.
1458 				 *
1459 				 * If we do not forbid deprecated addresses, we
1460 				 * accept the SYN packet.  RFC2462 does not
1461 				 * suggest dropping SYN in this case.
1462 				 * If we decipher RFC2462 5.5.4, it says like
1463 				 * this:
1464 				 * 1. use of deprecated addr with existing
1465 				 *    communication is okay - "SHOULD continue
1466 				 *    to be used"
1467 				 * 2. use of it with new communication:
1468 				 *   (2a) "SHOULD NOT be used if alternate
1469 				 *        address with sufficient scope is
1470 				 *        available"
1471 				 *   (2b) nothing mentioned otherwise.
1472 				 * Here we fall into (2b) case as we have no
1473 				 * choice in our source address selection - we
1474 				 * must obey the peer.
1475 				 *
1476 				 * The wording in RFC2462 is confusing, and
1477 				 * there are multiple description text for
1478 				 * deprecated address handling - worse, they
1479 				 * are not exactly the same.  I believe 5.5.4
1480 				 * is the best one, so we follow 5.5.4.
1481 				 */
1482 				if (af == AF_INET6 && !ip6_use_deprecated) {
1483 					struct in6_ifaddr *ia6;
1484 					if ((ia6 = in6ifa_ifpwithaddr(m->m_pkthdr.rcvif,
1485 					    &ip6->ip6_dst)) &&
1486 					    (ia6->ia6_flags & IN6_IFF_DEPRECATED)) {
1487 						tp = NULL;
1488 						goto dropwithreset;
1489 					}
1490 				}
1491 #endif
1492 
1493 #ifdef IPSEC
1494 				switch (af) {
1495 #ifdef INET
1496 				case AF_INET:
1497 					if (ipsec4_in_reject_so(m, so)) {
1498 						ipsecstat.in_polvio++;
1499 						tp = NULL;
1500 						goto dropwithreset;
1501 					}
1502 					break;
1503 #endif
1504 #ifdef INET6
1505 				case AF_INET6:
1506 					if (ipsec6_in_reject_so(m, so)) {
1507 						ipsec6stat.in_polvio++;
1508 						tp = NULL;
1509 						goto dropwithreset;
1510 					}
1511 					break;
1512 #endif
1513 				}
1514 #endif
1515 
1516 				/*
1517 				 * LISTEN socket received a SYN
1518 				 * from itself?  This can't possibly
1519 				 * be valid; drop the packet.
1520 				 */
1521 				if (th->th_sport == th->th_dport) {
1522 					int i;
1523 
1524 					switch (af) {
1525 #ifdef INET
1526 					case AF_INET:
1527 						i = in_hosteq(ip->ip_src, ip->ip_dst);
1528 						break;
1529 #endif
1530 #ifdef INET6
1531 					case AF_INET6:
1532 						i = IN6_ARE_ADDR_EQUAL(&ip6->ip6_src, &ip6->ip6_dst);
1533 						break;
1534 #endif
1535 					default:
1536 						i = 1;
1537 					}
1538 					if (i) {
1539 						tcpstat.tcps_badsyn++;
1540 						goto drop;
1541 					}
1542 				}
1543 
1544 				/*
1545 				 * SYN looks ok; create compressed TCP
1546 				 * state for it.
1547 				 */
1548 				if (so->so_qlen <= so->so_qlimit &&
1549 				    syn_cache_add(&src.sa, &dst.sa, th, tlen,
1550 						so, m, optp, optlen, &opti))
1551 					m = NULL;
1552 			}
1553 			goto drop;
1554 		}
1555 	}
1556 
1557 after_listen:
1558 #ifdef DIAGNOSTIC
1559 	/*
1560 	 * Should not happen now that all embryonic connections
1561 	 * are handled with compressed state.
1562 	 */
1563 	if (tp->t_state == TCPS_LISTEN)
1564 		panic("tcp_input: TCPS_LISTEN");
1565 #endif
1566 
1567 	/*
1568 	 * Segment received on connection.
1569 	 * Reset idle time and keep-alive timer.
1570 	 */
1571 	tp->t_rcvtime = tcp_now;
1572 	if (TCPS_HAVEESTABLISHED(tp->t_state))
1573 		TCP_TIMER_ARM(tp, TCPT_KEEP, tcp_keepidle);
1574 
1575 	/*
1576 	 * Process options.
1577 	 */
1578 #ifdef TCP_SIGNATURE
1579 	if (optp || (tp->t_flags & TF_SIGNATURE))
1580 #else
1581 	if (optp)
1582 #endif
1583 		if (tcp_dooptions(tp, optp, optlen, th, m, toff, &opti) < 0)
1584 			goto drop;
1585 
1586 	if (TCP_SACK_ENABLED(tp)) {
1587 		tcp_del_sackholes(tp, th);
1588 	}
1589 
1590 	if (opti.ts_present && opti.ts_ecr) {
1591 		/*
1592 		 * Calculate the RTT from the returned time stamp and the
1593 		 * connection's time base.  If the time stamp is later than
1594 		 * the current time, or is extremely old, fall back to non-1323
1595 		 * RTT calculation.  Since ts_ecr is unsigned, we can test both
1596 		 * at the same time.
1597 		 */
1598 		ts_rtt = TCP_TIMESTAMP(tp) - opti.ts_ecr + 1;
1599 		if (ts_rtt > TCP_PAWS_IDLE)
1600 			ts_rtt = 0;
1601 	} else {
1602 		ts_rtt = 0;
1603 	}
1604 
1605 	/*
1606 	 * Header prediction: check for the two common cases
1607 	 * of a uni-directional data xfer.  If the packet has
1608 	 * no control flags, is in-sequence, the window didn't
1609 	 * change and we're not retransmitting, it's a
1610 	 * candidate.  If the length is zero and the ack moved
1611 	 * forward, we're the sender side of the xfer.  Just
1612 	 * free the data acked & wake any higher level process
1613 	 * that was blocked waiting for space.  If the length
1614 	 * is non-zero and the ack didn't move, we're the
1615 	 * receiver side.  If we're getting packets in-order
1616 	 * (the reassembly queue is empty), add the data to
1617 	 * the socket buffer and note that we need a delayed ack.
1618 	 */
1619 	if (tp->t_state == TCPS_ESTABLISHED &&
1620 	    (tiflags & (TH_SYN|TH_FIN|TH_RST|TH_URG|TH_ACK)) == TH_ACK &&
1621 	    (!opti.ts_present || TSTMP_GEQ(opti.ts_val, tp->ts_recent)) &&
1622 	    th->th_seq == tp->rcv_nxt &&
1623 	    tiwin && tiwin == tp->snd_wnd &&
1624 	    tp->snd_nxt == tp->snd_max) {
1625 
1626 		/*
1627 		 * If last ACK falls within this segment's sequence numbers,
1628 		 *  record the timestamp.
1629 		 * NOTE:
1630 		 * 1) That the test incorporates suggestions from the latest
1631 		 *    proposal of the tcplw@cray.com list (Braden 1993/04/26).
1632 		 * 2) That updating only on newer timestamps interferes with
1633 		 *    our earlier PAWS tests, so this check should be solely
1634 		 *    predicated on the sequence space of this segment.
1635 		 * 3) That we modify the segment boundary check to be
1636 		 *        Last.ACK.Sent <= SEG.SEQ + SEG.Len
1637 		 *    instead of RFC1323's
1638 		 *        Last.ACK.Sent < SEG.SEQ + SEG.Len,
1639 		 *    This modified check allows us to overcome RFC1323's
1640 		 *    limitations as described in Stevens TCP/IP Illustrated
1641 		 *    Vol. 2 p.869. In such cases, we can still calculate the
1642 		 *    RTT correctly when RCV.NXT == Last.ACK.Sent.
1643 		 */
1644 		if (opti.ts_present &&
1645 		    SEQ_LEQ(th->th_seq, tp->last_ack_sent) &&
1646 		    SEQ_LEQ(tp->last_ack_sent, th->th_seq + tlen +
1647 		    ((tiflags & (TH_SYN|TH_FIN)) != 0))) {
1648 			tp->ts_recent_age = tcp_now;
1649 			tp->ts_recent = opti.ts_val;
1650 		}
1651 
1652 		if (tlen == 0) {
1653 			/* Ack prediction. */
1654 			if (SEQ_GT(th->th_ack, tp->snd_una) &&
1655 			    SEQ_LEQ(th->th_ack, tp->snd_max) &&
1656 			    tp->snd_cwnd >= tp->snd_wnd &&
1657 			    tp->t_partialacks < 0) {
1658 				/*
1659 				 * this is a pure ack for outstanding data.
1660 				 */
1661 				++tcpstat.tcps_predack;
1662 				if (ts_rtt)
1663 					tcp_xmit_timer(tp, ts_rtt);
1664 				else if (tp->t_rtttime &&
1665 				    SEQ_GT(th->th_ack, tp->t_rtseq))
1666 					tcp_xmit_timer(tp,
1667 					  tcp_now - tp->t_rtttime);
1668 				acked = th->th_ack - tp->snd_una;
1669 				tcpstat.tcps_rcvackpack++;
1670 				tcpstat.tcps_rcvackbyte += acked;
1671 				ND6_HINT(tp);
1672 
1673 				if (acked > (tp->t_lastoff - tp->t_inoff))
1674 					tp->t_lastm = NULL;
1675 				sbdrop(&so->so_snd, acked);
1676 				tp->t_lastoff -= acked;
1677 
1678 				ICMP_CHECK(tp, th, acked);
1679 
1680 				tp->snd_una = th->th_ack;
1681 				tp->snd_fack = tp->snd_una;
1682 				if (SEQ_LT(tp->snd_high, tp->snd_una))
1683 					tp->snd_high = tp->snd_una;
1684 				m_freem(m);
1685 
1686 				/*
1687 				 * If all outstanding data are acked, stop
1688 				 * retransmit timer, otherwise restart timer
1689 				 * using current (possibly backed-off) value.
1690 				 * If process is waiting for space,
1691 				 * wakeup/selwakeup/signal.  If data
1692 				 * are ready to send, let tcp_output
1693 				 * decide between more output or persist.
1694 				 */
1695 				if (tp->snd_una == tp->snd_max)
1696 					TCP_TIMER_DISARM(tp, TCPT_REXMT);
1697 				else if (TCP_TIMER_ISARMED(tp,
1698 				    TCPT_PERSIST) == 0)
1699 					TCP_TIMER_ARM(tp, TCPT_REXMT,
1700 					    tp->t_rxtcur);
1701 
1702 				sowwakeup(so);
1703 				if (so->so_snd.sb_cc)
1704 					(void) tcp_output(tp);
1705 				if (tcp_saveti)
1706 					m_freem(tcp_saveti);
1707 				return;
1708 			}
1709 		} else if (th->th_ack == tp->snd_una &&
1710 		    TAILQ_FIRST(&tp->segq) == NULL &&
1711 		    tlen <= sbspace(&so->so_rcv)) {
1712 			/*
1713 			 * this is a pure, in-sequence data packet
1714 			 * with nothing on the reassembly queue and
1715 			 * we have enough buffer space to take it.
1716 			 */
1717 			++tcpstat.tcps_preddat;
1718 			tp->rcv_nxt += tlen;
1719 			tcpstat.tcps_rcvpack++;
1720 			tcpstat.tcps_rcvbyte += tlen;
1721 			ND6_HINT(tp);
1722 			/*
1723 			 * Drop TCP, IP headers and TCP options then add data
1724 			 * to socket buffer.
1725 			 */
1726 			if (so->so_state & SS_CANTRCVMORE)
1727 				m_freem(m);
1728 			else {
1729 				m_adj(m, toff + off);
1730 				sbappendstream(&so->so_rcv, m);
1731 			}
1732 			sorwakeup(so);
1733 			TCP_SETUP_ACK(tp, th);
1734 			if (tp->t_flags & TF_ACKNOW)
1735 				(void) tcp_output(tp);
1736 			if (tcp_saveti)
1737 				m_freem(tcp_saveti);
1738 			return;
1739 		}
1740 	}
1741 
1742 	/*
1743 	 * Compute mbuf offset to TCP data segment.
1744 	 */
1745 	hdroptlen = toff + off;
1746 
1747 	/*
1748 	 * Calculate amount of space in receive window,
1749 	 * and then do TCP input processing.
1750 	 * Receive window is amount of space in rcv queue,
1751 	 * but not less than advertised window.
1752 	 */
1753 	{ int win;
1754 
1755 	win = sbspace(&so->so_rcv);
1756 	if (win < 0)
1757 		win = 0;
1758 	tp->rcv_wnd = imax(win, (int)(tp->rcv_adv - tp->rcv_nxt));
1759 	}
1760 
1761 	switch (tp->t_state) {
1762 	case TCPS_LISTEN:
1763 		/*
1764 		 * RFC1122 4.2.3.10, p. 104: discard bcast/mcast SYN
1765 		 */
1766 		if (m->m_flags & (M_BCAST|M_MCAST))
1767 			goto drop;
1768 		switch (af) {
1769 #ifdef INET6
1770 		case AF_INET6:
1771 			if (IN6_IS_ADDR_MULTICAST(&ip6->ip6_dst))
1772 				goto drop;
1773 			break;
1774 #endif /* INET6 */
1775 		case AF_INET:
1776 			if (IN_MULTICAST(ip->ip_dst.s_addr) ||
1777 			    in_broadcast(ip->ip_dst, m->m_pkthdr.rcvif))
1778 				goto drop;
1779 			break;
1780 		}
1781 		break;
1782 
1783 	/*
1784 	 * If the state is SYN_SENT:
1785 	 *	if seg contains an ACK, but not for our SYN, drop the input.
1786 	 *	if seg contains a RST, then drop the connection.
1787 	 *	if seg does not contain SYN, then drop it.
1788 	 * Otherwise this is an acceptable SYN segment
1789 	 *	initialize tp->rcv_nxt and tp->irs
1790 	 *	if seg contains ack then advance tp->snd_una
1791 	 *	if SYN has been acked change to ESTABLISHED else SYN_RCVD state
1792 	 *	arrange for segment to be acked (eventually)
1793 	 *	continue processing rest of data/controls, beginning with URG
1794 	 */
1795 	case TCPS_SYN_SENT:
1796 		if ((tiflags & TH_ACK) &&
1797 		    (SEQ_LEQ(th->th_ack, tp->iss) ||
1798 		     SEQ_GT(th->th_ack, tp->snd_max)))
1799 			goto dropwithreset;
1800 		if (tiflags & TH_RST) {
1801 			if (tiflags & TH_ACK)
1802 				tp = tcp_drop(tp, ECONNREFUSED);
1803 			goto drop;
1804 		}
1805 		if ((tiflags & TH_SYN) == 0)
1806 			goto drop;
1807 		if (tiflags & TH_ACK) {
1808 			tp->snd_una = th->th_ack;
1809 			if (SEQ_LT(tp->snd_nxt, tp->snd_una))
1810 				tp->snd_nxt = tp->snd_una;
1811 			if (SEQ_LT(tp->snd_high, tp->snd_una))
1812 				tp->snd_high = tp->snd_una;
1813 			TCP_TIMER_DISARM(tp, TCPT_REXMT);
1814 		}
1815 		tp->irs = th->th_seq;
1816 		tcp_rcvseqinit(tp);
1817 		tp->t_flags |= TF_ACKNOW;
1818 		tcp_mss_from_peer(tp, opti.maxseg);
1819 
1820 		/*
1821 		 * Initialize the initial congestion window.  If we
1822 		 * had to retransmit the SYN, we must initialize cwnd
1823 		 * to 1 segment (i.e. the Loss Window).
1824 		 */
1825 		if (tp->t_flags & TF_SYN_REXMT)
1826 			tp->snd_cwnd = tp->t_peermss;
1827 		else {
1828 			int ss = tcp_init_win;
1829 #ifdef INET
1830 			if (inp != NULL && in_localaddr(inp->inp_faddr))
1831 				ss = tcp_init_win_local;
1832 #endif
1833 #ifdef INET6
1834 			if (in6p != NULL && in6_localaddr(&in6p->in6p_faddr))
1835 				ss = tcp_init_win_local;
1836 #endif
1837 			tp->snd_cwnd = TCP_INITIAL_WINDOW(ss, tp->t_peermss);
1838 		}
1839 
1840 		tcp_rmx_rtt(tp);
1841 		if (tiflags & TH_ACK) {
1842 			tcpstat.tcps_connects++;
1843 			soisconnected(so);
1844 			tcp_established(tp);
1845 			/* Do window scaling on this connection? */
1846 			if ((tp->t_flags & (TF_RCVD_SCALE|TF_REQ_SCALE)) ==
1847 			    (TF_RCVD_SCALE|TF_REQ_SCALE)) {
1848 				tp->snd_scale = tp->requested_s_scale;
1849 				tp->rcv_scale = tp->request_r_scale;
1850 			}
1851 			TCP_REASS_LOCK(tp);
1852 			(void) tcp_reass(tp, NULL, (struct mbuf *)0, &tlen);
1853 			TCP_REASS_UNLOCK(tp);
1854 			/*
1855 			 * if we didn't have to retransmit the SYN,
1856 			 * use its rtt as our initial srtt & rtt var.
1857 			 */
1858 			if (tp->t_rtttime)
1859 				tcp_xmit_timer(tp, tcp_now - tp->t_rtttime);
1860 		} else
1861 			tp->t_state = TCPS_SYN_RECEIVED;
1862 
1863 		/*
1864 		 * Advance th->th_seq to correspond to first data byte.
1865 		 * If data, trim to stay within window,
1866 		 * dropping FIN if necessary.
1867 		 */
1868 		th->th_seq++;
1869 		if (tlen > tp->rcv_wnd) {
1870 			todrop = tlen - tp->rcv_wnd;
1871 			m_adj(m, -todrop);
1872 			tlen = tp->rcv_wnd;
1873 			tiflags &= ~TH_FIN;
1874 			tcpstat.tcps_rcvpackafterwin++;
1875 			tcpstat.tcps_rcvbyteafterwin += todrop;
1876 		}
1877 		tp->snd_wl1 = th->th_seq - 1;
1878 		tp->rcv_up = th->th_seq;
1879 		goto step6;
1880 
1881 	/*
1882 	 * If the state is SYN_RECEIVED:
1883 	 *	If seg contains an ACK, but not for our SYN, drop the input
1884 	 *	and generate an RST.  See page 36, rfc793
1885 	 */
1886 	case TCPS_SYN_RECEIVED:
1887 		if ((tiflags & TH_ACK) &&
1888 		    (SEQ_LEQ(th->th_ack, tp->iss) ||
1889 		     SEQ_GT(th->th_ack, tp->snd_max)))
1890 			goto dropwithreset;
1891 		break;
1892 	}
1893 
1894 	/*
1895 	 * States other than LISTEN or SYN_SENT.
1896 	 * First check timestamp, if present.
1897 	 * Then check that at least some bytes of segment are within
1898 	 * receive window.  If segment begins before rcv_nxt,
1899 	 * drop leading data (and SYN); if nothing left, just ack.
1900 	 *
1901 	 * RFC 1323 PAWS: If we have a timestamp reply on this segment
1902 	 * and it's less than ts_recent, drop it.
1903 	 */
1904 	if (opti.ts_present && (tiflags & TH_RST) == 0 && tp->ts_recent &&
1905 	    TSTMP_LT(opti.ts_val, tp->ts_recent)) {
1906 
1907 		/* Check to see if ts_recent is over 24 days old.  */
1908 		if (tcp_now - tp->ts_recent_age > TCP_PAWS_IDLE) {
1909 			/*
1910 			 * Invalidate ts_recent.  If this segment updates
1911 			 * ts_recent, the age will be reset later and ts_recent
1912 			 * will get a valid value.  If it does not, setting
1913 			 * ts_recent to zero will at least satisfy the
1914 			 * requirement that zero be placed in the timestamp
1915 			 * echo reply when ts_recent isn't valid.  The
1916 			 * age isn't reset until we get a valid ts_recent
1917 			 * because we don't want out-of-order segments to be
1918 			 * dropped when ts_recent is old.
1919 			 */
1920 			tp->ts_recent = 0;
1921 		} else {
1922 			tcpstat.tcps_rcvduppack++;
1923 			tcpstat.tcps_rcvdupbyte += tlen;
1924 			tcpstat.tcps_pawsdrop++;
1925 			tcp_new_dsack(tp, th->th_seq, tlen);
1926 			goto dropafterack;
1927 		}
1928 	}
1929 
1930 	todrop = tp->rcv_nxt - th->th_seq;
1931 	dupseg = FALSE;
1932 	if (todrop > 0) {
1933 		if (tiflags & TH_SYN) {
1934 			tiflags &= ~TH_SYN;
1935 			th->th_seq++;
1936 			if (th->th_urp > 1)
1937 				th->th_urp--;
1938 			else {
1939 				tiflags &= ~TH_URG;
1940 				th->th_urp = 0;
1941 			}
1942 			todrop--;
1943 		}
1944 		if (todrop > tlen ||
1945 		    (todrop == tlen && (tiflags & TH_FIN) == 0)) {
1946 			/*
1947 			 * Any valid FIN or RST must be to the left of the
1948 			 * window.  At this point the FIN or RST must be a
1949 			 * duplicate or out of sequence; drop it.
1950 			 */
1951 			if (tiflags & TH_RST)
1952 				goto drop;
1953 			tiflags &= ~(TH_FIN|TH_RST);
1954 			/*
1955 			 * Send an ACK to resynchronize and drop any data.
1956 			 * But keep on processing for RST or ACK.
1957 			 */
1958 			tp->t_flags |= TF_ACKNOW;
1959 			todrop = tlen;
1960 			dupseg = TRUE;
1961 			tcpstat.tcps_rcvdupbyte += todrop;
1962 			tcpstat.tcps_rcvduppack++;
1963 		} else if ((tiflags & TH_RST) &&
1964 			   th->th_seq != tp->last_ack_sent) {
1965 			/*
1966 			 * Test for reset before adjusting the sequence
1967 			 * number for overlapping data.
1968 			 */
1969 			goto dropafterack_ratelim;
1970 		} else {
1971 			tcpstat.tcps_rcvpartduppack++;
1972 			tcpstat.tcps_rcvpartdupbyte += todrop;
1973 		}
1974 		tcp_new_dsack(tp, th->th_seq, todrop);
1975 		hdroptlen += todrop;	/*drop from head afterwards*/
1976 		th->th_seq += todrop;
1977 		tlen -= todrop;
1978 		if (th->th_urp > todrop)
1979 			th->th_urp -= todrop;
1980 		else {
1981 			tiflags &= ~TH_URG;
1982 			th->th_urp = 0;
1983 		}
1984 	}
1985 
1986 	/*
1987 	 * If new data are received on a connection after the
1988 	 * user processes are gone, then RST the other end.
1989 	 */
1990 	if ((so->so_state & SS_NOFDREF) &&
1991 	    tp->t_state > TCPS_CLOSE_WAIT && tlen) {
1992 		tp = tcp_close(tp);
1993 		tcpstat.tcps_rcvafterclose++;
1994 		goto dropwithreset;
1995 	}
1996 
1997 	/*
1998 	 * If segment ends after window, drop trailing data
1999 	 * (and PUSH and FIN); if nothing left, just ACK.
2000 	 */
2001 	todrop = (th->th_seq + tlen) - (tp->rcv_nxt+tp->rcv_wnd);
2002 	if (todrop > 0) {
2003 		tcpstat.tcps_rcvpackafterwin++;
2004 		if (todrop >= tlen) {
2005 			/*
2006 			 * The segment actually starts after the window.
2007 			 * th->th_seq + tlen - tp->rcv_nxt - tp->rcv_wnd >= tlen
2008 			 * th->th_seq - tp->rcv_nxt - tp->rcv_wnd >= 0
2009 			 * th->th_seq >= tp->rcv_nxt + tp->rcv_wnd
2010 			 */
2011 			tcpstat.tcps_rcvbyteafterwin += tlen;
2012 			/*
2013 			 * If a new connection request is received
2014 			 * while in TIME_WAIT, drop the old connection
2015 			 * and start over if the sequence numbers
2016 			 * are above the previous ones.
2017 			 *
2018 			 * NOTE: We will checksum the packet again, and
2019 			 * so we need to put the header fields back into
2020 			 * network order!
2021 			 * XXX This kind of sucks, but we don't expect
2022 			 * XXX this to happen very often, so maybe it
2023 			 * XXX doesn't matter so much.
2024 			 */
2025 			if (tiflags & TH_SYN &&
2026 			    tp->t_state == TCPS_TIME_WAIT &&
2027 			    SEQ_GT(th->th_seq, tp->rcv_nxt)) {
2028 				tp = tcp_close(tp);
2029 				TCP_FIELDS_TO_NET(th);
2030 				goto findpcb;
2031 			}
2032 			/*
2033 			 * If window is closed can only take segments at
2034 			 * window edge, and have to drop data and PUSH from
2035 			 * incoming segments.  Continue processing, but
2036 			 * remember to ack.  Otherwise, drop segment
2037 			 * and (if not RST) ack.
2038 			 */
2039 			if (tp->rcv_wnd == 0 && th->th_seq == tp->rcv_nxt) {
2040 				tp->t_flags |= TF_ACKNOW;
2041 				tcpstat.tcps_rcvwinprobe++;
2042 			} else
2043 				goto dropafterack;
2044 		} else
2045 			tcpstat.tcps_rcvbyteafterwin += todrop;
2046 		m_adj(m, -todrop);
2047 		tlen -= todrop;
2048 		tiflags &= ~(TH_PUSH|TH_FIN);
2049 	}
2050 
2051 	/*
2052 	 * If last ACK falls within this segment's sequence numbers,
2053 	 * and the timestamp is newer, record it.
2054 	 */
2055 	if (opti.ts_present && TSTMP_GEQ(opti.ts_val, tp->ts_recent) &&
2056 	    SEQ_LEQ(th->th_seq, tp->last_ack_sent) &&
2057 	    SEQ_LT(tp->last_ack_sent, th->th_seq + tlen +
2058 		   ((tiflags & (TH_SYN|TH_FIN)) != 0))) {
2059 		tp->ts_recent_age = tcp_now;
2060 		tp->ts_recent = opti.ts_val;
2061 	}
2062 
2063 	/*
2064 	 * If the RST bit is set examine the state:
2065 	 *    SYN_RECEIVED STATE:
2066 	 *	If passive open, return to LISTEN state.
2067 	 *	If active open, inform user that connection was refused.
2068 	 *    ESTABLISHED, FIN_WAIT_1, FIN_WAIT2, CLOSE_WAIT STATES:
2069 	 *	Inform user that connection was reset, and close tcb.
2070 	 *    CLOSING, LAST_ACK, TIME_WAIT STATES
2071 	 *	Close the tcb.
2072 	 */
2073 	if (tiflags & TH_RST) {
2074 		if (th->th_seq != tp->last_ack_sent)
2075 			goto dropafterack_ratelim;
2076 
2077 		switch (tp->t_state) {
2078 		case TCPS_SYN_RECEIVED:
2079 			so->so_error = ECONNREFUSED;
2080 			goto close;
2081 
2082 		case TCPS_ESTABLISHED:
2083 		case TCPS_FIN_WAIT_1:
2084 		case TCPS_FIN_WAIT_2:
2085 		case TCPS_CLOSE_WAIT:
2086 			so->so_error = ECONNRESET;
2087 		close:
2088 			tp->t_state = TCPS_CLOSED;
2089 			tcpstat.tcps_drops++;
2090 			tp = tcp_close(tp);
2091 			goto drop;
2092 
2093 		case TCPS_CLOSING:
2094 		case TCPS_LAST_ACK:
2095 		case TCPS_TIME_WAIT:
2096 			tp = tcp_close(tp);
2097 			goto drop;
2098 		}
2099 	}
2100 
2101 	/*
2102 	 * Since we've covered the SYN-SENT and SYN-RECEIVED states above
2103 	 * we must be in a synchronized state.  RFC791 states (under RST
2104 	 * generation) that any unacceptable segment (an out-of-order SYN
2105 	 * qualifies) received in a synchronized state must elicit only an
2106 	 * empty acknowledgment segment ... and the connection remains in
2107 	 * the same state.
2108 	 */
2109 	if (tiflags & TH_SYN) {
2110 		if (tp->rcv_nxt == th->th_seq) {
2111 			tcp_respond(tp, m, m, th, (tcp_seq)0, th->th_ack - 1,
2112 			    TH_ACK);
2113 			if (tcp_saveti)
2114 				m_freem(tcp_saveti);
2115 			return;
2116 		}
2117 
2118 		goto dropafterack_ratelim;
2119 	}
2120 
2121 	/*
2122 	 * If the ACK bit is off we drop the segment and return.
2123 	 */
2124 	if ((tiflags & TH_ACK) == 0) {
2125 		if (tp->t_flags & TF_ACKNOW)
2126 			goto dropafterack;
2127 		else
2128 			goto drop;
2129 	}
2130 
2131 	/*
2132 	 * Ack processing.
2133 	 */
2134 	switch (tp->t_state) {
2135 
2136 	/*
2137 	 * In SYN_RECEIVED state if the ack ACKs our SYN then enter
2138 	 * ESTABLISHED state and continue processing, otherwise
2139 	 * send an RST.
2140 	 */
2141 	case TCPS_SYN_RECEIVED:
2142 		if (SEQ_GT(tp->snd_una, th->th_ack) ||
2143 		    SEQ_GT(th->th_ack, tp->snd_max))
2144 			goto dropwithreset;
2145 		tcpstat.tcps_connects++;
2146 		soisconnected(so);
2147 		tcp_established(tp);
2148 		/* Do window scaling? */
2149 		if ((tp->t_flags & (TF_RCVD_SCALE|TF_REQ_SCALE)) ==
2150 		    (TF_RCVD_SCALE|TF_REQ_SCALE)) {
2151 			tp->snd_scale = tp->requested_s_scale;
2152 			tp->rcv_scale = tp->request_r_scale;
2153 		}
2154 		TCP_REASS_LOCK(tp);
2155 		(void) tcp_reass(tp, NULL, (struct mbuf *)0, &tlen);
2156 		TCP_REASS_UNLOCK(tp);
2157 		tp->snd_wl1 = th->th_seq - 1;
2158 		/* fall into ... */
2159 
2160 	/*
2161 	 * In ESTABLISHED state: drop duplicate ACKs; ACK out of range
2162 	 * ACKs.  If the ack is in the range
2163 	 *	tp->snd_una < th->th_ack <= tp->snd_max
2164 	 * then advance tp->snd_una to th->th_ack and drop
2165 	 * data from the retransmission queue.  If this ACK reflects
2166 	 * more up to date window information we update our window information.
2167 	 */
2168 	case TCPS_ESTABLISHED:
2169 	case TCPS_FIN_WAIT_1:
2170 	case TCPS_FIN_WAIT_2:
2171 	case TCPS_CLOSE_WAIT:
2172 	case TCPS_CLOSING:
2173 	case TCPS_LAST_ACK:
2174 	case TCPS_TIME_WAIT:
2175 
2176 		if (SEQ_LEQ(th->th_ack, tp->snd_una)) {
2177 			if (tlen == 0 && !dupseg && tiwin == tp->snd_wnd) {
2178 				tcpstat.tcps_rcvdupack++;
2179 				/*
2180 				 * If we have outstanding data (other than
2181 				 * a window probe), this is a completely
2182 				 * duplicate ack (ie, window info didn't
2183 				 * change), the ack is the biggest we've
2184 				 * seen and we've seen exactly our rexmt
2185 				 * threshhold of them, assume a packet
2186 				 * has been dropped and retransmit it.
2187 				 * Kludge snd_nxt & the congestion
2188 				 * window so we send only this one
2189 				 * packet.
2190 				 *
2191 				 * We know we're losing at the current
2192 				 * window size so do congestion avoidance
2193 				 * (set ssthresh to half the current window
2194 				 * and pull our congestion window back to
2195 				 * the new ssthresh).
2196 				 *
2197 				 * Dup acks mean that packets have left the
2198 				 * network (they're now cached at the receiver)
2199 				 * so bump cwnd by the amount in the receiver
2200 				 * to keep a constant cwnd packets in the
2201 				 * network.
2202 				 *
2203 				 * If we are using TCP/SACK, then enter
2204 				 * Fast Recovery if the receiver SACKs
2205 				 * data that is tcprexmtthresh * MSS
2206 				 * bytes past the last ACKed segment,
2207 				 * irrespective of the number of DupAcks.
2208 				 */
2209 				if (TCP_TIMER_ISARMED(tp, TCPT_REXMT) == 0 ||
2210 				    th->th_ack != tp->snd_una)
2211 					tp->t_dupacks = 0;
2212 				else if (tp->t_partialacks < 0 &&
2213 					 (++tp->t_dupacks == tcprexmtthresh ||
2214 					 TCP_FACK_FASTRECOV(tp))) {
2215 					tcp_seq onxt;
2216 					u_int win;
2217 
2218 					if (tcp_do_newreno &&
2219 					    SEQ_LT(th->th_ack, tp->snd_high)) {
2220 						/*
2221 						 * False fast retransmit after
2222 						 * timeout.  Do not enter fast
2223 						 * recovery.
2224 						 */
2225 						tp->t_dupacks = 0;
2226 						break;
2227 					}
2228 
2229 					onxt = tp->snd_nxt;
2230 					win = min(tp->snd_wnd, tp->snd_cwnd) /
2231 					    2 /	tp->t_segsz;
2232 					if (win < 2)
2233 						win = 2;
2234 					tp->snd_ssthresh = win * tp->t_segsz;
2235 					tp->snd_recover = tp->snd_max;
2236 					tp->t_partialacks = 0;
2237 					TCP_TIMER_DISARM(tp, TCPT_REXMT);
2238 					tp->t_rtttime = 0;
2239 					if (TCP_SACK_ENABLED(tp)) {
2240 						tp->t_dupacks = tcprexmtthresh;
2241 						tp->sack_newdata = tp->snd_nxt;
2242 						tp->snd_cwnd = tp->t_segsz;
2243 						(void) tcp_output(tp);
2244 						goto drop;
2245 					}
2246 					tp->snd_nxt = th->th_ack;
2247 					tp->snd_cwnd = tp->t_segsz;
2248 					(void) tcp_output(tp);
2249 					tp->snd_cwnd = tp->snd_ssthresh +
2250 					       tp->t_segsz * tp->t_dupacks;
2251 					if (SEQ_GT(onxt, tp->snd_nxt))
2252 						tp->snd_nxt = onxt;
2253 					goto drop;
2254 				} else if (tp->t_dupacks > tcprexmtthresh) {
2255 					tp->snd_cwnd += tp->t_segsz;
2256 					(void) tcp_output(tp);
2257 					goto drop;
2258 				}
2259 			} else {
2260 				/*
2261 				 * If the ack appears to be very old, only
2262 				 * allow data that is in-sequence.  This
2263 				 * makes it somewhat more difficult to insert
2264 				 * forged data by guessing sequence numbers.
2265 				 * Sent an ack to try to update the send
2266 				 * sequence number on the other side.
2267 				 */
2268 				if (tlen && th->th_seq != tp->rcv_nxt &&
2269 				    SEQ_LT(th->th_ack,
2270 				    tp->snd_una - tp->max_sndwnd))
2271 					goto dropafterack;
2272 			}
2273 			break;
2274 		}
2275 		/*
2276 		 * If the congestion window was inflated to account
2277 		 * for the other side's cached packets, retract it.
2278 		 */
2279 		if (TCP_SACK_ENABLED(tp))
2280 			tcp_sack_newack(tp, th);
2281 		else if (tcp_do_newreno)
2282 			tcp_newreno_newack(tp, th);
2283 		else
2284 			tcp_reno_newack(tp, th);
2285 		if (SEQ_GT(th->th_ack, tp->snd_max)) {
2286 			tcpstat.tcps_rcvacktoomuch++;
2287 			goto dropafterack;
2288 		}
2289 		acked = th->th_ack - tp->snd_una;
2290 		tcpstat.tcps_rcvackpack++;
2291 		tcpstat.tcps_rcvackbyte += acked;
2292 
2293 		/*
2294 		 * If we have a timestamp reply, update smoothed
2295 		 * round trip time.  If no timestamp is present but
2296 		 * transmit timer is running and timed sequence
2297 		 * number was acked, update smoothed round trip time.
2298 		 * Since we now have an rtt measurement, cancel the
2299 		 * timer backoff (cf., Phil Karn's retransmit alg.).
2300 		 * Recompute the initial retransmit timer.
2301 		 */
2302 		if (ts_rtt)
2303 			tcp_xmit_timer(tp, ts_rtt);
2304 		else if (tp->t_rtttime && SEQ_GT(th->th_ack, tp->t_rtseq))
2305 			tcp_xmit_timer(tp, tcp_now - tp->t_rtttime);
2306 
2307 		/*
2308 		 * If all outstanding data is acked, stop retransmit
2309 		 * timer and remember to restart (more output or persist).
2310 		 * If there is more data to be acked, restart retransmit
2311 		 * timer, using current (possibly backed-off) value.
2312 		 */
2313 		if (th->th_ack == tp->snd_max) {
2314 			TCP_TIMER_DISARM(tp, TCPT_REXMT);
2315 			needoutput = 1;
2316 		} else if (TCP_TIMER_ISARMED(tp, TCPT_PERSIST) == 0)
2317 			TCP_TIMER_ARM(tp, TCPT_REXMT, tp->t_rxtcur);
2318 		/*
2319 		 * When new data is acked, open the congestion window.
2320 		 * If the window gives us less than ssthresh packets
2321 		 * in flight, open exponentially (segsz per packet).
2322 		 * Otherwise open linearly: segsz per window
2323 		 * (segsz^2 / cwnd per packet).
2324 		 *
2325 		 * If we are still in fast recovery (meaning we are using
2326 		 * NewReno and we have only received partial acks), do not
2327 		 * inflate the window yet.
2328 		 */
2329 		if (tp->t_partialacks < 0) {
2330 			u_int cw = tp->snd_cwnd;
2331 			u_int incr = tp->t_segsz;
2332 
2333 			if (cw >= tp->snd_ssthresh)
2334 				incr = incr * incr / cw;
2335 			tp->snd_cwnd = min(cw + incr,
2336 			    TCP_MAXWIN << tp->snd_scale);
2337 		}
2338 		ND6_HINT(tp);
2339 		if (acked > so->so_snd.sb_cc) {
2340 			tp->snd_wnd -= so->so_snd.sb_cc;
2341 			sbdrop(&so->so_snd, (int)so->so_snd.sb_cc);
2342 			ourfinisacked = 1;
2343 		} else {
2344 			if (acked > (tp->t_lastoff - tp->t_inoff))
2345 				tp->t_lastm = NULL;
2346 			sbdrop(&so->so_snd, acked);
2347 			tp->t_lastoff -= acked;
2348 			tp->snd_wnd -= acked;
2349 			ourfinisacked = 0;
2350 		}
2351 		sowwakeup(so);
2352 
2353 		ICMP_CHECK(tp, th, acked);
2354 
2355 		tp->snd_una = th->th_ack;
2356 		if (SEQ_GT(tp->snd_una, tp->snd_fack))
2357 			tp->snd_fack = tp->snd_una;
2358 		if (SEQ_LT(tp->snd_nxt, tp->snd_una))
2359 			tp->snd_nxt = tp->snd_una;
2360 		if (SEQ_LT(tp->snd_high, tp->snd_una))
2361 			tp->snd_high = tp->snd_una;
2362 
2363 		switch (tp->t_state) {
2364 
2365 		/*
2366 		 * In FIN_WAIT_1 STATE in addition to the processing
2367 		 * for the ESTABLISHED state if our FIN is now acknowledged
2368 		 * then enter FIN_WAIT_2.
2369 		 */
2370 		case TCPS_FIN_WAIT_1:
2371 			if (ourfinisacked) {
2372 				/*
2373 				 * If we can't receive any more
2374 				 * data, then closing user can proceed.
2375 				 * Starting the timer is contrary to the
2376 				 * specification, but if we don't get a FIN
2377 				 * we'll hang forever.
2378 				 */
2379 				if (so->so_state & SS_CANTRCVMORE) {
2380 					soisdisconnected(so);
2381 					if (tcp_maxidle > 0)
2382 						TCP_TIMER_ARM(tp, TCPT_2MSL,
2383 						    tcp_maxidle);
2384 				}
2385 				tp->t_state = TCPS_FIN_WAIT_2;
2386 			}
2387 			break;
2388 
2389 	 	/*
2390 		 * In CLOSING STATE in addition to the processing for
2391 		 * the ESTABLISHED state if the ACK acknowledges our FIN
2392 		 * then enter the TIME-WAIT state, otherwise ignore
2393 		 * the segment.
2394 		 */
2395 		case TCPS_CLOSING:
2396 			if (ourfinisacked) {
2397 				tp->t_state = TCPS_TIME_WAIT;
2398 				tcp_canceltimers(tp);
2399 				TCP_TIMER_ARM(tp, TCPT_2MSL, 2 * TCPTV_MSL);
2400 				soisdisconnected(so);
2401 			}
2402 			break;
2403 
2404 		/*
2405 		 * In LAST_ACK, we may still be waiting for data to drain
2406 		 * and/or to be acked, as well as for the ack of our FIN.
2407 		 * If our FIN is now acknowledged, delete the TCB,
2408 		 * enter the closed state and return.
2409 		 */
2410 		case TCPS_LAST_ACK:
2411 			if (ourfinisacked) {
2412 				tp = tcp_close(tp);
2413 				goto drop;
2414 			}
2415 			break;
2416 
2417 		/*
2418 		 * In TIME_WAIT state the only thing that should arrive
2419 		 * is a retransmission of the remote FIN.  Acknowledge
2420 		 * it and restart the finack timer.
2421 		 */
2422 		case TCPS_TIME_WAIT:
2423 			TCP_TIMER_ARM(tp, TCPT_2MSL, 2 * TCPTV_MSL);
2424 			goto dropafterack;
2425 		}
2426 	}
2427 
2428 step6:
2429 	/*
2430 	 * Update window information.
2431 	 * Don't look at window if no ACK: TAC's send garbage on first SYN.
2432 	 */
2433 	if ((tiflags & TH_ACK) && (SEQ_LT(tp->snd_wl1, th->th_seq) ||
2434 	    (tp->snd_wl1 == th->th_seq && (SEQ_LT(tp->snd_wl2, th->th_ack) ||
2435 	    (tp->snd_wl2 == th->th_ack && tiwin > tp->snd_wnd))))) {
2436 		/* keep track of pure window updates */
2437 		if (tlen == 0 &&
2438 		    tp->snd_wl2 == th->th_ack && tiwin > tp->snd_wnd)
2439 			tcpstat.tcps_rcvwinupd++;
2440 		tp->snd_wnd = tiwin;
2441 		tp->snd_wl1 = th->th_seq;
2442 		tp->snd_wl2 = th->th_ack;
2443 		if (tp->snd_wnd > tp->max_sndwnd)
2444 			tp->max_sndwnd = tp->snd_wnd;
2445 		needoutput = 1;
2446 	}
2447 
2448 	/*
2449 	 * Process segments with URG.
2450 	 */
2451 	if ((tiflags & TH_URG) && th->th_urp &&
2452 	    TCPS_HAVERCVDFIN(tp->t_state) == 0) {
2453 		/*
2454 		 * This is a kludge, but if we receive and accept
2455 		 * random urgent pointers, we'll crash in
2456 		 * soreceive.  It's hard to imagine someone
2457 		 * actually wanting to send this much urgent data.
2458 		 */
2459 		if (th->th_urp + so->so_rcv.sb_cc > sb_max) {
2460 			th->th_urp = 0;			/* XXX */
2461 			tiflags &= ~TH_URG;		/* XXX */
2462 			goto dodata;			/* XXX */
2463 		}
2464 		/*
2465 		 * If this segment advances the known urgent pointer,
2466 		 * then mark the data stream.  This should not happen
2467 		 * in CLOSE_WAIT, CLOSING, LAST_ACK or TIME_WAIT STATES since
2468 		 * a FIN has been received from the remote side.
2469 		 * In these states we ignore the URG.
2470 		 *
2471 		 * According to RFC961 (Assigned Protocols),
2472 		 * the urgent pointer points to the last octet
2473 		 * of urgent data.  We continue, however,
2474 		 * to consider it to indicate the first octet
2475 		 * of data past the urgent section as the original
2476 		 * spec states (in one of two places).
2477 		 */
2478 		if (SEQ_GT(th->th_seq+th->th_urp, tp->rcv_up)) {
2479 			tp->rcv_up = th->th_seq + th->th_urp;
2480 			so->so_oobmark = so->so_rcv.sb_cc +
2481 			    (tp->rcv_up - tp->rcv_nxt) - 1;
2482 			if (so->so_oobmark == 0)
2483 				so->so_state |= SS_RCVATMARK;
2484 			sohasoutofband(so);
2485 			tp->t_oobflags &= ~(TCPOOB_HAVEDATA | TCPOOB_HADDATA);
2486 		}
2487 		/*
2488 		 * Remove out of band data so doesn't get presented to user.
2489 		 * This can happen independent of advancing the URG pointer,
2490 		 * but if two URG's are pending at once, some out-of-band
2491 		 * data may creep in... ick.
2492 		 */
2493 		if (th->th_urp <= (u_int16_t) tlen
2494 #ifdef SO_OOBINLINE
2495 		     && (so->so_options & SO_OOBINLINE) == 0
2496 #endif
2497 		     )
2498 			tcp_pulloutofband(so, th, m, hdroptlen);
2499 	} else
2500 		/*
2501 		 * If no out of band data is expected,
2502 		 * pull receive urgent pointer along
2503 		 * with the receive window.
2504 		 */
2505 		if (SEQ_GT(tp->rcv_nxt, tp->rcv_up))
2506 			tp->rcv_up = tp->rcv_nxt;
2507 dodata:							/* XXX */
2508 
2509 	/*
2510 	 * Process the segment text, merging it into the TCP sequencing queue,
2511 	 * and arranging for acknowledgement of receipt if necessary.
2512 	 * This process logically involves adjusting tp->rcv_wnd as data
2513 	 * is presented to the user (this happens in tcp_usrreq.c,
2514 	 * case PRU_RCVD).  If a FIN has already been received on this
2515 	 * connection then we just ignore the text.
2516 	 */
2517 	if ((tlen || (tiflags & TH_FIN)) &&
2518 	    TCPS_HAVERCVDFIN(tp->t_state) == 0) {
2519 		/*
2520 		 * Insert segment ti into reassembly queue of tcp with
2521 		 * control block tp.  Return TH_FIN if reassembly now includes
2522 		 * a segment with FIN.  The macro form does the common case
2523 		 * inline (segment is the next to be received on an
2524 		 * established connection, and the queue is empty),
2525 		 * avoiding linkage into and removal from the queue and
2526 		 * repetition of various conversions.
2527 		 * Set DELACK for segments received in order, but ack
2528 		 * immediately when segments are out of order
2529 		 * (so fast retransmit can work).
2530 		 */
2531 		/* NOTE: this was TCP_REASS() macro, but used only once */
2532 		TCP_REASS_LOCK(tp);
2533 		if (th->th_seq == tp->rcv_nxt &&
2534 		    TAILQ_FIRST(&tp->segq) == NULL &&
2535 		    tp->t_state == TCPS_ESTABLISHED) {
2536 			TCP_SETUP_ACK(tp, th);
2537 			tp->rcv_nxt += tlen;
2538 			tiflags = th->th_flags & TH_FIN;
2539 			tcpstat.tcps_rcvpack++;
2540 			tcpstat.tcps_rcvbyte += tlen;
2541 			ND6_HINT(tp);
2542 			if (so->so_state & SS_CANTRCVMORE)
2543 				m_freem(m);
2544 			else {
2545 				m_adj(m, hdroptlen);
2546 				sbappendstream(&(so)->so_rcv, m);
2547 			}
2548 			sorwakeup(so);
2549 		} else {
2550 			m_adj(m, hdroptlen);
2551 			tiflags = tcp_reass(tp, th, m, &tlen);
2552 			tp->t_flags |= TF_ACKNOW;
2553 		}
2554 		TCP_REASS_UNLOCK(tp);
2555 
2556 		/*
2557 		 * Note the amount of data that peer has sent into
2558 		 * our window, in order to estimate the sender's
2559 		 * buffer size.
2560 		 */
2561 		len = so->so_rcv.sb_hiwat - (tp->rcv_adv - tp->rcv_nxt);
2562 	} else {
2563 		m_freem(m);
2564 		m = NULL;
2565 		tiflags &= ~TH_FIN;
2566 	}
2567 
2568 	/*
2569 	 * If FIN is received ACK the FIN and let the user know
2570 	 * that the connection is closing.  Ignore a FIN received before
2571 	 * the connection is fully established.
2572 	 */
2573 	if ((tiflags & TH_FIN) && TCPS_HAVEESTABLISHED(tp->t_state)) {
2574 		if (TCPS_HAVERCVDFIN(tp->t_state) == 0) {
2575 			socantrcvmore(so);
2576 			tp->t_flags |= TF_ACKNOW;
2577 			tp->rcv_nxt++;
2578 		}
2579 		switch (tp->t_state) {
2580 
2581 	 	/*
2582 		 * In ESTABLISHED STATE enter the CLOSE_WAIT state.
2583 		 */
2584 		case TCPS_ESTABLISHED:
2585 			tp->t_state = TCPS_CLOSE_WAIT;
2586 			break;
2587 
2588 	 	/*
2589 		 * If still in FIN_WAIT_1 STATE FIN has not been acked so
2590 		 * enter the CLOSING state.
2591 		 */
2592 		case TCPS_FIN_WAIT_1:
2593 			tp->t_state = TCPS_CLOSING;
2594 			break;
2595 
2596 	 	/*
2597 		 * In FIN_WAIT_2 state enter the TIME_WAIT state,
2598 		 * starting the time-wait timer, turning off the other
2599 		 * standard timers.
2600 		 */
2601 		case TCPS_FIN_WAIT_2:
2602 			tp->t_state = TCPS_TIME_WAIT;
2603 			tcp_canceltimers(tp);
2604 			TCP_TIMER_ARM(tp, TCPT_2MSL, 2 * TCPTV_MSL);
2605 			soisdisconnected(so);
2606 			break;
2607 
2608 		/*
2609 		 * In TIME_WAIT state restart the 2 MSL time_wait timer.
2610 		 */
2611 		case TCPS_TIME_WAIT:
2612 			TCP_TIMER_ARM(tp, TCPT_2MSL, 2 * TCPTV_MSL);
2613 			break;
2614 		}
2615 	}
2616 #ifdef TCP_DEBUG
2617 	if (so->so_options & SO_DEBUG)
2618 		tcp_trace(TA_INPUT, ostate, tp, tcp_saveti, 0);
2619 #endif
2620 
2621 	/*
2622 	 * Return any desired output.
2623 	 */
2624 	if (needoutput || (tp->t_flags & TF_ACKNOW)) {
2625 		(void) tcp_output(tp);
2626 	}
2627 	if (tcp_saveti)
2628 		m_freem(tcp_saveti);
2629 	return;
2630 
2631 badsyn:
2632 	/*
2633 	 * Received a bad SYN.  Increment counters and dropwithreset.
2634 	 */
2635 	tcpstat.tcps_badsyn++;
2636 	tp = NULL;
2637 	goto dropwithreset;
2638 
2639 dropafterack:
2640 	/*
2641 	 * Generate an ACK dropping incoming segment if it occupies
2642 	 * sequence space, where the ACK reflects our state.
2643 	 */
2644 	if (tiflags & TH_RST)
2645 		goto drop;
2646 	goto dropafterack2;
2647 
2648 dropafterack_ratelim:
2649 	/*
2650 	 * We may want to rate-limit ACKs against SYN/RST attack.
2651 	 */
2652 	if (ppsratecheck(&tcp_ackdrop_ppslim_last, &tcp_ackdrop_ppslim_count,
2653 	    tcp_ackdrop_ppslim) == 0) {
2654 		/* XXX stat */
2655 		goto drop;
2656 	}
2657 	/* ...fall into dropafterack2... */
2658 
2659 dropafterack2:
2660 	m_freem(m);
2661 	tp->t_flags |= TF_ACKNOW;
2662 	(void) tcp_output(tp);
2663 	if (tcp_saveti)
2664 		m_freem(tcp_saveti);
2665 	return;
2666 
2667 dropwithreset_ratelim:
2668 	/*
2669 	 * We may want to rate-limit RSTs in certain situations,
2670 	 * particularly if we are sending an RST in response to
2671 	 * an attempt to connect to or otherwise communicate with
2672 	 * a port for which we have no socket.
2673 	 */
2674 	if (ppsratecheck(&tcp_rst_ppslim_last, &tcp_rst_ppslim_count,
2675 	    tcp_rst_ppslim) == 0) {
2676 		/* XXX stat */
2677 		goto drop;
2678 	}
2679 	/* ...fall into dropwithreset... */
2680 
2681 dropwithreset:
2682 	/*
2683 	 * Generate a RST, dropping incoming segment.
2684 	 * Make ACK acceptable to originator of segment.
2685 	 */
2686 	if (tiflags & TH_RST)
2687 		goto drop;
2688 
2689 	switch (af) {
2690 #ifdef INET6
2691 	case AF_INET6:
2692 		/* For following calls to tcp_respond */
2693 		if (IN6_IS_ADDR_MULTICAST(&ip6->ip6_dst))
2694 			goto drop;
2695 		break;
2696 #endif /* INET6 */
2697 	case AF_INET:
2698 		if (IN_MULTICAST(ip->ip_dst.s_addr) ||
2699 		    in_broadcast(ip->ip_dst, m->m_pkthdr.rcvif))
2700 			goto drop;
2701 	}
2702 
2703 	if (tiflags & TH_ACK)
2704 		(void)tcp_respond(tp, m, m, th, (tcp_seq)0, th->th_ack, TH_RST);
2705 	else {
2706 		if (tiflags & TH_SYN)
2707 			tlen++;
2708 		(void)tcp_respond(tp, m, m, th, th->th_seq + tlen, (tcp_seq)0,
2709 		    TH_RST|TH_ACK);
2710 	}
2711 	if (tcp_saveti)
2712 		m_freem(tcp_saveti);
2713 	return;
2714 
2715 badcsum:
2716 drop:
2717 	/*
2718 	 * Drop space held by incoming segment and return.
2719 	 */
2720 	if (tp) {
2721 		if (tp->t_inpcb)
2722 			so = tp->t_inpcb->inp_socket;
2723 #ifdef INET6
2724 		else if (tp->t_in6pcb)
2725 			so = tp->t_in6pcb->in6p_socket;
2726 #endif
2727 		else
2728 			so = NULL;
2729 #ifdef TCP_DEBUG
2730 		if (so && (so->so_options & SO_DEBUG) != 0)
2731 			tcp_trace(TA_DROP, ostate, tp, tcp_saveti, 0);
2732 #endif
2733 	}
2734 	if (tcp_saveti)
2735 		m_freem(tcp_saveti);
2736 	m_freem(m);
2737 	return;
2738 }
2739 
2740 #ifdef TCP_SIGNATURE
2741 int
2742 tcp_signature_apply(void *fstate, caddr_t data, u_int len)
2743 {
2744 
2745 	MD5Update(fstate, (u_char *)data, len);
2746 	return (0);
2747 }
2748 
2749 struct secasvar *
2750 tcp_signature_getsav(struct mbuf *m, struct tcphdr *th)
2751 {
2752 	struct secasvar *sav;
2753 #ifdef FAST_IPSEC
2754 	union sockaddr_union dst;
2755 #endif
2756 	struct ip *ip;
2757 	struct ip6_hdr *ip6;
2758 
2759 	ip = mtod(m, struct ip *);
2760 	switch (ip->ip_v) {
2761 	case 4:
2762 		ip = mtod(m, struct ip *);
2763 		ip6 = NULL;
2764 		break;
2765 	case 6:
2766 		ip = NULL;
2767 		ip6 = mtod(m, struct ip6_hdr *);
2768 		break;
2769 	default:
2770 		return (NULL);
2771 	}
2772 
2773 #ifdef FAST_IPSEC
2774 	/* Extract the destination from the IP header in the mbuf. */
2775 	bzero(&dst, sizeof(union sockaddr_union));
2776 	dst.sa.sa_len = sizeof(struct sockaddr_in);
2777 	dst.sa.sa_family = AF_INET;
2778 	dst.sin.sin_addr = ip->ip_dst;
2779 
2780 	/*
2781 	 * Look up an SADB entry which matches the address of the peer.
2782 	 */
2783 	sav = KEY_ALLOCSA(&dst, IPPROTO_TCP, htonl(TCP_SIG_SPI));
2784 #else
2785 	if (ip)
2786 		sav = key_allocsa(AF_INET, (caddr_t)&ip->ip_src,
2787 		    (caddr_t)&ip->ip_dst, IPPROTO_TCP,
2788 		    htonl(TCP_SIG_SPI), 0, 0);
2789 	else
2790 		sav = key_allocsa(AF_INET6, (caddr_t)&ip6->ip6_src,
2791 		    (caddr_t)&ip6->ip6_dst, IPPROTO_TCP,
2792 		    htonl(TCP_SIG_SPI), 0, 0);
2793 #endif
2794 
2795 	return (sav);	/* freesav must be performed by caller */
2796 }
2797 
2798 int
2799 tcp_signature(struct mbuf *m, struct tcphdr *th, int thoff,
2800     struct secasvar *sav, char *sig)
2801 {
2802 	MD5_CTX ctx;
2803 	struct ip *ip;
2804 	struct ipovly *ipovly;
2805 	struct ip6_hdr *ip6;
2806 	struct ippseudo ippseudo;
2807 	struct ip6_hdr_pseudo ip6pseudo;
2808 	struct tcphdr th0;
2809 	int l, tcphdrlen;
2810 
2811 	if (sav == NULL)
2812 		return (-1);
2813 
2814 	tcphdrlen = th->th_off * 4;
2815 
2816 	switch (mtod(m, struct ip *)->ip_v) {
2817 	case 4:
2818 		ip = mtod(m, struct ip *);
2819 		ip6 = NULL;
2820 		break;
2821 	case 6:
2822 		ip = NULL;
2823 		ip6 = mtod(m, struct ip6_hdr *);
2824 		break;
2825 	default:
2826 		return (-1);
2827 	}
2828 
2829 	MD5Init(&ctx);
2830 
2831 	if (ip) {
2832 		memset(&ippseudo, 0, sizeof(ippseudo));
2833 		ipovly = (struct ipovly *)ip;
2834 		ippseudo.ippseudo_src = ipovly->ih_src;
2835 		ippseudo.ippseudo_dst = ipovly->ih_dst;
2836 		ippseudo.ippseudo_pad = 0;
2837 		ippseudo.ippseudo_p = IPPROTO_TCP;
2838 		ippseudo.ippseudo_len = htons(m->m_pkthdr.len - thoff);
2839 		MD5Update(&ctx, (char *)&ippseudo, sizeof(ippseudo));
2840 	} else {
2841 		memset(&ip6pseudo, 0, sizeof(ip6pseudo));
2842 		ip6pseudo.ip6ph_src = ip6->ip6_src;
2843 		in6_clearscope(&ip6pseudo.ip6ph_src);
2844 		ip6pseudo.ip6ph_dst = ip6->ip6_dst;
2845 		in6_clearscope(&ip6pseudo.ip6ph_dst);
2846 		ip6pseudo.ip6ph_len = htons(m->m_pkthdr.len - thoff);
2847 		ip6pseudo.ip6ph_nxt = IPPROTO_TCP;
2848 		MD5Update(&ctx, (char *)&ip6pseudo, sizeof(ip6pseudo));
2849 	}
2850 
2851 	th0 = *th;
2852 	th0.th_sum = 0;
2853 	MD5Update(&ctx, (char *)&th0, sizeof(th0));
2854 
2855 	l = m->m_pkthdr.len - thoff - tcphdrlen;
2856 	if (l > 0)
2857 		m_apply(m, thoff + tcphdrlen,
2858 		    m->m_pkthdr.len - thoff - tcphdrlen,
2859 		    tcp_signature_apply, &ctx);
2860 
2861 	MD5Update(&ctx, _KEYBUF(sav->key_auth), _KEYLEN(sav->key_auth));
2862 	MD5Final(sig, &ctx);
2863 
2864 	return (0);
2865 }
2866 #endif
2867 
2868 int
2869 tcp_dooptions(struct tcpcb *tp, u_char *cp, int cnt, struct tcphdr *th,
2870     struct mbuf *m, int toff, struct tcp_opt_info *oi)
2871 {
2872 	u_int16_t mss;
2873 	int opt, optlen = 0;
2874 #ifdef TCP_SIGNATURE
2875 	caddr_t sigp = NULL;
2876 	char sigbuf[TCP_SIGLEN];
2877 	struct secasvar *sav = NULL;
2878 #endif
2879 
2880 	for (; cp && cnt > 0; cnt -= optlen, cp += optlen) {
2881 		opt = cp[0];
2882 		if (opt == TCPOPT_EOL)
2883 			break;
2884 		if (opt == TCPOPT_NOP)
2885 			optlen = 1;
2886 		else {
2887 			if (cnt < 2)
2888 				break;
2889 			optlen = cp[1];
2890 			if (optlen < 2 || optlen > cnt)
2891 				break;
2892 		}
2893 		switch (opt) {
2894 
2895 		default:
2896 			continue;
2897 
2898 		case TCPOPT_MAXSEG:
2899 			if (optlen != TCPOLEN_MAXSEG)
2900 				continue;
2901 			if (!(th->th_flags & TH_SYN))
2902 				continue;
2903 			if (TCPS_HAVERCVDSYN(tp->t_state))
2904 				continue;
2905 			bcopy(cp + 2, &mss, sizeof(mss));
2906 			oi->maxseg = ntohs(mss);
2907 			break;
2908 
2909 		case TCPOPT_WINDOW:
2910 			if (optlen != TCPOLEN_WINDOW)
2911 				continue;
2912 			if (!(th->th_flags & TH_SYN))
2913 				continue;
2914 			if (TCPS_HAVERCVDSYN(tp->t_state))
2915 				continue;
2916 			tp->t_flags |= TF_RCVD_SCALE;
2917 			tp->requested_s_scale = cp[2];
2918 			if (tp->requested_s_scale > TCP_MAX_WINSHIFT) {
2919 #if 0	/*XXX*/
2920 				char *p;
2921 
2922 				if (ip)
2923 					p = ntohl(ip->ip_src);
2924 #ifdef INET6
2925 				else if (ip6)
2926 					p = ip6_sprintf(&ip6->ip6_src);
2927 #endif
2928 				else
2929 					p = "(unknown)";
2930 				log(LOG_ERR, "TCP: invalid wscale %d from %s, "
2931 				    "assuming %d\n",
2932 				    tp->requested_s_scale, p,
2933 				    TCP_MAX_WINSHIFT);
2934 #else
2935 				log(LOG_ERR, "TCP: invalid wscale %d, "
2936 				    "assuming %d\n",
2937 				    tp->requested_s_scale,
2938 				    TCP_MAX_WINSHIFT);
2939 #endif
2940 				tp->requested_s_scale = TCP_MAX_WINSHIFT;
2941 			}
2942 			break;
2943 
2944 		case TCPOPT_TIMESTAMP:
2945 			if (optlen != TCPOLEN_TIMESTAMP)
2946 				continue;
2947 			oi->ts_present = 1;
2948 			bcopy(cp + 2, &oi->ts_val, sizeof(oi->ts_val));
2949 			NTOHL(oi->ts_val);
2950 			bcopy(cp + 6, &oi->ts_ecr, sizeof(oi->ts_ecr));
2951 			NTOHL(oi->ts_ecr);
2952 
2953 			if (!(th->th_flags & TH_SYN))
2954 				continue;
2955 			if (TCPS_HAVERCVDSYN(tp->t_state))
2956 				continue;
2957 			/*
2958 			 * A timestamp received in a SYN makes
2959 			 * it ok to send timestamp requests and replies.
2960 			 */
2961 			tp->t_flags |= TF_RCVD_TSTMP;
2962 			tp->ts_recent = oi->ts_val;
2963 			tp->ts_recent_age = tcp_now;
2964                         break;
2965 
2966 		case TCPOPT_SACK_PERMITTED:
2967 			if (optlen != TCPOLEN_SACK_PERMITTED)
2968 				continue;
2969 			if (!(th->th_flags & TH_SYN))
2970 				continue;
2971 			if (TCPS_HAVERCVDSYN(tp->t_state))
2972 				continue;
2973 			if (tcp_do_sack) {
2974 				tp->t_flags |= TF_SACK_PERMIT;
2975 				tp->t_flags |= TF_WILL_SACK;
2976 			}
2977 			break;
2978 
2979 		case TCPOPT_SACK:
2980 			tcp_sack_option(tp, th, cp, optlen);
2981 			break;
2982 #ifdef TCP_SIGNATURE
2983 		case TCPOPT_SIGNATURE:
2984 			if (optlen != TCPOLEN_SIGNATURE)
2985 				continue;
2986 			if (sigp && bcmp(sigp, cp + 2, TCP_SIGLEN))
2987 				return (-1);
2988 
2989 			sigp = sigbuf;
2990 			memcpy(sigbuf, cp + 2, TCP_SIGLEN);
2991 			memset(cp + 2, 0, TCP_SIGLEN);
2992 			tp->t_flags |= TF_SIGNATURE;
2993 			break;
2994 #endif
2995 		}
2996 	}
2997 
2998 #ifdef TCP_SIGNATURE
2999 	if (tp->t_flags & TF_SIGNATURE) {
3000 
3001 		sav = tcp_signature_getsav(m, th);
3002 
3003 		if (sav == NULL && tp->t_state == TCPS_LISTEN)
3004 			return (-1);
3005 	}
3006 
3007 	if ((sigp ? TF_SIGNATURE : 0) ^ (tp->t_flags & TF_SIGNATURE)) {
3008 		if (sav == NULL)
3009 			return (-1);
3010 #ifdef FAST_IPSEC
3011 		KEY_FREESAV(&sav);
3012 #else
3013 		key_freesav(sav);
3014 #endif
3015 		return (-1);
3016 	}
3017 
3018 	if (sigp) {
3019 		char sig[TCP_SIGLEN];
3020 
3021 		TCP_FIELDS_TO_NET(th);
3022 		if (tcp_signature(m, th, toff, sav, sig) < 0) {
3023 			TCP_FIELDS_TO_HOST(th);
3024 			if (sav == NULL)
3025 				return (-1);
3026 #ifdef FAST_IPSEC
3027 			KEY_FREESAV(&sav);
3028 #else
3029 			key_freesav(sav);
3030 #endif
3031 			return (-1);
3032 		}
3033 		TCP_FIELDS_TO_HOST(th);
3034 
3035 		if (bcmp(sig, sigp, TCP_SIGLEN)) {
3036 			tcpstat.tcps_badsig++;
3037 			if (sav == NULL)
3038 				return (-1);
3039 #ifdef FAST_IPSEC
3040 			KEY_FREESAV(&sav);
3041 #else
3042 			key_freesav(sav);
3043 #endif
3044 			return (-1);
3045 		} else
3046 			tcpstat.tcps_goodsig++;
3047 
3048 		key_sa_recordxfer(sav, m);
3049 #ifdef FAST_IPSEC
3050 		KEY_FREESAV(&sav);
3051 #else
3052 		key_freesav(sav);
3053 #endif
3054 	}
3055 #endif
3056 
3057 	return (0);
3058 }
3059 
3060 /*
3061  * Pull out of band byte out of a segment so
3062  * it doesn't appear in the user's data queue.
3063  * It is still reflected in the segment length for
3064  * sequencing purposes.
3065  */
3066 void
3067 tcp_pulloutofband(struct socket *so, struct tcphdr *th,
3068     struct mbuf *m, int off)
3069 {
3070 	int cnt = off + th->th_urp - 1;
3071 
3072 	while (cnt >= 0) {
3073 		if (m->m_len > cnt) {
3074 			char *cp = mtod(m, caddr_t) + cnt;
3075 			struct tcpcb *tp = sototcpcb(so);
3076 
3077 			tp->t_iobc = *cp;
3078 			tp->t_oobflags |= TCPOOB_HAVEDATA;
3079 			bcopy(cp+1, cp, (unsigned)(m->m_len - cnt - 1));
3080 			m->m_len--;
3081 			return;
3082 		}
3083 		cnt -= m->m_len;
3084 		m = m->m_next;
3085 		if (m == 0)
3086 			break;
3087 	}
3088 	panic("tcp_pulloutofband");
3089 }
3090 
3091 /*
3092  * Collect new round-trip time estimate
3093  * and update averages and current timeout.
3094  */
3095 void
3096 tcp_xmit_timer(struct tcpcb *tp, uint32_t rtt)
3097 {
3098 	int32_t delta;
3099 
3100 	tcpstat.tcps_rttupdated++;
3101 	if (tp->t_srtt != 0) {
3102 		/*
3103 		 * srtt is stored as fixed point with 3 bits after the
3104 		 * binary point (i.e., scaled by 8).  The following magic
3105 		 * is equivalent to the smoothing algorithm in rfc793 with
3106 		 * an alpha of .875 (srtt = rtt/8 + srtt*7/8 in fixed
3107 		 * point).  Adjust rtt to origin 0.
3108 		 */
3109 		delta = (rtt << 2) - (tp->t_srtt >> TCP_RTT_SHIFT);
3110 		if ((tp->t_srtt += delta) <= 0)
3111 			tp->t_srtt = 1 << 2;
3112 		/*
3113 		 * We accumulate a smoothed rtt variance (actually, a
3114 		 * smoothed mean difference), then set the retransmit
3115 		 * timer to smoothed rtt + 4 times the smoothed variance.
3116 		 * rttvar is stored as fixed point with 2 bits after the
3117 		 * binary point (scaled by 4).  The following is
3118 		 * equivalent to rfc793 smoothing with an alpha of .75
3119 		 * (rttvar = rttvar*3/4 + |delta| / 4).  This replaces
3120 		 * rfc793's wired-in beta.
3121 		 */
3122 		if (delta < 0)
3123 			delta = -delta;
3124 		delta -= (tp->t_rttvar >> TCP_RTTVAR_SHIFT);
3125 		if ((tp->t_rttvar += delta) <= 0)
3126 			tp->t_rttvar = 1 << 2;
3127 	} else {
3128 		/*
3129 		 * No rtt measurement yet - use the unsmoothed rtt.
3130 		 * Set the variance to half the rtt (so our first
3131 		 * retransmit happens at 3*rtt).
3132 		 */
3133 		tp->t_srtt = rtt << (TCP_RTT_SHIFT + 2);
3134 		tp->t_rttvar = rtt << (TCP_RTTVAR_SHIFT + 2 - 1);
3135 	}
3136 	tp->t_rtttime = 0;
3137 	tp->t_rxtshift = 0;
3138 
3139 	/*
3140 	 * the retransmit should happen at rtt + 4 * rttvar.
3141 	 * Because of the way we do the smoothing, srtt and rttvar
3142 	 * will each average +1/2 tick of bias.  When we compute
3143 	 * the retransmit timer, we want 1/2 tick of rounding and
3144 	 * 1 extra tick because of +-1/2 tick uncertainty in the
3145 	 * firing of the timer.  The bias will give us exactly the
3146 	 * 1.5 tick we need.  But, because the bias is
3147 	 * statistical, we have to test that we don't drop below
3148 	 * the minimum feasible timer (which is 2 ticks).
3149 	 */
3150 	TCPT_RANGESET(tp->t_rxtcur, TCP_REXMTVAL(tp),
3151 	    max(tp->t_rttmin, rtt + 2), TCPTV_REXMTMAX);
3152 
3153 	/*
3154 	 * We received an ack for a packet that wasn't retransmitted;
3155 	 * it is probably safe to discard any error indications we've
3156 	 * received recently.  This isn't quite right, but close enough
3157 	 * for now (a route might have failed after we sent a segment,
3158 	 * and the return path might not be symmetrical).
3159 	 */
3160 	tp->t_softerror = 0;
3161 }
3162 
3163 void
3164 tcp_reno_newack(struct tcpcb *tp, struct tcphdr *th)
3165 {
3166 	if (tp->t_partialacks < 0) {
3167 		/*
3168 		 * We were not in fast recovery.  Reset the duplicate ack
3169 		 * counter.
3170 		 */
3171 		tp->t_dupacks = 0;
3172 	} else {
3173 		/*
3174 		 * Clamp the congestion window to the crossover point and
3175 		 * exit fast recovery.
3176 		 */
3177 		if (tp->snd_cwnd > tp->snd_ssthresh)
3178 			tp->snd_cwnd = tp->snd_ssthresh;
3179 		tp->t_partialacks = -1;
3180 		tp->t_dupacks = 0;
3181 	}
3182 }
3183 
3184 /*
3185  * Implement the NewReno response to a new ack, checking for partial acks in
3186  * fast recovery.
3187  */
3188 void
3189 tcp_newreno_newack(struct tcpcb *tp, struct tcphdr *th)
3190 {
3191 	if (tp->t_partialacks < 0) {
3192 		/*
3193 		 * We were not in fast recovery.  Reset the duplicate ack
3194 		 * counter.
3195 		 */
3196 		tp->t_dupacks = 0;
3197 	} else if (SEQ_LT(th->th_ack, tp->snd_recover)) {
3198 		/*
3199 		 * This is a partial ack.  Retransmit the first unacknowledged
3200 		 * segment and deflate the congestion window by the amount of
3201 		 * acknowledged data.  Do not exit fast recovery.
3202 		 */
3203 		tcp_seq onxt = tp->snd_nxt;
3204 		u_long ocwnd = tp->snd_cwnd;
3205 
3206 		/*
3207 		 * snd_una has not yet been updated and the socket's send
3208 		 * buffer has not yet drained off the ACK'd data, so we
3209 		 * have to leave snd_una as it was to get the correct data
3210 		 * offset in tcp_output().
3211 		 */
3212 		if (++tp->t_partialacks == 1)
3213 			TCP_TIMER_DISARM(tp, TCPT_REXMT);
3214 		tp->t_rtttime = 0;
3215 		tp->snd_nxt = th->th_ack;
3216 		/*
3217 		 * Set snd_cwnd to one segment beyond ACK'd offset.  snd_una
3218 		 * is not yet updated when we're called.
3219 		 */
3220 		tp->snd_cwnd = tp->t_segsz + (th->th_ack - tp->snd_una);
3221 		(void) tcp_output(tp);
3222 		tp->snd_cwnd = ocwnd;
3223 		if (SEQ_GT(onxt, tp->snd_nxt))
3224 			tp->snd_nxt = onxt;
3225 		/*
3226 		 * Partial window deflation.  Relies on fact that tp->snd_una
3227 		 * not updated yet.
3228 		 */
3229 		tp->snd_cwnd -= (th->th_ack - tp->snd_una - tp->t_segsz);
3230 	} else {
3231 		/*
3232 		 * Complete ack.  Inflate the congestion window to ssthresh
3233 		 * and exit fast recovery.
3234 		 *
3235 		 * Window inflation should have left us with approx.
3236 		 * snd_ssthresh outstanding data.  But in case we
3237 		 * would be inclined to send a burst, better to do
3238 		 * it via the slow start mechanism.
3239 		 */
3240 		if (SEQ_SUB(tp->snd_max, th->th_ack) < tp->snd_ssthresh)
3241 			tp->snd_cwnd = SEQ_SUB(tp->snd_max, th->th_ack)
3242 			    + tp->t_segsz;
3243 		else
3244 			tp->snd_cwnd = tp->snd_ssthresh;
3245 		tp->t_partialacks = -1;
3246 		tp->t_dupacks = 0;
3247 	}
3248 }
3249 
3250 
3251 /*
3252  * TCP compressed state engine.  Currently used to hold compressed
3253  * state for SYN_RECEIVED.
3254  */
3255 
3256 u_long	syn_cache_count;
3257 u_int32_t syn_hash1, syn_hash2;
3258 
3259 #define SYN_HASH(sa, sp, dp) \
3260 	((((sa)->s_addr^syn_hash1)*(((((u_int32_t)(dp))<<16) + \
3261 				     ((u_int32_t)(sp)))^syn_hash2)))
3262 #ifndef INET6
3263 #define	SYN_HASHALL(hash, src, dst) \
3264 do {									\
3265 	hash = SYN_HASH(&((const struct sockaddr_in *)(src))->sin_addr,	\
3266 		((const struct sockaddr_in *)(src))->sin_port,		\
3267 		((const struct sockaddr_in *)(dst))->sin_port);		\
3268 } while (/*CONSTCOND*/ 0)
3269 #else
3270 #define SYN_HASH6(sa, sp, dp) \
3271 	((((sa)->s6_addr32[0] ^ (sa)->s6_addr32[3] ^ syn_hash1) * \
3272 	  (((((u_int32_t)(dp))<<16) + ((u_int32_t)(sp)))^syn_hash2)) \
3273 	 & 0x7fffffff)
3274 
3275 #define SYN_HASHALL(hash, src, dst) \
3276 do {									\
3277 	switch ((src)->sa_family) {					\
3278 	case AF_INET:							\
3279 		hash = SYN_HASH(&((const struct sockaddr_in *)(src))->sin_addr, \
3280 			((const struct sockaddr_in *)(src))->sin_port,	\
3281 			((const struct sockaddr_in *)(dst))->sin_port);	\
3282 		break;							\
3283 	case AF_INET6:							\
3284 		hash = SYN_HASH6(&((const struct sockaddr_in6 *)(src))->sin6_addr, \
3285 			((const struct sockaddr_in6 *)(src))->sin6_port,	\
3286 			((const struct sockaddr_in6 *)(dst))->sin6_port);	\
3287 		break;							\
3288 	default:							\
3289 		hash = 0;						\
3290 	}								\
3291 } while (/*CONSTCOND*/0)
3292 #endif /* INET6 */
3293 
3294 #define	SYN_CACHE_RM(sc)						\
3295 do {									\
3296 	TAILQ_REMOVE(&tcp_syn_cache[(sc)->sc_bucketidx].sch_bucket,	\
3297 	    (sc), sc_bucketq);						\
3298 	(sc)->sc_tp = NULL;						\
3299 	LIST_REMOVE((sc), sc_tpq);					\
3300 	tcp_syn_cache[(sc)->sc_bucketidx].sch_length--;			\
3301 	callout_stop(&(sc)->sc_timer);					\
3302 	syn_cache_count--;						\
3303 } while (/*CONSTCOND*/0)
3304 
3305 #define	SYN_CACHE_PUT(sc)						\
3306 do {									\
3307 	if ((sc)->sc_ipopts)						\
3308 		(void) m_free((sc)->sc_ipopts);				\
3309 	if ((sc)->sc_route4.ro_rt != NULL)				\
3310 		RTFREE((sc)->sc_route4.ro_rt);				\
3311 	if (callout_invoking(&(sc)->sc_timer))				\
3312 		(sc)->sc_flags |= SCF_DEAD;				\
3313 	else								\
3314 		pool_put(&syn_cache_pool, (sc));			\
3315 } while (/*CONSTCOND*/0)
3316 
3317 POOL_INIT(syn_cache_pool, sizeof(struct syn_cache), 0, 0, 0, "synpl", NULL);
3318 
3319 /*
3320  * We don't estimate RTT with SYNs, so each packet starts with the default
3321  * RTT and each timer step has a fixed timeout value.
3322  */
3323 #define	SYN_CACHE_TIMER_ARM(sc)						\
3324 do {									\
3325 	TCPT_RANGESET((sc)->sc_rxtcur,					\
3326 	    TCPTV_SRTTDFLT * tcp_backoff[(sc)->sc_rxtshift], TCPTV_MIN,	\
3327 	    TCPTV_REXMTMAX);						\
3328 	callout_reset(&(sc)->sc_timer,					\
3329 	    (sc)->sc_rxtcur * (hz / PR_SLOWHZ), syn_cache_timer, (sc));	\
3330 } while (/*CONSTCOND*/0)
3331 
3332 #define	SYN_CACHE_TIMESTAMP(sc)	(tcp_now - (sc)->sc_timebase)
3333 
3334 void
3335 syn_cache_init(void)
3336 {
3337 	int i;
3338 
3339 	/* Initialize the hash buckets. */
3340 	for (i = 0; i < tcp_syn_cache_size; i++)
3341 		TAILQ_INIT(&tcp_syn_cache[i].sch_bucket);
3342 }
3343 
3344 void
3345 syn_cache_insert(struct syn_cache *sc, struct tcpcb *tp)
3346 {
3347 	struct syn_cache_head *scp;
3348 	struct syn_cache *sc2;
3349 	int s;
3350 
3351 	/*
3352 	 * If there are no entries in the hash table, reinitialize
3353 	 * the hash secrets.
3354 	 */
3355 	if (syn_cache_count == 0) {
3356 		syn_hash1 = arc4random();
3357 		syn_hash2 = arc4random();
3358 	}
3359 
3360 	SYN_HASHALL(sc->sc_hash, &sc->sc_src.sa, &sc->sc_dst.sa);
3361 	sc->sc_bucketidx = sc->sc_hash % tcp_syn_cache_size;
3362 	scp = &tcp_syn_cache[sc->sc_bucketidx];
3363 
3364 	/*
3365 	 * Make sure that we don't overflow the per-bucket
3366 	 * limit or the total cache size limit.
3367 	 */
3368 	s = splsoftnet();
3369 	if (scp->sch_length >= tcp_syn_bucket_limit) {
3370 		tcpstat.tcps_sc_bucketoverflow++;
3371 		/*
3372 		 * The bucket is full.  Toss the oldest element in the
3373 		 * bucket.  This will be the first entry in the bucket.
3374 		 */
3375 		sc2 = TAILQ_FIRST(&scp->sch_bucket);
3376 #ifdef DIAGNOSTIC
3377 		/*
3378 		 * This should never happen; we should always find an
3379 		 * entry in our bucket.
3380 		 */
3381 		if (sc2 == NULL)
3382 			panic("syn_cache_insert: bucketoverflow: impossible");
3383 #endif
3384 		SYN_CACHE_RM(sc2);
3385 		SYN_CACHE_PUT(sc2);
3386 	} else if (syn_cache_count >= tcp_syn_cache_limit) {
3387 		struct syn_cache_head *scp2, *sce;
3388 
3389 		tcpstat.tcps_sc_overflowed++;
3390 		/*
3391 		 * The cache is full.  Toss the oldest entry in the
3392 		 * first non-empty bucket we can find.
3393 		 *
3394 		 * XXX We would really like to toss the oldest
3395 		 * entry in the cache, but we hope that this
3396 		 * condition doesn't happen very often.
3397 		 */
3398 		scp2 = scp;
3399 		if (TAILQ_EMPTY(&scp2->sch_bucket)) {
3400 			sce = &tcp_syn_cache[tcp_syn_cache_size];
3401 			for (++scp2; scp2 != scp; scp2++) {
3402 				if (scp2 >= sce)
3403 					scp2 = &tcp_syn_cache[0];
3404 				if (! TAILQ_EMPTY(&scp2->sch_bucket))
3405 					break;
3406 			}
3407 #ifdef DIAGNOSTIC
3408 			/*
3409 			 * This should never happen; we should always find a
3410 			 * non-empty bucket.
3411 			 */
3412 			if (scp2 == scp)
3413 				panic("syn_cache_insert: cacheoverflow: "
3414 				    "impossible");
3415 #endif
3416 		}
3417 		sc2 = TAILQ_FIRST(&scp2->sch_bucket);
3418 		SYN_CACHE_RM(sc2);
3419 		SYN_CACHE_PUT(sc2);
3420 	}
3421 
3422 	/*
3423 	 * Initialize the entry's timer.
3424 	 */
3425 	sc->sc_rxttot = 0;
3426 	sc->sc_rxtshift = 0;
3427 	SYN_CACHE_TIMER_ARM(sc);
3428 
3429 	/* Link it from tcpcb entry */
3430 	LIST_INSERT_HEAD(&tp->t_sc, sc, sc_tpq);
3431 
3432 	/* Put it into the bucket. */
3433 	TAILQ_INSERT_TAIL(&scp->sch_bucket, sc, sc_bucketq);
3434 	scp->sch_length++;
3435 	syn_cache_count++;
3436 
3437 	tcpstat.tcps_sc_added++;
3438 	splx(s);
3439 }
3440 
3441 /*
3442  * Walk the timer queues, looking for SYN,ACKs that need to be retransmitted.
3443  * If we have retransmitted an entry the maximum number of times, expire
3444  * that entry.
3445  */
3446 void
3447 syn_cache_timer(void *arg)
3448 {
3449 	struct syn_cache *sc = arg;
3450 	int s;
3451 
3452 	s = splsoftnet();
3453 	callout_ack(&sc->sc_timer);
3454 
3455 	if (__predict_false(sc->sc_flags & SCF_DEAD)) {
3456 		tcpstat.tcps_sc_delayed_free++;
3457 		pool_put(&syn_cache_pool, sc);
3458 		splx(s);
3459 		return;
3460 	}
3461 
3462 	if (__predict_false(sc->sc_rxtshift == TCP_MAXRXTSHIFT)) {
3463 		/* Drop it -- too many retransmissions. */
3464 		goto dropit;
3465 	}
3466 
3467 	/*
3468 	 * Compute the total amount of time this entry has
3469 	 * been on a queue.  If this entry has been on longer
3470 	 * than the keep alive timer would allow, expire it.
3471 	 */
3472 	sc->sc_rxttot += sc->sc_rxtcur;
3473 	if (sc->sc_rxttot >= TCPTV_KEEP_INIT)
3474 		goto dropit;
3475 
3476 	tcpstat.tcps_sc_retransmitted++;
3477 	(void) syn_cache_respond(sc, NULL);
3478 
3479 	/* Advance the timer back-off. */
3480 	sc->sc_rxtshift++;
3481 	SYN_CACHE_TIMER_ARM(sc);
3482 
3483 	splx(s);
3484 	return;
3485 
3486  dropit:
3487 	tcpstat.tcps_sc_timed_out++;
3488 	SYN_CACHE_RM(sc);
3489 	SYN_CACHE_PUT(sc);
3490 	splx(s);
3491 }
3492 
3493 /*
3494  * Remove syn cache created by the specified tcb entry,
3495  * because this does not make sense to keep them
3496  * (if there's no tcb entry, syn cache entry will never be used)
3497  */
3498 void
3499 syn_cache_cleanup(struct tcpcb *tp)
3500 {
3501 	struct syn_cache *sc, *nsc;
3502 	int s;
3503 
3504 	s = splsoftnet();
3505 
3506 	for (sc = LIST_FIRST(&tp->t_sc); sc != NULL; sc = nsc) {
3507 		nsc = LIST_NEXT(sc, sc_tpq);
3508 
3509 #ifdef DIAGNOSTIC
3510 		if (sc->sc_tp != tp)
3511 			panic("invalid sc_tp in syn_cache_cleanup");
3512 #endif
3513 		SYN_CACHE_RM(sc);
3514 		SYN_CACHE_PUT(sc);
3515 	}
3516 	/* just for safety */
3517 	LIST_INIT(&tp->t_sc);
3518 
3519 	splx(s);
3520 }
3521 
3522 /*
3523  * Find an entry in the syn cache.
3524  */
3525 struct syn_cache *
3526 syn_cache_lookup(const struct sockaddr *src, const struct sockaddr *dst,
3527     struct syn_cache_head **headp)
3528 {
3529 	struct syn_cache *sc;
3530 	struct syn_cache_head *scp;
3531 	u_int32_t hash;
3532 	int s;
3533 
3534 	SYN_HASHALL(hash, src, dst);
3535 
3536 	scp = &tcp_syn_cache[hash % tcp_syn_cache_size];
3537 	*headp = scp;
3538 	s = splsoftnet();
3539 	for (sc = TAILQ_FIRST(&scp->sch_bucket); sc != NULL;
3540 	     sc = TAILQ_NEXT(sc, sc_bucketq)) {
3541 		if (sc->sc_hash != hash)
3542 			continue;
3543 		if (!bcmp(&sc->sc_src, src, src->sa_len) &&
3544 		    !bcmp(&sc->sc_dst, dst, dst->sa_len)) {
3545 			splx(s);
3546 			return (sc);
3547 		}
3548 	}
3549 	splx(s);
3550 	return (NULL);
3551 }
3552 
3553 /*
3554  * This function gets called when we receive an ACK for a
3555  * socket in the LISTEN state.  We look up the connection
3556  * in the syn cache, and if its there, we pull it out of
3557  * the cache and turn it into a full-blown connection in
3558  * the SYN-RECEIVED state.
3559  *
3560  * The return values may not be immediately obvious, and their effects
3561  * can be subtle, so here they are:
3562  *
3563  *	NULL	SYN was not found in cache; caller should drop the
3564  *		packet and send an RST.
3565  *
3566  *	-1	We were unable to create the new connection, and are
3567  *		aborting it.  An ACK,RST is being sent to the peer
3568  *		(unless we got screwey sequence numbners; see below),
3569  *		because the 3-way handshake has been completed.  Caller
3570  *		should not free the mbuf, since we may be using it.  If
3571  *		we are not, we will free it.
3572  *
3573  *	Otherwise, the return value is a pointer to the new socket
3574  *	associated with the connection.
3575  */
3576 struct socket *
3577 syn_cache_get(struct sockaddr *src, struct sockaddr *dst,
3578     struct tcphdr *th, unsigned int hlen, unsigned int tlen,
3579     struct socket *so, struct mbuf *m)
3580 {
3581 	struct syn_cache *sc;
3582 	struct syn_cache_head *scp;
3583 	struct inpcb *inp = NULL;
3584 #ifdef INET6
3585 	struct in6pcb *in6p = NULL;
3586 #endif
3587 	struct tcpcb *tp = 0;
3588 	struct mbuf *am;
3589 	int s;
3590 	struct socket *oso;
3591 
3592 	s = splsoftnet();
3593 	if ((sc = syn_cache_lookup(src, dst, &scp)) == NULL) {
3594 		splx(s);
3595 		return (NULL);
3596 	}
3597 
3598 	/*
3599 	 * Verify the sequence and ack numbers.  Try getting the correct
3600 	 * response again.
3601 	 */
3602 	if ((th->th_ack != sc->sc_iss + 1) ||
3603 	    SEQ_LEQ(th->th_seq, sc->sc_irs) ||
3604 	    SEQ_GT(th->th_seq, sc->sc_irs + 1 + sc->sc_win)) {
3605 		(void) syn_cache_respond(sc, m);
3606 		splx(s);
3607 		return ((struct socket *)(-1));
3608 	}
3609 
3610 	/* Remove this cache entry */
3611 	SYN_CACHE_RM(sc);
3612 	splx(s);
3613 
3614 	/*
3615 	 * Ok, create the full blown connection, and set things up
3616 	 * as they would have been set up if we had created the
3617 	 * connection when the SYN arrived.  If we can't create
3618 	 * the connection, abort it.
3619 	 */
3620 	/*
3621 	 * inp still has the OLD in_pcb stuff, set the
3622 	 * v6-related flags on the new guy, too.   This is
3623 	 * done particularly for the case where an AF_INET6
3624 	 * socket is bound only to a port, and a v4 connection
3625 	 * comes in on that port.
3626 	 * we also copy the flowinfo from the original pcb
3627 	 * to the new one.
3628 	 */
3629 	oso = so;
3630 	so = sonewconn(so, SS_ISCONNECTED);
3631 	if (so == NULL)
3632 		goto resetandabort;
3633 
3634 	switch (so->so_proto->pr_domain->dom_family) {
3635 #ifdef INET
3636 	case AF_INET:
3637 		inp = sotoinpcb(so);
3638 		break;
3639 #endif
3640 #ifdef INET6
3641 	case AF_INET6:
3642 		in6p = sotoin6pcb(so);
3643 		break;
3644 #endif
3645 	}
3646 	switch (src->sa_family) {
3647 #ifdef INET
3648 	case AF_INET:
3649 		if (inp) {
3650 			inp->inp_laddr = ((struct sockaddr_in *)dst)->sin_addr;
3651 			inp->inp_lport = ((struct sockaddr_in *)dst)->sin_port;
3652 			inp->inp_options = ip_srcroute();
3653 			in_pcbstate(inp, INP_BOUND);
3654 			if (inp->inp_options == NULL) {
3655 				inp->inp_options = sc->sc_ipopts;
3656 				sc->sc_ipopts = NULL;
3657 			}
3658 		}
3659 #ifdef INET6
3660 		else if (in6p) {
3661 			/* IPv4 packet to AF_INET6 socket */
3662 			bzero(&in6p->in6p_laddr, sizeof(in6p->in6p_laddr));
3663 			in6p->in6p_laddr.s6_addr16[5] = htons(0xffff);
3664 			bcopy(&((struct sockaddr_in *)dst)->sin_addr,
3665 				&in6p->in6p_laddr.s6_addr32[3],
3666 				sizeof(((struct sockaddr_in *)dst)->sin_addr));
3667 			in6p->in6p_lport = ((struct sockaddr_in *)dst)->sin_port;
3668 			in6totcpcb(in6p)->t_family = AF_INET;
3669 			if (sotoin6pcb(oso)->in6p_flags & IN6P_IPV6_V6ONLY)
3670 				in6p->in6p_flags |= IN6P_IPV6_V6ONLY;
3671 			else
3672 				in6p->in6p_flags &= ~IN6P_IPV6_V6ONLY;
3673 			in6_pcbstate(in6p, IN6P_BOUND);
3674 		}
3675 #endif
3676 		break;
3677 #endif
3678 #ifdef INET6
3679 	case AF_INET6:
3680 		if (in6p) {
3681 			in6p->in6p_laddr = ((struct sockaddr_in6 *)dst)->sin6_addr;
3682 			in6p->in6p_lport = ((struct sockaddr_in6 *)dst)->sin6_port;
3683 			in6_pcbstate(in6p, IN6P_BOUND);
3684 		}
3685 		break;
3686 #endif
3687 	}
3688 #ifdef INET6
3689 	if (in6p && in6totcpcb(in6p)->t_family == AF_INET6 && sotoinpcb(oso)) {
3690 		struct in6pcb *oin6p = sotoin6pcb(oso);
3691 		/* inherit socket options from the listening socket */
3692 		in6p->in6p_flags |= (oin6p->in6p_flags & IN6P_CONTROLOPTS);
3693 		if (in6p->in6p_flags & IN6P_CONTROLOPTS) {
3694 			m_freem(in6p->in6p_options);
3695 			in6p->in6p_options = 0;
3696 		}
3697 		ip6_savecontrol(in6p, &in6p->in6p_options,
3698 			mtod(m, struct ip6_hdr *), m);
3699 	}
3700 #endif
3701 
3702 #if defined(IPSEC) || defined(FAST_IPSEC)
3703 	/*
3704 	 * we make a copy of policy, instead of sharing the policy,
3705 	 * for better behavior in terms of SA lookup and dead SA removal.
3706 	 */
3707 	if (inp) {
3708 		/* copy old policy into new socket's */
3709 		if (ipsec_copy_pcbpolicy(sotoinpcb(oso)->inp_sp, inp->inp_sp))
3710 			printf("tcp_input: could not copy policy\n");
3711 	}
3712 #ifdef INET6
3713 	else if (in6p) {
3714 		/* copy old policy into new socket's */
3715 		if (ipsec_copy_pcbpolicy(sotoin6pcb(oso)->in6p_sp,
3716 		    in6p->in6p_sp))
3717 			printf("tcp_input: could not copy policy\n");
3718 	}
3719 #endif
3720 #endif
3721 
3722 	/*
3723 	 * Give the new socket our cached route reference.
3724 	 */
3725 	if (inp)
3726 		inp->inp_route = sc->sc_route4;		/* struct assignment */
3727 #ifdef INET6
3728 	else
3729 		in6p->in6p_route = sc->sc_route6;
3730 #endif
3731 	sc->sc_route4.ro_rt = NULL;
3732 
3733 	am = m_get(M_DONTWAIT, MT_SONAME);	/* XXX */
3734 	if (am == NULL)
3735 		goto resetandabort;
3736 	MCLAIM(am, &tcp_mowner);
3737 	am->m_len = src->sa_len;
3738 	bcopy(src, mtod(am, caddr_t), src->sa_len);
3739 	if (inp) {
3740 		if (in_pcbconnect(inp, am, NULL)) {
3741 			(void) m_free(am);
3742 			goto resetandabort;
3743 		}
3744 	}
3745 #ifdef INET6
3746 	else if (in6p) {
3747 		if (src->sa_family == AF_INET) {
3748 			/* IPv4 packet to AF_INET6 socket */
3749 			struct sockaddr_in6 *sin6;
3750 			sin6 = mtod(am, struct sockaddr_in6 *);
3751 			am->m_len = sizeof(*sin6);
3752 			bzero(sin6, sizeof(*sin6));
3753 			sin6->sin6_family = AF_INET6;
3754 			sin6->sin6_len = sizeof(*sin6);
3755 			sin6->sin6_port = ((struct sockaddr_in *)src)->sin_port;
3756 			sin6->sin6_addr.s6_addr16[5] = htons(0xffff);
3757 			bcopy(&((struct sockaddr_in *)src)->sin_addr,
3758 				&sin6->sin6_addr.s6_addr32[3],
3759 				sizeof(sin6->sin6_addr.s6_addr32[3]));
3760 		}
3761 		if (in6_pcbconnect(in6p, am, NULL)) {
3762 			(void) m_free(am);
3763 			goto resetandabort;
3764 		}
3765 	}
3766 #endif
3767 	else {
3768 		(void) m_free(am);
3769 		goto resetandabort;
3770 	}
3771 	(void) m_free(am);
3772 
3773 	if (inp)
3774 		tp = intotcpcb(inp);
3775 #ifdef INET6
3776 	else if (in6p)
3777 		tp = in6totcpcb(in6p);
3778 #endif
3779 	else
3780 		tp = NULL;
3781 	tp->t_flags = sototcpcb(oso)->t_flags & TF_NODELAY;
3782 	if (sc->sc_request_r_scale != 15) {
3783 		tp->requested_s_scale = sc->sc_requested_s_scale;
3784 		tp->request_r_scale = sc->sc_request_r_scale;
3785 		tp->snd_scale = sc->sc_requested_s_scale;
3786 		tp->rcv_scale = sc->sc_request_r_scale;
3787 		tp->t_flags |= TF_REQ_SCALE|TF_RCVD_SCALE;
3788 	}
3789 	if (sc->sc_flags & SCF_TIMESTAMP)
3790 		tp->t_flags |= TF_REQ_TSTMP|TF_RCVD_TSTMP;
3791 	tp->ts_timebase = sc->sc_timebase;
3792 
3793 	tp->t_template = tcp_template(tp);
3794 	if (tp->t_template == 0) {
3795 		tp = tcp_drop(tp, ENOBUFS);	/* destroys socket */
3796 		so = NULL;
3797 		m_freem(m);
3798 		goto abort;
3799 	}
3800 
3801 	tp->iss = sc->sc_iss;
3802 	tp->irs = sc->sc_irs;
3803 	tcp_sendseqinit(tp);
3804 	tcp_rcvseqinit(tp);
3805 	tp->t_state = TCPS_SYN_RECEIVED;
3806 	TCP_TIMER_ARM(tp, TCPT_KEEP, TCPTV_KEEP_INIT);
3807 	tcpstat.tcps_accepts++;
3808 
3809 	if ((sc->sc_flags & SCF_SACK_PERMIT) && tcp_do_sack)
3810 		tp->t_flags |= TF_WILL_SACK;
3811 
3812 #ifdef TCP_SIGNATURE
3813 	if (sc->sc_flags & SCF_SIGNATURE)
3814 		tp->t_flags |= TF_SIGNATURE;
3815 #endif
3816 
3817 	/* Initialize tp->t_ourmss before we deal with the peer's! */
3818 	tp->t_ourmss = sc->sc_ourmaxseg;
3819 	tcp_mss_from_peer(tp, sc->sc_peermaxseg);
3820 
3821 	/*
3822 	 * Initialize the initial congestion window.  If we
3823 	 * had to retransmit the SYN,ACK, we must initialize cwnd
3824 	 * to 1 segment (i.e. the Loss Window).
3825 	 */
3826 	if (sc->sc_rxtshift)
3827 		tp->snd_cwnd = tp->t_peermss;
3828 	else {
3829 		int ss = tcp_init_win;
3830 #ifdef INET
3831 		if (inp != NULL && in_localaddr(inp->inp_faddr))
3832 			ss = tcp_init_win_local;
3833 #endif
3834 #ifdef INET6
3835 		if (in6p != NULL && in6_localaddr(&in6p->in6p_faddr))
3836 			ss = tcp_init_win_local;
3837 #endif
3838 		tp->snd_cwnd = TCP_INITIAL_WINDOW(ss, tp->t_peermss);
3839 	}
3840 
3841 	tcp_rmx_rtt(tp);
3842 	tp->snd_wl1 = sc->sc_irs;
3843 	tp->rcv_up = sc->sc_irs + 1;
3844 
3845 	/*
3846 	 * This is what whould have happened in tcp_output() when
3847 	 * the SYN,ACK was sent.
3848 	 */
3849 	tp->snd_up = tp->snd_una;
3850 	tp->snd_max = tp->snd_nxt = tp->iss+1;
3851 	TCP_TIMER_ARM(tp, TCPT_REXMT, tp->t_rxtcur);
3852 	if (sc->sc_win > 0 && SEQ_GT(tp->rcv_nxt + sc->sc_win, tp->rcv_adv))
3853 		tp->rcv_adv = tp->rcv_nxt + sc->sc_win;
3854 	tp->last_ack_sent = tp->rcv_nxt;
3855 	tp->t_partialacks = -1;
3856 	tp->t_dupacks = 0;
3857 
3858 	tcpstat.tcps_sc_completed++;
3859 	SYN_CACHE_PUT(sc);
3860 	return (so);
3861 
3862 resetandabort:
3863 	(void)tcp_respond(NULL, m, m, th, (tcp_seq)0, th->th_ack, TH_RST);
3864 abort:
3865 	if (so != NULL)
3866 		(void) soabort(so);
3867 	SYN_CACHE_PUT(sc);
3868 	tcpstat.tcps_sc_aborted++;
3869 	return ((struct socket *)(-1));
3870 }
3871 
3872 /*
3873  * This function is called when we get a RST for a
3874  * non-existent connection, so that we can see if the
3875  * connection is in the syn cache.  If it is, zap it.
3876  */
3877 
3878 void
3879 syn_cache_reset(struct sockaddr *src, struct sockaddr *dst, struct tcphdr *th)
3880 {
3881 	struct syn_cache *sc;
3882 	struct syn_cache_head *scp;
3883 	int s = splsoftnet();
3884 
3885 	if ((sc = syn_cache_lookup(src, dst, &scp)) == NULL) {
3886 		splx(s);
3887 		return;
3888 	}
3889 	if (SEQ_LT(th->th_seq, sc->sc_irs) ||
3890 	    SEQ_GT(th->th_seq, sc->sc_irs+1)) {
3891 		splx(s);
3892 		return;
3893 	}
3894 	SYN_CACHE_RM(sc);
3895 	splx(s);
3896 	tcpstat.tcps_sc_reset++;
3897 	SYN_CACHE_PUT(sc);
3898 }
3899 
3900 void
3901 syn_cache_unreach(const struct sockaddr *src, const struct sockaddr *dst,
3902     struct tcphdr *th)
3903 {
3904 	struct syn_cache *sc;
3905 	struct syn_cache_head *scp;
3906 	int s;
3907 
3908 	s = splsoftnet();
3909 	if ((sc = syn_cache_lookup(src, dst, &scp)) == NULL) {
3910 		splx(s);
3911 		return;
3912 	}
3913 	/* If the sequence number != sc_iss, then it's a bogus ICMP msg */
3914 	if (ntohl (th->th_seq) != sc->sc_iss) {
3915 		splx(s);
3916 		return;
3917 	}
3918 
3919 	/*
3920 	 * If we've retransmitted 3 times and this is our second error,
3921 	 * we remove the entry.  Otherwise, we allow it to continue on.
3922 	 * This prevents us from incorrectly nuking an entry during a
3923 	 * spurious network outage.
3924 	 *
3925 	 * See tcp_notify().
3926 	 */
3927 	if ((sc->sc_flags & SCF_UNREACH) == 0 || sc->sc_rxtshift < 3) {
3928 		sc->sc_flags |= SCF_UNREACH;
3929 		splx(s);
3930 		return;
3931 	}
3932 
3933 	SYN_CACHE_RM(sc);
3934 	splx(s);
3935 	tcpstat.tcps_sc_unreach++;
3936 	SYN_CACHE_PUT(sc);
3937 }
3938 
3939 /*
3940  * Given a LISTEN socket and an inbound SYN request, add
3941  * this to the syn cache, and send back a segment:
3942  *	<SEQ=ISS><ACK=RCV_NXT><CTL=SYN,ACK>
3943  * to the source.
3944  *
3945  * IMPORTANT NOTE: We do _NOT_ ACK data that might accompany the SYN.
3946  * Doing so would require that we hold onto the data and deliver it
3947  * to the application.  However, if we are the target of a SYN-flood
3948  * DoS attack, an attacker could send data which would eventually
3949  * consume all available buffer space if it were ACKed.  By not ACKing
3950  * the data, we avoid this DoS scenario.
3951  */
3952 
3953 int
3954 syn_cache_add(struct sockaddr *src, struct sockaddr *dst, struct tcphdr *th,
3955     unsigned int hlen, struct socket *so, struct mbuf *m, u_char *optp,
3956     int optlen, struct tcp_opt_info *oi)
3957 {
3958 	struct tcpcb tb, *tp;
3959 	long win;
3960 	struct syn_cache *sc;
3961 	struct syn_cache_head *scp;
3962 	struct mbuf *ipopts;
3963 	struct tcp_opt_info opti;
3964 
3965 	tp = sototcpcb(so);
3966 
3967 	bzero(&opti, sizeof(opti));
3968 
3969 	/*
3970 	 * RFC1122 4.2.3.10, p. 104: discard bcast/mcast SYN
3971 	 *
3972 	 * Note this check is performed in tcp_input() very early on.
3973 	 */
3974 
3975 	/*
3976 	 * Initialize some local state.
3977 	 */
3978 	win = sbspace(&so->so_rcv);
3979 	if (win > TCP_MAXWIN)
3980 		win = TCP_MAXWIN;
3981 
3982 	switch (src->sa_family) {
3983 #ifdef INET
3984 	case AF_INET:
3985 		/*
3986 		 * Remember the IP options, if any.
3987 		 */
3988 		ipopts = ip_srcroute();
3989 		break;
3990 #endif
3991 	default:
3992 		ipopts = NULL;
3993 	}
3994 
3995 #ifdef TCP_SIGNATURE
3996 	if (optp || (tp->t_flags & TF_SIGNATURE))
3997 #else
3998 	if (optp)
3999 #endif
4000 	{
4001 		tb.t_flags = tcp_do_rfc1323 ? (TF_REQ_SCALE|TF_REQ_TSTMP) : 0;
4002 #ifdef TCP_SIGNATURE
4003 		tb.t_flags |= (tp->t_flags & TF_SIGNATURE);
4004 #endif
4005 		tb.t_state = TCPS_LISTEN;
4006 		if (tcp_dooptions(&tb, optp, optlen, th, m, m->m_pkthdr.len -
4007 		    sizeof(struct tcphdr) - optlen - hlen, oi) < 0)
4008 			return (0);
4009 	} else
4010 		tb.t_flags = 0;
4011 
4012 	/*
4013 	 * See if we already have an entry for this connection.
4014 	 * If we do, resend the SYN,ACK.  We do not count this
4015 	 * as a retransmission (XXX though maybe we should).
4016 	 */
4017 	if ((sc = syn_cache_lookup(src, dst, &scp)) != NULL) {
4018 		tcpstat.tcps_sc_dupesyn++;
4019 		if (ipopts) {
4020 			/*
4021 			 * If we were remembering a previous source route,
4022 			 * forget it and use the new one we've been given.
4023 			 */
4024 			if (sc->sc_ipopts)
4025 				(void) m_free(sc->sc_ipopts);
4026 			sc->sc_ipopts = ipopts;
4027 		}
4028 		sc->sc_timestamp = tb.ts_recent;
4029 		if (syn_cache_respond(sc, m) == 0) {
4030 			tcpstat.tcps_sndacks++;
4031 			tcpstat.tcps_sndtotal++;
4032 		}
4033 		return (1);
4034 	}
4035 
4036 	sc = pool_get(&syn_cache_pool, PR_NOWAIT);
4037 	if (sc == NULL) {
4038 		if (ipopts)
4039 			(void) m_free(ipopts);
4040 		return (0);
4041 	}
4042 
4043 	/*
4044 	 * Fill in the cache, and put the necessary IP and TCP
4045 	 * options into the reply.
4046 	 */
4047 	bzero(sc, sizeof(struct syn_cache));
4048 	callout_init(&sc->sc_timer);
4049 	bcopy(src, &sc->sc_src, src->sa_len);
4050 	bcopy(dst, &sc->sc_dst, dst->sa_len);
4051 	sc->sc_flags = 0;
4052 	sc->sc_ipopts = ipopts;
4053 	sc->sc_irs = th->th_seq;
4054 	switch (src->sa_family) {
4055 #ifdef INET
4056 	case AF_INET:
4057 	    {
4058 		struct sockaddr_in *srcin = (void *) src;
4059 		struct sockaddr_in *dstin = (void *) dst;
4060 
4061 		sc->sc_iss = tcp_new_iss1(&dstin->sin_addr,
4062 		    &srcin->sin_addr, dstin->sin_port,
4063 		    srcin->sin_port, sizeof(dstin->sin_addr), 0);
4064 		break;
4065 	    }
4066 #endif /* INET */
4067 #ifdef INET6
4068 	case AF_INET6:
4069 	    {
4070 		struct sockaddr_in6 *srcin6 = (void *) src;
4071 		struct sockaddr_in6 *dstin6 = (void *) dst;
4072 
4073 		sc->sc_iss = tcp_new_iss1(&dstin6->sin6_addr,
4074 		    &srcin6->sin6_addr, dstin6->sin6_port,
4075 		    srcin6->sin6_port, sizeof(dstin6->sin6_addr), 0);
4076 		break;
4077 	    }
4078 #endif /* INET6 */
4079 	}
4080 	sc->sc_peermaxseg = oi->maxseg;
4081 	sc->sc_ourmaxseg = tcp_mss_to_advertise(m->m_flags & M_PKTHDR ?
4082 						m->m_pkthdr.rcvif : NULL,
4083 						sc->sc_src.sa.sa_family);
4084 	sc->sc_win = win;
4085 	sc->sc_timebase = tcp_now;	/* see tcp_newtcpcb() */
4086 	sc->sc_timestamp = tb.ts_recent;
4087 	if ((tb.t_flags & (TF_REQ_TSTMP|TF_RCVD_TSTMP)) ==
4088 	    (TF_REQ_TSTMP|TF_RCVD_TSTMP))
4089 		sc->sc_flags |= SCF_TIMESTAMP;
4090 	if ((tb.t_flags & (TF_RCVD_SCALE|TF_REQ_SCALE)) ==
4091 	    (TF_RCVD_SCALE|TF_REQ_SCALE)) {
4092 		sc->sc_requested_s_scale = tb.requested_s_scale;
4093 		sc->sc_request_r_scale = 0;
4094 		while (sc->sc_request_r_scale < TCP_MAX_WINSHIFT &&
4095 		    TCP_MAXWIN << sc->sc_request_r_scale <
4096 		    so->so_rcv.sb_hiwat)
4097 			sc->sc_request_r_scale++;
4098 	} else {
4099 		sc->sc_requested_s_scale = 15;
4100 		sc->sc_request_r_scale = 15;
4101 	}
4102 	if ((tb.t_flags & TF_SACK_PERMIT) && tcp_do_sack)
4103 		sc->sc_flags |= SCF_SACK_PERMIT;
4104 #ifdef TCP_SIGNATURE
4105 	if (tb.t_flags & TF_SIGNATURE)
4106 		sc->sc_flags |= SCF_SIGNATURE;
4107 #endif
4108 	sc->sc_tp = tp;
4109 	if (syn_cache_respond(sc, m) == 0) {
4110 		syn_cache_insert(sc, tp);
4111 		tcpstat.tcps_sndacks++;
4112 		tcpstat.tcps_sndtotal++;
4113 	} else {
4114 		SYN_CACHE_PUT(sc);
4115 		tcpstat.tcps_sc_dropped++;
4116 	}
4117 	return (1);
4118 }
4119 
4120 int
4121 syn_cache_respond(struct syn_cache *sc, struct mbuf *m)
4122 {
4123 	struct route *ro;
4124 	u_int8_t *optp;
4125 	int optlen, error;
4126 	u_int16_t tlen;
4127 	struct ip *ip = NULL;
4128 #ifdef INET6
4129 	struct ip6_hdr *ip6 = NULL;
4130 #endif
4131 	struct tcpcb *tp;
4132 	struct tcphdr *th;
4133 	u_int hlen;
4134 	struct socket *so;
4135 
4136 	switch (sc->sc_src.sa.sa_family) {
4137 	case AF_INET:
4138 		hlen = sizeof(struct ip);
4139 		ro = &sc->sc_route4;
4140 		break;
4141 #ifdef INET6
4142 	case AF_INET6:
4143 		hlen = sizeof(struct ip6_hdr);
4144 		ro = (struct route *)&sc->sc_route6;
4145 		break;
4146 #endif
4147 	default:
4148 		if (m)
4149 			m_freem(m);
4150 		return (EAFNOSUPPORT);
4151 	}
4152 
4153 	/* Compute the size of the TCP options. */
4154 	optlen = 4 + (sc->sc_request_r_scale != 15 ? 4 : 0) +
4155 	    ((sc->sc_flags & SCF_SACK_PERMIT) ? (TCPOLEN_SACK_PERMITTED + 2) : 0) +
4156 #ifdef TCP_SIGNATURE
4157 	    ((sc->sc_flags & SCF_SIGNATURE) ? (TCPOLEN_SIGNATURE + 2) : 0) +
4158 #endif
4159 	    ((sc->sc_flags & SCF_TIMESTAMP) ? TCPOLEN_TSTAMP_APPA : 0);
4160 
4161 	tlen = hlen + sizeof(struct tcphdr) + optlen;
4162 
4163 	/*
4164 	 * Create the IP+TCP header from scratch.
4165 	 */
4166 	if (m)
4167 		m_freem(m);
4168 #ifdef DIAGNOSTIC
4169 	if (max_linkhdr + tlen > MCLBYTES)
4170 		return (ENOBUFS);
4171 #endif
4172 	MGETHDR(m, M_DONTWAIT, MT_DATA);
4173 	if (m && tlen > MHLEN) {
4174 		MCLGET(m, M_DONTWAIT);
4175 		if ((m->m_flags & M_EXT) == 0) {
4176 			m_freem(m);
4177 			m = NULL;
4178 		}
4179 	}
4180 	if (m == NULL)
4181 		return (ENOBUFS);
4182 	MCLAIM(m, &tcp_tx_mowner);
4183 
4184 	/* Fixup the mbuf. */
4185 	m->m_data += max_linkhdr;
4186 	m->m_len = m->m_pkthdr.len = tlen;
4187 	if (sc->sc_tp) {
4188 		tp = sc->sc_tp;
4189 		if (tp->t_inpcb)
4190 			so = tp->t_inpcb->inp_socket;
4191 #ifdef INET6
4192 		else if (tp->t_in6pcb)
4193 			so = tp->t_in6pcb->in6p_socket;
4194 #endif
4195 		else
4196 			so = NULL;
4197 	} else
4198 		so = NULL;
4199 	m->m_pkthdr.rcvif = NULL;
4200 	memset(mtod(m, u_char *), 0, tlen);
4201 
4202 	switch (sc->sc_src.sa.sa_family) {
4203 	case AF_INET:
4204 		ip = mtod(m, struct ip *);
4205 		ip->ip_v = 4;
4206 		ip->ip_dst = sc->sc_src.sin.sin_addr;
4207 		ip->ip_src = sc->sc_dst.sin.sin_addr;
4208 		ip->ip_p = IPPROTO_TCP;
4209 		th = (struct tcphdr *)(ip + 1);
4210 		th->th_dport = sc->sc_src.sin.sin_port;
4211 		th->th_sport = sc->sc_dst.sin.sin_port;
4212 		break;
4213 #ifdef INET6
4214 	case AF_INET6:
4215 		ip6 = mtod(m, struct ip6_hdr *);
4216 		ip6->ip6_vfc = IPV6_VERSION;
4217 		ip6->ip6_dst = sc->sc_src.sin6.sin6_addr;
4218 		ip6->ip6_src = sc->sc_dst.sin6.sin6_addr;
4219 		ip6->ip6_nxt = IPPROTO_TCP;
4220 		/* ip6_plen will be updated in ip6_output() */
4221 		th = (struct tcphdr *)(ip6 + 1);
4222 		th->th_dport = sc->sc_src.sin6.sin6_port;
4223 		th->th_sport = sc->sc_dst.sin6.sin6_port;
4224 		break;
4225 #endif
4226 	default:
4227 		th = NULL;
4228 	}
4229 
4230 	th->th_seq = htonl(sc->sc_iss);
4231 	th->th_ack = htonl(sc->sc_irs + 1);
4232 	th->th_off = (sizeof(struct tcphdr) + optlen) >> 2;
4233 	th->th_flags = TH_SYN|TH_ACK;
4234 	th->th_win = htons(sc->sc_win);
4235 	/* th_sum already 0 */
4236 	/* th_urp already 0 */
4237 
4238 	/* Tack on the TCP options. */
4239 	optp = (u_int8_t *)(th + 1);
4240 	*optp++ = TCPOPT_MAXSEG;
4241 	*optp++ = 4;
4242 	*optp++ = (sc->sc_ourmaxseg >> 8) & 0xff;
4243 	*optp++ = sc->sc_ourmaxseg & 0xff;
4244 
4245 	if (sc->sc_request_r_scale != 15) {
4246 		*((u_int32_t *)optp) = htonl(TCPOPT_NOP << 24 |
4247 		    TCPOPT_WINDOW << 16 | TCPOLEN_WINDOW << 8 |
4248 		    sc->sc_request_r_scale);
4249 		optp += 4;
4250 	}
4251 
4252 	if (sc->sc_flags & SCF_TIMESTAMP) {
4253 		u_int32_t *lp = (u_int32_t *)(optp);
4254 		/* Form timestamp option as shown in appendix A of RFC 1323. */
4255 		*lp++ = htonl(TCPOPT_TSTAMP_HDR);
4256 		*lp++ = htonl(SYN_CACHE_TIMESTAMP(sc));
4257 		*lp   = htonl(sc->sc_timestamp);
4258 		optp += TCPOLEN_TSTAMP_APPA;
4259 	}
4260 
4261 	if (sc->sc_flags & SCF_SACK_PERMIT) {
4262 		u_int8_t *p = optp;
4263 
4264 		/* Let the peer know that we will SACK. */
4265 		p[0] = TCPOPT_SACK_PERMITTED;
4266 		p[1] = 2;
4267 		p[2] = TCPOPT_NOP;
4268 		p[3] = TCPOPT_NOP;
4269 		optp += 4;
4270 	}
4271 
4272 #ifdef TCP_SIGNATURE
4273 	if (sc->sc_flags & SCF_SIGNATURE) {
4274 		struct secasvar *sav;
4275 		u_int8_t *sigp;
4276 
4277 		sav = tcp_signature_getsav(m, th);
4278 
4279 		if (sav == NULL) {
4280 			if (m)
4281 				m_freem(m);
4282 			return (EPERM);
4283 		}
4284 
4285 		*optp++ = TCPOPT_SIGNATURE;
4286 		*optp++ = TCPOLEN_SIGNATURE;
4287 		sigp = optp;
4288 		bzero(optp, TCP_SIGLEN);
4289 		optp += TCP_SIGLEN;
4290 		*optp++ = TCPOPT_NOP;
4291 		*optp++ = TCPOPT_EOL;
4292 
4293 		(void)tcp_signature(m, th, hlen, sav, sigp);
4294 
4295 		key_sa_recordxfer(sav, m);
4296 #ifdef FAST_IPSEC
4297 		KEY_FREESAV(&sav);
4298 #else
4299 		key_freesav(sav);
4300 #endif
4301 	}
4302 #endif
4303 
4304 	/* Compute the packet's checksum. */
4305 	switch (sc->sc_src.sa.sa_family) {
4306 	case AF_INET:
4307 		ip->ip_len = htons(tlen - hlen);
4308 		th->th_sum = 0;
4309 		th->th_sum = in4_cksum(m, IPPROTO_TCP, hlen, tlen - hlen);
4310 		break;
4311 #ifdef INET6
4312 	case AF_INET6:
4313 		ip6->ip6_plen = htons(tlen - hlen);
4314 		th->th_sum = 0;
4315 		th->th_sum = in6_cksum(m, IPPROTO_TCP, hlen, tlen - hlen);
4316 		break;
4317 #endif
4318 	}
4319 
4320 	/*
4321 	 * Fill in some straggling IP bits.  Note the stack expects
4322 	 * ip_len to be in host order, for convenience.
4323 	 */
4324 	switch (sc->sc_src.sa.sa_family) {
4325 #ifdef INET
4326 	case AF_INET:
4327 		ip->ip_len = htons(tlen);
4328 		ip->ip_ttl = ip_defttl;
4329 		/* XXX tos? */
4330 		break;
4331 #endif
4332 #ifdef INET6
4333 	case AF_INET6:
4334 		ip6->ip6_vfc &= ~IPV6_VERSION_MASK;
4335 		ip6->ip6_vfc |= IPV6_VERSION;
4336 		ip6->ip6_plen = htons(tlen - hlen);
4337 		/* ip6_hlim will be initialized afterwards */
4338 		/* XXX flowlabel? */
4339 		break;
4340 #endif
4341 	}
4342 
4343 	/* XXX use IPsec policy on listening socket, on SYN ACK */
4344 	tp = sc->sc_tp;
4345 
4346 	switch (sc->sc_src.sa.sa_family) {
4347 #ifdef INET
4348 	case AF_INET:
4349 		error = ip_output(m, sc->sc_ipopts, ro,
4350 		    (ip_mtudisc ? IP_MTUDISC : 0),
4351 		    (struct ip_moptions *)NULL, so);
4352 		break;
4353 #endif
4354 #ifdef INET6
4355 	case AF_INET6:
4356 		ip6->ip6_hlim = in6_selecthlim(NULL,
4357 				ro->ro_rt ? ro->ro_rt->rt_ifp : NULL);
4358 
4359 		error = ip6_output(m, NULL /*XXX*/, (struct route_in6 *)ro, 0,
4360 			(struct ip6_moptions *)0, so, NULL);
4361 		break;
4362 #endif
4363 	default:
4364 		error = EAFNOSUPPORT;
4365 		break;
4366 	}
4367 	return (error);
4368 }
4369