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