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