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