Home | History | Annotate | Line # | Download | only in netinet
tcp_input.c revision 1.228
      1 /*	$NetBSD: tcp_input.c,v 1.228 2005/05/29 21:41:23 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.228 2005/05/29 21:41:23 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 
    926 	MCLAIM(m, &tcp_rx_mowner);
    927 	va_start(ap, m);
    928 	toff = va_arg(ap, int);
    929 	(void)va_arg(ap, int);		/* ignore value, advance ap */
    930 	va_end(ap);
    931 
    932 	tcpstat.tcps_rcvtotal++;
    933 
    934 	bzero(&opti, sizeof(opti));
    935 	opti.ts_present = 0;
    936 	opti.maxseg = 0;
    937 
    938 	/*
    939 	 * RFC1122 4.2.3.10, p. 104: discard bcast/mcast SYN.
    940 	 *
    941 	 * TCP is, by definition, unicast, so we reject all
    942 	 * multicast outright.
    943 	 *
    944 	 * Note, there are additional src/dst address checks in
    945 	 * the AF-specific code below.
    946 	 */
    947 	if (m->m_flags & (M_BCAST|M_MCAST)) {
    948 		/* XXX stat */
    949 		goto drop;
    950 	}
    951 #ifdef INET6
    952 	if (m->m_flags & M_ANYCAST6) {
    953 		/* XXX stat */
    954 		goto drop;
    955 	}
    956 #endif
    957 
    958 	/*
    959 	 * Get IP and TCP header.
    960 	 * Note: IP leaves IP header in first mbuf.
    961 	 */
    962 	ip = mtod(m, struct ip *);
    963 #ifdef INET6
    964 	ip6 = NULL;
    965 #endif
    966 	switch (ip->ip_v) {
    967 #ifdef INET
    968 	case 4:
    969 		af = AF_INET;
    970 		iphlen = sizeof(struct ip);
    971 		ip = mtod(m, struct ip *);
    972 		IP6_EXTHDR_GET(th, struct tcphdr *, m, toff,
    973 			sizeof(struct tcphdr));
    974 		if (th == NULL) {
    975 			tcpstat.tcps_rcvshort++;
    976 			return;
    977 		}
    978 		/* We do the checksum after PCB lookup... */
    979 		len = ntohs(ip->ip_len);
    980 		tlen = len - toff;
    981 		break;
    982 #endif
    983 #ifdef INET6
    984 	case 6:
    985 		ip = NULL;
    986 		iphlen = sizeof(struct ip6_hdr);
    987 		af = AF_INET6;
    988 		ip6 = mtod(m, struct ip6_hdr *);
    989 		IP6_EXTHDR_GET(th, struct tcphdr *, m, toff,
    990 			sizeof(struct tcphdr));
    991 		if (th == NULL) {
    992 			tcpstat.tcps_rcvshort++;
    993 			return;
    994 		}
    995 
    996 		/* Be proactive about malicious use of IPv4 mapped address */
    997 		if (IN6_IS_ADDR_V4MAPPED(&ip6->ip6_src) ||
    998 		    IN6_IS_ADDR_V4MAPPED(&ip6->ip6_dst)) {
    999 			/* XXX stat */
   1000 			goto drop;
   1001 		}
   1002 
   1003 		/*
   1004 		 * Be proactive about unspecified IPv6 address in source.
   1005 		 * As we use all-zero to indicate unbounded/unconnected pcb,
   1006 		 * unspecified IPv6 address can be used to confuse us.
   1007 		 *
   1008 		 * Note that packets with unspecified IPv6 destination is
   1009 		 * already dropped in ip6_input.
   1010 		 */
   1011 		if (IN6_IS_ADDR_UNSPECIFIED(&ip6->ip6_src)) {
   1012 			/* XXX stat */
   1013 			goto drop;
   1014 		}
   1015 
   1016 		/*
   1017 		 * Make sure destination address is not multicast.
   1018 		 * Source address checked in ip6_input().
   1019 		 */
   1020 		if (IN6_IS_ADDR_MULTICAST(&ip6->ip6_dst)) {
   1021 			/* XXX stat */
   1022 			goto drop;
   1023 		}
   1024 
   1025 		/* We do the checksum after PCB lookup... */
   1026 		len = m->m_pkthdr.len;
   1027 		tlen = len - toff;
   1028 		break;
   1029 #endif
   1030 	default:
   1031 		m_freem(m);
   1032 		return;
   1033 	}
   1034 
   1035 	KASSERT(TCP_HDR_ALIGNED_P(th));
   1036 
   1037 	/*
   1038 	 * Check that TCP offset makes sense,
   1039 	 * pull out TCP options and adjust length.		XXX
   1040 	 */
   1041 	off = th->th_off << 2;
   1042 	if (off < sizeof (struct tcphdr) || off > tlen) {
   1043 		tcpstat.tcps_rcvbadoff++;
   1044 		goto drop;
   1045 	}
   1046 	tlen -= off;
   1047 
   1048 	/*
   1049 	 * tcp_input() has been modified to use tlen to mean the TCP data
   1050 	 * length throughout the function.  Other functions can use
   1051 	 * m->m_pkthdr.len as the basis for calculating the TCP data length.
   1052 	 * rja
   1053 	 */
   1054 
   1055 	if (off > sizeof (struct tcphdr)) {
   1056 		IP6_EXTHDR_GET(th, struct tcphdr *, m, toff, off);
   1057 		if (th == NULL) {
   1058 			tcpstat.tcps_rcvshort++;
   1059 			return;
   1060 		}
   1061 		/*
   1062 		 * NOTE: ip/ip6 will not be affected by m_pulldown()
   1063 		 * (as they're before toff) and we don't need to update those.
   1064 		 */
   1065 		KASSERT(TCP_HDR_ALIGNED_P(th));
   1066 		optlen = off - sizeof (struct tcphdr);
   1067 		optp = ((u_int8_t *)th) + sizeof(struct tcphdr);
   1068 		/*
   1069 		 * Do quick retrieval of timestamp options ("options
   1070 		 * prediction?").  If timestamp is the only option and it's
   1071 		 * formatted as recommended in RFC 1323 appendix A, we
   1072 		 * quickly get the values now and not bother calling
   1073 		 * tcp_dooptions(), etc.
   1074 		 */
   1075 		if ((optlen == TCPOLEN_TSTAMP_APPA ||
   1076 		     (optlen > TCPOLEN_TSTAMP_APPA &&
   1077 			optp[TCPOLEN_TSTAMP_APPA] == TCPOPT_EOL)) &&
   1078 		     *(u_int32_t *)optp == htonl(TCPOPT_TSTAMP_HDR) &&
   1079 		     (th->th_flags & TH_SYN) == 0) {
   1080 			opti.ts_present = 1;
   1081 			opti.ts_val = ntohl(*(u_int32_t *)(optp + 4));
   1082 			opti.ts_ecr = ntohl(*(u_int32_t *)(optp + 8));
   1083 			optp = NULL;	/* we've parsed the options */
   1084 		}
   1085 	}
   1086 	tiflags = th->th_flags;
   1087 
   1088 	/*
   1089 	 * Locate pcb for segment.
   1090 	 */
   1091 findpcb:
   1092 	inp = NULL;
   1093 #ifdef INET6
   1094 	in6p = NULL;
   1095 #endif
   1096 	switch (af) {
   1097 #ifdef INET
   1098 	case AF_INET:
   1099 		inp = in_pcblookup_connect(&tcbtable, ip->ip_src, th->th_sport,
   1100 		    ip->ip_dst, th->th_dport);
   1101 		if (inp == 0) {
   1102 			++tcpstat.tcps_pcbhashmiss;
   1103 			inp = in_pcblookup_bind(&tcbtable, ip->ip_dst, th->th_dport);
   1104 		}
   1105 #ifdef INET6
   1106 		if (inp == 0) {
   1107 			struct in6_addr s, d;
   1108 
   1109 			/* mapped addr case */
   1110 			bzero(&s, sizeof(s));
   1111 			s.s6_addr16[5] = htons(0xffff);
   1112 			bcopy(&ip->ip_src, &s.s6_addr32[3], sizeof(ip->ip_src));
   1113 			bzero(&d, sizeof(d));
   1114 			d.s6_addr16[5] = htons(0xffff);
   1115 			bcopy(&ip->ip_dst, &d.s6_addr32[3], sizeof(ip->ip_dst));
   1116 			in6p = in6_pcblookup_connect(&tcbtable, &s,
   1117 			    th->th_sport, &d, th->th_dport, 0);
   1118 			if (in6p == 0) {
   1119 				++tcpstat.tcps_pcbhashmiss;
   1120 				in6p = in6_pcblookup_bind(&tcbtable, &d,
   1121 				    th->th_dport, 0);
   1122 			}
   1123 		}
   1124 #endif
   1125 #ifndef INET6
   1126 		if (inp == 0)
   1127 #else
   1128 		if (inp == 0 && in6p == 0)
   1129 #endif
   1130 		{
   1131 			++tcpstat.tcps_noport;
   1132 			if (tcp_log_refused &&
   1133 			    (tiflags & (TH_RST|TH_ACK|TH_SYN)) == TH_SYN) {
   1134 				tcp4_log_refused(ip, th);
   1135 			}
   1136 			TCP_FIELDS_TO_HOST(th);
   1137 			goto dropwithreset_ratelim;
   1138 		}
   1139 #if defined(IPSEC) || defined(FAST_IPSEC)
   1140 		if (inp && (inp->inp_socket->so_options & SO_ACCEPTCONN) == 0 &&
   1141 		    ipsec4_in_reject(m, inp)) {
   1142 			ipsecstat.in_polvio++;
   1143 			goto drop;
   1144 		}
   1145 #ifdef INET6
   1146 		else if (in6p &&
   1147 		    (in6p->in6p_socket->so_options & SO_ACCEPTCONN) == 0 &&
   1148 		    ipsec4_in_reject_so(m, in6p->in6p_socket)) {
   1149 			ipsecstat.in_polvio++;
   1150 			goto drop;
   1151 		}
   1152 #endif
   1153 #endif /*IPSEC*/
   1154 		break;
   1155 #endif /*INET*/
   1156 #ifdef INET6
   1157 	case AF_INET6:
   1158 	    {
   1159 		int faith;
   1160 
   1161 #if defined(NFAITH) && NFAITH > 0
   1162 		faith = faithprefix(&ip6->ip6_dst);
   1163 #else
   1164 		faith = 0;
   1165 #endif
   1166 		in6p = in6_pcblookup_connect(&tcbtable, &ip6->ip6_src,
   1167 		    th->th_sport, &ip6->ip6_dst, th->th_dport, faith);
   1168 		if (in6p == NULL) {
   1169 			++tcpstat.tcps_pcbhashmiss;
   1170 			in6p = in6_pcblookup_bind(&tcbtable, &ip6->ip6_dst,
   1171 				th->th_dport, faith);
   1172 		}
   1173 		if (in6p == NULL) {
   1174 			++tcpstat.tcps_noport;
   1175 			if (tcp_log_refused &&
   1176 			    (tiflags & (TH_RST|TH_ACK|TH_SYN)) == TH_SYN) {
   1177 				tcp6_log_refused(ip6, th);
   1178 			}
   1179 			TCP_FIELDS_TO_HOST(th);
   1180 			goto dropwithreset_ratelim;
   1181 		}
   1182 #if defined(IPSEC) || defined(FAST_IPSEC)
   1183 		if ((in6p->in6p_socket->so_options & SO_ACCEPTCONN) == 0 &&
   1184 		    ipsec6_in_reject(m, in6p)) {
   1185 			ipsec6stat.in_polvio++;
   1186 			goto drop;
   1187 		}
   1188 #endif /*IPSEC*/
   1189 		break;
   1190 	    }
   1191 #endif
   1192 	}
   1193 
   1194 	/*
   1195 	 * If the state is CLOSED (i.e., TCB does not exist) then
   1196 	 * all data in the incoming segment is discarded.
   1197 	 * If the TCB exists but is in CLOSED state, it is embryonic,
   1198 	 * but should either do a listen or a connect soon.
   1199 	 */
   1200 	tp = NULL;
   1201 	so = NULL;
   1202 	if (inp) {
   1203 		tp = intotcpcb(inp);
   1204 		so = inp->inp_socket;
   1205 	}
   1206 #ifdef INET6
   1207 	else if (in6p) {
   1208 		tp = in6totcpcb(in6p);
   1209 		so = in6p->in6p_socket;
   1210 	}
   1211 #endif
   1212 	if (tp == 0) {
   1213 		TCP_FIELDS_TO_HOST(th);
   1214 		goto dropwithreset_ratelim;
   1215 	}
   1216 	if (tp->t_state == TCPS_CLOSED)
   1217 		goto drop;
   1218 
   1219 	/*
   1220 	 * Checksum extended TCP header and data.
   1221 	 */
   1222 	if (tcp_input_checksum(af, m, th, toff, off, tlen))
   1223 		goto badcsum;
   1224 
   1225 	TCP_FIELDS_TO_HOST(th);
   1226 
   1227 	/* Unscale the window into a 32-bit value. */
   1228 	if ((tiflags & TH_SYN) == 0)
   1229 		tiwin = th->th_win << tp->snd_scale;
   1230 	else
   1231 		tiwin = th->th_win;
   1232 
   1233 #ifdef INET6
   1234 	/* save packet options if user wanted */
   1235 	if (in6p && (in6p->in6p_flags & IN6P_CONTROLOPTS)) {
   1236 		if (in6p->in6p_options) {
   1237 			m_freem(in6p->in6p_options);
   1238 			in6p->in6p_options = 0;
   1239 		}
   1240 		ip6_savecontrol(in6p, &in6p->in6p_options, ip6, m);
   1241 	}
   1242 #endif
   1243 
   1244 	if (so->so_options & (SO_DEBUG|SO_ACCEPTCONN)) {
   1245 		union syn_cache_sa src;
   1246 		union syn_cache_sa dst;
   1247 
   1248 		bzero(&src, sizeof(src));
   1249 		bzero(&dst, sizeof(dst));
   1250 		switch (af) {
   1251 #ifdef INET
   1252 		case AF_INET:
   1253 			src.sin.sin_len = sizeof(struct sockaddr_in);
   1254 			src.sin.sin_family = AF_INET;
   1255 			src.sin.sin_addr = ip->ip_src;
   1256 			src.sin.sin_port = th->th_sport;
   1257 
   1258 			dst.sin.sin_len = sizeof(struct sockaddr_in);
   1259 			dst.sin.sin_family = AF_INET;
   1260 			dst.sin.sin_addr = ip->ip_dst;
   1261 			dst.sin.sin_port = th->th_dport;
   1262 			break;
   1263 #endif
   1264 #ifdef INET6
   1265 		case AF_INET6:
   1266 			src.sin6.sin6_len = sizeof(struct sockaddr_in6);
   1267 			src.sin6.sin6_family = AF_INET6;
   1268 			src.sin6.sin6_addr = ip6->ip6_src;
   1269 			src.sin6.sin6_port = th->th_sport;
   1270 
   1271 			dst.sin6.sin6_len = sizeof(struct sockaddr_in6);
   1272 			dst.sin6.sin6_family = AF_INET6;
   1273 			dst.sin6.sin6_addr = ip6->ip6_dst;
   1274 			dst.sin6.sin6_port = th->th_dport;
   1275 			break;
   1276 #endif /* INET6 */
   1277 		default:
   1278 			goto badsyn;	/*sanity*/
   1279 		}
   1280 
   1281 		if (so->so_options & SO_DEBUG) {
   1282 #ifdef TCP_DEBUG
   1283 			ostate = tp->t_state;
   1284 #endif
   1285 
   1286 			tcp_saveti = NULL;
   1287 			if (iphlen + sizeof(struct tcphdr) > MHLEN)
   1288 				goto nosave;
   1289 
   1290 			if (m->m_len > iphlen && (m->m_flags & M_EXT) == 0) {
   1291 				tcp_saveti = m_copym(m, 0, iphlen, M_DONTWAIT);
   1292 				if (!tcp_saveti)
   1293 					goto nosave;
   1294 			} else {
   1295 				MGETHDR(tcp_saveti, M_DONTWAIT, MT_HEADER);
   1296 				if (!tcp_saveti)
   1297 					goto nosave;
   1298 				MCLAIM(m, &tcp_mowner);
   1299 				tcp_saveti->m_len = iphlen;
   1300 				m_copydata(m, 0, iphlen,
   1301 				    mtod(tcp_saveti, caddr_t));
   1302 			}
   1303 
   1304 			if (M_TRAILINGSPACE(tcp_saveti) < sizeof(struct tcphdr)) {
   1305 				m_freem(tcp_saveti);
   1306 				tcp_saveti = NULL;
   1307 			} else {
   1308 				tcp_saveti->m_len += sizeof(struct tcphdr);
   1309 				bcopy(th, mtod(tcp_saveti, caddr_t) + iphlen,
   1310 				    sizeof(struct tcphdr));
   1311 			}
   1312 	nosave:;
   1313 		}
   1314 		if (so->so_options & SO_ACCEPTCONN) {
   1315 			if ((tiflags & (TH_RST|TH_ACK|TH_SYN)) != TH_SYN) {
   1316 				if (tiflags & TH_RST) {
   1317 					syn_cache_reset(&src.sa, &dst.sa, th);
   1318 				} else if ((tiflags & (TH_ACK|TH_SYN)) ==
   1319 				    (TH_ACK|TH_SYN)) {
   1320 					/*
   1321 					 * Received a SYN,ACK.  This should
   1322 					 * never happen while we are in
   1323 					 * LISTEN.  Send an RST.
   1324 					 */
   1325 					goto badsyn;
   1326 				} else if (tiflags & TH_ACK) {
   1327 					so = syn_cache_get(&src.sa, &dst.sa,
   1328 						th, toff, tlen, so, m);
   1329 					if (so == NULL) {
   1330 						/*
   1331 						 * We don't have a SYN for
   1332 						 * this ACK; send an RST.
   1333 						 */
   1334 						goto badsyn;
   1335 					} else if (so ==
   1336 					    (struct socket *)(-1)) {
   1337 						/*
   1338 						 * We were unable to create
   1339 						 * the connection.  If the
   1340 						 * 3-way handshake was
   1341 						 * completed, and RST has
   1342 						 * been sent to the peer.
   1343 						 * Since the mbuf might be
   1344 						 * in use for the reply,
   1345 						 * do not free it.
   1346 						 */
   1347 						m = NULL;
   1348 					} else {
   1349 						/*
   1350 						 * We have created a
   1351 						 * full-blown connection.
   1352 						 */
   1353 						tp = NULL;
   1354 						inp = NULL;
   1355 #ifdef INET6
   1356 						in6p = NULL;
   1357 #endif
   1358 						switch (so->so_proto->pr_domain->dom_family) {
   1359 #ifdef INET
   1360 						case AF_INET:
   1361 							inp = sotoinpcb(so);
   1362 							tp = intotcpcb(inp);
   1363 							break;
   1364 #endif
   1365 #ifdef INET6
   1366 						case AF_INET6:
   1367 							in6p = sotoin6pcb(so);
   1368 							tp = in6totcpcb(in6p);
   1369 							break;
   1370 #endif
   1371 						}
   1372 						if (tp == NULL)
   1373 							goto badsyn;	/*XXX*/
   1374 						tiwin <<= tp->snd_scale;
   1375 						goto after_listen;
   1376 					}
   1377 				} else {
   1378 					/*
   1379 					 * None of RST, SYN or ACK was set.
   1380 					 * This is an invalid packet for a
   1381 					 * TCB in LISTEN state.  Send a RST.
   1382 					 */
   1383 					goto badsyn;
   1384 				}
   1385 			} else {
   1386 				/*
   1387 				 * Received a SYN.
   1388 				 */
   1389 
   1390 #ifdef INET6
   1391 				/*
   1392 				 * If deprecated address is forbidden, we do
   1393 				 * not accept SYN to deprecated interface
   1394 				 * address to prevent any new inbound
   1395 				 * connection from getting established.
   1396 				 * When we do not accept SYN, we send a TCP
   1397 				 * RST, with deprecated source address (instead
   1398 				 * of dropping it).  We compromise it as it is
   1399 				 * much better for peer to send a RST, and
   1400 				 * RST will be the final packet for the
   1401 				 * exchange.
   1402 				 *
   1403 				 * If we do not forbid deprecated addresses, we
   1404 				 * accept the SYN packet.  RFC2462 does not
   1405 				 * suggest dropping SYN in this case.
   1406 				 * If we decipher RFC2462 5.5.4, it says like
   1407 				 * this:
   1408 				 * 1. use of deprecated addr with existing
   1409 				 *    communication is okay - "SHOULD continue
   1410 				 *    to be used"
   1411 				 * 2. use of it with new communication:
   1412 				 *   (2a) "SHOULD NOT be used if alternate
   1413 				 *        address with sufficient scope is
   1414 				 *        available"
   1415 				 *   (2b) nothing mentioned otherwise.
   1416 				 * Here we fall into (2b) case as we have no
   1417 				 * choice in our source address selection - we
   1418 				 * must obey the peer.
   1419 				 *
   1420 				 * The wording in RFC2462 is confusing, and
   1421 				 * there are multiple description text for
   1422 				 * deprecated address handling - worse, they
   1423 				 * are not exactly the same.  I believe 5.5.4
   1424 				 * is the best one, so we follow 5.5.4.
   1425 				 */
   1426 				if (af == AF_INET6 && !ip6_use_deprecated) {
   1427 					struct in6_ifaddr *ia6;
   1428 					if ((ia6 = in6ifa_ifpwithaddr(m->m_pkthdr.rcvif,
   1429 					    &ip6->ip6_dst)) &&
   1430 					    (ia6->ia6_flags & IN6_IFF_DEPRECATED)) {
   1431 						tp = NULL;
   1432 						goto dropwithreset;
   1433 					}
   1434 				}
   1435 #endif
   1436 
   1437 #ifdef IPSEC
   1438 				switch (af) {
   1439 #ifdef INET
   1440 				case AF_INET:
   1441 					if (ipsec4_in_reject_so(m, so)) {
   1442 						ipsecstat.in_polvio++;
   1443 						tp = NULL;
   1444 						goto dropwithreset;
   1445 					}
   1446 					break;
   1447 #endif
   1448 #ifdef INET6
   1449 				case AF_INET6:
   1450 					if (ipsec6_in_reject_so(m, so)) {
   1451 						ipsec6stat.in_polvio++;
   1452 						tp = NULL;
   1453 						goto dropwithreset;
   1454 					}
   1455 					break;
   1456 #endif
   1457 				}
   1458 #endif
   1459 
   1460 				/*
   1461 				 * LISTEN socket received a SYN
   1462 				 * from itself?  This can't possibly
   1463 				 * be valid; drop the packet.
   1464 				 */
   1465 				if (th->th_sport == th->th_dport) {
   1466 					int i;
   1467 
   1468 					switch (af) {
   1469 #ifdef INET
   1470 					case AF_INET:
   1471 						i = in_hosteq(ip->ip_src, ip->ip_dst);
   1472 						break;
   1473 #endif
   1474 #ifdef INET6
   1475 					case AF_INET6:
   1476 						i = IN6_ARE_ADDR_EQUAL(&ip6->ip6_src, &ip6->ip6_dst);
   1477 						break;
   1478 #endif
   1479 					default:
   1480 						i = 1;
   1481 					}
   1482 					if (i) {
   1483 						tcpstat.tcps_badsyn++;
   1484 						goto drop;
   1485 					}
   1486 				}
   1487 
   1488 				/*
   1489 				 * SYN looks ok; create compressed TCP
   1490 				 * state for it.
   1491 				 */
   1492 				if (so->so_qlen <= so->so_qlimit &&
   1493 				    syn_cache_add(&src.sa, &dst.sa, th, tlen,
   1494 						so, m, optp, optlen, &opti))
   1495 					m = NULL;
   1496 			}
   1497 			goto drop;
   1498 		}
   1499 	}
   1500 
   1501 after_listen:
   1502 #ifdef DIAGNOSTIC
   1503 	/*
   1504 	 * Should not happen now that all embryonic connections
   1505 	 * are handled with compressed state.
   1506 	 */
   1507 	if (tp->t_state == TCPS_LISTEN)
   1508 		panic("tcp_input: TCPS_LISTEN");
   1509 #endif
   1510 
   1511 	/*
   1512 	 * Segment received on connection.
   1513 	 * Reset idle time and keep-alive timer.
   1514 	 */
   1515 	tp->t_rcvtime = tcp_now;
   1516 	if (TCPS_HAVEESTABLISHED(tp->t_state))
   1517 		TCP_TIMER_ARM(tp, TCPT_KEEP, tcp_keepidle);
   1518 
   1519 	/*
   1520 	 * Process options.
   1521 	 */
   1522 #ifdef TCP_SIGNATURE
   1523 	if (optp || (tp->t_flags & TF_SIGNATURE))
   1524 #else
   1525 	if (optp)
   1526 #endif
   1527 		if (tcp_dooptions(tp, optp, optlen, th, m, toff, &opti) < 0)
   1528 			goto drop;
   1529 
   1530 	if (TCP_SACK_ENABLED(tp)) {
   1531 		tcp_del_sackholes(tp, th);
   1532 	}
   1533 
   1534 	if (opti.ts_present && opti.ts_ecr) {
   1535 		/*
   1536 		 * Calculate the RTT from the returned time stamp and the
   1537 		 * connection's time base.  If the time stamp is later than
   1538 		 * the current time, or is extremely old, fall back to non-1323
   1539 		 * RTT calculation.  Since ts_ecr is unsigned, we can test both
   1540 		 * at the same time.
   1541 		 */
   1542 		opti.ts_ecr = TCP_TIMESTAMP(tp) - opti.ts_ecr + 1;
   1543 		if (opti.ts_ecr > TCP_PAWS_IDLE)
   1544 			opti.ts_ecr = 0;
   1545 	}
   1546 
   1547 	/*
   1548 	 * Header prediction: check for the two common cases
   1549 	 * of a uni-directional data xfer.  If the packet has
   1550 	 * no control flags, is in-sequence, the window didn't
   1551 	 * change and we're not retransmitting, it's a
   1552 	 * candidate.  If the length is zero and the ack moved
   1553 	 * forward, we're the sender side of the xfer.  Just
   1554 	 * free the data acked & wake any higher level process
   1555 	 * that was blocked waiting for space.  If the length
   1556 	 * is non-zero and the ack didn't move, we're the
   1557 	 * receiver side.  If we're getting packets in-order
   1558 	 * (the reassembly queue is empty), add the data to
   1559 	 * the socket buffer and note that we need a delayed ack.
   1560 	 */
   1561 	if (tp->t_state == TCPS_ESTABLISHED &&
   1562 	    (tiflags & (TH_SYN|TH_FIN|TH_RST|TH_URG|TH_ACK)) == TH_ACK &&
   1563 	    (!opti.ts_present || TSTMP_GEQ(opti.ts_val, tp->ts_recent)) &&
   1564 	    th->th_seq == tp->rcv_nxt &&
   1565 	    tiwin && tiwin == tp->snd_wnd &&
   1566 	    tp->snd_nxt == tp->snd_max) {
   1567 
   1568 		/*
   1569 		 * If last ACK falls within this segment's sequence numbers,
   1570 		 *  record the timestamp.
   1571 		 */
   1572 		if (opti.ts_present &&
   1573 		    SEQ_LEQ(th->th_seq, tp->last_ack_sent) &&
   1574 		    SEQ_LT(tp->last_ack_sent, th->th_seq + tlen)) {
   1575 			tp->ts_recent_age = tcp_now;
   1576 			tp->ts_recent = opti.ts_val;
   1577 		}
   1578 
   1579 		if (tlen == 0) {
   1580 			/* Ack prediction. */
   1581 			if (SEQ_GT(th->th_ack, tp->snd_una) &&
   1582 			    SEQ_LEQ(th->th_ack, tp->snd_max) &&
   1583 			    tp->snd_cwnd >= tp->snd_wnd &&
   1584 			    tp->t_partialacks < 0) {
   1585 				/*
   1586 				 * this is a pure ack for outstanding data.
   1587 				 */
   1588 				++tcpstat.tcps_predack;
   1589 				if (opti.ts_present && opti.ts_ecr)
   1590 					tcp_xmit_timer(tp, opti.ts_ecr);
   1591 				else if (tp->t_rtttime &&
   1592 				    SEQ_GT(th->th_ack, tp->t_rtseq))
   1593 					tcp_xmit_timer(tp,
   1594 					  tcp_now - tp->t_rtttime);
   1595 				acked = th->th_ack - tp->snd_una;
   1596 				tcpstat.tcps_rcvackpack++;
   1597 				tcpstat.tcps_rcvackbyte += acked;
   1598 				ND6_HINT(tp);
   1599 
   1600 				if (acked > (tp->t_lastoff - tp->t_inoff))
   1601 					tp->t_lastm = NULL;
   1602 				sbdrop(&so->so_snd, acked);
   1603 				tp->t_lastoff -= acked;
   1604 
   1605 				tp->snd_una = th->th_ack;
   1606 				tp->snd_fack = tp->snd_una;
   1607 				if (SEQ_LT(tp->snd_high, tp->snd_una))
   1608 					tp->snd_high = tp->snd_una;
   1609 				m_freem(m);
   1610 
   1611 				/*
   1612 				 * If all outstanding data are acked, stop
   1613 				 * retransmit timer, otherwise restart timer
   1614 				 * using current (possibly backed-off) value.
   1615 				 * If process is waiting for space,
   1616 				 * wakeup/selwakeup/signal.  If data
   1617 				 * are ready to send, let tcp_output
   1618 				 * decide between more output or persist.
   1619 				 */
   1620 				if (tp->snd_una == tp->snd_max)
   1621 					TCP_TIMER_DISARM(tp, TCPT_REXMT);
   1622 				else if (TCP_TIMER_ISARMED(tp,
   1623 				    TCPT_PERSIST) == 0)
   1624 					TCP_TIMER_ARM(tp, TCPT_REXMT,
   1625 					    tp->t_rxtcur);
   1626 
   1627 				sowwakeup(so);
   1628 				if (so->so_snd.sb_cc)
   1629 					(void) tcp_output(tp);
   1630 				if (tcp_saveti)
   1631 					m_freem(tcp_saveti);
   1632 				return;
   1633 			}
   1634 		} else if (th->th_ack == tp->snd_una &&
   1635 		    TAILQ_FIRST(&tp->segq) == NULL &&
   1636 		    tlen <= sbspace(&so->so_rcv)) {
   1637 			/*
   1638 			 * this is a pure, in-sequence data packet
   1639 			 * with nothing on the reassembly queue and
   1640 			 * we have enough buffer space to take it.
   1641 			 */
   1642 			++tcpstat.tcps_preddat;
   1643 			tp->rcv_nxt += tlen;
   1644 			tcpstat.tcps_rcvpack++;
   1645 			tcpstat.tcps_rcvbyte += tlen;
   1646 			ND6_HINT(tp);
   1647 			/*
   1648 			 * Drop TCP, IP headers and TCP options then add data
   1649 			 * to socket buffer.
   1650 			 */
   1651 			if (so->so_state & SS_CANTRCVMORE)
   1652 				m_freem(m);
   1653 			else {
   1654 				m_adj(m, toff + off);
   1655 				sbappendstream(&so->so_rcv, m);
   1656 			}
   1657 			sorwakeup(so);
   1658 			TCP_SETUP_ACK(tp, th);
   1659 			if (tp->t_flags & TF_ACKNOW)
   1660 				(void) tcp_output(tp);
   1661 			if (tcp_saveti)
   1662 				m_freem(tcp_saveti);
   1663 			return;
   1664 		}
   1665 	}
   1666 
   1667 	/*
   1668 	 * Compute mbuf offset to TCP data segment.
   1669 	 */
   1670 	hdroptlen = toff + off;
   1671 
   1672 	/*
   1673 	 * Calculate amount of space in receive window,
   1674 	 * and then do TCP input processing.
   1675 	 * Receive window is amount of space in rcv queue,
   1676 	 * but not less than advertised window.
   1677 	 */
   1678 	{ int win;
   1679 
   1680 	win = sbspace(&so->so_rcv);
   1681 	if (win < 0)
   1682 		win = 0;
   1683 	tp->rcv_wnd = imax(win, (int)(tp->rcv_adv - tp->rcv_nxt));
   1684 	}
   1685 
   1686 	switch (tp->t_state) {
   1687 	case TCPS_LISTEN:
   1688 		/*
   1689 		 * RFC1122 4.2.3.10, p. 104: discard bcast/mcast SYN
   1690 		 */
   1691 		if (m->m_flags & (M_BCAST|M_MCAST))
   1692 			goto drop;
   1693 		switch (af) {
   1694 #ifdef INET6
   1695 		case AF_INET6:
   1696 			if (IN6_IS_ADDR_MULTICAST(&ip6->ip6_dst))
   1697 				goto drop;
   1698 			break;
   1699 #endif /* INET6 */
   1700 		case AF_INET:
   1701 			if (IN_MULTICAST(ip->ip_dst.s_addr) ||
   1702 			    in_broadcast(ip->ip_dst, m->m_pkthdr.rcvif))
   1703 				goto drop;
   1704 			break;
   1705 		}
   1706 		break;
   1707 
   1708 	/*
   1709 	 * If the state is SYN_SENT:
   1710 	 *	if seg contains an ACK, but not for our SYN, drop the input.
   1711 	 *	if seg contains a RST, then drop the connection.
   1712 	 *	if seg does not contain SYN, then drop it.
   1713 	 * Otherwise this is an acceptable SYN segment
   1714 	 *	initialize tp->rcv_nxt and tp->irs
   1715 	 *	if seg contains ack then advance tp->snd_una
   1716 	 *	if SYN has been acked change to ESTABLISHED else SYN_RCVD state
   1717 	 *	arrange for segment to be acked (eventually)
   1718 	 *	continue processing rest of data/controls, beginning with URG
   1719 	 */
   1720 	case TCPS_SYN_SENT:
   1721 		if ((tiflags & TH_ACK) &&
   1722 		    (SEQ_LEQ(th->th_ack, tp->iss) ||
   1723 		     SEQ_GT(th->th_ack, tp->snd_max)))
   1724 			goto dropwithreset;
   1725 		if (tiflags & TH_RST) {
   1726 			if (tiflags & TH_ACK)
   1727 				tp = tcp_drop(tp, ECONNREFUSED);
   1728 			goto drop;
   1729 		}
   1730 		if ((tiflags & TH_SYN) == 0)
   1731 			goto drop;
   1732 		if (tiflags & TH_ACK) {
   1733 			tp->snd_una = th->th_ack;
   1734 			if (SEQ_LT(tp->snd_nxt, tp->snd_una))
   1735 				tp->snd_nxt = tp->snd_una;
   1736 			if (SEQ_LT(tp->snd_high, tp->snd_una))
   1737 				tp->snd_high = tp->snd_una;
   1738 			TCP_TIMER_DISARM(tp, TCPT_REXMT);
   1739 		}
   1740 		tp->irs = th->th_seq;
   1741 		tcp_rcvseqinit(tp);
   1742 		tp->t_flags |= TF_ACKNOW;
   1743 		tcp_mss_from_peer(tp, opti.maxseg);
   1744 
   1745 		/*
   1746 		 * Initialize the initial congestion window.  If we
   1747 		 * had to retransmit the SYN, we must initialize cwnd
   1748 		 * to 1 segment (i.e. the Loss Window).
   1749 		 */
   1750 		if (tp->t_flags & TF_SYN_REXMT)
   1751 			tp->snd_cwnd = tp->t_peermss;
   1752 		else {
   1753 			int ss = tcp_init_win;
   1754 #ifdef INET
   1755 			if (inp != NULL && in_localaddr(inp->inp_faddr))
   1756 				ss = tcp_init_win_local;
   1757 #endif
   1758 #ifdef INET6
   1759 			if (in6p != NULL && in6_localaddr(&in6p->in6p_faddr))
   1760 				ss = tcp_init_win_local;
   1761 #endif
   1762 			tp->snd_cwnd = TCP_INITIAL_WINDOW(ss, tp->t_peermss);
   1763 		}
   1764 
   1765 		tcp_rmx_rtt(tp);
   1766 		if (tiflags & TH_ACK) {
   1767 			tcpstat.tcps_connects++;
   1768 			soisconnected(so);
   1769 			tcp_established(tp);
   1770 			/* Do window scaling on this connection? */
   1771 			if ((tp->t_flags & (TF_RCVD_SCALE|TF_REQ_SCALE)) ==
   1772 			    (TF_RCVD_SCALE|TF_REQ_SCALE)) {
   1773 				tp->snd_scale = tp->requested_s_scale;
   1774 				tp->rcv_scale = tp->request_r_scale;
   1775 			}
   1776 			TCP_REASS_LOCK(tp);
   1777 			(void) tcp_reass(tp, NULL, (struct mbuf *)0, &tlen);
   1778 			TCP_REASS_UNLOCK(tp);
   1779 			/*
   1780 			 * if we didn't have to retransmit the SYN,
   1781 			 * use its rtt as our initial srtt & rtt var.
   1782 			 */
   1783 			if (tp->t_rtttime)
   1784 				tcp_xmit_timer(tp, tcp_now - tp->t_rtttime);
   1785 		} else
   1786 			tp->t_state = TCPS_SYN_RECEIVED;
   1787 
   1788 		/*
   1789 		 * Advance th->th_seq to correspond to first data byte.
   1790 		 * If data, trim to stay within window,
   1791 		 * dropping FIN if necessary.
   1792 		 */
   1793 		th->th_seq++;
   1794 		if (tlen > tp->rcv_wnd) {
   1795 			todrop = tlen - tp->rcv_wnd;
   1796 			m_adj(m, -todrop);
   1797 			tlen = tp->rcv_wnd;
   1798 			tiflags &= ~TH_FIN;
   1799 			tcpstat.tcps_rcvpackafterwin++;
   1800 			tcpstat.tcps_rcvbyteafterwin += todrop;
   1801 		}
   1802 		tp->snd_wl1 = th->th_seq - 1;
   1803 		tp->rcv_up = th->th_seq;
   1804 		goto step6;
   1805 
   1806 	/*
   1807 	 * If the state is SYN_RECEIVED:
   1808 	 *	If seg contains an ACK, but not for our SYN, drop the input
   1809 	 *	and generate an RST.  See page 36, rfc793
   1810 	 */
   1811 	case TCPS_SYN_RECEIVED:
   1812 		if ((tiflags & TH_ACK) &&
   1813 		    (SEQ_LEQ(th->th_ack, tp->iss) ||
   1814 		     SEQ_GT(th->th_ack, tp->snd_max)))
   1815 			goto dropwithreset;
   1816 		break;
   1817 	}
   1818 
   1819 	/*
   1820 	 * States other than LISTEN or SYN_SENT.
   1821 	 * First check timestamp, if present.
   1822 	 * Then check that at least some bytes of segment are within
   1823 	 * receive window.  If segment begins before rcv_nxt,
   1824 	 * drop leading data (and SYN); if nothing left, just ack.
   1825 	 *
   1826 	 * RFC 1323 PAWS: If we have a timestamp reply on this segment
   1827 	 * and it's less than ts_recent, drop it.
   1828 	 */
   1829 	if (opti.ts_present && (tiflags & TH_RST) == 0 && tp->ts_recent &&
   1830 	    TSTMP_LT(opti.ts_val, tp->ts_recent)) {
   1831 
   1832 		/* Check to see if ts_recent is over 24 days old.  */
   1833 		if (tcp_now - tp->ts_recent_age > TCP_PAWS_IDLE) {
   1834 			/*
   1835 			 * Invalidate ts_recent.  If this segment updates
   1836 			 * ts_recent, the age will be reset later and ts_recent
   1837 			 * will get a valid value.  If it does not, setting
   1838 			 * ts_recent to zero will at least satisfy the
   1839 			 * requirement that zero be placed in the timestamp
   1840 			 * echo reply when ts_recent isn't valid.  The
   1841 			 * age isn't reset until we get a valid ts_recent
   1842 			 * because we don't want out-of-order segments to be
   1843 			 * dropped when ts_recent is old.
   1844 			 */
   1845 			tp->ts_recent = 0;
   1846 		} else {
   1847 			tcpstat.tcps_rcvduppack++;
   1848 			tcpstat.tcps_rcvdupbyte += tlen;
   1849 			tcpstat.tcps_pawsdrop++;
   1850 			tcp_new_dsack(tp, th->th_seq, tlen);
   1851 			goto dropafterack;
   1852 		}
   1853 	}
   1854 
   1855 	todrop = tp->rcv_nxt - th->th_seq;
   1856 	dupseg = FALSE;
   1857 	if (todrop > 0) {
   1858 		if (tiflags & TH_SYN) {
   1859 			tiflags &= ~TH_SYN;
   1860 			th->th_seq++;
   1861 			if (th->th_urp > 1)
   1862 				th->th_urp--;
   1863 			else {
   1864 				tiflags &= ~TH_URG;
   1865 				th->th_urp = 0;
   1866 			}
   1867 			todrop--;
   1868 		}
   1869 		if (todrop > tlen ||
   1870 		    (todrop == tlen && (tiflags & TH_FIN) == 0)) {
   1871 			/*
   1872 			 * Any valid FIN or RST must be to the left of the
   1873 			 * window.  At this point the FIN or RST must be a
   1874 			 * duplicate or out of sequence; drop it.
   1875 			 */
   1876 			if (tiflags & TH_RST)
   1877 				goto drop;
   1878 			tiflags &= ~(TH_FIN|TH_RST);
   1879 			/*
   1880 			 * Send an ACK to resynchronize and drop any data.
   1881 			 * But keep on processing for RST or ACK.
   1882 			 */
   1883 			tp->t_flags |= TF_ACKNOW;
   1884 			todrop = tlen;
   1885 			dupseg = TRUE;
   1886 			tcpstat.tcps_rcvdupbyte += todrop;
   1887 			tcpstat.tcps_rcvduppack++;
   1888 		} else if ((tiflags & TH_RST) &&
   1889 			   th->th_seq != tp->last_ack_sent) {
   1890 			/*
   1891 			 * Test for reset before adjusting the sequence
   1892 			 * number for overlapping data.
   1893 			 */
   1894 			goto dropafterack_ratelim;
   1895 		} else {
   1896 			tcpstat.tcps_rcvpartduppack++;
   1897 			tcpstat.tcps_rcvpartdupbyte += todrop;
   1898 		}
   1899 		tcp_new_dsack(tp, th->th_seq, todrop);
   1900 		hdroptlen += todrop;	/*drop from head afterwards*/
   1901 		th->th_seq += todrop;
   1902 		tlen -= todrop;
   1903 		if (th->th_urp > todrop)
   1904 			th->th_urp -= todrop;
   1905 		else {
   1906 			tiflags &= ~TH_URG;
   1907 			th->th_urp = 0;
   1908 		}
   1909 	}
   1910 
   1911 	/*
   1912 	 * If new data are received on a connection after the
   1913 	 * user processes are gone, then RST the other end.
   1914 	 */
   1915 	if ((so->so_state & SS_NOFDREF) &&
   1916 	    tp->t_state > TCPS_CLOSE_WAIT && tlen) {
   1917 		tp = tcp_close(tp);
   1918 		tcpstat.tcps_rcvafterclose++;
   1919 		goto dropwithreset;
   1920 	}
   1921 
   1922 	/*
   1923 	 * If segment ends after window, drop trailing data
   1924 	 * (and PUSH and FIN); if nothing left, just ACK.
   1925 	 */
   1926 	todrop = (th->th_seq + tlen) - (tp->rcv_nxt+tp->rcv_wnd);
   1927 	if (todrop > 0) {
   1928 		tcpstat.tcps_rcvpackafterwin++;
   1929 		if (todrop >= tlen) {
   1930 			/*
   1931 			 * The segment actually starts after the window.
   1932 			 * th->th_seq + tlen - tp->rcv_nxt - tp->rcv_wnd >= tlen
   1933 			 * th->th_seq - tp->rcv_nxt - tp->rcv_wnd >= 0
   1934 			 * th->th_seq >= tp->rcv_nxt + tp->rcv_wnd
   1935 			 */
   1936 			tcpstat.tcps_rcvbyteafterwin += tlen;
   1937 			/*
   1938 			 * If a new connection request is received
   1939 			 * while in TIME_WAIT, drop the old connection
   1940 			 * and start over if the sequence numbers
   1941 			 * are above the previous ones.
   1942 			 *
   1943 			 * NOTE: We will checksum the packet again, and
   1944 			 * so we need to put the header fields back into
   1945 			 * network order!
   1946 			 * XXX This kind of sucks, but we don't expect
   1947 			 * XXX this to happen very often, so maybe it
   1948 			 * XXX doesn't matter so much.
   1949 			 */
   1950 			if (tiflags & TH_SYN &&
   1951 			    tp->t_state == TCPS_TIME_WAIT &&
   1952 			    SEQ_GT(th->th_seq, tp->rcv_nxt)) {
   1953 				iss = tcp_new_iss(tp, tp->snd_nxt);
   1954 				tp = tcp_close(tp);
   1955 				TCP_FIELDS_TO_NET(th);
   1956 				goto findpcb;
   1957 			}
   1958 			/*
   1959 			 * If window is closed can only take segments at
   1960 			 * window edge, and have to drop data and PUSH from
   1961 			 * incoming segments.  Continue processing, but
   1962 			 * remember to ack.  Otherwise, drop segment
   1963 			 * and (if not RST) ack.
   1964 			 */
   1965 			if (tp->rcv_wnd == 0 && th->th_seq == tp->rcv_nxt) {
   1966 				tp->t_flags |= TF_ACKNOW;
   1967 				tcpstat.tcps_rcvwinprobe++;
   1968 			} else
   1969 				goto dropafterack;
   1970 		} else
   1971 			tcpstat.tcps_rcvbyteafterwin += todrop;
   1972 		m_adj(m, -todrop);
   1973 		tlen -= todrop;
   1974 		tiflags &= ~(TH_PUSH|TH_FIN);
   1975 	}
   1976 
   1977 	/*
   1978 	 * If last ACK falls within this segment's sequence numbers,
   1979 	 * and the timestamp is newer, record it.
   1980 	 */
   1981 	if (opti.ts_present && TSTMP_GEQ(opti.ts_val, tp->ts_recent) &&
   1982 	    SEQ_LEQ(th->th_seq, tp->last_ack_sent) &&
   1983 	    SEQ_LT(tp->last_ack_sent, th->th_seq + tlen +
   1984 		   ((tiflags & (TH_SYN|TH_FIN)) != 0))) {
   1985 		tp->ts_recent_age = tcp_now;
   1986 		tp->ts_recent = opti.ts_val;
   1987 	}
   1988 
   1989 	/*
   1990 	 * If the RST bit is set examine the state:
   1991 	 *    SYN_RECEIVED STATE:
   1992 	 *	If passive open, return to LISTEN state.
   1993 	 *	If active open, inform user that connection was refused.
   1994 	 *    ESTABLISHED, FIN_WAIT_1, FIN_WAIT2, CLOSE_WAIT STATES:
   1995 	 *	Inform user that connection was reset, and close tcb.
   1996 	 *    CLOSING, LAST_ACK, TIME_WAIT STATES
   1997 	 *	Close the tcb.
   1998 	 */
   1999 	if (tiflags & TH_RST) {
   2000 		if (th->th_seq != tp->last_ack_sent)
   2001 			goto dropafterack_ratelim;
   2002 
   2003 		switch (tp->t_state) {
   2004 		case TCPS_SYN_RECEIVED:
   2005 			so->so_error = ECONNREFUSED;
   2006 			goto close;
   2007 
   2008 		case TCPS_ESTABLISHED:
   2009 		case TCPS_FIN_WAIT_1:
   2010 		case TCPS_FIN_WAIT_2:
   2011 		case TCPS_CLOSE_WAIT:
   2012 			so->so_error = ECONNRESET;
   2013 		close:
   2014 			tp->t_state = TCPS_CLOSED;
   2015 			tcpstat.tcps_drops++;
   2016 			tp = tcp_close(tp);
   2017 			goto drop;
   2018 
   2019 		case TCPS_CLOSING:
   2020 		case TCPS_LAST_ACK:
   2021 		case TCPS_TIME_WAIT:
   2022 			tp = tcp_close(tp);
   2023 			goto drop;
   2024 		}
   2025 	}
   2026 
   2027 	/*
   2028 	 * Since we've covered the SYN-SENT and SYN-RECEIVED states above
   2029 	 * we must be in a synchronized state.  RFC791 states (under RST
   2030 	 * generation) that any unacceptable segment (an out-of-order SYN
   2031 	 * qualifies) received in a synchronized state must elicit only an
   2032 	 * empty acknowledgment segment ... and the connection remains in
   2033 	 * the same state.
   2034 	 */
   2035 	if (tiflags & TH_SYN) {
   2036 		if (tp->rcv_nxt == th->th_seq) {
   2037 			tcp_respond(tp, m, m, th, (tcp_seq)0, th->th_ack - 1,
   2038 			    TH_ACK);
   2039 			if (tcp_saveti)
   2040 				m_freem(tcp_saveti);
   2041 			return;
   2042 		}
   2043 
   2044 		goto dropafterack_ratelim;
   2045 	}
   2046 
   2047 	/*
   2048 	 * If the ACK bit is off we drop the segment and return.
   2049 	 */
   2050 	if ((tiflags & TH_ACK) == 0) {
   2051 		if (tp->t_flags & TF_ACKNOW)
   2052 			goto dropafterack;
   2053 		else
   2054 			goto drop;
   2055 	}
   2056 
   2057 	/*
   2058 	 * Ack processing.
   2059 	 */
   2060 	switch (tp->t_state) {
   2061 
   2062 	/*
   2063 	 * In SYN_RECEIVED state if the ack ACKs our SYN then enter
   2064 	 * ESTABLISHED state and continue processing, otherwise
   2065 	 * send an RST.
   2066 	 */
   2067 	case TCPS_SYN_RECEIVED:
   2068 		if (SEQ_GT(tp->snd_una, th->th_ack) ||
   2069 		    SEQ_GT(th->th_ack, tp->snd_max))
   2070 			goto dropwithreset;
   2071 		tcpstat.tcps_connects++;
   2072 		soisconnected(so);
   2073 		tcp_established(tp);
   2074 		/* Do window scaling? */
   2075 		if ((tp->t_flags & (TF_RCVD_SCALE|TF_REQ_SCALE)) ==
   2076 		    (TF_RCVD_SCALE|TF_REQ_SCALE)) {
   2077 			tp->snd_scale = tp->requested_s_scale;
   2078 			tp->rcv_scale = tp->request_r_scale;
   2079 		}
   2080 		TCP_REASS_LOCK(tp);
   2081 		(void) tcp_reass(tp, NULL, (struct mbuf *)0, &tlen);
   2082 		TCP_REASS_UNLOCK(tp);
   2083 		tp->snd_wl1 = th->th_seq - 1;
   2084 		/* fall into ... */
   2085 
   2086 	/*
   2087 	 * In ESTABLISHED state: drop duplicate ACKs; ACK out of range
   2088 	 * ACKs.  If the ack is in the range
   2089 	 *	tp->snd_una < th->th_ack <= tp->snd_max
   2090 	 * then advance tp->snd_una to th->th_ack and drop
   2091 	 * data from the retransmission queue.  If this ACK reflects
   2092 	 * more up to date window information we update our window information.
   2093 	 */
   2094 	case TCPS_ESTABLISHED:
   2095 	case TCPS_FIN_WAIT_1:
   2096 	case TCPS_FIN_WAIT_2:
   2097 	case TCPS_CLOSE_WAIT:
   2098 	case TCPS_CLOSING:
   2099 	case TCPS_LAST_ACK:
   2100 	case TCPS_TIME_WAIT:
   2101 
   2102 		if (SEQ_LEQ(th->th_ack, tp->snd_una)) {
   2103 			if (tlen == 0 && !dupseg && tiwin == tp->snd_wnd) {
   2104 				tcpstat.tcps_rcvdupack++;
   2105 				/*
   2106 				 * If we have outstanding data (other than
   2107 				 * a window probe), this is a completely
   2108 				 * duplicate ack (ie, window info didn't
   2109 				 * change), the ack is the biggest we've
   2110 				 * seen and we've seen exactly our rexmt
   2111 				 * threshhold of them, assume a packet
   2112 				 * has been dropped and retransmit it.
   2113 				 * Kludge snd_nxt & the congestion
   2114 				 * window so we send only this one
   2115 				 * packet.
   2116 				 *
   2117 				 * We know we're losing at the current
   2118 				 * window size so do congestion avoidance
   2119 				 * (set ssthresh to half the current window
   2120 				 * and pull our congestion window back to
   2121 				 * the new ssthresh).
   2122 				 *
   2123 				 * Dup acks mean that packets have left the
   2124 				 * network (they're now cached at the receiver)
   2125 				 * so bump cwnd by the amount in the receiver
   2126 				 * to keep a constant cwnd packets in the
   2127 				 * network.
   2128 				 *
   2129 				 * If we are using TCP/SACK, then enter
   2130 				 * Fast Recovery if the receiver SACKs
   2131 				 * data that is tcprexmtthresh * MSS
   2132 				 * bytes past the last ACKed segment,
   2133 				 * irrespective of the number of DupAcks.
   2134 				 */
   2135 				if (TCP_TIMER_ISARMED(tp, TCPT_REXMT) == 0 ||
   2136 				    th->th_ack != tp->snd_una)
   2137 					tp->t_dupacks = 0;
   2138 				else if (tp->t_partialacks < 0 &&
   2139 					 (++tp->t_dupacks == tcprexmtthresh ||
   2140 					 TCP_FACK_FASTRECOV(tp))) {
   2141 					tcp_seq onxt;
   2142 					u_int win;
   2143 
   2144 					if (tcp_do_newreno &&
   2145 					    SEQ_LT(th->th_ack, tp->snd_high)) {
   2146 						/*
   2147 						 * False fast retransmit after
   2148 						 * timeout.  Do not enter fast
   2149 						 * recovery.
   2150 						 */
   2151 						tp->t_dupacks = 0;
   2152 						break;
   2153 					}
   2154 
   2155 					onxt = tp->snd_nxt;
   2156 					win = min(tp->snd_wnd, tp->snd_cwnd) /
   2157 					    2 /	tp->t_segsz;
   2158 					if (win < 2)
   2159 						win = 2;
   2160 					tp->snd_ssthresh = win * tp->t_segsz;
   2161 					tp->snd_recover = tp->snd_max;
   2162 					tp->t_partialacks = 0;
   2163 					TCP_TIMER_DISARM(tp, TCPT_REXMT);
   2164 					tp->t_rtttime = 0;
   2165 					if (TCP_SACK_ENABLED(tp)) {
   2166 						tp->t_dupacks = tcprexmtthresh;
   2167 						tp->sack_newdata = tp->snd_nxt;
   2168 						tp->snd_cwnd = tp->t_segsz;
   2169 						(void) tcp_output(tp);
   2170 						goto drop;
   2171 					}
   2172 					tp->snd_nxt = th->th_ack;
   2173 					tp->snd_cwnd = tp->t_segsz;
   2174 					(void) tcp_output(tp);
   2175 					tp->snd_cwnd = tp->snd_ssthresh +
   2176 					       tp->t_segsz * tp->t_dupacks;
   2177 					if (SEQ_GT(onxt, tp->snd_nxt))
   2178 						tp->snd_nxt = onxt;
   2179 					goto drop;
   2180 				} else if (tp->t_dupacks > tcprexmtthresh) {
   2181 					tp->snd_cwnd += tp->t_segsz;
   2182 					(void) tcp_output(tp);
   2183 					goto drop;
   2184 				}
   2185 			} else {
   2186 				/*
   2187 				 * If the ack appears to be very old, only
   2188 				 * allow data that is in-sequence.  This
   2189 				 * makes it somewhat more difficult to insert
   2190 				 * forged data by guessing sequence numbers.
   2191 				 * Sent an ack to try to update the send
   2192 				 * sequence number on the other side.
   2193 				 */
   2194 				if (tlen && th->th_seq != tp->rcv_nxt &&
   2195 				    SEQ_LT(th->th_ack,
   2196 				    tp->snd_una - tp->max_sndwnd))
   2197 					goto dropafterack;
   2198 			}
   2199 			break;
   2200 		}
   2201 		/*
   2202 		 * If the congestion window was inflated to account
   2203 		 * for the other side's cached packets, retract it.
   2204 		 */
   2205 		if (TCP_SACK_ENABLED(tp))
   2206 			tcp_sack_newack(tp, th);
   2207 		else if (tcp_do_newreno)
   2208 			tcp_newreno_newack(tp, th);
   2209 		else
   2210 			tcp_reno_newack(tp, th);
   2211 		if (SEQ_GT(th->th_ack, tp->snd_max)) {
   2212 			tcpstat.tcps_rcvacktoomuch++;
   2213 			goto dropafterack;
   2214 		}
   2215 		acked = th->th_ack - tp->snd_una;
   2216 		tcpstat.tcps_rcvackpack++;
   2217 		tcpstat.tcps_rcvackbyte += acked;
   2218 
   2219 		/*
   2220 		 * If we have a timestamp reply, update smoothed
   2221 		 * round trip time.  If no timestamp is present but
   2222 		 * transmit timer is running and timed sequence
   2223 		 * number was acked, update smoothed round trip time.
   2224 		 * Since we now have an rtt measurement, cancel the
   2225 		 * timer backoff (cf., Phil Karn's retransmit alg.).
   2226 		 * Recompute the initial retransmit timer.
   2227 		 */
   2228 		if (opti.ts_present && opti.ts_ecr)
   2229 			tcp_xmit_timer(tp, opti.ts_ecr);
   2230 		else if (tp->t_rtttime && SEQ_GT(th->th_ack, tp->t_rtseq))
   2231 			tcp_xmit_timer(tp, tcp_now - tp->t_rtttime);
   2232 
   2233 		/*
   2234 		 * If all outstanding data is acked, stop retransmit
   2235 		 * timer and remember to restart (more output or persist).
   2236 		 * If there is more data to be acked, restart retransmit
   2237 		 * timer, using current (possibly backed-off) value.
   2238 		 */
   2239 		if (th->th_ack == tp->snd_max) {
   2240 			TCP_TIMER_DISARM(tp, TCPT_REXMT);
   2241 			needoutput = 1;
   2242 		} else if (TCP_TIMER_ISARMED(tp, TCPT_PERSIST) == 0)
   2243 			TCP_TIMER_ARM(tp, TCPT_REXMT, tp->t_rxtcur);
   2244 		/*
   2245 		 * When new data is acked, open the congestion window.
   2246 		 * If the window gives us less than ssthresh packets
   2247 		 * in flight, open exponentially (segsz per packet).
   2248 		 * Otherwise open linearly: segsz per window
   2249 		 * (segsz^2 / cwnd per packet).
   2250 		 *
   2251 		 * If we are still in fast recovery (meaning we are using
   2252 		 * NewReno and we have only received partial acks), do not
   2253 		 * inflate the window yet.
   2254 		 */
   2255 		if (tp->t_partialacks < 0) {
   2256 			u_int cw = tp->snd_cwnd;
   2257 			u_int incr = tp->t_segsz;
   2258 
   2259 			if (cw >= tp->snd_ssthresh)
   2260 				incr = incr * incr / cw;
   2261 			tp->snd_cwnd = min(cw + incr,
   2262 			    TCP_MAXWIN << tp->snd_scale);
   2263 		}
   2264 		ND6_HINT(tp);
   2265 		if (acked > so->so_snd.sb_cc) {
   2266 			tp->snd_wnd -= so->so_snd.sb_cc;
   2267 			sbdrop(&so->so_snd, (int)so->so_snd.sb_cc);
   2268 			ourfinisacked = 1;
   2269 		} else {
   2270 			if (acked > (tp->t_lastoff - tp->t_inoff))
   2271 				tp->t_lastm = NULL;
   2272 			sbdrop(&so->so_snd, acked);
   2273 			tp->t_lastoff -= acked;
   2274 			tp->snd_wnd -= acked;
   2275 			ourfinisacked = 0;
   2276 		}
   2277 		sowwakeup(so);
   2278 		tp->snd_una = th->th_ack;
   2279 		if (SEQ_GT(tp->snd_una, tp->snd_fack))
   2280 			tp->snd_fack = tp->snd_una;
   2281 		if (SEQ_LT(tp->snd_nxt, tp->snd_una))
   2282 			tp->snd_nxt = tp->snd_una;
   2283 		if (SEQ_LT(tp->snd_high, tp->snd_una))
   2284 			tp->snd_high = tp->snd_una;
   2285 
   2286 		switch (tp->t_state) {
   2287 
   2288 		/*
   2289 		 * In FIN_WAIT_1 STATE in addition to the processing
   2290 		 * for the ESTABLISHED state if our FIN is now acknowledged
   2291 		 * then enter FIN_WAIT_2.
   2292 		 */
   2293 		case TCPS_FIN_WAIT_1:
   2294 			if (ourfinisacked) {
   2295 				/*
   2296 				 * If we can't receive any more
   2297 				 * data, then closing user can proceed.
   2298 				 * Starting the timer is contrary to the
   2299 				 * specification, but if we don't get a FIN
   2300 				 * we'll hang forever.
   2301 				 */
   2302 				if (so->so_state & SS_CANTRCVMORE) {
   2303 					soisdisconnected(so);
   2304 					if (tcp_maxidle > 0)
   2305 						TCP_TIMER_ARM(tp, TCPT_2MSL,
   2306 						    tcp_maxidle);
   2307 				}
   2308 				tp->t_state = TCPS_FIN_WAIT_2;
   2309 			}
   2310 			break;
   2311 
   2312 	 	/*
   2313 		 * In CLOSING STATE in addition to the processing for
   2314 		 * the ESTABLISHED state if the ACK acknowledges our FIN
   2315 		 * then enter the TIME-WAIT state, otherwise ignore
   2316 		 * the segment.
   2317 		 */
   2318 		case TCPS_CLOSING:
   2319 			if (ourfinisacked) {
   2320 				tp->t_state = TCPS_TIME_WAIT;
   2321 				tcp_canceltimers(tp);
   2322 				TCP_TIMER_ARM(tp, TCPT_2MSL, 2 * TCPTV_MSL);
   2323 				soisdisconnected(so);
   2324 			}
   2325 			break;
   2326 
   2327 		/*
   2328 		 * In LAST_ACK, we may still be waiting for data to drain
   2329 		 * and/or to be acked, as well as for the ack of our FIN.
   2330 		 * If our FIN is now acknowledged, delete the TCB,
   2331 		 * enter the closed state and return.
   2332 		 */
   2333 		case TCPS_LAST_ACK:
   2334 			if (ourfinisacked) {
   2335 				tp = tcp_close(tp);
   2336 				goto drop;
   2337 			}
   2338 			break;
   2339 
   2340 		/*
   2341 		 * In TIME_WAIT state the only thing that should arrive
   2342 		 * is a retransmission of the remote FIN.  Acknowledge
   2343 		 * it and restart the finack timer.
   2344 		 */
   2345 		case TCPS_TIME_WAIT:
   2346 			TCP_TIMER_ARM(tp, TCPT_2MSL, 2 * TCPTV_MSL);
   2347 			goto dropafterack;
   2348 		}
   2349 	}
   2350 
   2351 step6:
   2352 	/*
   2353 	 * Update window information.
   2354 	 * Don't look at window if no ACK: TAC's send garbage on first SYN.
   2355 	 */
   2356 	if ((tiflags & TH_ACK) && (SEQ_LT(tp->snd_wl1, th->th_seq) ||
   2357 	    (tp->snd_wl1 == th->th_seq && SEQ_LT(tp->snd_wl2, th->th_ack)) ||
   2358 	    (tp->snd_wl2 == th->th_ack && tiwin > tp->snd_wnd))) {
   2359 		/* keep track of pure window updates */
   2360 		if (tlen == 0 &&
   2361 		    tp->snd_wl2 == th->th_ack && tiwin > tp->snd_wnd)
   2362 			tcpstat.tcps_rcvwinupd++;
   2363 		tp->snd_wnd = tiwin;
   2364 		tp->snd_wl1 = th->th_seq;
   2365 		tp->snd_wl2 = th->th_ack;
   2366 		if (tp->snd_wnd > tp->max_sndwnd)
   2367 			tp->max_sndwnd = tp->snd_wnd;
   2368 		needoutput = 1;
   2369 	}
   2370 
   2371 	/*
   2372 	 * Process segments with URG.
   2373 	 */
   2374 	if ((tiflags & TH_URG) && th->th_urp &&
   2375 	    TCPS_HAVERCVDFIN(tp->t_state) == 0) {
   2376 		/*
   2377 		 * This is a kludge, but if we receive and accept
   2378 		 * random urgent pointers, we'll crash in
   2379 		 * soreceive.  It's hard to imagine someone
   2380 		 * actually wanting to send this much urgent data.
   2381 		 */
   2382 		if (th->th_urp + so->so_rcv.sb_cc > sb_max) {
   2383 			th->th_urp = 0;			/* XXX */
   2384 			tiflags &= ~TH_URG;		/* XXX */
   2385 			goto dodata;			/* XXX */
   2386 		}
   2387 		/*
   2388 		 * If this segment advances the known urgent pointer,
   2389 		 * then mark the data stream.  This should not happen
   2390 		 * in CLOSE_WAIT, CLOSING, LAST_ACK or TIME_WAIT STATES since
   2391 		 * a FIN has been received from the remote side.
   2392 		 * In these states we ignore the URG.
   2393 		 *
   2394 		 * According to RFC961 (Assigned Protocols),
   2395 		 * the urgent pointer points to the last octet
   2396 		 * of urgent data.  We continue, however,
   2397 		 * to consider it to indicate the first octet
   2398 		 * of data past the urgent section as the original
   2399 		 * spec states (in one of two places).
   2400 		 */
   2401 		if (SEQ_GT(th->th_seq+th->th_urp, tp->rcv_up)) {
   2402 			tp->rcv_up = th->th_seq + th->th_urp;
   2403 			so->so_oobmark = so->so_rcv.sb_cc +
   2404 			    (tp->rcv_up - tp->rcv_nxt) - 1;
   2405 			if (so->so_oobmark == 0)
   2406 				so->so_state |= SS_RCVATMARK;
   2407 			sohasoutofband(so);
   2408 			tp->t_oobflags &= ~(TCPOOB_HAVEDATA | TCPOOB_HADDATA);
   2409 		}
   2410 		/*
   2411 		 * Remove out of band data so doesn't get presented to user.
   2412 		 * This can happen independent of advancing the URG pointer,
   2413 		 * but if two URG's are pending at once, some out-of-band
   2414 		 * data may creep in... ick.
   2415 		 */
   2416 		if (th->th_urp <= (u_int16_t) tlen
   2417 #ifdef SO_OOBINLINE
   2418 		     && (so->so_options & SO_OOBINLINE) == 0
   2419 #endif
   2420 		     )
   2421 			tcp_pulloutofband(so, th, m, hdroptlen);
   2422 	} else
   2423 		/*
   2424 		 * If no out of band data is expected,
   2425 		 * pull receive urgent pointer along
   2426 		 * with the receive window.
   2427 		 */
   2428 		if (SEQ_GT(tp->rcv_nxt, tp->rcv_up))
   2429 			tp->rcv_up = tp->rcv_nxt;
   2430 dodata:							/* XXX */
   2431 
   2432 	/*
   2433 	 * Process the segment text, merging it into the TCP sequencing queue,
   2434 	 * and arranging for acknowledgement of receipt if necessary.
   2435 	 * This process logically involves adjusting tp->rcv_wnd as data
   2436 	 * is presented to the user (this happens in tcp_usrreq.c,
   2437 	 * case PRU_RCVD).  If a FIN has already been received on this
   2438 	 * connection then we just ignore the text.
   2439 	 */
   2440 	if ((tlen || (tiflags & TH_FIN)) &&
   2441 	    TCPS_HAVERCVDFIN(tp->t_state) == 0) {
   2442 		/*
   2443 		 * Insert segment ti into reassembly queue of tcp with
   2444 		 * control block tp.  Return TH_FIN if reassembly now includes
   2445 		 * a segment with FIN.  The macro form does the common case
   2446 		 * inline (segment is the next to be received on an
   2447 		 * established connection, and the queue is empty),
   2448 		 * avoiding linkage into and removal from the queue and
   2449 		 * repetition of various conversions.
   2450 		 * Set DELACK for segments received in order, but ack
   2451 		 * immediately when segments are out of order
   2452 		 * (so fast retransmit can work).
   2453 		 */
   2454 		/* NOTE: this was TCP_REASS() macro, but used only once */
   2455 		TCP_REASS_LOCK(tp);
   2456 		if (th->th_seq == tp->rcv_nxt &&
   2457 		    TAILQ_FIRST(&tp->segq) == NULL &&
   2458 		    tp->t_state == TCPS_ESTABLISHED) {
   2459 			TCP_SETUP_ACK(tp, th);
   2460 			tp->rcv_nxt += tlen;
   2461 			tiflags = th->th_flags & TH_FIN;
   2462 			tcpstat.tcps_rcvpack++;
   2463 			tcpstat.tcps_rcvbyte += tlen;
   2464 			ND6_HINT(tp);
   2465 			if (so->so_state & SS_CANTRCVMORE)
   2466 				m_freem(m);
   2467 			else {
   2468 				m_adj(m, hdroptlen);
   2469 				sbappendstream(&(so)->so_rcv, m);
   2470 			}
   2471 			sorwakeup(so);
   2472 		} else {
   2473 			m_adj(m, hdroptlen);
   2474 			tiflags = tcp_reass(tp, th, m, &tlen);
   2475 			tp->t_flags |= TF_ACKNOW;
   2476 		}
   2477 		TCP_REASS_UNLOCK(tp);
   2478 
   2479 		/*
   2480 		 * Note the amount of data that peer has sent into
   2481 		 * our window, in order to estimate the sender's
   2482 		 * buffer size.
   2483 		 */
   2484 		len = so->so_rcv.sb_hiwat - (tp->rcv_adv - tp->rcv_nxt);
   2485 	} else {
   2486 		m_freem(m);
   2487 		m = NULL;
   2488 		tiflags &= ~TH_FIN;
   2489 	}
   2490 
   2491 	/*
   2492 	 * If FIN is received ACK the FIN and let the user know
   2493 	 * that the connection is closing.  Ignore a FIN received before
   2494 	 * the connection is fully established.
   2495 	 */
   2496 	if ((tiflags & TH_FIN) && TCPS_HAVEESTABLISHED(tp->t_state)) {
   2497 		if (TCPS_HAVERCVDFIN(tp->t_state) == 0) {
   2498 			socantrcvmore(so);
   2499 			tp->t_flags |= TF_ACKNOW;
   2500 			tp->rcv_nxt++;
   2501 		}
   2502 		switch (tp->t_state) {
   2503 
   2504 	 	/*
   2505 		 * In ESTABLISHED STATE enter the CLOSE_WAIT state.
   2506 		 */
   2507 		case TCPS_ESTABLISHED:
   2508 			tp->t_state = TCPS_CLOSE_WAIT;
   2509 			break;
   2510 
   2511 	 	/*
   2512 		 * If still in FIN_WAIT_1 STATE FIN has not been acked so
   2513 		 * enter the CLOSING state.
   2514 		 */
   2515 		case TCPS_FIN_WAIT_1:
   2516 			tp->t_state = TCPS_CLOSING;
   2517 			break;
   2518 
   2519 	 	/*
   2520 		 * In FIN_WAIT_2 state enter the TIME_WAIT state,
   2521 		 * starting the time-wait timer, turning off the other
   2522 		 * standard timers.
   2523 		 */
   2524 		case TCPS_FIN_WAIT_2:
   2525 			tp->t_state = TCPS_TIME_WAIT;
   2526 			tcp_canceltimers(tp);
   2527 			TCP_TIMER_ARM(tp, TCPT_2MSL, 2 * TCPTV_MSL);
   2528 			soisdisconnected(so);
   2529 			break;
   2530 
   2531 		/*
   2532 		 * In TIME_WAIT state restart the 2 MSL time_wait timer.
   2533 		 */
   2534 		case TCPS_TIME_WAIT:
   2535 			TCP_TIMER_ARM(tp, TCPT_2MSL, 2 * TCPTV_MSL);
   2536 			break;
   2537 		}
   2538 	}
   2539 #ifdef TCP_DEBUG
   2540 	if (so->so_options & SO_DEBUG)
   2541 		tcp_trace(TA_INPUT, ostate, tp, tcp_saveti, 0);
   2542 #endif
   2543 
   2544 	/*
   2545 	 * Return any desired output.
   2546 	 */
   2547 	if (needoutput || (tp->t_flags & TF_ACKNOW)) {
   2548 		(void) tcp_output(tp);
   2549 	}
   2550 	if (tcp_saveti)
   2551 		m_freem(tcp_saveti);
   2552 	return;
   2553 
   2554 badsyn:
   2555 	/*
   2556 	 * Received a bad SYN.  Increment counters and dropwithreset.
   2557 	 */
   2558 	tcpstat.tcps_badsyn++;
   2559 	tp = NULL;
   2560 	goto dropwithreset;
   2561 
   2562 dropafterack:
   2563 	/*
   2564 	 * Generate an ACK dropping incoming segment if it occupies
   2565 	 * sequence space, where the ACK reflects our state.
   2566 	 */
   2567 	if (tiflags & TH_RST)
   2568 		goto drop;
   2569 	goto dropafterack2;
   2570 
   2571 dropafterack_ratelim:
   2572 	/*
   2573 	 * We may want to rate-limit ACKs against SYN/RST attack.
   2574 	 */
   2575 	if (ppsratecheck(&tcp_ackdrop_ppslim_last, &tcp_ackdrop_ppslim_count,
   2576 	    tcp_ackdrop_ppslim) == 0) {
   2577 		/* XXX stat */
   2578 		goto drop;
   2579 	}
   2580 	/* ...fall into dropafterack2... */
   2581 
   2582 dropafterack2:
   2583 	m_freem(m);
   2584 	tp->t_flags |= TF_ACKNOW;
   2585 	(void) tcp_output(tp);
   2586 	if (tcp_saveti)
   2587 		m_freem(tcp_saveti);
   2588 	return;
   2589 
   2590 dropwithreset_ratelim:
   2591 	/*
   2592 	 * We may want to rate-limit RSTs in certain situations,
   2593 	 * particularly if we are sending an RST in response to
   2594 	 * an attempt to connect to or otherwise communicate with
   2595 	 * a port for which we have no socket.
   2596 	 */
   2597 	if (ppsratecheck(&tcp_rst_ppslim_last, &tcp_rst_ppslim_count,
   2598 	    tcp_rst_ppslim) == 0) {
   2599 		/* XXX stat */
   2600 		goto drop;
   2601 	}
   2602 	/* ...fall into dropwithreset... */
   2603 
   2604 dropwithreset:
   2605 	/*
   2606 	 * Generate a RST, dropping incoming segment.
   2607 	 * Make ACK acceptable to originator of segment.
   2608 	 */
   2609 	if (tiflags & TH_RST)
   2610 		goto drop;
   2611 
   2612 	switch (af) {
   2613 #ifdef INET6
   2614 	case AF_INET6:
   2615 		/* For following calls to tcp_respond */
   2616 		if (IN6_IS_ADDR_MULTICAST(&ip6->ip6_dst))
   2617 			goto drop;
   2618 		break;
   2619 #endif /* INET6 */
   2620 	case AF_INET:
   2621 		if (IN_MULTICAST(ip->ip_dst.s_addr) ||
   2622 		    in_broadcast(ip->ip_dst, m->m_pkthdr.rcvif))
   2623 			goto drop;
   2624 	}
   2625 
   2626 	if (tiflags & TH_ACK)
   2627 		(void)tcp_respond(tp, m, m, th, (tcp_seq)0, th->th_ack, TH_RST);
   2628 	else {
   2629 		if (tiflags & TH_SYN)
   2630 			tlen++;
   2631 		(void)tcp_respond(tp, m, m, th, th->th_seq + tlen, (tcp_seq)0,
   2632 		    TH_RST|TH_ACK);
   2633 	}
   2634 	if (tcp_saveti)
   2635 		m_freem(tcp_saveti);
   2636 	return;
   2637 
   2638 badcsum:
   2639 drop:
   2640 	/*
   2641 	 * Drop space held by incoming segment and return.
   2642 	 */
   2643 	if (tp) {
   2644 		if (tp->t_inpcb)
   2645 			so = tp->t_inpcb->inp_socket;
   2646 #ifdef INET6
   2647 		else if (tp->t_in6pcb)
   2648 			so = tp->t_in6pcb->in6p_socket;
   2649 #endif
   2650 		else
   2651 			so = NULL;
   2652 #ifdef TCP_DEBUG
   2653 		if (so && (so->so_options & SO_DEBUG) != 0)
   2654 			tcp_trace(TA_DROP, ostate, tp, tcp_saveti, 0);
   2655 #endif
   2656 	}
   2657 	if (tcp_saveti)
   2658 		m_freem(tcp_saveti);
   2659 	m_freem(m);
   2660 	return;
   2661 }
   2662 
   2663 #ifdef TCP_SIGNATURE
   2664 int
   2665 tcp_signature_apply(void *fstate, caddr_t data, u_int len)
   2666 {
   2667 
   2668 	MD5Update(fstate, (u_char *)data, len);
   2669 	return (0);
   2670 }
   2671 
   2672 struct secasvar *
   2673 tcp_signature_getsav(struct mbuf *m, struct tcphdr *th)
   2674 {
   2675 	struct secasvar *sav;
   2676 #ifdef FAST_IPSEC
   2677 	union sockaddr_union dst;
   2678 #endif
   2679 	struct ip *ip;
   2680 	struct ip6_hdr *ip6;
   2681 
   2682 	ip = mtod(m, struct ip *);
   2683 	switch (ip->ip_v) {
   2684 	case 4:
   2685 		ip = mtod(m, struct ip *);
   2686 		ip6 = NULL;
   2687 		break;
   2688 	case 6:
   2689 		ip = NULL;
   2690 		ip6 = mtod(m, struct ip6_hdr *);
   2691 		break;
   2692 	default:
   2693 		return (NULL);
   2694 	}
   2695 
   2696 #ifdef FAST_IPSEC
   2697 	/* Extract the destination from the IP header in the mbuf. */
   2698 	bzero(&dst, sizeof(union sockaddr_union));
   2699 	dst.sa.sa_len = sizeof(struct sockaddr_in);
   2700 	dst.sa.sa_family = AF_INET;
   2701 	dst.sin.sin_addr = ip->ip_dst;
   2702 
   2703 	/*
   2704 	 * Look up an SADB entry which matches the address of the peer.
   2705 	 */
   2706 	sav = KEY_ALLOCSA(&dst, IPPROTO_TCP, htonl(TCP_SIG_SPI));
   2707 #else
   2708 	if (ip)
   2709 		sav = key_allocsa(AF_INET, (caddr_t)&ip->ip_src,
   2710 		    (caddr_t)&ip->ip_dst, IPPROTO_TCP,
   2711 		    htonl(TCP_SIG_SPI), 0, 0);
   2712 	else
   2713 		sav = key_allocsa(AF_INET6, (caddr_t)&ip6->ip6_src,
   2714 		    (caddr_t)&ip6->ip6_dst, IPPROTO_TCP,
   2715 		    htonl(TCP_SIG_SPI), 0, 0);
   2716 #endif
   2717 
   2718 	return (sav);	/* freesav must be performed by caller */
   2719 }
   2720 
   2721 int
   2722 tcp_signature(struct mbuf *m, struct tcphdr *th, int thoff,
   2723     struct secasvar *sav, char *sig)
   2724 {
   2725 	MD5_CTX ctx;
   2726 	struct ip *ip;
   2727 	struct ipovly *ipovly;
   2728 	struct ip6_hdr *ip6;
   2729 	struct ippseudo ippseudo;
   2730 	struct ip6_hdr_pseudo ip6pseudo;
   2731 	struct tcphdr th0;
   2732 	int l, tcphdrlen;
   2733 
   2734 	if (sav == NULL)
   2735 		return (-1);
   2736 
   2737 	tcphdrlen = th->th_off * 4;
   2738 
   2739 	switch (mtod(m, struct ip *)->ip_v) {
   2740 	case 4:
   2741 		ip = mtod(m, struct ip *);
   2742 		ip6 = NULL;
   2743 		break;
   2744 	case 6:
   2745 		ip = NULL;
   2746 		ip6 = mtod(m, struct ip6_hdr *);
   2747 		break;
   2748 	default:
   2749 		return (-1);
   2750 	}
   2751 
   2752 	MD5Init(&ctx);
   2753 
   2754 	if (ip) {
   2755 		memset(&ippseudo, 0, sizeof(ippseudo));
   2756 		ipovly = (struct ipovly *)ip;
   2757 		ippseudo.ippseudo_src = ipovly->ih_src;
   2758 		ippseudo.ippseudo_dst = ipovly->ih_dst;
   2759 		ippseudo.ippseudo_pad = 0;
   2760 		ippseudo.ippseudo_p = IPPROTO_TCP;
   2761 		ippseudo.ippseudo_len = htons(m->m_pkthdr.len - thoff);
   2762 		MD5Update(&ctx, (char *)&ippseudo, sizeof(ippseudo));
   2763 	} else {
   2764 		memset(&ip6pseudo, 0, sizeof(ip6pseudo));
   2765 		ip6pseudo.ip6ph_src = ip6->ip6_src;
   2766 		in6_clearscope(&ip6pseudo.ip6ph_src);
   2767 		ip6pseudo.ip6ph_dst = ip6->ip6_dst;
   2768 		in6_clearscope(&ip6pseudo.ip6ph_dst);
   2769 		ip6pseudo.ip6ph_len = htons(m->m_pkthdr.len - thoff);
   2770 		ip6pseudo.ip6ph_nxt = IPPROTO_TCP;
   2771 		MD5Update(&ctx, (char *)&ip6pseudo, sizeof(ip6pseudo));
   2772 	}
   2773 
   2774 	th0 = *th;
   2775 	th0.th_sum = 0;
   2776 	MD5Update(&ctx, (char *)&th0, sizeof(th0));
   2777 
   2778 	l = m->m_pkthdr.len - thoff - tcphdrlen;
   2779 	if (l > 0)
   2780 		m_apply(m, thoff + tcphdrlen,
   2781 		    m->m_pkthdr.len - thoff - tcphdrlen,
   2782 		    tcp_signature_apply, &ctx);
   2783 
   2784 	MD5Update(&ctx, _KEYBUF(sav->key_auth), _KEYLEN(sav->key_auth));
   2785 	MD5Final(sig, &ctx);
   2786 
   2787 	return (0);
   2788 }
   2789 #endif
   2790 
   2791 int
   2792 tcp_dooptions(struct tcpcb *tp, u_char *cp, int cnt, struct tcphdr *th,
   2793     struct mbuf *m, int toff, struct tcp_opt_info *oi)
   2794 {
   2795 	u_int16_t mss;
   2796 	int opt, optlen = 0;
   2797 #ifdef TCP_SIGNATURE
   2798 	caddr_t sigp = NULL;
   2799 	char sigbuf[TCP_SIGLEN];
   2800 	struct secasvar *sav = NULL;
   2801 #endif
   2802 
   2803 	for (; cp && cnt > 0; cnt -= optlen, cp += optlen) {
   2804 		opt = cp[0];
   2805 		if (opt == TCPOPT_EOL)
   2806 			break;
   2807 		if (opt == TCPOPT_NOP)
   2808 			optlen = 1;
   2809 		else {
   2810 			if (cnt < 2)
   2811 				break;
   2812 			optlen = cp[1];
   2813 			if (optlen < 2 || optlen > cnt)
   2814 				break;
   2815 		}
   2816 		switch (opt) {
   2817 
   2818 		default:
   2819 			continue;
   2820 
   2821 		case TCPOPT_MAXSEG:
   2822 			if (optlen != TCPOLEN_MAXSEG)
   2823 				continue;
   2824 			if (!(th->th_flags & TH_SYN))
   2825 				continue;
   2826 			bcopy(cp + 2, &mss, sizeof(mss));
   2827 			oi->maxseg = ntohs(mss);
   2828 			break;
   2829 
   2830 		case TCPOPT_WINDOW:
   2831 			if (optlen != TCPOLEN_WINDOW)
   2832 				continue;
   2833 			if (!(th->th_flags & TH_SYN))
   2834 				continue;
   2835 			tp->t_flags |= TF_RCVD_SCALE;
   2836 			tp->requested_s_scale = cp[2];
   2837 			if (tp->requested_s_scale > TCP_MAX_WINSHIFT) {
   2838 #if 0	/*XXX*/
   2839 				char *p;
   2840 
   2841 				if (ip)
   2842 					p = ntohl(ip->ip_src);
   2843 #ifdef INET6
   2844 				else if (ip6)
   2845 					p = ip6_sprintf(&ip6->ip6_src);
   2846 #endif
   2847 				else
   2848 					p = "(unknown)";
   2849 				log(LOG_ERR, "TCP: invalid wscale %d from %s, "
   2850 				    "assuming %d\n",
   2851 				    tp->requested_s_scale, p,
   2852 				    TCP_MAX_WINSHIFT);
   2853 #else
   2854 				log(LOG_ERR, "TCP: invalid wscale %d, "
   2855 				    "assuming %d\n",
   2856 				    tp->requested_s_scale,
   2857 				    TCP_MAX_WINSHIFT);
   2858 #endif
   2859 				tp->requested_s_scale = TCP_MAX_WINSHIFT;
   2860 			}
   2861 			break;
   2862 
   2863 		case TCPOPT_TIMESTAMP:
   2864 			if (optlen != TCPOLEN_TIMESTAMP)
   2865 				continue;
   2866 			oi->ts_present = 1;
   2867 			bcopy(cp + 2, &oi->ts_val, sizeof(oi->ts_val));
   2868 			NTOHL(oi->ts_val);
   2869 			bcopy(cp + 6, &oi->ts_ecr, sizeof(oi->ts_ecr));
   2870 			NTOHL(oi->ts_ecr);
   2871 
   2872 			/*
   2873 			 * A timestamp received in a SYN makes
   2874 			 * it ok to send timestamp requests and replies.
   2875 			 */
   2876 			if (th->th_flags & TH_SYN) {
   2877 				tp->t_flags |= TF_RCVD_TSTMP;
   2878 				tp->ts_recent = oi->ts_val;
   2879 				tp->ts_recent_age = tcp_now;
   2880 			}
   2881 			break;
   2882 		case TCPOPT_SACK_PERMITTED:
   2883 			if (optlen != TCPOLEN_SACK_PERMITTED)
   2884 				continue;
   2885 			if (!(th->th_flags & TH_SYN))
   2886 				continue;
   2887 			if (tcp_do_sack) {
   2888 				tp->t_flags |= TF_SACK_PERMIT;
   2889 				tp->t_flags |= TF_WILL_SACK;
   2890 			}
   2891 			break;
   2892 
   2893 		case TCPOPT_SACK:
   2894 			tcp_sack_option(tp, th, cp, optlen);
   2895 			break;
   2896 #ifdef TCP_SIGNATURE
   2897 		case TCPOPT_SIGNATURE:
   2898 			if (optlen != TCPOLEN_SIGNATURE)
   2899 				continue;
   2900 			if (sigp && bcmp(sigp, cp + 2, TCP_SIGLEN))
   2901 				return (-1);
   2902 
   2903 			sigp = sigbuf;
   2904 			memcpy(sigbuf, cp + 2, TCP_SIGLEN);
   2905 			memset(cp + 2, 0, TCP_SIGLEN);
   2906 			tp->t_flags |= TF_SIGNATURE;
   2907 			break;
   2908 #endif
   2909 		}
   2910 	}
   2911 
   2912 #ifdef TCP_SIGNATURE
   2913 	if (tp->t_flags & TF_SIGNATURE) {
   2914 
   2915 		sav = tcp_signature_getsav(m, th);
   2916 
   2917 		if (sav == NULL && tp->t_state == TCPS_LISTEN)
   2918 			return (-1);
   2919 	}
   2920 
   2921 	if ((sigp ? TF_SIGNATURE : 0) ^ (tp->t_flags & TF_SIGNATURE)) {
   2922 		if (sav == NULL)
   2923 			return (-1);
   2924 #ifdef FAST_IPSEC
   2925 		KEY_FREESAV(&sav);
   2926 #else
   2927 		key_freesav(sav);
   2928 #endif
   2929 		return (-1);
   2930 	}
   2931 
   2932 	if (sigp) {
   2933 		char sig[TCP_SIGLEN];
   2934 
   2935 		TCP_FIELDS_TO_NET(th);
   2936 		if (tcp_signature(m, th, toff, sav, sig) < 0) {
   2937 			TCP_FIELDS_TO_HOST(th);
   2938 			if (sav == NULL)
   2939 				return (-1);
   2940 #ifdef FAST_IPSEC
   2941 			KEY_FREESAV(&sav);
   2942 #else
   2943 			key_freesav(sav);
   2944 #endif
   2945 			return (-1);
   2946 		}
   2947 		TCP_FIELDS_TO_HOST(th);
   2948 
   2949 		if (bcmp(sig, sigp, TCP_SIGLEN)) {
   2950 			tcpstat.tcps_badsig++;
   2951 			if (sav == NULL)
   2952 				return (-1);
   2953 #ifdef FAST_IPSEC
   2954 			KEY_FREESAV(&sav);
   2955 #else
   2956 			key_freesav(sav);
   2957 #endif
   2958 			return (-1);
   2959 		} else
   2960 			tcpstat.tcps_goodsig++;
   2961 
   2962 		key_sa_recordxfer(sav, m);
   2963 #ifdef FAST_IPSEC
   2964 		KEY_FREESAV(&sav);
   2965 #else
   2966 		key_freesav(sav);
   2967 #endif
   2968 	}
   2969 #endif
   2970 
   2971 	return (0);
   2972 }
   2973 
   2974 /*
   2975  * Pull out of band byte out of a segment so
   2976  * it doesn't appear in the user's data queue.
   2977  * It is still reflected in the segment length for
   2978  * sequencing purposes.
   2979  */
   2980 void
   2981 tcp_pulloutofband(struct socket *so, struct tcphdr *th,
   2982     struct mbuf *m, int off)
   2983 {
   2984 	int cnt = off + th->th_urp - 1;
   2985 
   2986 	while (cnt >= 0) {
   2987 		if (m->m_len > cnt) {
   2988 			char *cp = mtod(m, caddr_t) + cnt;
   2989 			struct tcpcb *tp = sototcpcb(so);
   2990 
   2991 			tp->t_iobc = *cp;
   2992 			tp->t_oobflags |= TCPOOB_HAVEDATA;
   2993 			bcopy(cp+1, cp, (unsigned)(m->m_len - cnt - 1));
   2994 			m->m_len--;
   2995 			return;
   2996 		}
   2997 		cnt -= m->m_len;
   2998 		m = m->m_next;
   2999 		if (m == 0)
   3000 			break;
   3001 	}
   3002 	panic("tcp_pulloutofband");
   3003 }
   3004 
   3005 /*
   3006  * Collect new round-trip time estimate
   3007  * and update averages and current timeout.
   3008  */
   3009 void
   3010 tcp_xmit_timer(struct tcpcb *tp, uint32_t rtt)
   3011 {
   3012 	int32_t delta;
   3013 
   3014 	tcpstat.tcps_rttupdated++;
   3015 	if (tp->t_srtt != 0) {
   3016 		/*
   3017 		 * srtt is stored as fixed point with 3 bits after the
   3018 		 * binary point (i.e., scaled by 8).  The following magic
   3019 		 * is equivalent to the smoothing algorithm in rfc793 with
   3020 		 * an alpha of .875 (srtt = rtt/8 + srtt*7/8 in fixed
   3021 		 * point).  Adjust rtt to origin 0.
   3022 		 */
   3023 		delta = (rtt << 2) - (tp->t_srtt >> TCP_RTT_SHIFT);
   3024 		if ((tp->t_srtt += delta) <= 0)
   3025 			tp->t_srtt = 1 << 2;
   3026 		/*
   3027 		 * We accumulate a smoothed rtt variance (actually, a
   3028 		 * smoothed mean difference), then set the retransmit
   3029 		 * timer to smoothed rtt + 4 times the smoothed variance.
   3030 		 * rttvar is stored as fixed point with 2 bits after the
   3031 		 * binary point (scaled by 4).  The following is
   3032 		 * equivalent to rfc793 smoothing with an alpha of .75
   3033 		 * (rttvar = rttvar*3/4 + |delta| / 4).  This replaces
   3034 		 * rfc793's wired-in beta.
   3035 		 */
   3036 		if (delta < 0)
   3037 			delta = -delta;
   3038 		delta -= (tp->t_rttvar >> TCP_RTTVAR_SHIFT);
   3039 		if ((tp->t_rttvar += delta) <= 0)
   3040 			tp->t_rttvar = 1 << 2;
   3041 	} else {
   3042 		/*
   3043 		 * No rtt measurement yet - use the unsmoothed rtt.
   3044 		 * Set the variance to half the rtt (so our first
   3045 		 * retransmit happens at 3*rtt).
   3046 		 */
   3047 		tp->t_srtt = rtt << (TCP_RTT_SHIFT + 2);
   3048 		tp->t_rttvar = rtt << (TCP_RTTVAR_SHIFT + 2 - 1);
   3049 	}
   3050 	tp->t_rtttime = 0;
   3051 	tp->t_rxtshift = 0;
   3052 
   3053 	/*
   3054 	 * the retransmit should happen at rtt + 4 * rttvar.
   3055 	 * Because of the way we do the smoothing, srtt and rttvar
   3056 	 * will each average +1/2 tick of bias.  When we compute
   3057 	 * the retransmit timer, we want 1/2 tick of rounding and
   3058 	 * 1 extra tick because of +-1/2 tick uncertainty in the
   3059 	 * firing of the timer.  The bias will give us exactly the
   3060 	 * 1.5 tick we need.  But, because the bias is
   3061 	 * statistical, we have to test that we don't drop below
   3062 	 * the minimum feasible timer (which is 2 ticks).
   3063 	 */
   3064 	TCPT_RANGESET(tp->t_rxtcur, TCP_REXMTVAL(tp),
   3065 	    max(tp->t_rttmin, rtt + 2), TCPTV_REXMTMAX);
   3066 
   3067 	/*
   3068 	 * We received an ack for a packet that wasn't retransmitted;
   3069 	 * it is probably safe to discard any error indications we've
   3070 	 * received recently.  This isn't quite right, but close enough
   3071 	 * for now (a route might have failed after we sent a segment,
   3072 	 * and the return path might not be symmetrical).
   3073 	 */
   3074 	tp->t_softerror = 0;
   3075 }
   3076 
   3077 void
   3078 tcp_reno_newack(struct tcpcb *tp, struct tcphdr *th)
   3079 {
   3080 	if (tp->t_partialacks < 0) {
   3081 		/*
   3082 		 * We were not in fast recovery.  Reset the duplicate ack
   3083 		 * counter.
   3084 		 */
   3085 		tp->t_dupacks = 0;
   3086 	} else {
   3087 		/*
   3088 		 * Clamp the congestion window to the crossover point and
   3089 		 * exit fast recovery.
   3090 		 */
   3091 		if (tp->snd_cwnd > tp->snd_ssthresh)
   3092 			tp->snd_cwnd = tp->snd_ssthresh;
   3093 		tp->t_partialacks = -1;
   3094 		tp->t_dupacks = 0;
   3095 	}
   3096 }
   3097 
   3098 /*
   3099  * Implement the NewReno response to a new ack, checking for partial acks in
   3100  * fast recovery.
   3101  */
   3102 void
   3103 tcp_newreno_newack(struct tcpcb *tp, struct tcphdr *th)
   3104 {
   3105 	if (tp->t_partialacks < 0) {
   3106 		/*
   3107 		 * We were not in fast recovery.  Reset the duplicate ack
   3108 		 * counter.
   3109 		 */
   3110 		tp->t_dupacks = 0;
   3111 	} else if (SEQ_LT(th->th_ack, tp->snd_recover)) {
   3112 		/*
   3113 		 * This is a partial ack.  Retransmit the first unacknowledged
   3114 		 * segment and deflate the congestion window by the amount of
   3115 		 * acknowledged data.  Do not exit fast recovery.
   3116 		 */
   3117 		tcp_seq onxt = tp->snd_nxt;
   3118 		u_long ocwnd = tp->snd_cwnd;
   3119 
   3120 		/*
   3121 		 * snd_una has not yet been updated and the socket's send
   3122 		 * buffer has not yet drained off the ACK'd data, so we
   3123 		 * have to leave snd_una as it was to get the correct data
   3124 		 * offset in tcp_output().
   3125 		 */
   3126 		if (++tp->t_partialacks == 1)
   3127 			TCP_TIMER_DISARM(tp, TCPT_REXMT);
   3128 		tp->t_rtttime = 0;
   3129 		tp->snd_nxt = th->th_ack;
   3130 		/*
   3131 		 * Set snd_cwnd to one segment beyond ACK'd offset.  snd_una
   3132 		 * is not yet updated when we're called.
   3133 		 */
   3134 		tp->snd_cwnd = tp->t_segsz + (th->th_ack - tp->snd_una);
   3135 		(void) tcp_output(tp);
   3136 		tp->snd_cwnd = ocwnd;
   3137 		if (SEQ_GT(onxt, tp->snd_nxt))
   3138 			tp->snd_nxt = onxt;
   3139 		/*
   3140 		 * Partial window deflation.  Relies on fact that tp->snd_una
   3141 		 * not updated yet.
   3142 		 */
   3143 		tp->snd_cwnd -= (th->th_ack - tp->snd_una - tp->t_segsz);
   3144 	} else {
   3145 		/*
   3146 		 * Complete ack.  Inflate the congestion window to ssthresh
   3147 		 * and exit fast recovery.
   3148 		 *
   3149 		 * Window inflation should have left us with approx.
   3150 		 * snd_ssthresh outstanding data.  But in case we
   3151 		 * would be inclined to send a burst, better to do
   3152 		 * it via the slow start mechanism.
   3153 		 */
   3154 		if (SEQ_SUB(tp->snd_max, th->th_ack) < tp->snd_ssthresh)
   3155 			tp->snd_cwnd = SEQ_SUB(tp->snd_max, th->th_ack)
   3156 			    + tp->t_segsz;
   3157 		else
   3158 			tp->snd_cwnd = tp->snd_ssthresh;
   3159 		tp->t_partialacks = -1;
   3160 		tp->t_dupacks = 0;
   3161 	}
   3162 }
   3163 
   3164 
   3165 /*
   3166  * TCP compressed state engine.  Currently used to hold compressed
   3167  * state for SYN_RECEIVED.
   3168  */
   3169 
   3170 u_long	syn_cache_count;
   3171 u_int32_t syn_hash1, syn_hash2;
   3172 
   3173 #define SYN_HASH(sa, sp, dp) \
   3174 	((((sa)->s_addr^syn_hash1)*(((((u_int32_t)(dp))<<16) + \
   3175 				     ((u_int32_t)(sp)))^syn_hash2)))
   3176 #ifndef INET6
   3177 #define	SYN_HASHALL(hash, src, dst) \
   3178 do {									\
   3179 	hash = SYN_HASH(&((const struct sockaddr_in *)(src))->sin_addr,	\
   3180 		((const struct sockaddr_in *)(src))->sin_port,		\
   3181 		((const struct sockaddr_in *)(dst))->sin_port);		\
   3182 } while (/*CONSTCOND*/ 0)
   3183 #else
   3184 #define SYN_HASH6(sa, sp, dp) \
   3185 	((((sa)->s6_addr32[0] ^ (sa)->s6_addr32[3] ^ syn_hash1) * \
   3186 	  (((((u_int32_t)(dp))<<16) + ((u_int32_t)(sp)))^syn_hash2)) \
   3187 	 & 0x7fffffff)
   3188 
   3189 #define SYN_HASHALL(hash, src, dst) \
   3190 do {									\
   3191 	switch ((src)->sa_family) {					\
   3192 	case AF_INET:							\
   3193 		hash = SYN_HASH(&((const struct sockaddr_in *)(src))->sin_addr, \
   3194 			((const struct sockaddr_in *)(src))->sin_port,	\
   3195 			((const struct sockaddr_in *)(dst))->sin_port);	\
   3196 		break;							\
   3197 	case AF_INET6:							\
   3198 		hash = SYN_HASH6(&((const struct sockaddr_in6 *)(src))->sin6_addr, \
   3199 			((const struct sockaddr_in6 *)(src))->sin6_port,	\
   3200 			((const struct sockaddr_in6 *)(dst))->sin6_port);	\
   3201 		break;							\
   3202 	default:							\
   3203 		hash = 0;						\
   3204 	}								\
   3205 } while (/*CONSTCOND*/0)
   3206 #endif /* INET6 */
   3207 
   3208 #define	SYN_CACHE_RM(sc)						\
   3209 do {									\
   3210 	TAILQ_REMOVE(&tcp_syn_cache[(sc)->sc_bucketidx].sch_bucket,	\
   3211 	    (sc), sc_bucketq);						\
   3212 	(sc)->sc_tp = NULL;						\
   3213 	LIST_REMOVE((sc), sc_tpq);					\
   3214 	tcp_syn_cache[(sc)->sc_bucketidx].sch_length--;			\
   3215 	callout_stop(&(sc)->sc_timer);					\
   3216 	syn_cache_count--;						\
   3217 } while (/*CONSTCOND*/0)
   3218 
   3219 #define	SYN_CACHE_PUT(sc)						\
   3220 do {									\
   3221 	if ((sc)->sc_ipopts)						\
   3222 		(void) m_free((sc)->sc_ipopts);				\
   3223 	if ((sc)->sc_route4.ro_rt != NULL)				\
   3224 		RTFREE((sc)->sc_route4.ro_rt);				\
   3225 	if (callout_invoking(&(sc)->sc_timer))				\
   3226 		(sc)->sc_flags |= SCF_DEAD;				\
   3227 	else								\
   3228 		pool_put(&syn_cache_pool, (sc));			\
   3229 } while (/*CONSTCOND*/0)
   3230 
   3231 POOL_INIT(syn_cache_pool, sizeof(struct syn_cache), 0, 0, 0, "synpl", NULL);
   3232 
   3233 /*
   3234  * We don't estimate RTT with SYNs, so each packet starts with the default
   3235  * RTT and each timer step has a fixed timeout value.
   3236  */
   3237 #define	SYN_CACHE_TIMER_ARM(sc)						\
   3238 do {									\
   3239 	TCPT_RANGESET((sc)->sc_rxtcur,					\
   3240 	    TCPTV_SRTTDFLT * tcp_backoff[(sc)->sc_rxtshift], TCPTV_MIN,	\
   3241 	    TCPTV_REXMTMAX);						\
   3242 	callout_reset(&(sc)->sc_timer,					\
   3243 	    (sc)->sc_rxtcur * (hz / PR_SLOWHZ), syn_cache_timer, (sc));	\
   3244 } while (/*CONSTCOND*/0)
   3245 
   3246 #define	SYN_CACHE_TIMESTAMP(sc)	(tcp_now - (sc)->sc_timebase)
   3247 
   3248 void
   3249 syn_cache_init(void)
   3250 {
   3251 	int i;
   3252 
   3253 	/* Initialize the hash buckets. */
   3254 	for (i = 0; i < tcp_syn_cache_size; i++)
   3255 		TAILQ_INIT(&tcp_syn_cache[i].sch_bucket);
   3256 }
   3257 
   3258 void
   3259 syn_cache_insert(struct syn_cache *sc, struct tcpcb *tp)
   3260 {
   3261 	struct syn_cache_head *scp;
   3262 	struct syn_cache *sc2;
   3263 	int s;
   3264 
   3265 	/*
   3266 	 * If there are no entries in the hash table, reinitialize
   3267 	 * the hash secrets.
   3268 	 */
   3269 	if (syn_cache_count == 0) {
   3270 		syn_hash1 = arc4random();
   3271 		syn_hash2 = arc4random();
   3272 	}
   3273 
   3274 	SYN_HASHALL(sc->sc_hash, &sc->sc_src.sa, &sc->sc_dst.sa);
   3275 	sc->sc_bucketidx = sc->sc_hash % tcp_syn_cache_size;
   3276 	scp = &tcp_syn_cache[sc->sc_bucketidx];
   3277 
   3278 	/*
   3279 	 * Make sure that we don't overflow the per-bucket
   3280 	 * limit or the total cache size limit.
   3281 	 */
   3282 	s = splsoftnet();
   3283 	if (scp->sch_length >= tcp_syn_bucket_limit) {
   3284 		tcpstat.tcps_sc_bucketoverflow++;
   3285 		/*
   3286 		 * The bucket is full.  Toss the oldest element in the
   3287 		 * bucket.  This will be the first entry in the bucket.
   3288 		 */
   3289 		sc2 = TAILQ_FIRST(&scp->sch_bucket);
   3290 #ifdef DIAGNOSTIC
   3291 		/*
   3292 		 * This should never happen; we should always find an
   3293 		 * entry in our bucket.
   3294 		 */
   3295 		if (sc2 == NULL)
   3296 			panic("syn_cache_insert: bucketoverflow: impossible");
   3297 #endif
   3298 		SYN_CACHE_RM(sc2);
   3299 		SYN_CACHE_PUT(sc2);
   3300 	} else if (syn_cache_count >= tcp_syn_cache_limit) {
   3301 		struct syn_cache_head *scp2, *sce;
   3302 
   3303 		tcpstat.tcps_sc_overflowed++;
   3304 		/*
   3305 		 * The cache is full.  Toss the oldest entry in the
   3306 		 * first non-empty bucket we can find.
   3307 		 *
   3308 		 * XXX We would really like to toss the oldest
   3309 		 * entry in the cache, but we hope that this
   3310 		 * condition doesn't happen very often.
   3311 		 */
   3312 		scp2 = scp;
   3313 		if (TAILQ_EMPTY(&scp2->sch_bucket)) {
   3314 			sce = &tcp_syn_cache[tcp_syn_cache_size];
   3315 			for (++scp2; scp2 != scp; scp2++) {
   3316 				if (scp2 >= sce)
   3317 					scp2 = &tcp_syn_cache[0];
   3318 				if (! TAILQ_EMPTY(&scp2->sch_bucket))
   3319 					break;
   3320 			}
   3321 #ifdef DIAGNOSTIC
   3322 			/*
   3323 			 * This should never happen; we should always find a
   3324 			 * non-empty bucket.
   3325 			 */
   3326 			if (scp2 == scp)
   3327 				panic("syn_cache_insert: cacheoverflow: "
   3328 				    "impossible");
   3329 #endif
   3330 		}
   3331 		sc2 = TAILQ_FIRST(&scp2->sch_bucket);
   3332 		SYN_CACHE_RM(sc2);
   3333 		SYN_CACHE_PUT(sc2);
   3334 	}
   3335 
   3336 	/*
   3337 	 * Initialize the entry's timer.
   3338 	 */
   3339 	sc->sc_rxttot = 0;
   3340 	sc->sc_rxtshift = 0;
   3341 	SYN_CACHE_TIMER_ARM(sc);
   3342 
   3343 	/* Link it from tcpcb entry */
   3344 	LIST_INSERT_HEAD(&tp->t_sc, sc, sc_tpq);
   3345 
   3346 	/* Put it into the bucket. */
   3347 	TAILQ_INSERT_TAIL(&scp->sch_bucket, sc, sc_bucketq);
   3348 	scp->sch_length++;
   3349 	syn_cache_count++;
   3350 
   3351 	tcpstat.tcps_sc_added++;
   3352 	splx(s);
   3353 }
   3354 
   3355 /*
   3356  * Walk the timer queues, looking for SYN,ACKs that need to be retransmitted.
   3357  * If we have retransmitted an entry the maximum number of times, expire
   3358  * that entry.
   3359  */
   3360 void
   3361 syn_cache_timer(void *arg)
   3362 {
   3363 	struct syn_cache *sc = arg;
   3364 	int s;
   3365 
   3366 	s = splsoftnet();
   3367 	callout_ack(&sc->sc_timer);
   3368 
   3369 	if (__predict_false(sc->sc_flags & SCF_DEAD)) {
   3370 		tcpstat.tcps_sc_delayed_free++;
   3371 		pool_put(&syn_cache_pool, sc);
   3372 		splx(s);
   3373 		return;
   3374 	}
   3375 
   3376 	if (__predict_false(sc->sc_rxtshift == TCP_MAXRXTSHIFT)) {
   3377 		/* Drop it -- too many retransmissions. */
   3378 		goto dropit;
   3379 	}
   3380 
   3381 	/*
   3382 	 * Compute the total amount of time this entry has
   3383 	 * been on a queue.  If this entry has been on longer
   3384 	 * than the keep alive timer would allow, expire it.
   3385 	 */
   3386 	sc->sc_rxttot += sc->sc_rxtcur;
   3387 	if (sc->sc_rxttot >= TCPTV_KEEP_INIT)
   3388 		goto dropit;
   3389 
   3390 	tcpstat.tcps_sc_retransmitted++;
   3391 	(void) syn_cache_respond(sc, NULL);
   3392 
   3393 	/* Advance the timer back-off. */
   3394 	sc->sc_rxtshift++;
   3395 	SYN_CACHE_TIMER_ARM(sc);
   3396 
   3397 	splx(s);
   3398 	return;
   3399 
   3400  dropit:
   3401 	tcpstat.tcps_sc_timed_out++;
   3402 	SYN_CACHE_RM(sc);
   3403 	SYN_CACHE_PUT(sc);
   3404 	splx(s);
   3405 }
   3406 
   3407 /*
   3408  * Remove syn cache created by the specified tcb entry,
   3409  * because this does not make sense to keep them
   3410  * (if there's no tcb entry, syn cache entry will never be used)
   3411  */
   3412 void
   3413 syn_cache_cleanup(struct tcpcb *tp)
   3414 {
   3415 	struct syn_cache *sc, *nsc;
   3416 	int s;
   3417 
   3418 	s = splsoftnet();
   3419 
   3420 	for (sc = LIST_FIRST(&tp->t_sc); sc != NULL; sc = nsc) {
   3421 		nsc = LIST_NEXT(sc, sc_tpq);
   3422 
   3423 #ifdef DIAGNOSTIC
   3424 		if (sc->sc_tp != tp)
   3425 			panic("invalid sc_tp in syn_cache_cleanup");
   3426 #endif
   3427 		SYN_CACHE_RM(sc);
   3428 		SYN_CACHE_PUT(sc);
   3429 	}
   3430 	/* just for safety */
   3431 	LIST_INIT(&tp->t_sc);
   3432 
   3433 	splx(s);
   3434 }
   3435 
   3436 /*
   3437  * Find an entry in the syn cache.
   3438  */
   3439 struct syn_cache *
   3440 syn_cache_lookup(const struct sockaddr *src, const struct sockaddr *dst,
   3441     struct syn_cache_head **headp)
   3442 {
   3443 	struct syn_cache *sc;
   3444 	struct syn_cache_head *scp;
   3445 	u_int32_t hash;
   3446 	int s;
   3447 
   3448 	SYN_HASHALL(hash, src, dst);
   3449 
   3450 	scp = &tcp_syn_cache[hash % tcp_syn_cache_size];
   3451 	*headp = scp;
   3452 	s = splsoftnet();
   3453 	for (sc = TAILQ_FIRST(&scp->sch_bucket); sc != NULL;
   3454 	     sc = TAILQ_NEXT(sc, sc_bucketq)) {
   3455 		if (sc->sc_hash != hash)
   3456 			continue;
   3457 		if (!bcmp(&sc->sc_src, src, src->sa_len) &&
   3458 		    !bcmp(&sc->sc_dst, dst, dst->sa_len)) {
   3459 			splx(s);
   3460 			return (sc);
   3461 		}
   3462 	}
   3463 	splx(s);
   3464 	return (NULL);
   3465 }
   3466 
   3467 /*
   3468  * This function gets called when we receive an ACK for a
   3469  * socket in the LISTEN state.  We look up the connection
   3470  * in the syn cache, and if its there, we pull it out of
   3471  * the cache and turn it into a full-blown connection in
   3472  * the SYN-RECEIVED state.
   3473  *
   3474  * The return values may not be immediately obvious, and their effects
   3475  * can be subtle, so here they are:
   3476  *
   3477  *	NULL	SYN was not found in cache; caller should drop the
   3478  *		packet and send an RST.
   3479  *
   3480  *	-1	We were unable to create the new connection, and are
   3481  *		aborting it.  An ACK,RST is being sent to the peer
   3482  *		(unless we got screwey sequence numbners; see below),
   3483  *		because the 3-way handshake has been completed.  Caller
   3484  *		should not free the mbuf, since we may be using it.  If
   3485  *		we are not, we will free it.
   3486  *
   3487  *	Otherwise, the return value is a pointer to the new socket
   3488  *	associated with the connection.
   3489  */
   3490 struct socket *
   3491 syn_cache_get(struct sockaddr *src, struct sockaddr *dst,
   3492     struct tcphdr *th, unsigned int hlen, unsigned int tlen,
   3493     struct socket *so, struct mbuf *m)
   3494 {
   3495 	struct syn_cache *sc;
   3496 	struct syn_cache_head *scp;
   3497 	struct inpcb *inp = NULL;
   3498 #ifdef INET6
   3499 	struct in6pcb *in6p = NULL;
   3500 #endif
   3501 	struct tcpcb *tp = 0;
   3502 	struct mbuf *am;
   3503 	int s;
   3504 	struct socket *oso;
   3505 
   3506 	s = splsoftnet();
   3507 	if ((sc = syn_cache_lookup(src, dst, &scp)) == NULL) {
   3508 		splx(s);
   3509 		return (NULL);
   3510 	}
   3511 
   3512 	/*
   3513 	 * Verify the sequence and ack numbers.  Try getting the correct
   3514 	 * response again.
   3515 	 */
   3516 	if ((th->th_ack != sc->sc_iss + 1) ||
   3517 	    SEQ_LEQ(th->th_seq, sc->sc_irs) ||
   3518 	    SEQ_GT(th->th_seq, sc->sc_irs + 1 + sc->sc_win)) {
   3519 		(void) syn_cache_respond(sc, m);
   3520 		splx(s);
   3521 		return ((struct socket *)(-1));
   3522 	}
   3523 
   3524 	/* Remove this cache entry */
   3525 	SYN_CACHE_RM(sc);
   3526 	splx(s);
   3527 
   3528 	/*
   3529 	 * Ok, create the full blown connection, and set things up
   3530 	 * as they would have been set up if we had created the
   3531 	 * connection when the SYN arrived.  If we can't create
   3532 	 * the connection, abort it.
   3533 	 */
   3534 	/*
   3535 	 * inp still has the OLD in_pcb stuff, set the
   3536 	 * v6-related flags on the new guy, too.   This is
   3537 	 * done particularly for the case where an AF_INET6
   3538 	 * socket is bound only to a port, and a v4 connection
   3539 	 * comes in on that port.
   3540 	 * we also copy the flowinfo from the original pcb
   3541 	 * to the new one.
   3542 	 */
   3543 	oso = so;
   3544 	so = sonewconn(so, SS_ISCONNECTED);
   3545 	if (so == NULL)
   3546 		goto resetandabort;
   3547 
   3548 	switch (so->so_proto->pr_domain->dom_family) {
   3549 #ifdef INET
   3550 	case AF_INET:
   3551 		inp = sotoinpcb(so);
   3552 		break;
   3553 #endif
   3554 #ifdef INET6
   3555 	case AF_INET6:
   3556 		in6p = sotoin6pcb(so);
   3557 		break;
   3558 #endif
   3559 	}
   3560 	switch (src->sa_family) {
   3561 #ifdef INET
   3562 	case AF_INET:
   3563 		if (inp) {
   3564 			inp->inp_laddr = ((struct sockaddr_in *)dst)->sin_addr;
   3565 			inp->inp_lport = ((struct sockaddr_in *)dst)->sin_port;
   3566 			inp->inp_options = ip_srcroute();
   3567 			in_pcbstate(inp, INP_BOUND);
   3568 			if (inp->inp_options == NULL) {
   3569 				inp->inp_options = sc->sc_ipopts;
   3570 				sc->sc_ipopts = NULL;
   3571 			}
   3572 		}
   3573 #ifdef INET6
   3574 		else if (in6p) {
   3575 			/* IPv4 packet to AF_INET6 socket */
   3576 			bzero(&in6p->in6p_laddr, sizeof(in6p->in6p_laddr));
   3577 			in6p->in6p_laddr.s6_addr16[5] = htons(0xffff);
   3578 			bcopy(&((struct sockaddr_in *)dst)->sin_addr,
   3579 				&in6p->in6p_laddr.s6_addr32[3],
   3580 				sizeof(((struct sockaddr_in *)dst)->sin_addr));
   3581 			in6p->in6p_lport = ((struct sockaddr_in *)dst)->sin_port;
   3582 			in6totcpcb(in6p)->t_family = AF_INET;
   3583 			if (sotoin6pcb(oso)->in6p_flags & IN6P_IPV6_V6ONLY)
   3584 				in6p->in6p_flags |= IN6P_IPV6_V6ONLY;
   3585 			else
   3586 				in6p->in6p_flags &= ~IN6P_IPV6_V6ONLY;
   3587 			in6_pcbstate(in6p, IN6P_BOUND);
   3588 		}
   3589 #endif
   3590 		break;
   3591 #endif
   3592 #ifdef INET6
   3593 	case AF_INET6:
   3594 		if (in6p) {
   3595 			in6p->in6p_laddr = ((struct sockaddr_in6 *)dst)->sin6_addr;
   3596 			in6p->in6p_lport = ((struct sockaddr_in6 *)dst)->sin6_port;
   3597 			in6_pcbstate(in6p, IN6P_BOUND);
   3598 		}
   3599 		break;
   3600 #endif
   3601 	}
   3602 #ifdef INET6
   3603 	if (in6p && in6totcpcb(in6p)->t_family == AF_INET6 && sotoinpcb(oso)) {
   3604 		struct in6pcb *oin6p = sotoin6pcb(oso);
   3605 		/* inherit socket options from the listening socket */
   3606 		in6p->in6p_flags |= (oin6p->in6p_flags & IN6P_CONTROLOPTS);
   3607 		if (in6p->in6p_flags & IN6P_CONTROLOPTS) {
   3608 			m_freem(in6p->in6p_options);
   3609 			in6p->in6p_options = 0;
   3610 		}
   3611 		ip6_savecontrol(in6p, &in6p->in6p_options,
   3612 			mtod(m, struct ip6_hdr *), m);
   3613 	}
   3614 #endif
   3615 
   3616 #if defined(IPSEC) || defined(FAST_IPSEC)
   3617 	/*
   3618 	 * we make a copy of policy, instead of sharing the policy,
   3619 	 * for better behavior in terms of SA lookup and dead SA removal.
   3620 	 */
   3621 	if (inp) {
   3622 		/* copy old policy into new socket's */
   3623 		if (ipsec_copy_pcbpolicy(sotoinpcb(oso)->inp_sp, inp->inp_sp))
   3624 			printf("tcp_input: could not copy policy\n");
   3625 	}
   3626 #ifdef INET6
   3627 	else if (in6p) {
   3628 		/* copy old policy into new socket's */
   3629 		if (ipsec_copy_pcbpolicy(sotoin6pcb(oso)->in6p_sp,
   3630 		    in6p->in6p_sp))
   3631 			printf("tcp_input: could not copy policy\n");
   3632 	}
   3633 #endif
   3634 #endif
   3635 
   3636 	/*
   3637 	 * Give the new socket our cached route reference.
   3638 	 */
   3639 	if (inp)
   3640 		inp->inp_route = sc->sc_route4;		/* struct assignment */
   3641 #ifdef INET6
   3642 	else
   3643 		in6p->in6p_route = sc->sc_route6;
   3644 #endif
   3645 	sc->sc_route4.ro_rt = NULL;
   3646 
   3647 	am = m_get(M_DONTWAIT, MT_SONAME);	/* XXX */
   3648 	if (am == NULL)
   3649 		goto resetandabort;
   3650 	MCLAIM(am, &tcp_mowner);
   3651 	am->m_len = src->sa_len;
   3652 	bcopy(src, mtod(am, caddr_t), src->sa_len);
   3653 	if (inp) {
   3654 		if (in_pcbconnect(inp, am)) {
   3655 			(void) m_free(am);
   3656 			goto resetandabort;
   3657 		}
   3658 	}
   3659 #ifdef INET6
   3660 	else if (in6p) {
   3661 		if (src->sa_family == AF_INET) {
   3662 			/* IPv4 packet to AF_INET6 socket */
   3663 			struct sockaddr_in6 *sin6;
   3664 			sin6 = mtod(am, struct sockaddr_in6 *);
   3665 			am->m_len = sizeof(*sin6);
   3666 			bzero(sin6, sizeof(*sin6));
   3667 			sin6->sin6_family = AF_INET6;
   3668 			sin6->sin6_len = sizeof(*sin6);
   3669 			sin6->sin6_port = ((struct sockaddr_in *)src)->sin_port;
   3670 			sin6->sin6_addr.s6_addr16[5] = htons(0xffff);
   3671 			bcopy(&((struct sockaddr_in *)src)->sin_addr,
   3672 				&sin6->sin6_addr.s6_addr32[3],
   3673 				sizeof(sin6->sin6_addr.s6_addr32[3]));
   3674 		}
   3675 		if (in6_pcbconnect(in6p, am)) {
   3676 			(void) m_free(am);
   3677 			goto resetandabort;
   3678 		}
   3679 	}
   3680 #endif
   3681 	else {
   3682 		(void) m_free(am);
   3683 		goto resetandabort;
   3684 	}
   3685 	(void) m_free(am);
   3686 
   3687 	if (inp)
   3688 		tp = intotcpcb(inp);
   3689 #ifdef INET6
   3690 	else if (in6p)
   3691 		tp = in6totcpcb(in6p);
   3692 #endif
   3693 	else
   3694 		tp = NULL;
   3695 	tp->t_flags = sototcpcb(oso)->t_flags & TF_NODELAY;
   3696 	if (sc->sc_request_r_scale != 15) {
   3697 		tp->requested_s_scale = sc->sc_requested_s_scale;
   3698 		tp->request_r_scale = sc->sc_request_r_scale;
   3699 		tp->snd_scale = sc->sc_requested_s_scale;
   3700 		tp->rcv_scale = sc->sc_request_r_scale;
   3701 		tp->t_flags |= TF_REQ_SCALE|TF_RCVD_SCALE;
   3702 	}
   3703 	if (sc->sc_flags & SCF_TIMESTAMP)
   3704 		tp->t_flags |= TF_REQ_TSTMP|TF_RCVD_TSTMP;
   3705 	tp->ts_timebase = sc->sc_timebase;
   3706 
   3707 	tp->t_template = tcp_template(tp);
   3708 	if (tp->t_template == 0) {
   3709 		tp = tcp_drop(tp, ENOBUFS);	/* destroys socket */
   3710 		so = NULL;
   3711 		m_freem(m);
   3712 		goto abort;
   3713 	}
   3714 
   3715 	tp->iss = sc->sc_iss;
   3716 	tp->irs = sc->sc_irs;
   3717 	tcp_sendseqinit(tp);
   3718 	tcp_rcvseqinit(tp);
   3719 	tp->t_state = TCPS_SYN_RECEIVED;
   3720 	TCP_TIMER_ARM(tp, TCPT_KEEP, TCPTV_KEEP_INIT);
   3721 	tcpstat.tcps_accepts++;
   3722 
   3723 	if ((sc->sc_flags & SCF_SACK_PERMIT) && tcp_do_sack)
   3724 		tp->t_flags |= TF_WILL_SACK;
   3725 
   3726 #ifdef TCP_SIGNATURE
   3727 	if (sc->sc_flags & SCF_SIGNATURE)
   3728 		tp->t_flags |= TF_SIGNATURE;
   3729 #endif
   3730 
   3731 	/* Initialize tp->t_ourmss before we deal with the peer's! */
   3732 	tp->t_ourmss = sc->sc_ourmaxseg;
   3733 	tcp_mss_from_peer(tp, sc->sc_peermaxseg);
   3734 
   3735 	/*
   3736 	 * Initialize the initial congestion window.  If we
   3737 	 * had to retransmit the SYN,ACK, we must initialize cwnd
   3738 	 * to 1 segment (i.e. the Loss Window).
   3739 	 */
   3740 	if (sc->sc_rxtshift)
   3741 		tp->snd_cwnd = tp->t_peermss;
   3742 	else {
   3743 		int ss = tcp_init_win;
   3744 #ifdef INET
   3745 		if (inp != NULL && in_localaddr(inp->inp_faddr))
   3746 			ss = tcp_init_win_local;
   3747 #endif
   3748 #ifdef INET6
   3749 		if (in6p != NULL && in6_localaddr(&in6p->in6p_faddr))
   3750 			ss = tcp_init_win_local;
   3751 #endif
   3752 		tp->snd_cwnd = TCP_INITIAL_WINDOW(ss, tp->t_peermss);
   3753 	}
   3754 
   3755 	tcp_rmx_rtt(tp);
   3756 	tp->snd_wl1 = sc->sc_irs;
   3757 	tp->rcv_up = sc->sc_irs + 1;
   3758 
   3759 	/*
   3760 	 * This is what whould have happened in tcp_output() when
   3761 	 * the SYN,ACK was sent.
   3762 	 */
   3763 	tp->snd_up = tp->snd_una;
   3764 	tp->snd_max = tp->snd_nxt = tp->iss+1;
   3765 	TCP_TIMER_ARM(tp, TCPT_REXMT, tp->t_rxtcur);
   3766 	if (sc->sc_win > 0 && SEQ_GT(tp->rcv_nxt + sc->sc_win, tp->rcv_adv))
   3767 		tp->rcv_adv = tp->rcv_nxt + sc->sc_win;
   3768 	tp->last_ack_sent = tp->rcv_nxt;
   3769 	tp->t_partialacks = -1;
   3770 	tp->t_dupacks = 0;
   3771 
   3772 	tcpstat.tcps_sc_completed++;
   3773 	SYN_CACHE_PUT(sc);
   3774 	return (so);
   3775 
   3776 resetandabort:
   3777 	(void)tcp_respond(NULL, m, m, th, (tcp_seq)0, th->th_ack, TH_RST);
   3778 abort:
   3779 	if (so != NULL)
   3780 		(void) soabort(so);
   3781 	SYN_CACHE_PUT(sc);
   3782 	tcpstat.tcps_sc_aborted++;
   3783 	return ((struct socket *)(-1));
   3784 }
   3785 
   3786 /*
   3787  * This function is called when we get a RST for a
   3788  * non-existent connection, so that we can see if the
   3789  * connection is in the syn cache.  If it is, zap it.
   3790  */
   3791 
   3792 void
   3793 syn_cache_reset(struct sockaddr *src, struct sockaddr *dst, struct tcphdr *th)
   3794 {
   3795 	struct syn_cache *sc;
   3796 	struct syn_cache_head *scp;
   3797 	int s = splsoftnet();
   3798 
   3799 	if ((sc = syn_cache_lookup(src, dst, &scp)) == NULL) {
   3800 		splx(s);
   3801 		return;
   3802 	}
   3803 	if (SEQ_LT(th->th_seq, sc->sc_irs) ||
   3804 	    SEQ_GT(th->th_seq, sc->sc_irs+1)) {
   3805 		splx(s);
   3806 		return;
   3807 	}
   3808 	SYN_CACHE_RM(sc);
   3809 	splx(s);
   3810 	tcpstat.tcps_sc_reset++;
   3811 	SYN_CACHE_PUT(sc);
   3812 }
   3813 
   3814 void
   3815 syn_cache_unreach(const struct sockaddr *src, const struct sockaddr *dst,
   3816     struct tcphdr *th)
   3817 {
   3818 	struct syn_cache *sc;
   3819 	struct syn_cache_head *scp;
   3820 	int s;
   3821 
   3822 	s = splsoftnet();
   3823 	if ((sc = syn_cache_lookup(src, dst, &scp)) == NULL) {
   3824 		splx(s);
   3825 		return;
   3826 	}
   3827 	/* If the sequence number != sc_iss, then it's a bogus ICMP msg */
   3828 	if (ntohl (th->th_seq) != sc->sc_iss) {
   3829 		splx(s);
   3830 		return;
   3831 	}
   3832 
   3833 	/*
   3834 	 * If we've retransmitted 3 times and this is our second error,
   3835 	 * we remove the entry.  Otherwise, we allow it to continue on.
   3836 	 * This prevents us from incorrectly nuking an entry during a
   3837 	 * spurious network outage.
   3838 	 *
   3839 	 * See tcp_notify().
   3840 	 */
   3841 	if ((sc->sc_flags & SCF_UNREACH) == 0 || sc->sc_rxtshift < 3) {
   3842 		sc->sc_flags |= SCF_UNREACH;
   3843 		splx(s);
   3844 		return;
   3845 	}
   3846 
   3847 	SYN_CACHE_RM(sc);
   3848 	splx(s);
   3849 	tcpstat.tcps_sc_unreach++;
   3850 	SYN_CACHE_PUT(sc);
   3851 }
   3852 
   3853 /*
   3854  * Given a LISTEN socket and an inbound SYN request, add
   3855  * this to the syn cache, and send back a segment:
   3856  *	<SEQ=ISS><ACK=RCV_NXT><CTL=SYN,ACK>
   3857  * to the source.
   3858  *
   3859  * IMPORTANT NOTE: We do _NOT_ ACK data that might accompany the SYN.
   3860  * Doing so would require that we hold onto the data and deliver it
   3861  * to the application.  However, if we are the target of a SYN-flood
   3862  * DoS attack, an attacker could send data which would eventually
   3863  * consume all available buffer space if it were ACKed.  By not ACKing
   3864  * the data, we avoid this DoS scenario.
   3865  */
   3866 
   3867 int
   3868 syn_cache_add(struct sockaddr *src, struct sockaddr *dst, struct tcphdr *th,
   3869     unsigned int hlen, struct socket *so, struct mbuf *m, u_char *optp,
   3870     int optlen, struct tcp_opt_info *oi)
   3871 {
   3872 	struct tcpcb tb, *tp;
   3873 	long win;
   3874 	struct syn_cache *sc;
   3875 	struct syn_cache_head *scp;
   3876 	struct mbuf *ipopts;
   3877 	struct tcp_opt_info opti;
   3878 
   3879 	tp = sototcpcb(so);
   3880 
   3881 	bzero(&opti, sizeof(opti));
   3882 
   3883 	/*
   3884 	 * RFC1122 4.2.3.10, p. 104: discard bcast/mcast SYN
   3885 	 *
   3886 	 * Note this check is performed in tcp_input() very early on.
   3887 	 */
   3888 
   3889 	/*
   3890 	 * Initialize some local state.
   3891 	 */
   3892 	win = sbspace(&so->so_rcv);
   3893 	if (win > TCP_MAXWIN)
   3894 		win = TCP_MAXWIN;
   3895 
   3896 	switch (src->sa_family) {
   3897 #ifdef INET
   3898 	case AF_INET:
   3899 		/*
   3900 		 * Remember the IP options, if any.
   3901 		 */
   3902 		ipopts = ip_srcroute();
   3903 		break;
   3904 #endif
   3905 	default:
   3906 		ipopts = NULL;
   3907 	}
   3908 
   3909 #ifdef TCP_SIGNATURE
   3910 	if (optp || (tp->t_flags & TF_SIGNATURE))
   3911 #else
   3912 	if (optp)
   3913 #endif
   3914 	{
   3915 		tb.t_flags = tcp_do_rfc1323 ? (TF_REQ_SCALE|TF_REQ_TSTMP) : 0;
   3916 #ifdef TCP_SIGNATURE
   3917 		tb.t_flags |= (tp->t_flags & TF_SIGNATURE);
   3918 #endif
   3919 		if (tcp_dooptions(&tb, optp, optlen, th, m, m->m_pkthdr.len -
   3920 		    sizeof(struct tcphdr) - optlen - hlen, oi) < 0)
   3921 			return (0);
   3922 	} else
   3923 		tb.t_flags = 0;
   3924 
   3925 	/*
   3926 	 * See if we already have an entry for this connection.
   3927 	 * If we do, resend the SYN,ACK.  We do not count this
   3928 	 * as a retransmission (XXX though maybe we should).
   3929 	 */
   3930 	if ((sc = syn_cache_lookup(src, dst, &scp)) != NULL) {
   3931 		tcpstat.tcps_sc_dupesyn++;
   3932 		if (ipopts) {
   3933 			/*
   3934 			 * If we were remembering a previous source route,
   3935 			 * forget it and use the new one we've been given.
   3936 			 */
   3937 			if (sc->sc_ipopts)
   3938 				(void) m_free(sc->sc_ipopts);
   3939 			sc->sc_ipopts = ipopts;
   3940 		}
   3941 		sc->sc_timestamp = tb.ts_recent;
   3942 		if (syn_cache_respond(sc, m) == 0) {
   3943 			tcpstat.tcps_sndacks++;
   3944 			tcpstat.tcps_sndtotal++;
   3945 		}
   3946 		return (1);
   3947 	}
   3948 
   3949 	sc = pool_get(&syn_cache_pool, PR_NOWAIT);
   3950 	if (sc == NULL) {
   3951 		if (ipopts)
   3952 			(void) m_free(ipopts);
   3953 		return (0);
   3954 	}
   3955 
   3956 	/*
   3957 	 * Fill in the cache, and put the necessary IP and TCP
   3958 	 * options into the reply.
   3959 	 */
   3960 	bzero(sc, sizeof(struct syn_cache));
   3961 	callout_init(&sc->sc_timer);
   3962 	bcopy(src, &sc->sc_src, src->sa_len);
   3963 	bcopy(dst, &sc->sc_dst, dst->sa_len);
   3964 	sc->sc_flags = 0;
   3965 	sc->sc_ipopts = ipopts;
   3966 	sc->sc_irs = th->th_seq;
   3967 	switch (src->sa_family) {
   3968 #ifdef INET
   3969 	case AF_INET:
   3970 	    {
   3971 		struct sockaddr_in *srcin = (void *) src;
   3972 		struct sockaddr_in *dstin = (void *) dst;
   3973 
   3974 		sc->sc_iss = tcp_new_iss1(&dstin->sin_addr,
   3975 		    &srcin->sin_addr, dstin->sin_port,
   3976 		    srcin->sin_port, sizeof(dstin->sin_addr), 0);
   3977 		break;
   3978 	    }
   3979 #endif /* INET */
   3980 #ifdef INET6
   3981 	case AF_INET6:
   3982 	    {
   3983 		struct sockaddr_in6 *srcin6 = (void *) src;
   3984 		struct sockaddr_in6 *dstin6 = (void *) dst;
   3985 
   3986 		sc->sc_iss = tcp_new_iss1(&dstin6->sin6_addr,
   3987 		    &srcin6->sin6_addr, dstin6->sin6_port,
   3988 		    srcin6->sin6_port, sizeof(dstin6->sin6_addr), 0);
   3989 		break;
   3990 	    }
   3991 #endif /* INET6 */
   3992 	}
   3993 	sc->sc_peermaxseg = oi->maxseg;
   3994 	sc->sc_ourmaxseg = tcp_mss_to_advertise(m->m_flags & M_PKTHDR ?
   3995 						m->m_pkthdr.rcvif : NULL,
   3996 						sc->sc_src.sa.sa_family);
   3997 	sc->sc_win = win;
   3998 	sc->sc_timebase = tcp_now;	/* see tcp_newtcpcb() */
   3999 	sc->sc_timestamp = tb.ts_recent;
   4000 	if ((tb.t_flags & (TF_REQ_TSTMP|TF_RCVD_TSTMP)) ==
   4001 	    (TF_REQ_TSTMP|TF_RCVD_TSTMP))
   4002 		sc->sc_flags |= SCF_TIMESTAMP;
   4003 	if ((tb.t_flags & (TF_RCVD_SCALE|TF_REQ_SCALE)) ==
   4004 	    (TF_RCVD_SCALE|TF_REQ_SCALE)) {
   4005 		sc->sc_requested_s_scale = tb.requested_s_scale;
   4006 		sc->sc_request_r_scale = 0;
   4007 		while (sc->sc_request_r_scale < TCP_MAX_WINSHIFT &&
   4008 		    TCP_MAXWIN << sc->sc_request_r_scale <
   4009 		    so->so_rcv.sb_hiwat)
   4010 			sc->sc_request_r_scale++;
   4011 	} else {
   4012 		sc->sc_requested_s_scale = 15;
   4013 		sc->sc_request_r_scale = 15;
   4014 	}
   4015 	if ((tb.t_flags & TF_SACK_PERMIT) && tcp_do_sack)
   4016 		sc->sc_flags |= SCF_SACK_PERMIT;
   4017 #ifdef TCP_SIGNATURE
   4018 	if (tb.t_flags & TF_SIGNATURE)
   4019 		sc->sc_flags |= SCF_SIGNATURE;
   4020 #endif
   4021 	sc->sc_tp = tp;
   4022 	if (syn_cache_respond(sc, m) == 0) {
   4023 		syn_cache_insert(sc, tp);
   4024 		tcpstat.tcps_sndacks++;
   4025 		tcpstat.tcps_sndtotal++;
   4026 	} else {
   4027 		SYN_CACHE_PUT(sc);
   4028 		tcpstat.tcps_sc_dropped++;
   4029 	}
   4030 	return (1);
   4031 }
   4032 
   4033 int
   4034 syn_cache_respond(struct syn_cache *sc, struct mbuf *m)
   4035 {
   4036 	struct route *ro;
   4037 	u_int8_t *optp;
   4038 	int optlen, error;
   4039 	u_int16_t tlen;
   4040 	struct ip *ip = NULL;
   4041 #ifdef INET6
   4042 	struct ip6_hdr *ip6 = NULL;
   4043 #endif
   4044 	struct tcpcb *tp;
   4045 	struct tcphdr *th;
   4046 	u_int hlen;
   4047 	struct socket *so;
   4048 
   4049 	switch (sc->sc_src.sa.sa_family) {
   4050 	case AF_INET:
   4051 		hlen = sizeof(struct ip);
   4052 		ro = &sc->sc_route4;
   4053 		break;
   4054 #ifdef INET6
   4055 	case AF_INET6:
   4056 		hlen = sizeof(struct ip6_hdr);
   4057 		ro = (struct route *)&sc->sc_route6;
   4058 		break;
   4059 #endif
   4060 	default:
   4061 		if (m)
   4062 			m_freem(m);
   4063 		return (EAFNOSUPPORT);
   4064 	}
   4065 
   4066 	/* Compute the size of the TCP options. */
   4067 	optlen = 4 + (sc->sc_request_r_scale != 15 ? 4 : 0) +
   4068 	    ((sc->sc_flags & SCF_SACK_PERMIT) ? (TCPOLEN_SACK_PERMITTED + 2) : 0) +
   4069 #ifdef TCP_SIGNATURE
   4070 	    ((sc->sc_flags & SCF_SIGNATURE) ? (TCPOLEN_SIGNATURE + 2) : 0) +
   4071 #endif
   4072 	    ((sc->sc_flags & SCF_TIMESTAMP) ? TCPOLEN_TSTAMP_APPA : 0);
   4073 
   4074 	tlen = hlen + sizeof(struct tcphdr) + optlen;
   4075 
   4076 	/*
   4077 	 * Create the IP+TCP header from scratch.
   4078 	 */
   4079 	if (m)
   4080 		m_freem(m);
   4081 #ifdef DIAGNOSTIC
   4082 	if (max_linkhdr + tlen > MCLBYTES)
   4083 		return (ENOBUFS);
   4084 #endif
   4085 	MGETHDR(m, M_DONTWAIT, MT_DATA);
   4086 	if (m && tlen > MHLEN) {
   4087 		MCLGET(m, M_DONTWAIT);
   4088 		if ((m->m_flags & M_EXT) == 0) {
   4089 			m_freem(m);
   4090 			m = NULL;
   4091 		}
   4092 	}
   4093 	if (m == NULL)
   4094 		return (ENOBUFS);
   4095 	MCLAIM(m, &tcp_tx_mowner);
   4096 
   4097 	/* Fixup the mbuf. */
   4098 	m->m_data += max_linkhdr;
   4099 	m->m_len = m->m_pkthdr.len = tlen;
   4100 	if (sc->sc_tp) {
   4101 		tp = sc->sc_tp;
   4102 		if (tp->t_inpcb)
   4103 			so = tp->t_inpcb->inp_socket;
   4104 #ifdef INET6
   4105 		else if (tp->t_in6pcb)
   4106 			so = tp->t_in6pcb->in6p_socket;
   4107 #endif
   4108 		else
   4109 			so = NULL;
   4110 	} else
   4111 		so = NULL;
   4112 	m->m_pkthdr.rcvif = NULL;
   4113 	memset(mtod(m, u_char *), 0, tlen);
   4114 
   4115 	switch (sc->sc_src.sa.sa_family) {
   4116 	case AF_INET:
   4117 		ip = mtod(m, struct ip *);
   4118 		ip->ip_v = 4;
   4119 		ip->ip_dst = sc->sc_src.sin.sin_addr;
   4120 		ip->ip_src = sc->sc_dst.sin.sin_addr;
   4121 		ip->ip_p = IPPROTO_TCP;
   4122 		th = (struct tcphdr *)(ip + 1);
   4123 		th->th_dport = sc->sc_src.sin.sin_port;
   4124 		th->th_sport = sc->sc_dst.sin.sin_port;
   4125 		break;
   4126 #ifdef INET6
   4127 	case AF_INET6:
   4128 		ip6 = mtod(m, struct ip6_hdr *);
   4129 		ip6->ip6_vfc = IPV6_VERSION;
   4130 		ip6->ip6_dst = sc->sc_src.sin6.sin6_addr;
   4131 		ip6->ip6_src = sc->sc_dst.sin6.sin6_addr;
   4132 		ip6->ip6_nxt = IPPROTO_TCP;
   4133 		/* ip6_plen will be updated in ip6_output() */
   4134 		th = (struct tcphdr *)(ip6 + 1);
   4135 		th->th_dport = sc->sc_src.sin6.sin6_port;
   4136 		th->th_sport = sc->sc_dst.sin6.sin6_port;
   4137 		break;
   4138 #endif
   4139 	default:
   4140 		th = NULL;
   4141 	}
   4142 
   4143 	th->th_seq = htonl(sc->sc_iss);
   4144 	th->th_ack = htonl(sc->sc_irs + 1);
   4145 	th->th_off = (sizeof(struct tcphdr) + optlen) >> 2;
   4146 	th->th_flags = TH_SYN|TH_ACK;
   4147 	th->th_win = htons(sc->sc_win);
   4148 	/* th_sum already 0 */
   4149 	/* th_urp already 0 */
   4150 
   4151 	/* Tack on the TCP options. */
   4152 	optp = (u_int8_t *)(th + 1);
   4153 	*optp++ = TCPOPT_MAXSEG;
   4154 	*optp++ = 4;
   4155 	*optp++ = (sc->sc_ourmaxseg >> 8) & 0xff;
   4156 	*optp++ = sc->sc_ourmaxseg & 0xff;
   4157 
   4158 	if (sc->sc_request_r_scale != 15) {
   4159 		*((u_int32_t *)optp) = htonl(TCPOPT_NOP << 24 |
   4160 		    TCPOPT_WINDOW << 16 | TCPOLEN_WINDOW << 8 |
   4161 		    sc->sc_request_r_scale);
   4162 		optp += 4;
   4163 	}
   4164 
   4165 	if (sc->sc_flags & SCF_TIMESTAMP) {
   4166 		u_int32_t *lp = (u_int32_t *)(optp);
   4167 		/* Form timestamp option as shown in appendix A of RFC 1323. */
   4168 		*lp++ = htonl(TCPOPT_TSTAMP_HDR);
   4169 		*lp++ = htonl(SYN_CACHE_TIMESTAMP(sc));
   4170 		*lp   = htonl(sc->sc_timestamp);
   4171 		optp += TCPOLEN_TSTAMP_APPA;
   4172 	}
   4173 
   4174 	if (sc->sc_flags & SCF_SACK_PERMIT) {
   4175 		u_int8_t *p = optp;
   4176 
   4177 		/* Let the peer know that we will SACK. */
   4178 		p[0] = TCPOPT_SACK_PERMITTED;
   4179 		p[1] = 2;
   4180 		p[2] = TCPOPT_NOP;
   4181 		p[3] = TCPOPT_NOP;
   4182 		optp += 4;
   4183 	}
   4184 
   4185 #ifdef TCP_SIGNATURE
   4186 	if (sc->sc_flags & SCF_SIGNATURE) {
   4187 		struct secasvar *sav;
   4188 		u_int8_t *sigp;
   4189 
   4190 		sav = tcp_signature_getsav(m, th);
   4191 
   4192 		if (sav == NULL) {
   4193 			if (m)
   4194 				m_freem(m);
   4195 			return (EPERM);
   4196 		}
   4197 
   4198 		*optp++ = TCPOPT_SIGNATURE;
   4199 		*optp++ = TCPOLEN_SIGNATURE;
   4200 		sigp = optp;
   4201 		bzero(optp, TCP_SIGLEN);
   4202 		optp += TCP_SIGLEN;
   4203 		*optp++ = TCPOPT_NOP;
   4204 		*optp++ = TCPOPT_EOL;
   4205 
   4206 		(void)tcp_signature(m, th, hlen, sav, sigp);
   4207 
   4208 		key_sa_recordxfer(sav, m);
   4209 #ifdef FAST_IPSEC
   4210 		KEY_FREESAV(&sav);
   4211 #else
   4212 		key_freesav(sav);
   4213 #endif
   4214 	}
   4215 #endif
   4216 
   4217 	/* Compute the packet's checksum. */
   4218 	switch (sc->sc_src.sa.sa_family) {
   4219 	case AF_INET:
   4220 		ip->ip_len = htons(tlen - hlen);
   4221 		th->th_sum = 0;
   4222 		th->th_sum = in4_cksum(m, IPPROTO_TCP, hlen, tlen - hlen);
   4223 		break;
   4224 #ifdef INET6
   4225 	case AF_INET6:
   4226 		ip6->ip6_plen = htons(tlen - hlen);
   4227 		th->th_sum = 0;
   4228 		th->th_sum = in6_cksum(m, IPPROTO_TCP, hlen, tlen - hlen);
   4229 		break;
   4230 #endif
   4231 	}
   4232 
   4233 	/*
   4234 	 * Fill in some straggling IP bits.  Note the stack expects
   4235 	 * ip_len to be in host order, for convenience.
   4236 	 */
   4237 	switch (sc->sc_src.sa.sa_family) {
   4238 #ifdef INET
   4239 	case AF_INET:
   4240 		ip->ip_len = htons(tlen);
   4241 		ip->ip_ttl = ip_defttl;
   4242 		/* XXX tos? */
   4243 		break;
   4244 #endif
   4245 #ifdef INET6
   4246 	case AF_INET6:
   4247 		ip6->ip6_vfc &= ~IPV6_VERSION_MASK;
   4248 		ip6->ip6_vfc |= IPV6_VERSION;
   4249 		ip6->ip6_plen = htons(tlen - hlen);
   4250 		/* ip6_hlim will be initialized afterwards */
   4251 		/* XXX flowlabel? */
   4252 		break;
   4253 #endif
   4254 	}
   4255 
   4256 	/* XXX use IPsec policy on listening socket, on SYN ACK */
   4257 	tp = sc->sc_tp;
   4258 
   4259 	switch (sc->sc_src.sa.sa_family) {
   4260 #ifdef INET
   4261 	case AF_INET:
   4262 		error = ip_output(m, sc->sc_ipopts, ro,
   4263 		    (ip_mtudisc ? IP_MTUDISC : 0),
   4264 		    (struct ip_moptions *)NULL, so);
   4265 		break;
   4266 #endif
   4267 #ifdef INET6
   4268 	case AF_INET6:
   4269 		ip6->ip6_hlim = in6_selecthlim(NULL,
   4270 				ro->ro_rt ? ro->ro_rt->rt_ifp : NULL);
   4271 
   4272 		error = ip6_output(m, NULL /*XXX*/, (struct route_in6 *)ro, 0,
   4273 			(struct ip6_moptions *)0, so, NULL);
   4274 		break;
   4275 #endif
   4276 	default:
   4277 		error = EAFNOSUPPORT;
   4278 		break;
   4279 	}
   4280 	return (error);
   4281 }
   4282