Home | History | Annotate | Line # | Download | only in netinet
tcp_input.c revision 1.82
      1 /*	$NetBSD: tcp_input.c,v 1.82 1999/05/23 20:33:50 ad Exp $	*/
      2 
      3 /*-
      4  * Copyright (c) 1997, 1998, 1999 The NetBSD Foundation, Inc.
      5  * All rights reserved.
      6  *
      7  * This code is derived from software contributed to The NetBSD Foundation
      8  * by Jason R. Thorpe and Kevin M. Lahey of the Numerical Aerospace Simulation
      9  * Facility, NASA Ames Research Center.
     10  *
     11  * Redistribution and use in source and binary forms, with or without
     12  * modification, are permitted provided that the following conditions
     13  * are met:
     14  * 1. Redistributions of source code must retain the above copyright
     15  *    notice, this list of conditions and the following disclaimer.
     16  * 2. Redistributions in binary form must reproduce the above copyright
     17  *    notice, this list of conditions and the following disclaimer in the
     18  *    documentation and/or other materials provided with the distribution.
     19  * 3. All advertising materials mentioning features or use of this software
     20  *    must display the following acknowledgement:
     21  *	This product includes software developed by the NetBSD
     22  *	Foundation, Inc. and its contributors.
     23  * 4. Neither the name of The NetBSD Foundation nor the names of its
     24  *    contributors may be used to endorse or promote products derived
     25  *    from this software without specific prior written permission.
     26  *
     27  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
     28  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
     29  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
     30  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
     31  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
     32  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
     33  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
     34  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
     35  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
     36  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
     37  * POSSIBILITY OF SUCH DAMAGE.
     38  */
     39 
     40 /*
     41  * Copyright (c) 1982, 1986, 1988, 1990, 1993, 1994, 1995
     42  *	The Regents of the University of California.  All rights reserved.
     43  *
     44  * Redistribution and use in source and binary forms, with or without
     45  * modification, are permitted provided that the following conditions
     46  * are met:
     47  * 1. Redistributions of source code must retain the above copyright
     48  *    notice, this list of conditions and the following disclaimer.
     49  * 2. Redistributions in binary form must reproduce the above copyright
     50  *    notice, this list of conditions and the following disclaimer in the
     51  *    documentation and/or other materials provided with the distribution.
     52  * 3. All advertising materials mentioning features or use of this software
     53  *    must display the following acknowledgement:
     54  *	This product includes software developed by the University of
     55  *	California, Berkeley and its contributors.
     56  * 4. Neither the name of the University nor the names of its contributors
     57  *    may be used to endorse or promote products derived from this software
     58  *    without specific prior written permission.
     59  *
     60  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
     61  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     62  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     63  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
     64  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     65  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     66  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     67  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     68  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     69  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     70  * SUCH DAMAGE.
     71  *
     72  *	@(#)tcp_input.c	8.12 (Berkeley) 5/24/95
     73  */
     74 
     75 /*
     76  *	TODO list for SYN cache stuff:
     77  *
     78  *	Find room for a "state" field, which is needed to keep a
     79  *	compressed state for TIME_WAIT TCBs.  It's been noted already
     80  *	that this is fairly important for very high-volume web and
     81  *	mail servers, which use a large number of short-lived
     82  *	connections.
     83  */
     84 
     85 #include <sys/param.h>
     86 #include <sys/systm.h>
     87 #include <sys/malloc.h>
     88 #include <sys/mbuf.h>
     89 #include <sys/protosw.h>
     90 #include <sys/socket.h>
     91 #include <sys/socketvar.h>
     92 #include <sys/errno.h>
     93 #include <sys/syslog.h>
     94 #include <sys/pool.h>
     95 
     96 #include <net/if.h>
     97 #include <net/route.h>
     98 
     99 #include <netinet/in.h>
    100 #include <netinet/in_systm.h>
    101 #include <netinet/ip.h>
    102 #include <netinet/in_pcb.h>
    103 #include <netinet/ip_var.h>
    104 #include <netinet/tcp.h>
    105 #include <netinet/tcp_fsm.h>
    106 #include <netinet/tcp_seq.h>
    107 #include <netinet/tcp_timer.h>
    108 #include <netinet/tcp_var.h>
    109 #include <netinet/tcpip.h>
    110 #include <netinet/tcp_debug.h>
    111 
    112 #include <machine/stdarg.h>
    113 
    114 int	tcprexmtthresh = 3;
    115 int	tcp_log_refused;
    116 struct	tcpiphdr tcp_saveti;
    117 
    118 #define TCP_PAWS_IDLE	(24 * 24 * 60 * 60 * PR_SLOWHZ)
    119 
    120 /* for modulo comparisons of timestamps */
    121 #define TSTMP_LT(a,b)	((int)((a)-(b)) < 0)
    122 #define TSTMP_GEQ(a,b)	((int)((a)-(b)) >= 0)
    123 
    124 /*
    125  * Macro to compute ACK transmission behavior.  Delay the ACK unless
    126  * we have already delayed an ACK (must send an ACK every two segments).
    127  * We also ACK immediately if we received a PUSH and the ACK-on-PUSH
    128  * option is enabled.
    129  */
    130 #define	TCP_SETUP_ACK(tp, ti) \
    131 do { \
    132 	if ((tp)->t_flags & TF_DELACK || \
    133 	    (tcp_ack_on_push && (ti)->ti_flags & TH_PUSH)) \
    134 		tp->t_flags |= TF_ACKNOW; \
    135 	else \
    136 		TCP_SET_DELACK(tp); \
    137 } while (0)
    138 
    139 /*
    140  * Insert segment ti into reassembly queue of tcp with
    141  * control block tp.  Return TH_FIN if reassembly now includes
    142  * a segment with FIN.  The macro form does the common case inline
    143  * (segment is the next to be received on an established connection,
    144  * and the queue is empty), avoiding linkage into and removal
    145  * from the queue and repetition of various conversions.
    146  * Set DELACK for segments received in order, but ack immediately
    147  * when segments are out of order (so fast retransmit can work).
    148  */
    149 #define	TCP_REASS(tp, ti, m, so, flags) { \
    150 	TCP_REASS_LOCK((tp)); \
    151 	if ((ti)->ti_seq == (tp)->rcv_nxt && \
    152 	    (tp)->segq.lh_first == NULL && \
    153 	    (tp)->t_state == TCPS_ESTABLISHED) { \
    154 		TCP_SETUP_ACK(tp, ti); \
    155 		(tp)->rcv_nxt += (ti)->ti_len; \
    156 		flags = (ti)->ti_flags & TH_FIN; \
    157 		tcpstat.tcps_rcvpack++;\
    158 		tcpstat.tcps_rcvbyte += (ti)->ti_len;\
    159 		sbappend(&(so)->so_rcv, (m)); \
    160 		sorwakeup(so); \
    161 	} else { \
    162 		(flags) = tcp_reass((tp), (ti), (m)); \
    163 		tp->t_flags |= TF_ACKNOW; \
    164 	} \
    165 	TCP_REASS_UNLOCK((tp)); \
    166 }
    167 
    168 int
    169 tcp_reass(tp, ti, m)
    170 	register struct tcpcb *tp;
    171 	register struct tcpiphdr *ti;
    172 	struct mbuf *m;
    173 {
    174 	register struct ipqent *p, *q, *nq, *tiqe = NULL;
    175 	struct socket *so = tp->t_inpcb->inp_socket;
    176 	int pkt_flags;
    177 	tcp_seq pkt_seq;
    178 	unsigned pkt_len;
    179 	u_long rcvpartdupbyte = 0;
    180 	u_long rcvoobyte;
    181 
    182 	TCP_REASS_LOCK_CHECK(tp);
    183 
    184 	/*
    185 	 * Call with ti==0 after become established to
    186 	 * force pre-ESTABLISHED data up to user socket.
    187 	 */
    188 	if (ti == 0)
    189 		goto present;
    190 
    191 	rcvoobyte = ti->ti_len;
    192 	/*
    193 	 * Copy these to local variables because the tcpiphdr
    194 	 * gets munged while we are collapsing mbufs.
    195 	 */
    196 	pkt_seq = ti->ti_seq;
    197 	pkt_len = ti->ti_len;
    198 	pkt_flags = ti->ti_flags;
    199 	/*
    200 	 * Find a segment which begins after this one does.
    201 	 */
    202 	for (p = NULL, q = tp->segq.lh_first; q != NULL; q = nq) {
    203 		nq = q->ipqe_q.le_next;
    204 		/*
    205 		 * If the received segment is just right after this
    206 		 * fragment, merge the two together and then check
    207 		 * for further overlaps.
    208 		 */
    209 		if (q->ipqe_seq + q->ipqe_len == pkt_seq) {
    210 #ifdef TCPREASS_DEBUG
    211 			printf("tcp_reass[%p]: concat %u:%u(%u) to %u:%u(%u)\n",
    212 			       tp, pkt_seq, pkt_seq + pkt_len, pkt_len,
    213 			       q->ipqe_seq, q->ipqe_seq + q->ipqe_len, q->ipqe_len);
    214 #endif
    215 			pkt_len += q->ipqe_len;
    216 			pkt_flags |= q->ipqe_flags;
    217 			pkt_seq = q->ipqe_seq;
    218 			m_cat(q->ipqe_m, m);
    219 			m = q->ipqe_m;
    220 			goto free_ipqe;
    221 		}
    222 		/*
    223 		 * If the received segment is completely past this
    224 		 * fragment, we need to go the next fragment.
    225 		 */
    226 		if (SEQ_LT(q->ipqe_seq + q->ipqe_len, pkt_seq)) {
    227 			p = q;
    228 			continue;
    229 		}
    230 		/*
    231 		 * If the fragment is past the received segment,
    232 		 * it (or any following) can't be concatenated.
    233 		 */
    234 		if (SEQ_GT(q->ipqe_seq, pkt_seq + pkt_len))
    235 			break;
    236 		/*
    237 		 * We've received all the data in this segment before.
    238 		 * mark it as a duplicate and return.
    239 		 */
    240 		if (SEQ_LEQ(q->ipqe_seq, pkt_seq) &&
    241 		    SEQ_GEQ(q->ipqe_seq + q->ipqe_len, pkt_seq + pkt_len)) {
    242 			tcpstat.tcps_rcvduppack++;
    243 			tcpstat.tcps_rcvdupbyte += pkt_len;
    244 			m_freem(m);
    245 			if (tiqe != NULL)
    246 				pool_put(&ipqent_pool, tiqe);
    247 			return (0);
    248 		}
    249 		/*
    250 		 * Received segment completely overlaps this fragment
    251 		 * so we drop the fragment (this keeps the temporal
    252 		 * ordering of segments correct).
    253 		 */
    254 		if (SEQ_GEQ(q->ipqe_seq, pkt_seq) &&
    255 		    SEQ_LEQ(q->ipqe_seq + q->ipqe_len, pkt_seq + pkt_len)) {
    256 			rcvpartdupbyte += q->ipqe_len;
    257 			m_freem(q->ipqe_m);
    258 			goto free_ipqe;
    259 		}
    260 		/*
    261 		 * RX'ed segment extends past the end of the
    262 		 * fragment.  Drop the overlapping bytes.  Then
    263 		 * merge the fragment and segment then treat as
    264 		 * a longer received packet.
    265 		 */
    266 		if (SEQ_LT(q->ipqe_seq, pkt_seq)
    267 		    && SEQ_GT(q->ipqe_seq + q->ipqe_len, pkt_seq))  {
    268 			int overlap = q->ipqe_seq + q->ipqe_len - pkt_seq;
    269 #ifdef TCPREASS_DEBUG
    270 			printf("tcp_reass[%p]: trim starting %d bytes of %u:%u(%u)\n",
    271 			       tp, overlap,
    272 			       pkt_seq, pkt_seq + pkt_len, pkt_len);
    273 #endif
    274 			m_adj(m, overlap);
    275 			rcvpartdupbyte += overlap;
    276 			m_cat(q->ipqe_m, m);
    277 			m = q->ipqe_m;
    278 			pkt_seq = q->ipqe_seq;
    279 			pkt_len += q->ipqe_len - overlap;
    280 			rcvoobyte -= overlap;
    281 			goto free_ipqe;
    282 		}
    283 		/*
    284 		 * RX'ed segment extends past the front of the
    285 		 * fragment.  Drop the overlapping bytes on the
    286 		 * received packet.  The packet will then be
    287 		 * contatentated with this fragment a bit later.
    288 		 */
    289 		if (SEQ_GT(q->ipqe_seq, pkt_seq)
    290 		    && SEQ_LT(q->ipqe_seq, pkt_seq + pkt_len))  {
    291 			int overlap = pkt_seq + pkt_len - q->ipqe_seq;
    292 #ifdef TCPREASS_DEBUG
    293 			printf("tcp_reass[%p]: trim trailing %d bytes of %u:%u(%u)\n",
    294 			       tp, overlap,
    295 			       pkt_seq, pkt_seq + pkt_len, pkt_len);
    296 #endif
    297 			m_adj(m, -overlap);
    298 			pkt_len -= overlap;
    299 			rcvpartdupbyte += overlap;
    300 			rcvoobyte -= overlap;
    301 		}
    302 		/*
    303 		 * If the received segment immediates precedes this
    304 		 * fragment then tack the fragment onto this segment
    305 		 * and reinsert the data.
    306 		 */
    307 		if (q->ipqe_seq == pkt_seq + pkt_len) {
    308 #ifdef TCPREASS_DEBUG
    309 			printf("tcp_reass[%p]: append %u:%u(%u) to %u:%u(%u)\n",
    310 			       tp, q->ipqe_seq, q->ipqe_seq + q->ipqe_len, q->ipqe_len,
    311 			       pkt_seq, pkt_seq + pkt_len, pkt_len);
    312 #endif
    313 			pkt_len += q->ipqe_len;
    314 			pkt_flags |= q->ipqe_flags;
    315 			m_cat(m, q->ipqe_m);
    316 			LIST_REMOVE(q, ipqe_q);
    317 			LIST_REMOVE(q, ipqe_timeq);
    318 			if (tiqe == NULL) {
    319 			    tiqe = q;
    320 			} else {
    321 			    pool_put(&ipqent_pool, q);
    322 			}
    323 			break;
    324 		}
    325 		/*
    326 		 * If the fragment is before the segment, remember it.
    327 		 * When this loop is terminated, p will contain the
    328 		 * pointer to fragment that is right before the received
    329 		 * segment.
    330 		 */
    331 		if (SEQ_LEQ(q->ipqe_seq, pkt_seq))
    332 			p = q;
    333 
    334 		continue;
    335 
    336 		/*
    337 		 * This is a common operation.  It also will allow
    338 		 * to save doing a malloc/free in most instances.
    339 		 */
    340 	  free_ipqe:
    341 		LIST_REMOVE(q, ipqe_q);
    342 		LIST_REMOVE(q, ipqe_timeq);
    343 		if (tiqe == NULL) {
    344 		    tiqe = q;
    345 		} else {
    346 		    pool_put(&ipqent_pool, q);
    347 		}
    348 	}
    349 
    350 	/*
    351 	 * Allocate a new queue entry since the received segment did not
    352 	 * collapse onto any other out-of-order block; thus we are allocating
    353 	 * a new block.  If it had collapsed, tiqe would not be NULL and
    354 	 * we would be reusing it.
    355 	 * XXX If we can't, just drop the packet.  XXX
    356 	 */
    357 	if (tiqe == NULL) {
    358 		tiqe = pool_get(&ipqent_pool, PR_NOWAIT);
    359 		if (tiqe == NULL) {
    360 			tcpstat.tcps_rcvmemdrop++;
    361 			m_freem(m);
    362 			return (0);
    363 		}
    364 	}
    365 
    366 	/*
    367 	 * Update the counters.
    368 	 */
    369 	tcpstat.tcps_rcvoopack++;
    370 	tcpstat.tcps_rcvoobyte += rcvoobyte;
    371 	if (rcvpartdupbyte) {
    372 	    tcpstat.tcps_rcvpartduppack++;
    373 	    tcpstat.tcps_rcvpartdupbyte += rcvpartdupbyte;
    374 	}
    375 
    376 	/*
    377 	 * Insert the new fragment queue entry into both queues.
    378 	 */
    379 	tiqe->ipqe_m = m;
    380 	tiqe->ipqe_seq = pkt_seq;
    381 	tiqe->ipqe_len = pkt_len;
    382 	tiqe->ipqe_flags = pkt_flags;
    383 	if (p == NULL) {
    384 		LIST_INSERT_HEAD(&tp->segq, tiqe, ipqe_q);
    385 #ifdef TCPREASS_DEBUG
    386 		if (tiqe->ipqe_seq != tp->rcv_nxt)
    387 			printf("tcp_reass[%p]: insert %u:%u(%u) at front\n",
    388 			       tp, pkt_seq, pkt_seq + pkt_len, pkt_len);
    389 #endif
    390 	} else {
    391 		LIST_INSERT_AFTER(p, tiqe, ipqe_q);
    392 #ifdef TCPREASS_DEBUG
    393 		printf("tcp_reass[%p]: insert %u:%u(%u) after %u:%u(%u)\n",
    394 		       tp, pkt_seq, pkt_seq + pkt_len, pkt_len,
    395 		       p->ipqe_seq, p->ipqe_seq + p->ipqe_len, p->ipqe_len);
    396 #endif
    397 	}
    398 
    399 	LIST_INSERT_HEAD(&tp->timeq, tiqe, ipqe_timeq);
    400 
    401 present:
    402 	/*
    403 	 * Present data to user, advancing rcv_nxt through
    404 	 * completed sequence space.
    405 	 */
    406 	if (TCPS_HAVEESTABLISHED(tp->t_state) == 0)
    407 		return (0);
    408 	q = tp->segq.lh_first;
    409 	if (q == NULL || q->ipqe_seq != tp->rcv_nxt)
    410 		return (0);
    411 	if (tp->t_state == TCPS_SYN_RECEIVED && q->ipqe_len)
    412 		return (0);
    413 
    414 	tp->rcv_nxt += q->ipqe_len;
    415 	pkt_flags = q->ipqe_flags & TH_FIN;
    416 
    417 	LIST_REMOVE(q, ipqe_q);
    418 	LIST_REMOVE(q, ipqe_timeq);
    419 	if (so->so_state & SS_CANTRCVMORE)
    420 		m_freem(q->ipqe_m);
    421 	else
    422 		sbappend(&so->so_rcv, q->ipqe_m);
    423 	pool_put(&ipqent_pool, q);
    424 	sorwakeup(so);
    425 	return (pkt_flags);
    426 }
    427 
    428 /*
    429  * TCP input routine, follows pages 65-76 of the
    430  * protocol specification dated September, 1981 very closely.
    431  */
    432 void
    433 #if __STDC__
    434 tcp_input(struct mbuf *m, ...)
    435 #else
    436 tcp_input(m, va_alist)
    437 	register struct mbuf *m;
    438 #endif
    439 {
    440 	register struct tcpiphdr *ti;
    441 	register struct inpcb *inp;
    442 	caddr_t optp = NULL;
    443 	int optlen = 0;
    444 	int len, tlen, off, hdroptlen;
    445 	register struct tcpcb *tp = 0;
    446 	register int tiflags;
    447 	struct socket *so = NULL;
    448 	int todrop, acked, ourfinisacked, needoutput = 0;
    449 	short ostate = 0;
    450 	int iss = 0;
    451 	u_long tiwin;
    452 	struct tcp_opt_info opti;
    453 	int iphlen;
    454 	va_list ap;
    455 
    456 	va_start(ap, m);
    457 	iphlen = va_arg(ap, int);
    458 	va_end(ap);
    459 
    460 	tcpstat.tcps_rcvtotal++;
    461 
    462 	opti.ts_present = 0;
    463 	opti.maxseg = 0;
    464 
    465 	/*
    466 	 * Get IP and TCP header together in first mbuf.
    467 	 * Note: IP leaves IP header in first mbuf.
    468 	 */
    469 	ti = mtod(m, struct tcpiphdr *);
    470 	if (iphlen > sizeof (struct ip))
    471 		ip_stripoptions(m, (struct mbuf *)0);
    472 	if (m->m_len < sizeof (struct tcpiphdr)) {
    473 		if ((m = m_pullup(m, sizeof (struct tcpiphdr))) == 0) {
    474 			tcpstat.tcps_rcvshort++;
    475 			return;
    476 		}
    477 		ti = mtod(m, struct tcpiphdr *);
    478 	}
    479 
    480 	/*
    481 	 * Checksum extended TCP header and data.
    482 	 */
    483 	len = ((struct ip *)ti)->ip_len;
    484 	tlen = len - sizeof (struct ip);
    485 	bzero(ti->ti_x1, sizeof ti->ti_x1);
    486 	ti->ti_len = (u_int16_t)tlen;
    487 	HTONS(ti->ti_len);
    488 	if (in_cksum(m, len) != 0) {
    489 		tcpstat.tcps_rcvbadsum++;
    490 		goto drop;
    491 	}
    492 
    493 	/*
    494 	 * Check that TCP offset makes sense,
    495 	 * pull out TCP options and adjust length.		XXX
    496 	 */
    497 	off = ti->ti_off << 2;
    498 	if (off < sizeof (struct tcphdr) || off > tlen) {
    499 		tcpstat.tcps_rcvbadoff++;
    500 		goto drop;
    501 	}
    502 	tlen -= off;
    503 	ti->ti_len = tlen;
    504 	if (off > sizeof (struct tcphdr)) {
    505 		if (m->m_len < sizeof(struct ip) + off) {
    506 			if ((m = m_pullup(m, sizeof (struct ip) + off)) == 0) {
    507 				tcpstat.tcps_rcvshort++;
    508 				return;
    509 			}
    510 			ti = mtod(m, struct tcpiphdr *);
    511 		}
    512 		optlen = off - sizeof (struct tcphdr);
    513 		optp = mtod(m, caddr_t) + sizeof (struct tcpiphdr);
    514 		/*
    515 		 * Do quick retrieval of timestamp options ("options
    516 		 * prediction?").  If timestamp is the only option and it's
    517 		 * formatted as recommended in RFC 1323 appendix A, we
    518 		 * quickly get the values now and not bother calling
    519 		 * tcp_dooptions(), etc.
    520 		 */
    521 		if ((optlen == TCPOLEN_TSTAMP_APPA ||
    522 		     (optlen > TCPOLEN_TSTAMP_APPA &&
    523 			optp[TCPOLEN_TSTAMP_APPA] == TCPOPT_EOL)) &&
    524 		     *(u_int32_t *)optp == htonl(TCPOPT_TSTAMP_HDR) &&
    525 		     (ti->ti_flags & TH_SYN) == 0) {
    526 			opti.ts_present = 1;
    527 			opti.ts_val = ntohl(*(u_int32_t *)(optp + 4));
    528 			opti.ts_ecr = ntohl(*(u_int32_t *)(optp + 8));
    529 			optp = NULL;	/* we've parsed the options */
    530 		}
    531 	}
    532 	tiflags = ti->ti_flags;
    533 
    534 	/*
    535 	 * Convert TCP protocol specific fields to host format.
    536 	 */
    537 	NTOHL(ti->ti_seq);
    538 	NTOHL(ti->ti_ack);
    539 	NTOHS(ti->ti_win);
    540 	NTOHS(ti->ti_urp);
    541 
    542 	/*
    543 	 * Locate pcb for segment.
    544 	 */
    545 findpcb:
    546 	inp = in_pcblookup_connect(&tcbtable, ti->ti_src, ti->ti_sport,
    547 	    ti->ti_dst, ti->ti_dport);
    548 	if (inp == 0) {
    549 		++tcpstat.tcps_pcbhashmiss;
    550 		inp = in_pcblookup_bind(&tcbtable, ti->ti_dst, ti->ti_dport);
    551 		if (inp == 0) {
    552 			++tcpstat.tcps_noport;
    553 			if (tcp_log_refused && (tiflags & TH_SYN)) {
    554 				char buf[4*sizeof "123"];
    555 				strcpy(buf, inet_ntoa(ti->ti_dst));
    556 				log(LOG_INFO,
    557 				    "Connection attempt to TCP %s:%d from %s:%d\n",
    558 				    buf, ntohs(ti->ti_dport), inet_ntoa(ti->ti_src),
    559 				    ntohs(ti->ti_sport));
    560 			}
    561 			goto dropwithreset;
    562 		}
    563 	}
    564 
    565 	/*
    566 	 * If the state is CLOSED (i.e., TCB does not exist) then
    567 	 * all data in the incoming segment is discarded.
    568 	 * If the TCB exists but is in CLOSED state, it is embryonic,
    569 	 * but should either do a listen or a connect soon.
    570 	 */
    571 	tp = intotcpcb(inp);
    572 	if (tp == 0)
    573 		goto dropwithreset;
    574 	if (tp->t_state == TCPS_CLOSED)
    575 		goto drop;
    576 
    577 	/* Unscale the window into a 32-bit value. */
    578 	if ((tiflags & TH_SYN) == 0)
    579 		tiwin = ti->ti_win << tp->snd_scale;
    580 	else
    581 		tiwin = ti->ti_win;
    582 
    583 	so = inp->inp_socket;
    584 	if (so->so_options & (SO_DEBUG|SO_ACCEPTCONN)) {
    585 		if (so->so_options & SO_DEBUG) {
    586 			ostate = tp->t_state;
    587 			tcp_saveti = *ti;
    588 		}
    589 		if (so->so_options & SO_ACCEPTCONN) {
    590   			if ((tiflags & (TH_RST|TH_ACK|TH_SYN)) != TH_SYN) {
    591 				if (tiflags & TH_RST) {
    592 					syn_cache_reset(ti);
    593 				} else if ((tiflags & (TH_ACK|TH_SYN)) ==
    594 				    (TH_ACK|TH_SYN)) {
    595 					/*
    596 					 * Received a SYN,ACK.  This should
    597 					 * never happen while we are in
    598 					 * LISTEN.  Send an RST.
    599 					 */
    600 					goto badsyn;
    601 				} else if (tiflags & TH_ACK) {
    602 					so = syn_cache_get(so, m);
    603 					if (so == NULL) {
    604 						/*
    605 						 * We don't have a SYN for
    606 						 * this ACK; send an RST.
    607 						 */
    608 						goto badsyn;
    609 					} else if (so ==
    610 					    (struct socket *)(-1)) {
    611 						/*
    612 						 * We were unable to create
    613 						 * the connection.  If the
    614 						 * 3-way handshake was
    615 						 * completed, and RST has
    616 						 * been sent to the peer.
    617 						 * Since the mbuf might be
    618 						 * in use for the reply,
    619 						 * do not free it.
    620 						 */
    621 						m = NULL;
    622 					} else {
    623 						/*
    624 						 * We have created a
    625 						 * full-blown connection.
    626 						 */
    627 						inp = sotoinpcb(so);
    628 						tp = intotcpcb(inp);
    629 						tiwin <<= tp->snd_scale;
    630 						goto after_listen;
    631 					}
    632   				} else {
    633 					/*
    634 					 * None of RST, SYN or ACK was set.
    635 					 * This is an invalid packet for a
    636 					 * TCB in LISTEN state.  Send a RST.
    637 					 */
    638 					goto badsyn;
    639 				}
    640   			} else {
    641 				/*
    642 				 * Received a SYN.
    643 				 */
    644 				if (in_hosteq(ti->ti_src, ti->ti_dst) &&
    645 				    ti->ti_sport == ti->ti_dport) {
    646 					/*
    647 					 * LISTEN socket received a SYN
    648 					 * from itself?  This can't possibly
    649 					 * be valid; drop the packet.
    650 					 */
    651 					tcpstat.tcps_badsyn++;
    652 					goto drop;
    653 				}
    654 				/*
    655 				 * SYN looks ok; create compressed TCP
    656 				 * state for it.
    657 				 */
    658 				if (so->so_qlen <= so->so_qlimit &&
    659 				    syn_cache_add(so, m, optp, optlen, &opti))
    660 					m = NULL;
    661 			}
    662 			goto drop;
    663 		}
    664 	}
    665 
    666 after_listen:
    667 #ifdef DIAGNOSTIC
    668 	/*
    669 	 * Should not happen now that all embryonic connections
    670 	 * are handled with compressed state.
    671 	 */
    672 	if (tp->t_state == TCPS_LISTEN)
    673 		panic("tcp_input: TCPS_LISTEN");
    674 #endif
    675 
    676 	/*
    677 	 * Segment received on connection.
    678 	 * Reset idle time and keep-alive timer.
    679 	 */
    680 	tp->t_idle = 0;
    681 	if (TCPS_HAVEESTABLISHED(tp->t_state))
    682 		TCP_TIMER_ARM(tp, TCPT_KEEP, tcp_keepidle);
    683 
    684 	/*
    685 	 * Process options.
    686 	 */
    687 	if (optp)
    688 		tcp_dooptions(tp, optp, optlen, ti, &opti);
    689 
    690 	/*
    691 	 * Header prediction: check for the two common cases
    692 	 * of a uni-directional data xfer.  If the packet has
    693 	 * no control flags, is in-sequence, the window didn't
    694 	 * change and we're not retransmitting, it's a
    695 	 * candidate.  If the length is zero and the ack moved
    696 	 * forward, we're the sender side of the xfer.  Just
    697 	 * free the data acked & wake any higher level process
    698 	 * that was blocked waiting for space.  If the length
    699 	 * is non-zero and the ack didn't move, we're the
    700 	 * receiver side.  If we're getting packets in-order
    701 	 * (the reassembly queue is empty), add the data to
    702 	 * the socket buffer and note that we need a delayed ack.
    703 	 */
    704 	if (tp->t_state == TCPS_ESTABLISHED &&
    705 	    (tiflags & (TH_SYN|TH_FIN|TH_RST|TH_URG|TH_ACK)) == TH_ACK &&
    706 	    (!opti.ts_present || TSTMP_GEQ(opti.ts_val, tp->ts_recent)) &&
    707 	    ti->ti_seq == tp->rcv_nxt &&
    708 	    tiwin && tiwin == tp->snd_wnd &&
    709 	    tp->snd_nxt == tp->snd_max) {
    710 
    711 		/*
    712 		 * If last ACK falls within this segment's sequence numbers,
    713 		 *  record the timestamp.
    714 		 */
    715 		if (opti.ts_present &&
    716 		    SEQ_LEQ(ti->ti_seq, tp->last_ack_sent) &&
    717 		    SEQ_LT(tp->last_ack_sent, ti->ti_seq + ti->ti_len)) {
    718 			tp->ts_recent_age = tcp_now;
    719 			tp->ts_recent = opti.ts_val;
    720 		}
    721 
    722 		if (ti->ti_len == 0) {
    723 			if (SEQ_GT(ti->ti_ack, tp->snd_una) &&
    724 			    SEQ_LEQ(ti->ti_ack, tp->snd_max) &&
    725 			    tp->snd_cwnd >= tp->snd_wnd &&
    726 			    tp->t_dupacks < tcprexmtthresh) {
    727 				/*
    728 				 * this is a pure ack for outstanding data.
    729 				 */
    730 				++tcpstat.tcps_predack;
    731 				if (opti.ts_present)
    732 					tcp_xmit_timer(tp,
    733 					    tcp_now-opti.ts_ecr+1);
    734 				else if (tp->t_rtt &&
    735 				    SEQ_GT(ti->ti_ack, tp->t_rtseq))
    736 					tcp_xmit_timer(tp, tp->t_rtt);
    737 				acked = ti->ti_ack - tp->snd_una;
    738 				tcpstat.tcps_rcvackpack++;
    739 				tcpstat.tcps_rcvackbyte += acked;
    740 				sbdrop(&so->so_snd, acked);
    741 				tp->snd_una = ti->ti_ack;
    742 				m_freem(m);
    743 
    744 				/*
    745 				 * If all outstanding data are acked, stop
    746 				 * retransmit timer, otherwise restart timer
    747 				 * using current (possibly backed-off) value.
    748 				 * If process is waiting for space,
    749 				 * wakeup/selwakeup/signal.  If data
    750 				 * are ready to send, let tcp_output
    751 				 * decide between more output or persist.
    752 				 */
    753 				if (tp->snd_una == tp->snd_max)
    754 					TCP_TIMER_DISARM(tp, TCPT_REXMT);
    755 				else if (TCP_TIMER_ISARMED(tp,
    756 				    TCPT_PERSIST) == 0)
    757 					TCP_TIMER_ARM(tp, TCPT_REXMT,
    758 					    tp->t_rxtcur);
    759 
    760 				sowwakeup(so);
    761 				if (so->so_snd.sb_cc)
    762 					(void) tcp_output(tp);
    763 				return;
    764 			}
    765 		} else if (ti->ti_ack == tp->snd_una &&
    766 		    tp->segq.lh_first == NULL &&
    767 		    ti->ti_len <= sbspace(&so->so_rcv)) {
    768 			/*
    769 			 * this is a pure, in-sequence data packet
    770 			 * with nothing on the reassembly queue and
    771 			 * we have enough buffer space to take it.
    772 			 */
    773 			++tcpstat.tcps_preddat;
    774 			tp->rcv_nxt += ti->ti_len;
    775 			tcpstat.tcps_rcvpack++;
    776 			tcpstat.tcps_rcvbyte += ti->ti_len;
    777 			/*
    778 			 * Drop TCP, IP headers and TCP options then add data
    779 			 * to socket buffer.
    780 			 */
    781 			m->m_data += sizeof(struct tcpiphdr)+off-sizeof(struct tcphdr);
    782 			m->m_len -= sizeof(struct tcpiphdr)+off-sizeof(struct tcphdr);
    783 			sbappend(&so->so_rcv, m);
    784 			sorwakeup(so);
    785 			TCP_SETUP_ACK(tp, ti);
    786 			if (tp->t_flags & TF_ACKNOW)
    787 				(void) tcp_output(tp);
    788 			return;
    789 		}
    790 	}
    791 
    792 	/*
    793 	 * Drop TCP, IP headers and TCP options.
    794 	 */
    795 	hdroptlen  = sizeof(struct tcpiphdr) + off - sizeof(struct tcphdr);
    796 	m->m_data += hdroptlen;
    797 	m->m_len  -= hdroptlen;
    798 
    799 	/*
    800 	 * Calculate amount of space in receive window,
    801 	 * and then do TCP input processing.
    802 	 * Receive window is amount of space in rcv queue,
    803 	 * but not less than advertised window.
    804 	 */
    805 	{ int win;
    806 
    807 	win = sbspace(&so->so_rcv);
    808 	if (win < 0)
    809 		win = 0;
    810 	tp->rcv_wnd = imax(win, (int)(tp->rcv_adv - tp->rcv_nxt));
    811 	}
    812 
    813 	switch (tp->t_state) {
    814 
    815 	/*
    816 	 * If the state is SYN_SENT:
    817 	 *	if seg contains an ACK, but not for our SYN, drop the input.
    818 	 *	if seg contains a RST, then drop the connection.
    819 	 *	if seg does not contain SYN, then drop it.
    820 	 * Otherwise this is an acceptable SYN segment
    821 	 *	initialize tp->rcv_nxt and tp->irs
    822 	 *	if seg contains ack then advance tp->snd_una
    823 	 *	if SYN has been acked change to ESTABLISHED else SYN_RCVD state
    824 	 *	arrange for segment to be acked (eventually)
    825 	 *	continue processing rest of data/controls, beginning with URG
    826 	 */
    827 	case TCPS_SYN_SENT:
    828 		if ((tiflags & TH_ACK) &&
    829 		    (SEQ_LEQ(ti->ti_ack, tp->iss) ||
    830 		     SEQ_GT(ti->ti_ack, tp->snd_max)))
    831 			goto dropwithreset;
    832 		if (tiflags & TH_RST) {
    833 			if (tiflags & TH_ACK)
    834 				tp = tcp_drop(tp, ECONNREFUSED);
    835 			goto drop;
    836 		}
    837 		if ((tiflags & TH_SYN) == 0)
    838 			goto drop;
    839 		if (tiflags & TH_ACK) {
    840 			tp->snd_una = ti->ti_ack;
    841 			if (SEQ_LT(tp->snd_nxt, tp->snd_una))
    842 				tp->snd_nxt = tp->snd_una;
    843 		}
    844 		TCP_TIMER_DISARM(tp, TCPT_REXMT);
    845 		tp->irs = ti->ti_seq;
    846 		tcp_rcvseqinit(tp);
    847 		tp->t_flags |= TF_ACKNOW;
    848 		tcp_mss_from_peer(tp, opti.maxseg);
    849 
    850 		/*
    851 		 * Initialize the initial congestion window.  If we
    852 		 * had to retransmit the SYN, we must initialize cwnd
    853 		 * to 1 segment (i.e. the Loss Window).
    854 		 */
    855 		if (tp->t_flags & TF_SYN_REXMT)
    856 			tp->snd_cwnd = tp->t_peermss;
    857 		else
    858 			tp->snd_cwnd = TCP_INITIAL_WINDOW(tcp_init_win,
    859 			    tp->t_peermss);
    860 
    861 		tcp_rmx_rtt(tp);
    862 		if (tiflags & TH_ACK && SEQ_GT(tp->snd_una, tp->iss)) {
    863 			tcpstat.tcps_connects++;
    864 			soisconnected(so);
    865 			tcp_established(tp);
    866 			/* Do window scaling on this connection? */
    867 			if ((tp->t_flags & (TF_RCVD_SCALE|TF_REQ_SCALE)) ==
    868 				(TF_RCVD_SCALE|TF_REQ_SCALE)) {
    869 				tp->snd_scale = tp->requested_s_scale;
    870 				tp->rcv_scale = tp->request_r_scale;
    871 			}
    872 			TCP_REASS_LOCK(tp);
    873 			(void) tcp_reass(tp, (struct tcpiphdr *)0,
    874 				(struct mbuf *)0);
    875 			TCP_REASS_UNLOCK(tp);
    876 			/*
    877 			 * if we didn't have to retransmit the SYN,
    878 			 * use its rtt as our initial srtt & rtt var.
    879 			 */
    880 			if (tp->t_rtt)
    881 				tcp_xmit_timer(tp, tp->t_rtt);
    882 		} else
    883 			tp->t_state = TCPS_SYN_RECEIVED;
    884 
    885 		/*
    886 		 * Advance ti->ti_seq to correspond to first data byte.
    887 		 * If data, trim to stay within window,
    888 		 * dropping FIN if necessary.
    889 		 */
    890 		ti->ti_seq++;
    891 		if (ti->ti_len > tp->rcv_wnd) {
    892 			todrop = ti->ti_len - tp->rcv_wnd;
    893 			m_adj(m, -todrop);
    894 			ti->ti_len = tp->rcv_wnd;
    895 			tiflags &= ~TH_FIN;
    896 			tcpstat.tcps_rcvpackafterwin++;
    897 			tcpstat.tcps_rcvbyteafterwin += todrop;
    898 		}
    899 		tp->snd_wl1 = ti->ti_seq - 1;
    900 		tp->rcv_up = ti->ti_seq;
    901 		goto step6;
    902 
    903 	/*
    904 	 * If the state is SYN_RECEIVED:
    905 	 *	If seg contains an ACK, but not for our SYN, drop the input
    906 	 *	and generate an RST.  See page 36, rfc793
    907 	 */
    908 	case TCPS_SYN_RECEIVED:
    909 		if ((tiflags & TH_ACK) &&
    910 		    (SEQ_LEQ(ti->ti_ack, tp->iss) ||
    911 		     SEQ_GT(ti->ti_ack, tp->snd_max)))
    912 			goto dropwithreset;
    913 		break;
    914 	}
    915 
    916 	/*
    917 	 * States other than LISTEN or SYN_SENT.
    918 	 * First check timestamp, if present.
    919 	 * Then check that at least some bytes of segment are within
    920 	 * receive window.  If segment begins before rcv_nxt,
    921 	 * drop leading data (and SYN); if nothing left, just ack.
    922 	 *
    923 	 * RFC 1323 PAWS: If we have a timestamp reply on this segment
    924 	 * and it's less than ts_recent, drop it.
    925 	 */
    926 	if (opti.ts_present && (tiflags & TH_RST) == 0 && tp->ts_recent &&
    927 	    TSTMP_LT(opti.ts_val, tp->ts_recent)) {
    928 
    929 		/* Check to see if ts_recent is over 24 days old.  */
    930 		if ((int)(tcp_now - tp->ts_recent_age) > TCP_PAWS_IDLE) {
    931 			/*
    932 			 * Invalidate ts_recent.  If this segment updates
    933 			 * ts_recent, the age will be reset later and ts_recent
    934 			 * will get a valid value.  If it does not, setting
    935 			 * ts_recent to zero will at least satisfy the
    936 			 * requirement that zero be placed in the timestamp
    937 			 * echo reply when ts_recent isn't valid.  The
    938 			 * age isn't reset until we get a valid ts_recent
    939 			 * because we don't want out-of-order segments to be
    940 			 * dropped when ts_recent is old.
    941 			 */
    942 			tp->ts_recent = 0;
    943 		} else {
    944 			tcpstat.tcps_rcvduppack++;
    945 			tcpstat.tcps_rcvdupbyte += ti->ti_len;
    946 			tcpstat.tcps_pawsdrop++;
    947 			goto dropafterack;
    948 		}
    949 	}
    950 
    951 	todrop = tp->rcv_nxt - ti->ti_seq;
    952 	if (todrop > 0) {
    953 		if (tiflags & TH_SYN) {
    954 			tiflags &= ~TH_SYN;
    955 			ti->ti_seq++;
    956 			if (ti->ti_urp > 1)
    957 				ti->ti_urp--;
    958 			else {
    959 				tiflags &= ~TH_URG;
    960 				ti->ti_urp = 0;
    961 			}
    962 			todrop--;
    963 		}
    964 		if (todrop > ti->ti_len ||
    965 		    (todrop == ti->ti_len && (tiflags & TH_FIN) == 0)) {
    966 			/*
    967 			 * Any valid FIN must be to the left of the window.
    968 			 * At this point the FIN must be a duplicate or
    969 			 * out of sequence; drop it.
    970 			 */
    971 			tiflags &= ~TH_FIN;
    972 			/*
    973 			 * Send an ACK to resynchronize and drop any data.
    974 			 * But keep on processing for RST or ACK.
    975 			 */
    976 			tp->t_flags |= TF_ACKNOW;
    977 			todrop = ti->ti_len;
    978 			tcpstat.tcps_rcvdupbyte += todrop;
    979 			tcpstat.tcps_rcvduppack++;
    980 		} else {
    981 			tcpstat.tcps_rcvpartduppack++;
    982 			tcpstat.tcps_rcvpartdupbyte += todrop;
    983 		}
    984 		m_adj(m, todrop);
    985 		ti->ti_seq += todrop;
    986 		ti->ti_len -= todrop;
    987 		if (ti->ti_urp > todrop)
    988 			ti->ti_urp -= todrop;
    989 		else {
    990 			tiflags &= ~TH_URG;
    991 			ti->ti_urp = 0;
    992 		}
    993 	}
    994 
    995 	/*
    996 	 * If new data are received on a connection after the
    997 	 * user processes are gone, then RST the other end.
    998 	 */
    999 	if ((so->so_state & SS_NOFDREF) &&
   1000 	    tp->t_state > TCPS_CLOSE_WAIT && ti->ti_len) {
   1001 		tp = tcp_close(tp);
   1002 		tcpstat.tcps_rcvafterclose++;
   1003 		goto dropwithreset;
   1004 	}
   1005 
   1006 	/*
   1007 	 * If segment ends after window, drop trailing data
   1008 	 * (and PUSH and FIN); if nothing left, just ACK.
   1009 	 */
   1010 	todrop = (ti->ti_seq+ti->ti_len) - (tp->rcv_nxt+tp->rcv_wnd);
   1011 	if (todrop > 0) {
   1012 		tcpstat.tcps_rcvpackafterwin++;
   1013 		if (todrop >= ti->ti_len) {
   1014 			tcpstat.tcps_rcvbyteafterwin += ti->ti_len;
   1015 			/*
   1016 			 * If a new connection request is received
   1017 			 * while in TIME_WAIT, drop the old connection
   1018 			 * and start over if the sequence numbers
   1019 			 * are above the previous ones.
   1020 			 */
   1021 			if (tiflags & TH_SYN &&
   1022 			    tp->t_state == TCPS_TIME_WAIT &&
   1023 			    SEQ_GT(ti->ti_seq, tp->rcv_nxt)) {
   1024 				iss = tcp_new_iss(tp, sizeof(struct tcpcb),
   1025 						  tp->snd_nxt);
   1026 				tp = tcp_close(tp);
   1027 				/*
   1028 				 * We have already advanced the mbuf
   1029 				 * pointers past the IP+TCP headers and
   1030 				 * options.  Restore those pointers before
   1031 				 * attempting to use the TCP header again.
   1032 				 */
   1033 				m->m_data -= hdroptlen;
   1034 				m->m_len  += hdroptlen;
   1035 				goto findpcb;
   1036 			}
   1037 			/*
   1038 			 * If window is closed can only take segments at
   1039 			 * window edge, and have to drop data and PUSH from
   1040 			 * incoming segments.  Continue processing, but
   1041 			 * remember to ack.  Otherwise, drop segment
   1042 			 * and ack.
   1043 			 */
   1044 			if (tp->rcv_wnd == 0 && ti->ti_seq == tp->rcv_nxt) {
   1045 				tp->t_flags |= TF_ACKNOW;
   1046 				tcpstat.tcps_rcvwinprobe++;
   1047 			} else
   1048 				goto dropafterack;
   1049 		} else
   1050 			tcpstat.tcps_rcvbyteafterwin += todrop;
   1051 		m_adj(m, -todrop);
   1052 		ti->ti_len -= todrop;
   1053 		tiflags &= ~(TH_PUSH|TH_FIN);
   1054 	}
   1055 
   1056 	/*
   1057 	 * If last ACK falls within this segment's sequence numbers,
   1058 	 * and the timestamp is newer, record it.
   1059 	 */
   1060 	if (opti.ts_present && TSTMP_GEQ(opti.ts_val, tp->ts_recent) &&
   1061 	    SEQ_LEQ(ti->ti_seq, tp->last_ack_sent) &&
   1062 	    SEQ_LT(tp->last_ack_sent, ti->ti_seq + ti->ti_len +
   1063 		   ((tiflags & (TH_SYN|TH_FIN)) != 0))) {
   1064 		tp->ts_recent_age = tcp_now;
   1065 		tp->ts_recent = opti.ts_val;
   1066 	}
   1067 
   1068 	/*
   1069 	 * If the RST bit is set examine the state:
   1070 	 *    SYN_RECEIVED STATE:
   1071 	 *	If passive open, return to LISTEN state.
   1072 	 *	If active open, inform user that connection was refused.
   1073 	 *    ESTABLISHED, FIN_WAIT_1, FIN_WAIT2, CLOSE_WAIT STATES:
   1074 	 *	Inform user that connection was reset, and close tcb.
   1075 	 *    CLOSING, LAST_ACK, TIME_WAIT STATES
   1076 	 *	Close the tcb.
   1077 	 */
   1078 	if (tiflags&TH_RST) switch (tp->t_state) {
   1079 
   1080 	case TCPS_SYN_RECEIVED:
   1081 		so->so_error = ECONNREFUSED;
   1082 		goto close;
   1083 
   1084 	case TCPS_ESTABLISHED:
   1085 	case TCPS_FIN_WAIT_1:
   1086 	case TCPS_FIN_WAIT_2:
   1087 	case TCPS_CLOSE_WAIT:
   1088 		so->so_error = ECONNRESET;
   1089 	close:
   1090 		tp->t_state = TCPS_CLOSED;
   1091 		tcpstat.tcps_drops++;
   1092 		tp = tcp_close(tp);
   1093 		goto drop;
   1094 
   1095 	case TCPS_CLOSING:
   1096 	case TCPS_LAST_ACK:
   1097 	case TCPS_TIME_WAIT:
   1098 		tp = tcp_close(tp);
   1099 		goto drop;
   1100 	}
   1101 
   1102 	/*
   1103 	 * If a SYN is in the window, then this is an
   1104 	 * error and we send an RST and drop the connection.
   1105 	 */
   1106 	if (tiflags & TH_SYN) {
   1107 		tp = tcp_drop(tp, ECONNRESET);
   1108 		goto dropwithreset;
   1109 	}
   1110 
   1111 	/*
   1112 	 * If the ACK bit is off we drop the segment and return.
   1113 	 */
   1114 	if ((tiflags & TH_ACK) == 0) {
   1115 		if (tp->t_flags & TF_ACKNOW)
   1116 			goto dropafterack;
   1117 		else
   1118 			goto drop;
   1119 	}
   1120 
   1121 	/*
   1122 	 * Ack processing.
   1123 	 */
   1124 	switch (tp->t_state) {
   1125 
   1126 	/*
   1127 	 * In SYN_RECEIVED state if the ack ACKs our SYN then enter
   1128 	 * ESTABLISHED state and continue processing, otherwise
   1129 	 * send an RST.
   1130 	 */
   1131 	case TCPS_SYN_RECEIVED:
   1132 		if (SEQ_GT(tp->snd_una, ti->ti_ack) ||
   1133 		    SEQ_GT(ti->ti_ack, tp->snd_max))
   1134 			goto dropwithreset;
   1135 		tcpstat.tcps_connects++;
   1136 		soisconnected(so);
   1137 		tcp_established(tp);
   1138 		/* Do window scaling? */
   1139 		if ((tp->t_flags & (TF_RCVD_SCALE|TF_REQ_SCALE)) ==
   1140 			(TF_RCVD_SCALE|TF_REQ_SCALE)) {
   1141 			tp->snd_scale = tp->requested_s_scale;
   1142 			tp->rcv_scale = tp->request_r_scale;
   1143 		}
   1144 		TCP_REASS_LOCK(tp);
   1145 		(void) tcp_reass(tp, (struct tcpiphdr *)0, (struct mbuf *)0);
   1146 		TCP_REASS_UNLOCK(tp);
   1147 		tp->snd_wl1 = ti->ti_seq - 1;
   1148 		/* fall into ... */
   1149 
   1150 	/*
   1151 	 * In ESTABLISHED state: drop duplicate ACKs; ACK out of range
   1152 	 * ACKs.  If the ack is in the range
   1153 	 *	tp->snd_una < ti->ti_ack <= tp->snd_max
   1154 	 * then advance tp->snd_una to ti->ti_ack and drop
   1155 	 * data from the retransmission queue.  If this ACK reflects
   1156 	 * more up to date window information we update our window information.
   1157 	 */
   1158 	case TCPS_ESTABLISHED:
   1159 	case TCPS_FIN_WAIT_1:
   1160 	case TCPS_FIN_WAIT_2:
   1161 	case TCPS_CLOSE_WAIT:
   1162 	case TCPS_CLOSING:
   1163 	case TCPS_LAST_ACK:
   1164 	case TCPS_TIME_WAIT:
   1165 
   1166 		if (SEQ_LEQ(ti->ti_ack, tp->snd_una)) {
   1167 			if (ti->ti_len == 0 && tiwin == tp->snd_wnd) {
   1168 				tcpstat.tcps_rcvdupack++;
   1169 				/*
   1170 				 * If we have outstanding data (other than
   1171 				 * a window probe), this is a completely
   1172 				 * duplicate ack (ie, window info didn't
   1173 				 * change), the ack is the biggest we've
   1174 				 * seen and we've seen exactly our rexmt
   1175 				 * threshhold of them, assume a packet
   1176 				 * has been dropped and retransmit it.
   1177 				 * Kludge snd_nxt & the congestion
   1178 				 * window so we send only this one
   1179 				 * packet.
   1180 				 *
   1181 				 * We know we're losing at the current
   1182 				 * window size so do congestion avoidance
   1183 				 * (set ssthresh to half the current window
   1184 				 * and pull our congestion window back to
   1185 				 * the new ssthresh).
   1186 				 *
   1187 				 * Dup acks mean that packets have left the
   1188 				 * network (they're now cached at the receiver)
   1189 				 * so bump cwnd by the amount in the receiver
   1190 				 * to keep a constant cwnd packets in the
   1191 				 * network.
   1192 				 */
   1193 				if (TCP_TIMER_ISARMED(tp, TCPT_REXMT) == 0 ||
   1194 				    ti->ti_ack != tp->snd_una)
   1195 					tp->t_dupacks = 0;
   1196 				else if (++tp->t_dupacks == tcprexmtthresh) {
   1197 					tcp_seq onxt = tp->snd_nxt;
   1198 					u_int win =
   1199 					    min(tp->snd_wnd, tp->snd_cwnd) /
   1200 					    2 /	tp->t_segsz;
   1201 					if (SEQ_LT(ti->ti_ack, tp->snd_recover)) {
   1202 						/*
   1203 						 * False fast retransmit after
   1204 						 * timeout.  Do not cut window.
   1205 						 */
   1206 						tp->snd_cwnd += tp->t_segsz;
   1207 						tp->t_dupacks = 0;
   1208 						(void) tcp_output(tp);
   1209 						goto drop;
   1210 					}
   1211 
   1212 					if (win < 2)
   1213 						win = 2;
   1214 					tp->snd_ssthresh = win * tp->t_segsz;
   1215 					tp->snd_recover = tp->snd_max;
   1216 					TCP_TIMER_DISARM(tp, TCPT_REXMT);
   1217 					tp->t_rtt = 0;
   1218 					tp->snd_nxt = ti->ti_ack;
   1219 					tp->snd_cwnd = tp->t_segsz;
   1220 					(void) tcp_output(tp);
   1221 					tp->snd_cwnd = tp->snd_ssthresh +
   1222 					       tp->t_segsz * tp->t_dupacks;
   1223 					if (SEQ_GT(onxt, tp->snd_nxt))
   1224 						tp->snd_nxt = onxt;
   1225 					goto drop;
   1226 				} else if (tp->t_dupacks > tcprexmtthresh) {
   1227 					tp->snd_cwnd += tp->t_segsz;
   1228 					(void) tcp_output(tp);
   1229 					goto drop;
   1230 				}
   1231 			} else
   1232 				tp->t_dupacks = 0;
   1233 			break;
   1234 		}
   1235 		/*
   1236 		 * If the congestion window was inflated to account
   1237 		 * for the other side's cached packets, retract it.
   1238 		 */
   1239 		if (!tcp_do_newreno) {
   1240 			if (tp->t_dupacks >= tcprexmtthresh &&
   1241 			    tp->snd_cwnd > tp->snd_ssthresh)
   1242 				tp->snd_cwnd = tp->snd_ssthresh;
   1243 			tp->t_dupacks = 0;
   1244 		} else if (tp->t_dupacks >= tcprexmtthresh
   1245 		    && !tcp_newreno(tp, ti)) {
   1246 			tp->snd_cwnd = tp->snd_ssthresh;
   1247 			/*
   1248 			 * Window inflation should have left us with approx.
   1249 			 * snd_ssthresh outstanding data.  But in case we
   1250 			 * would be inclined to send a burst, better to do
   1251 			 * it via the slow start mechanism.
   1252 			 */
   1253 			if (SEQ_SUB(tp->snd_max, ti->ti_ack) < tp->snd_ssthresh)
   1254 				tp->snd_cwnd = SEQ_SUB(tp->snd_max, ti->ti_ack)
   1255 				     + tp->t_segsz;
   1256 			tp->t_dupacks = 0;
   1257 		}
   1258 		if (SEQ_GT(ti->ti_ack, tp->snd_max)) {
   1259 			tcpstat.tcps_rcvacktoomuch++;
   1260 			goto dropafterack;
   1261 		}
   1262 		acked = ti->ti_ack - tp->snd_una;
   1263 		tcpstat.tcps_rcvackpack++;
   1264 		tcpstat.tcps_rcvackbyte += acked;
   1265 
   1266 		/*
   1267 		 * If we have a timestamp reply, update smoothed
   1268 		 * round trip time.  If no timestamp is present but
   1269 		 * transmit timer is running and timed sequence
   1270 		 * number was acked, update smoothed round trip time.
   1271 		 * Since we now have an rtt measurement, cancel the
   1272 		 * timer backoff (cf., Phil Karn's retransmit alg.).
   1273 		 * Recompute the initial retransmit timer.
   1274 		 */
   1275 		if (opti.ts_present)
   1276 			tcp_xmit_timer(tp, tcp_now - opti.ts_ecr + 1);
   1277 		else if (tp->t_rtt && SEQ_GT(ti->ti_ack, tp->t_rtseq))
   1278 			tcp_xmit_timer(tp,tp->t_rtt);
   1279 
   1280 		/*
   1281 		 * If all outstanding data is acked, stop retransmit
   1282 		 * timer and remember to restart (more output or persist).
   1283 		 * If there is more data to be acked, restart retransmit
   1284 		 * timer, using current (possibly backed-off) value.
   1285 		 */
   1286 		if (ti->ti_ack == tp->snd_max) {
   1287 			TCP_TIMER_DISARM(tp, TCPT_REXMT);
   1288 			needoutput = 1;
   1289 		} else if (TCP_TIMER_ISARMED(tp, TCPT_PERSIST) == 0)
   1290 			TCP_TIMER_ARM(tp, TCPT_REXMT, tp->t_rxtcur);
   1291 		/*
   1292 		 * When new data is acked, open the congestion window.
   1293 		 * If the window gives us less than ssthresh packets
   1294 		 * in flight, open exponentially (segsz per packet).
   1295 		 * Otherwise open linearly: segsz per window
   1296 		 * (segsz^2 / cwnd per packet), plus a constant
   1297 		 * fraction of a packet (segsz/8) to help larger windows
   1298 		 * open quickly enough.
   1299 		 */
   1300 		{
   1301 		register u_int cw = tp->snd_cwnd;
   1302 		register u_int incr = tp->t_segsz;
   1303 
   1304 		if (cw > tp->snd_ssthresh)
   1305 			incr = incr * incr / cw;
   1306 		if (!tcp_do_newreno || SEQ_GEQ(ti->ti_ack, tp->snd_recover))
   1307 			tp->snd_cwnd = min(cw + incr,TCP_MAXWIN<<tp->snd_scale);
   1308 		}
   1309 		if (acked > so->so_snd.sb_cc) {
   1310 			tp->snd_wnd -= so->so_snd.sb_cc;
   1311 			sbdrop(&so->so_snd, (int)so->so_snd.sb_cc);
   1312 			ourfinisacked = 1;
   1313 		} else {
   1314 			sbdrop(&so->so_snd, acked);
   1315 			tp->snd_wnd -= acked;
   1316 			ourfinisacked = 0;
   1317 		}
   1318 		sowwakeup(so);
   1319 		tp->snd_una = ti->ti_ack;
   1320 		if (SEQ_LT(tp->snd_nxt, tp->snd_una))
   1321 			tp->snd_nxt = tp->snd_una;
   1322 
   1323 		switch (tp->t_state) {
   1324 
   1325 		/*
   1326 		 * In FIN_WAIT_1 STATE in addition to the processing
   1327 		 * for the ESTABLISHED state if our FIN is now acknowledged
   1328 		 * then enter FIN_WAIT_2.
   1329 		 */
   1330 		case TCPS_FIN_WAIT_1:
   1331 			if (ourfinisacked) {
   1332 				/*
   1333 				 * If we can't receive any more
   1334 				 * data, then closing user can proceed.
   1335 				 * Starting the timer is contrary to the
   1336 				 * specification, but if we don't get a FIN
   1337 				 * we'll hang forever.
   1338 				 */
   1339 				if (so->so_state & SS_CANTRCVMORE) {
   1340 					soisdisconnected(so);
   1341 					if (tcp_maxidle > 0)
   1342 						TCP_TIMER_ARM(tp, TCPT_2MSL,
   1343 						    tcp_maxidle);
   1344 				}
   1345 				tp->t_state = TCPS_FIN_WAIT_2;
   1346 			}
   1347 			break;
   1348 
   1349 	 	/*
   1350 		 * In CLOSING STATE in addition to the processing for
   1351 		 * the ESTABLISHED state if the ACK acknowledges our FIN
   1352 		 * then enter the TIME-WAIT state, otherwise ignore
   1353 		 * the segment.
   1354 		 */
   1355 		case TCPS_CLOSING:
   1356 			if (ourfinisacked) {
   1357 				tp->t_state = TCPS_TIME_WAIT;
   1358 				tcp_canceltimers(tp);
   1359 				TCP_TIMER_ARM(tp, TCPT_2MSL, 2 * TCPTV_MSL);
   1360 				soisdisconnected(so);
   1361 			}
   1362 			break;
   1363 
   1364 		/*
   1365 		 * In LAST_ACK, we may still be waiting for data to drain
   1366 		 * and/or to be acked, as well as for the ack of our FIN.
   1367 		 * If our FIN is now acknowledged, delete the TCB,
   1368 		 * enter the closed state and return.
   1369 		 */
   1370 		case TCPS_LAST_ACK:
   1371 			if (ourfinisacked) {
   1372 				tp = tcp_close(tp);
   1373 				goto drop;
   1374 			}
   1375 			break;
   1376 
   1377 		/*
   1378 		 * In TIME_WAIT state the only thing that should arrive
   1379 		 * is a retransmission of the remote FIN.  Acknowledge
   1380 		 * it and restart the finack timer.
   1381 		 */
   1382 		case TCPS_TIME_WAIT:
   1383 			TCP_TIMER_ARM(tp, TCPT_2MSL, 2 * TCPTV_MSL);
   1384 			goto dropafterack;
   1385 		}
   1386 	}
   1387 
   1388 step6:
   1389 	/*
   1390 	 * Update window information.
   1391 	 * Don't look at window if no ACK: TAC's send garbage on first SYN.
   1392 	 */
   1393 	if ((tiflags & TH_ACK) && (SEQ_LT(tp->snd_wl1, ti->ti_seq) ||
   1394 	    (tp->snd_wl1 == ti->ti_seq && SEQ_LT(tp->snd_wl2, ti->ti_ack)) ||
   1395 	    (tp->snd_wl2 == ti->ti_ack && tiwin > tp->snd_wnd))) {
   1396 		/* keep track of pure window updates */
   1397 		if (ti->ti_len == 0 &&
   1398 		    tp->snd_wl2 == ti->ti_ack && tiwin > tp->snd_wnd)
   1399 			tcpstat.tcps_rcvwinupd++;
   1400 		tp->snd_wnd = tiwin;
   1401 		tp->snd_wl1 = ti->ti_seq;
   1402 		tp->snd_wl2 = ti->ti_ack;
   1403 		if (tp->snd_wnd > tp->max_sndwnd)
   1404 			tp->max_sndwnd = tp->snd_wnd;
   1405 		needoutput = 1;
   1406 	}
   1407 
   1408 	/*
   1409 	 * Process segments with URG.
   1410 	 */
   1411 	if ((tiflags & TH_URG) && ti->ti_urp &&
   1412 	    TCPS_HAVERCVDFIN(tp->t_state) == 0) {
   1413 		/*
   1414 		 * This is a kludge, but if we receive and accept
   1415 		 * random urgent pointers, we'll crash in
   1416 		 * soreceive.  It's hard to imagine someone
   1417 		 * actually wanting to send this much urgent data.
   1418 		 */
   1419 		if (ti->ti_urp + so->so_rcv.sb_cc > sb_max) {
   1420 			ti->ti_urp = 0;			/* XXX */
   1421 			tiflags &= ~TH_URG;		/* XXX */
   1422 			goto dodata;			/* XXX */
   1423 		}
   1424 		/*
   1425 		 * If this segment advances the known urgent pointer,
   1426 		 * then mark the data stream.  This should not happen
   1427 		 * in CLOSE_WAIT, CLOSING, LAST_ACK or TIME_WAIT STATES since
   1428 		 * a FIN has been received from the remote side.
   1429 		 * In these states we ignore the URG.
   1430 		 *
   1431 		 * According to RFC961 (Assigned Protocols),
   1432 		 * the urgent pointer points to the last octet
   1433 		 * of urgent data.  We continue, however,
   1434 		 * to consider it to indicate the first octet
   1435 		 * of data past the urgent section as the original
   1436 		 * spec states (in one of two places).
   1437 		 */
   1438 		if (SEQ_GT(ti->ti_seq+ti->ti_urp, tp->rcv_up)) {
   1439 			tp->rcv_up = ti->ti_seq + ti->ti_urp;
   1440 			so->so_oobmark = so->so_rcv.sb_cc +
   1441 			    (tp->rcv_up - tp->rcv_nxt) - 1;
   1442 			if (so->so_oobmark == 0)
   1443 				so->so_state |= SS_RCVATMARK;
   1444 			sohasoutofband(so);
   1445 			tp->t_oobflags &= ~(TCPOOB_HAVEDATA | TCPOOB_HADDATA);
   1446 		}
   1447 		/*
   1448 		 * Remove out of band data so doesn't get presented to user.
   1449 		 * This can happen independent of advancing the URG pointer,
   1450 		 * but if two URG's are pending at once, some out-of-band
   1451 		 * data may creep in... ick.
   1452 		 */
   1453 		if (ti->ti_urp <= (u_int16_t) ti->ti_len
   1454 #ifdef SO_OOBINLINE
   1455 		     && (so->so_options & SO_OOBINLINE) == 0
   1456 #endif
   1457 		     )
   1458 			tcp_pulloutofband(so, ti, m);
   1459 	} else
   1460 		/*
   1461 		 * If no out of band data is expected,
   1462 		 * pull receive urgent pointer along
   1463 		 * with the receive window.
   1464 		 */
   1465 		if (SEQ_GT(tp->rcv_nxt, tp->rcv_up))
   1466 			tp->rcv_up = tp->rcv_nxt;
   1467 dodata:							/* XXX */
   1468 
   1469 	/*
   1470 	 * Process the segment text, merging it into the TCP sequencing queue,
   1471 	 * and arranging for acknowledgment of receipt if necessary.
   1472 	 * This process logically involves adjusting tp->rcv_wnd as data
   1473 	 * is presented to the user (this happens in tcp_usrreq.c,
   1474 	 * case PRU_RCVD).  If a FIN has already been received on this
   1475 	 * connection then we just ignore the text.
   1476 	 */
   1477 	if ((ti->ti_len || (tiflags & TH_FIN)) &&
   1478 	    TCPS_HAVERCVDFIN(tp->t_state) == 0) {
   1479 		TCP_REASS(tp, ti, m, so, tiflags);
   1480 		/*
   1481 		 * Note the amount of data that peer has sent into
   1482 		 * our window, in order to estimate the sender's
   1483 		 * buffer size.
   1484 		 */
   1485 		len = so->so_rcv.sb_hiwat - (tp->rcv_adv - tp->rcv_nxt);
   1486 	} else {
   1487 		m_freem(m);
   1488 		tiflags &= ~TH_FIN;
   1489 	}
   1490 
   1491 	/*
   1492 	 * If FIN is received ACK the FIN and let the user know
   1493 	 * that the connection is closing.  Ignore a FIN received before
   1494 	 * the connection is fully established.
   1495 	 */
   1496 	if ((tiflags & TH_FIN) && TCPS_HAVEESTABLISHED(tp->t_state)) {
   1497 		if (TCPS_HAVERCVDFIN(tp->t_state) == 0) {
   1498 			socantrcvmore(so);
   1499 			tp->t_flags |= TF_ACKNOW;
   1500 			tp->rcv_nxt++;
   1501 		}
   1502 		switch (tp->t_state) {
   1503 
   1504 	 	/*
   1505 		 * In ESTABLISHED STATE enter the CLOSE_WAIT state.
   1506 		 */
   1507 		case TCPS_ESTABLISHED:
   1508 			tp->t_state = TCPS_CLOSE_WAIT;
   1509 			break;
   1510 
   1511 	 	/*
   1512 		 * If still in FIN_WAIT_1 STATE FIN has not been acked so
   1513 		 * enter the CLOSING state.
   1514 		 */
   1515 		case TCPS_FIN_WAIT_1:
   1516 			tp->t_state = TCPS_CLOSING;
   1517 			break;
   1518 
   1519 	 	/*
   1520 		 * In FIN_WAIT_2 state enter the TIME_WAIT state,
   1521 		 * starting the time-wait timer, turning off the other
   1522 		 * standard timers.
   1523 		 */
   1524 		case TCPS_FIN_WAIT_2:
   1525 			tp->t_state = TCPS_TIME_WAIT;
   1526 			tcp_canceltimers(tp);
   1527 			TCP_TIMER_ARM(tp, TCPT_2MSL, 2 * TCPTV_MSL);
   1528 			soisdisconnected(so);
   1529 			break;
   1530 
   1531 		/*
   1532 		 * In TIME_WAIT state restart the 2 MSL time_wait timer.
   1533 		 */
   1534 		case TCPS_TIME_WAIT:
   1535 			TCP_TIMER_ARM(tp, TCPT_2MSL, 2 * TCPTV_MSL);
   1536 			break;
   1537 		}
   1538 	}
   1539 	if (so->so_options & SO_DEBUG)
   1540 		tcp_trace(TA_INPUT, ostate, tp, &tcp_saveti, 0);
   1541 
   1542 	/*
   1543 	 * Return any desired output.
   1544 	 */
   1545 	if (needoutput || (tp->t_flags & TF_ACKNOW))
   1546 		(void) tcp_output(tp);
   1547 	return;
   1548 
   1549 badsyn:
   1550 	/*
   1551 	 * Received a bad SYN.  Increment counters and dropwithreset.
   1552 	 */
   1553 	tcpstat.tcps_badsyn++;
   1554 	tp = NULL;
   1555 	goto dropwithreset;
   1556 
   1557 dropafterack:
   1558 	/*
   1559 	 * Generate an ACK dropping incoming segment if it occupies
   1560 	 * sequence space, where the ACK reflects our state.
   1561 	 */
   1562 	if (tiflags & TH_RST)
   1563 		goto drop;
   1564 	m_freem(m);
   1565 	tp->t_flags |= TF_ACKNOW;
   1566 	(void) tcp_output(tp);
   1567 	return;
   1568 
   1569 dropwithreset:
   1570 	/*
   1571 	 * Generate a RST, dropping incoming segment.
   1572 	 * Make ACK acceptable to originator of segment.
   1573 	 * Don't bother to respond if destination was broadcast/multicast.
   1574 	 */
   1575 	if ((tiflags & TH_RST) || m->m_flags & (M_BCAST|M_MCAST) ||
   1576 	    IN_MULTICAST(ti->ti_dst.s_addr))
   1577 		goto drop;
   1578 	if (tiflags & TH_ACK)
   1579 		(void)tcp_respond(tp, ti, m, (tcp_seq)0, ti->ti_ack, TH_RST);
   1580 	else {
   1581 		if (tiflags & TH_SYN)
   1582 			ti->ti_len++;
   1583 		(void)tcp_respond(tp, ti, m, ti->ti_seq+ti->ti_len, (tcp_seq)0,
   1584 		    TH_RST|TH_ACK);
   1585 	}
   1586 	return;
   1587 
   1588 drop:
   1589 	/*
   1590 	 * Drop space held by incoming segment and return.
   1591 	 */
   1592 	if (tp && (tp->t_inpcb->inp_socket->so_options & SO_DEBUG))
   1593 		tcp_trace(TA_DROP, ostate, tp, &tcp_saveti, 0);
   1594 	m_freem(m);
   1595 	return;
   1596 }
   1597 
   1598 void
   1599 tcp_dooptions(tp, cp, cnt, ti, oi)
   1600 	struct tcpcb *tp;
   1601 	u_char *cp;
   1602 	int cnt;
   1603 	struct tcpiphdr *ti;
   1604 	struct tcp_opt_info *oi;
   1605 {
   1606 	u_int16_t mss;
   1607 	int opt, optlen;
   1608 
   1609 	for (; cnt > 0; cnt -= optlen, cp += optlen) {
   1610 		opt = cp[0];
   1611 		if (opt == TCPOPT_EOL)
   1612 			break;
   1613 		if (opt == TCPOPT_NOP)
   1614 			optlen = 1;
   1615 		else {
   1616 			optlen = cp[1];
   1617 			if (optlen <= 0)
   1618 				break;
   1619 		}
   1620 		switch (opt) {
   1621 
   1622 		default:
   1623 			continue;
   1624 
   1625 		case TCPOPT_MAXSEG:
   1626 			if (optlen != TCPOLEN_MAXSEG)
   1627 				continue;
   1628 			if (!(ti->ti_flags & TH_SYN))
   1629 				continue;
   1630 			bcopy(cp + 2, &mss, sizeof(mss));
   1631 			oi->maxseg = ntohs(mss);
   1632 			break;
   1633 
   1634 		case TCPOPT_WINDOW:
   1635 			if (optlen != TCPOLEN_WINDOW)
   1636 				continue;
   1637 			if (!(ti->ti_flags & TH_SYN))
   1638 				continue;
   1639 			tp->t_flags |= TF_RCVD_SCALE;
   1640 			tp->requested_s_scale = cp[2];
   1641 			if (tp->requested_s_scale > TCP_MAX_WINSHIFT) {
   1642 				log(LOG_ERR, "TCP: invalid wscale %d from "
   1643 				    "0x%08x, assuming %d\n",
   1644 				    tp->requested_s_scale,
   1645 				    ntohl(ti->ti_src.s_addr),
   1646 				    TCP_MAX_WINSHIFT);
   1647 				tp->requested_s_scale = TCP_MAX_WINSHIFT;
   1648 			}
   1649 			break;
   1650 
   1651 		case TCPOPT_TIMESTAMP:
   1652 			if (optlen != TCPOLEN_TIMESTAMP)
   1653 				continue;
   1654 			oi->ts_present = 1;
   1655 			bcopy(cp + 2, &oi->ts_val, sizeof(oi->ts_val));
   1656 			NTOHL(oi->ts_val);
   1657 			bcopy(cp + 6, &oi->ts_ecr, sizeof(oi->ts_ecr));
   1658 			NTOHL(oi->ts_ecr);
   1659 
   1660 			/*
   1661 			 * A timestamp received in a SYN makes
   1662 			 * it ok to send timestamp requests and replies.
   1663 			 */
   1664 			if (ti->ti_flags & TH_SYN) {
   1665 				tp->t_flags |= TF_RCVD_TSTMP;
   1666 				tp->ts_recent = oi->ts_val;
   1667 				tp->ts_recent_age = tcp_now;
   1668 			}
   1669 			break;
   1670 		case TCPOPT_SACK_PERMITTED:
   1671 			if (optlen != TCPOLEN_SACK_PERMITTED)
   1672 				continue;
   1673 			if (!(ti->ti_flags & TH_SYN))
   1674 				continue;
   1675 			tp->t_flags &= ~TF_CANT_TXSACK;
   1676 			break;
   1677 
   1678 		case TCPOPT_SACK:
   1679 			if (tp->t_flags & TF_IGNR_RXSACK)
   1680 				continue;
   1681 			if (optlen % 8 != 2 || optlen < 10)
   1682 				continue;
   1683 			cp += 2;
   1684 			optlen -= 2;
   1685 			for (; optlen > 0; cp -= 8, optlen -= 8) {
   1686 				tcp_seq lwe, rwe;
   1687 				bcopy((char *)cp, (char *) &lwe, sizeof(lwe));
   1688 				NTOHL(lwe);
   1689 				bcopy((char *)cp, (char *) &rwe, sizeof(rwe));
   1690 				NTOHL(rwe);
   1691 				/* tcp_mark_sacked(tp, lwe, rwe); */
   1692 			}
   1693 			break;
   1694 		}
   1695 	}
   1696 }
   1697 
   1698 /*
   1699  * Pull out of band byte out of a segment so
   1700  * it doesn't appear in the user's data queue.
   1701  * It is still reflected in the segment length for
   1702  * sequencing purposes.
   1703  */
   1704 void
   1705 tcp_pulloutofband(so, ti, m)
   1706 	struct socket *so;
   1707 	struct tcpiphdr *ti;
   1708 	register struct mbuf *m;
   1709 {
   1710 	int cnt = ti->ti_urp - 1;
   1711 
   1712 	while (cnt >= 0) {
   1713 		if (m->m_len > cnt) {
   1714 			char *cp = mtod(m, caddr_t) + cnt;
   1715 			struct tcpcb *tp = sototcpcb(so);
   1716 
   1717 			tp->t_iobc = *cp;
   1718 			tp->t_oobflags |= TCPOOB_HAVEDATA;
   1719 			bcopy(cp+1, cp, (unsigned)(m->m_len - cnt - 1));
   1720 			m->m_len--;
   1721 			return;
   1722 		}
   1723 		cnt -= m->m_len;
   1724 		m = m->m_next;
   1725 		if (m == 0)
   1726 			break;
   1727 	}
   1728 	panic("tcp_pulloutofband");
   1729 }
   1730 
   1731 /*
   1732  * Collect new round-trip time estimate
   1733  * and update averages and current timeout.
   1734  */
   1735 void
   1736 tcp_xmit_timer(tp, rtt)
   1737 	register struct tcpcb *tp;
   1738 	short rtt;
   1739 {
   1740 	register short delta;
   1741 	short rttmin;
   1742 
   1743 	tcpstat.tcps_rttupdated++;
   1744 	--rtt;
   1745 	if (tp->t_srtt != 0) {
   1746 		/*
   1747 		 * srtt is stored as fixed point with 3 bits after the
   1748 		 * binary point (i.e., scaled by 8).  The following magic
   1749 		 * is equivalent to the smoothing algorithm in rfc793 with
   1750 		 * an alpha of .875 (srtt = rtt/8 + srtt*7/8 in fixed
   1751 		 * point).  Adjust rtt to origin 0.
   1752 		 */
   1753 		delta = (rtt << 2) - (tp->t_srtt >> TCP_RTT_SHIFT);
   1754 		if ((tp->t_srtt += delta) <= 0)
   1755 			tp->t_srtt = 1 << 2;
   1756 		/*
   1757 		 * We accumulate a smoothed rtt variance (actually, a
   1758 		 * smoothed mean difference), then set the retransmit
   1759 		 * timer to smoothed rtt + 4 times the smoothed variance.
   1760 		 * rttvar is stored as fixed point with 2 bits after the
   1761 		 * binary point (scaled by 4).  The following is
   1762 		 * equivalent to rfc793 smoothing with an alpha of .75
   1763 		 * (rttvar = rttvar*3/4 + |delta| / 4).  This replaces
   1764 		 * rfc793's wired-in beta.
   1765 		 */
   1766 		if (delta < 0)
   1767 			delta = -delta;
   1768 		delta -= (tp->t_rttvar >> TCP_RTTVAR_SHIFT);
   1769 		if ((tp->t_rttvar += delta) <= 0)
   1770 			tp->t_rttvar = 1 << 2;
   1771 	} else {
   1772 		/*
   1773 		 * No rtt measurement yet - use the unsmoothed rtt.
   1774 		 * Set the variance to half the rtt (so our first
   1775 		 * retransmit happens at 3*rtt).
   1776 		 */
   1777 		tp->t_srtt = rtt << (TCP_RTT_SHIFT + 2);
   1778 		tp->t_rttvar = rtt << (TCP_RTTVAR_SHIFT + 2 - 1);
   1779 	}
   1780 	tp->t_rtt = 0;
   1781 	tp->t_rxtshift = 0;
   1782 
   1783 	/*
   1784 	 * the retransmit should happen at rtt + 4 * rttvar.
   1785 	 * Because of the way we do the smoothing, srtt and rttvar
   1786 	 * will each average +1/2 tick of bias.  When we compute
   1787 	 * the retransmit timer, we want 1/2 tick of rounding and
   1788 	 * 1 extra tick because of +-1/2 tick uncertainty in the
   1789 	 * firing of the timer.  The bias will give us exactly the
   1790 	 * 1.5 tick we need.  But, because the bias is
   1791 	 * statistical, we have to test that we don't drop below
   1792 	 * the minimum feasible timer (which is 2 ticks).
   1793 	 */
   1794 	if (tp->t_rttmin > rtt + 2)
   1795 		rttmin = tp->t_rttmin;
   1796 	else
   1797 		rttmin = rtt + 2;
   1798 	TCPT_RANGESET(tp->t_rxtcur, TCP_REXMTVAL(tp), rttmin, TCPTV_REXMTMAX);
   1799 
   1800 	/*
   1801 	 * We received an ack for a packet that wasn't retransmitted;
   1802 	 * it is probably safe to discard any error indications we've
   1803 	 * received recently.  This isn't quite right, but close enough
   1804 	 * for now (a route might have failed after we sent a segment,
   1805 	 * and the return path might not be symmetrical).
   1806 	 */
   1807 	tp->t_softerror = 0;
   1808 }
   1809 
   1810 /*
   1811  * Checks for partial ack.  If partial ack arrives, force the retransmission
   1812  * of the next unacknowledged segment, do not clear tp->t_dupacks, and return
   1813  * 1.  By setting snd_nxt to ti_ack, this forces retransmission timer to
   1814  * be started again.  If the ack advances at least to tp->snd_recover, return 0.
   1815  */
   1816 int
   1817 tcp_newreno(tp, ti)
   1818 	struct tcpcb *tp;
   1819 	struct tcpiphdr *ti;
   1820 {
   1821 	if (SEQ_LT(ti->ti_ack, tp->snd_recover)) {
   1822 	        tcp_seq onxt = tp->snd_nxt;
   1823 	        tcp_seq ouna = tp->snd_una;  /* Haven't updated snd_una yet*/
   1824 	        u_long  ocwnd = tp->snd_cwnd;
   1825 		TCP_TIMER_DISARM(tp, TCPT_REXMT);
   1826 	        tp->t_rtt = 0;
   1827 	        tp->snd_nxt = ti->ti_ack;
   1828 	        tp->snd_cwnd = tp->t_segsz;
   1829 	        tp->snd_una = ti->ti_ack;
   1830 	        (void) tcp_output(tp);
   1831 	        tp->snd_cwnd = ocwnd;
   1832 	        tp->snd_una = ouna;
   1833 	        if (SEQ_GT(onxt, tp->snd_nxt))
   1834 	                tp->snd_nxt = onxt;
   1835 	        /*
   1836 	         * Partial window deflation.  Relies on fact that tp->snd_una
   1837 	         * not updated yet.
   1838 	         */
   1839 	        tp->snd_cwnd -= (ti->ti_ack - tp->snd_una - tp->t_segsz);
   1840 	        return 1;
   1841 	}
   1842 	return 0;
   1843 }
   1844 
   1845 
   1846 /*
   1847  * TCP compressed state engine.  Currently used to hold compressed
   1848  * state for SYN_RECEIVED.
   1849  */
   1850 
   1851 u_long	syn_cache_count;
   1852 u_int32_t syn_hash1, syn_hash2;
   1853 
   1854 #define SYN_HASH(sa, sp, dp) \
   1855 	((((sa)->s_addr^syn_hash1)*(((((u_int32_t)(dp))<<16) + \
   1856 				     ((u_int32_t)(sp)))^syn_hash2)))
   1857 
   1858 #define	SYN_CACHE_RM(sc)						\
   1859 do {									\
   1860 	LIST_REMOVE((sc), sc_bucketq);					\
   1861 	tcp_syn_cache[(sc)->sc_bucketidx].sch_length--;			\
   1862 	TAILQ_REMOVE(&tcp_syn_cache_timeq[(sc)->sc_rxtshift], (sc), sc_timeq); \
   1863 	syn_cache_count--;						\
   1864 } while (0)
   1865 
   1866 #define	SYN_CACHE_PUT(sc)						\
   1867 do {									\
   1868 	if ((sc)->sc_ipopts)						\
   1869 		(void) m_free((sc)->sc_ipopts);				\
   1870 	if ((sc)->sc_route.ro_rt != NULL)				\
   1871 		RTFREE((sc)->sc_route.ro_rt);				\
   1872 	pool_put(&syn_cache_pool, (sc));				\
   1873 } while (0)
   1874 
   1875 struct pool syn_cache_pool;
   1876 
   1877 /*
   1878  * We don't estimate RTT with SYNs, so each packet starts with the default
   1879  * RTT and each timer queue has a fixed timeout value.  This allows us to
   1880  * optimize the timer queues somewhat.
   1881  */
   1882 #define	SYN_CACHE_TIMER_ARM(sc)						\
   1883 do {									\
   1884 	TCPT_RANGESET((sc)->sc_rxtcur,					\
   1885 	    TCPTV_SRTTDFLT * tcp_backoff[(sc)->sc_rxtshift], TCPTV_MIN,	\
   1886 	    TCPTV_REXMTMAX);						\
   1887 	PRT_SLOW_ARM((sc)->sc_rexmt, (sc)->sc_rxtcur);			\
   1888 } while (0)
   1889 
   1890 TAILQ_HEAD(, syn_cache) tcp_syn_cache_timeq[TCP_MAXRXTSHIFT + 1];
   1891 
   1892 void
   1893 syn_cache_init()
   1894 {
   1895 	int i;
   1896 
   1897 	/* Initialize the hash buckets. */
   1898 	for (i = 0; i < tcp_syn_cache_size; i++)
   1899 		LIST_INIT(&tcp_syn_cache[i].sch_bucket);
   1900 
   1901 	/* Initialize the timer queues. */
   1902 	for (i = 0; i <= TCP_MAXRXTSHIFT; i++)
   1903 		TAILQ_INIT(&tcp_syn_cache_timeq[i]);
   1904 
   1905 	/* Initialize the syn cache pool. */
   1906 	pool_init(&syn_cache_pool, sizeof(struct syn_cache), 0, 0, 0,
   1907 	    "synpl", 0, NULL, NULL, M_PCB);
   1908 }
   1909 
   1910 void
   1911 syn_cache_insert(sc)
   1912 	struct syn_cache *sc;
   1913 {
   1914 	struct syn_cache_head *scp;
   1915 	struct syn_cache *sc2;
   1916 	int s, i;
   1917 
   1918 	/*
   1919 	 * If there are no entries in the hash table, reinitialize
   1920 	 * the hash secrets.
   1921 	 */
   1922 	if (syn_cache_count == 0) {
   1923 		struct timeval tv;
   1924 		microtime(&tv);
   1925 		syn_hash1 = random() ^ (u_long)&sc;
   1926 		syn_hash2 = random() ^ tv.tv_usec;
   1927 	}
   1928 
   1929 	sc->sc_hash = SYN_HASH(&sc->sc_src, sc->sc_sport, sc->sc_dport);
   1930 	sc->sc_bucketidx = sc->sc_hash % tcp_syn_cache_size;
   1931 	scp = &tcp_syn_cache[sc->sc_bucketidx];
   1932 
   1933 	/*
   1934 	 * Make sure that we don't overflow the per-bucket
   1935 	 * limit or the total cache size limit.
   1936 	 */
   1937 	s = splsoftnet();
   1938 	if (scp->sch_length >= tcp_syn_bucket_limit) {
   1939 		tcpstat.tcps_sc_bucketoverflow++;
   1940 		/*
   1941 		 * The bucket is full.  Toss the oldest element in the
   1942 		 * bucket.  This will be the entry with our bucket
   1943 		 * index closest to the front of the timer queue with
   1944 		 * the largest timeout value.
   1945 		 *
   1946 		 * Note: This timer queue traversal may be expensive, so
   1947 		 * we hope that this doesn't happen very often.  It is
   1948 		 * much more likely that we'll overflow the entire
   1949 		 * cache, which is much easier to handle; see below.
   1950 		 */
   1951 		for (i = TCP_MAXRXTSHIFT; i >= 0; i--) {
   1952 			for (sc2 = TAILQ_FIRST(&tcp_syn_cache_timeq[i]);
   1953 			     sc2 != NULL;
   1954 			     sc2 = TAILQ_NEXT(sc2, sc_timeq)) {
   1955 				if (sc2->sc_bucketidx == sc->sc_bucketidx) {
   1956 					SYN_CACHE_RM(sc2);
   1957 					SYN_CACHE_PUT(sc2);
   1958 					goto insert;	/* 2 level break */
   1959 				}
   1960 			}
   1961 		}
   1962 #ifdef DIAGNOSTIC
   1963 		/*
   1964 		 * This should never happen; we should always find an
   1965 		 * entry in our bucket.
   1966 		 */
   1967 		panic("syn_cache_insert: bucketoverflow: impossible");
   1968 #endif
   1969 	} else if (syn_cache_count >= tcp_syn_cache_limit) {
   1970 		tcpstat.tcps_sc_overflowed++;
   1971 		/*
   1972 		 * The cache is full.  Toss the oldest entry in the
   1973 		 * entire cache.  This is the front entry in the
   1974 		 * first non-empty timer queue with the largest
   1975 		 * timeout value.
   1976 		 */
   1977 		for (i = TCP_MAXRXTSHIFT; i >= 0; i--) {
   1978 			sc2 = TAILQ_FIRST(&tcp_syn_cache_timeq[i]);
   1979 			if (sc2 == NULL)
   1980 				continue;
   1981 			SYN_CACHE_RM(sc2);
   1982 			SYN_CACHE_PUT(sc2);
   1983 			goto insert;		/* symmetry with above */
   1984 		}
   1985 #ifdef DIAGNOSTIC
   1986 		/*
   1987 		 * This should never happen; we should always find an
   1988 		 * entry in the cache.
   1989 		 */
   1990 		panic("syn_cache_insert: cache overflow: impossible");
   1991 #endif
   1992 	}
   1993 
   1994  insert:
   1995 	/*
   1996 	 * Initialize the entry's timer.
   1997 	 */
   1998 	sc->sc_rxttot = 0;
   1999 	sc->sc_rxtshift = 0;
   2000 	SYN_CACHE_TIMER_ARM(sc);
   2001 	TAILQ_INSERT_TAIL(&tcp_syn_cache_timeq[sc->sc_rxtshift], sc, sc_timeq);
   2002 
   2003 	/* Put it into the bucket. */
   2004 	LIST_INSERT_HEAD(&scp->sch_bucket, sc, sc_bucketq);
   2005 	scp->sch_length++;
   2006 	syn_cache_count++;
   2007 
   2008 	tcpstat.tcps_sc_added++;
   2009 	splx(s);
   2010 }
   2011 
   2012 /*
   2013  * Walk the timer queues, looking for SYN,ACKs that need to be retransmitted.
   2014  * If we have retransmitted an entry the maximum number of times, expire
   2015  * that entry.
   2016  */
   2017 void
   2018 syn_cache_timer()
   2019 {
   2020 	struct syn_cache *sc, *nsc;
   2021 	int i, s;
   2022 
   2023 	s = splsoftnet();
   2024 
   2025 	/*
   2026 	 * First, get all the entries that need to be retransmitted, or
   2027 	 * must be expired due to exceeding the initial keepalive time.
   2028 	 */
   2029 	for (i = 0; i < TCP_MAXRXTSHIFT; i++) {
   2030 		for (sc = TAILQ_FIRST(&tcp_syn_cache_timeq[i]);
   2031 		     sc != NULL && PRT_SLOW_ISEXPIRED(sc->sc_rexmt);
   2032 		     sc = nsc) {
   2033 			nsc = TAILQ_NEXT(sc, sc_timeq);
   2034 
   2035 			/*
   2036 			 * Compute the total amount of time this entry has
   2037 			 * been on a queue.  If this entry has been on longer
   2038 			 * than the keep alive timer would allow, expire it.
   2039 			 */
   2040 			sc->sc_rxttot += sc->sc_rxtcur;
   2041 			if (sc->sc_rxttot >= TCPTV_KEEP_INIT) {
   2042 				tcpstat.tcps_sc_timed_out++;
   2043 				SYN_CACHE_RM(sc);
   2044 				SYN_CACHE_PUT(sc);
   2045 				continue;
   2046 			}
   2047 
   2048 			tcpstat.tcps_sc_retransmitted++;
   2049 			(void) syn_cache_respond(sc, NULL);
   2050 
   2051 			/* Advance this entry onto the next timer queue. */
   2052 			TAILQ_REMOVE(&tcp_syn_cache_timeq[i], sc, sc_timeq);
   2053 			sc->sc_rxtshift = i + 1;
   2054 			SYN_CACHE_TIMER_ARM(sc);
   2055 			TAILQ_INSERT_TAIL(&tcp_syn_cache_timeq[sc->sc_rxtshift],
   2056 			    sc, sc_timeq);
   2057 		}
   2058 	}
   2059 
   2060 	/*
   2061 	 * Now get all the entries that are expired due to too many
   2062 	 * retransmissions.
   2063 	 */
   2064 	for (sc = TAILQ_FIRST(&tcp_syn_cache_timeq[TCP_MAXRXTSHIFT]);
   2065 	     sc != NULL && PRT_SLOW_ISEXPIRED(sc->sc_rexmt);
   2066 	     sc = nsc) {
   2067 		nsc = TAILQ_NEXT(sc, sc_timeq);
   2068 		tcpstat.tcps_sc_timed_out++;
   2069 		SYN_CACHE_RM(sc);
   2070 		SYN_CACHE_PUT(sc);
   2071 	}
   2072 	splx(s);
   2073 }
   2074 
   2075 /*
   2076  * Find an entry in the syn cache.
   2077  */
   2078 struct syn_cache *
   2079 syn_cache_lookup(ti, headp)
   2080 	struct tcpiphdr *ti;
   2081 	struct syn_cache_head **headp;
   2082 {
   2083 	struct syn_cache *sc;
   2084 	struct syn_cache_head *scp;
   2085 	u_int32_t hash;
   2086 	int s;
   2087 
   2088 	hash = SYN_HASH(&ti->ti_src, ti->ti_sport, ti->ti_dport);
   2089 
   2090 	scp = &tcp_syn_cache[hash % tcp_syn_cache_size];
   2091 	*headp = scp;
   2092 	s = splsoftnet();
   2093 	for (sc = LIST_FIRST(&scp->sch_bucket); sc != NULL;
   2094 	     sc = LIST_NEXT(sc, sc_bucketq)) {
   2095 		if (sc->sc_hash != hash)
   2096 			continue;
   2097 		if (sc->sc_src.s_addr == ti->ti_src.s_addr &&
   2098 		    sc->sc_sport == ti->ti_sport &&
   2099 		    sc->sc_dport == ti->ti_dport &&
   2100 		    sc->sc_dst.s_addr == ti->ti_dst.s_addr) {
   2101 			splx(s);
   2102 			return (sc);
   2103 		}
   2104 	}
   2105 	splx(s);
   2106 	return (NULL);
   2107 }
   2108 
   2109 /*
   2110  * This function gets called when we receive an ACK for a
   2111  * socket in the LISTEN state.  We look up the connection
   2112  * in the syn cache, and if its there, we pull it out of
   2113  * the cache and turn it into a full-blown connection in
   2114  * the SYN-RECEIVED state.
   2115  *
   2116  * The return values may not be immediately obvious, and their effects
   2117  * can be subtle, so here they are:
   2118  *
   2119  *	NULL	SYN was not found in cache; caller should drop the
   2120  *		packet and send an RST.
   2121  *
   2122  *	-1	We were unable to create the new connection, and are
   2123  *		aborting it.  An ACK,RST is being sent to the peer
   2124  *		(unless we got screwey sequence numbners; see below),
   2125  *		because the 3-way handshake has been completed.  Caller
   2126  *		should not free the mbuf, since we may be using it.  If
   2127  *		we are not, we will free it.
   2128  *
   2129  *	Otherwise, the return value is a pointer to the new socket
   2130  *	associated with the connection.
   2131  */
   2132 struct socket *
   2133 syn_cache_get(so, m)
   2134 	struct socket *so;
   2135 	struct mbuf *m;
   2136 {
   2137 	struct syn_cache *sc;
   2138 	struct syn_cache_head *scp;
   2139 	register struct inpcb *inp;
   2140 	register struct tcpcb *tp = 0;
   2141 	register struct tcpiphdr *ti;
   2142 	struct sockaddr_in *sin;
   2143 	struct mbuf *am;
   2144 	int s;
   2145 
   2146 	ti = mtod(m, struct tcpiphdr *);
   2147 	s = splsoftnet();
   2148 	if ((sc = syn_cache_lookup(ti, &scp)) == NULL) {
   2149 		splx(s);
   2150 		return (NULL);
   2151 	}
   2152 
   2153 	/*
   2154 	 * Verify the sequence and ack numbers.  Try getting the correct
   2155 	 * response again.
   2156 	 */
   2157 	if ((ti->ti_ack != sc->sc_iss + 1) ||
   2158 	    SEQ_LEQ(ti->ti_seq, sc->sc_irs) ||
   2159 	    SEQ_GT(ti->ti_seq, sc->sc_irs + 1 + sc->sc_win)) {
   2160 		(void) syn_cache_respond(sc, m);
   2161 		splx(s);
   2162 		return ((struct socket *)(-1));
   2163 	}
   2164 
   2165 	/* Remove this cache entry */
   2166 	SYN_CACHE_RM(sc);
   2167 	splx(s);
   2168 
   2169 	/*
   2170 	 * Ok, create the full blown connection, and set things up
   2171 	 * as they would have been set up if we had created the
   2172 	 * connection when the SYN arrived.  If we can't create
   2173 	 * the connection, abort it.
   2174 	 */
   2175 	so = sonewconn(so, SS_ISCONNECTED);
   2176 	if (so == NULL)
   2177 		goto resetandabort;
   2178 
   2179 	inp = sotoinpcb(so);
   2180 	inp->inp_laddr = sc->sc_dst;
   2181 	inp->inp_lport = sc->sc_dport;
   2182 	in_pcbstate(inp, INP_BOUND);
   2183 	inp->inp_options = ip_srcroute();
   2184 	if (inp->inp_options == NULL) {
   2185 		inp->inp_options = sc->sc_ipopts;
   2186 		sc->sc_ipopts = NULL;
   2187 	}
   2188 
   2189 	/*
   2190 	 * Give the new socket our cached route reference.
   2191 	 */
   2192 	inp->inp_route = sc->sc_route;		/* struct assignment */
   2193 	sc->sc_route.ro_rt = NULL;
   2194 
   2195 	am = m_get(M_DONTWAIT, MT_SONAME);	/* XXX */
   2196 	if (am == NULL)
   2197 		goto resetandabort;
   2198 	am->m_len = sizeof(struct sockaddr_in);
   2199 	sin = mtod(am, struct sockaddr_in *);
   2200 	sin->sin_family = AF_INET;
   2201 	sin->sin_len = sizeof(*sin);
   2202 	sin->sin_addr = sc->sc_src;
   2203 	sin->sin_port = sc->sc_sport;
   2204 	bzero((caddr_t)sin->sin_zero, sizeof(sin->sin_zero));
   2205 	if (in_pcbconnect(inp, am)) {
   2206 		(void) m_free(am);
   2207 		goto resetandabort;
   2208 	}
   2209 	(void) m_free(am);
   2210 
   2211 	tp = intotcpcb(inp);
   2212 	if (sc->sc_request_r_scale != 15) {
   2213 		tp->requested_s_scale = sc->sc_requested_s_scale;
   2214 		tp->request_r_scale = sc->sc_request_r_scale;
   2215 		tp->snd_scale = sc->sc_requested_s_scale;
   2216 		tp->rcv_scale = sc->sc_request_r_scale;
   2217 		tp->t_flags |= TF_RCVD_SCALE;
   2218 	}
   2219 	if (sc->sc_flags & SCF_TIMESTAMP)
   2220 		tp->t_flags |= TF_RCVD_TSTMP;
   2221 
   2222 	tp->t_template = tcp_template(tp);
   2223 	if (tp->t_template == 0) {
   2224 		tp = tcp_drop(tp, ENOBUFS);	/* destroys socket */
   2225 		so = NULL;
   2226 		m_freem(m);
   2227 		goto abort;
   2228 	}
   2229 
   2230 	tp->iss = sc->sc_iss;
   2231 	tp->irs = sc->sc_irs;
   2232 	tcp_sendseqinit(tp);
   2233 	tcp_rcvseqinit(tp);
   2234 	tp->t_state = TCPS_SYN_RECEIVED;
   2235 	TCP_TIMER_ARM(tp, TCPT_KEEP, TCPTV_KEEP_INIT);
   2236 	tcpstat.tcps_accepts++;
   2237 
   2238 	/* Initialize tp->t_ourmss before we deal with the peer's! */
   2239 	tp->t_ourmss = sc->sc_ourmaxseg;
   2240 	tcp_mss_from_peer(tp, sc->sc_peermaxseg);
   2241 
   2242 	/*
   2243 	 * Initialize the initial congestion window.  If we
   2244 	 * had to retransmit the SYN,ACK, we must initialize cwnd
   2245 	 * to 1 segment (i.e. the Loss Window).
   2246 	 */
   2247 	if (sc->sc_rxtshift)
   2248 		tp->snd_cwnd = tp->t_peermss;
   2249 	else
   2250 		tp->snd_cwnd = TCP_INITIAL_WINDOW(tcp_init_win, tp->t_peermss);
   2251 
   2252 	tcp_rmx_rtt(tp);
   2253 	tp->snd_wl1 = sc->sc_irs;
   2254 	tp->rcv_up = sc->sc_irs + 1;
   2255 
   2256 	/*
   2257 	 * This is what whould have happened in tcp_ouput() when
   2258 	 * the SYN,ACK was sent.
   2259 	 */
   2260 	tp->snd_up = tp->snd_una;
   2261 	tp->snd_max = tp->snd_nxt = tp->iss+1;
   2262 	TCP_TIMER_ARM(tp, TCPT_REXMT, tp->t_rxtcur);
   2263 	if (sc->sc_win > 0 && SEQ_GT(tp->rcv_nxt + sc->sc_win, tp->rcv_adv))
   2264 		tp->rcv_adv = tp->rcv_nxt + sc->sc_win;
   2265 	tp->last_ack_sent = tp->rcv_nxt;
   2266 
   2267 	tcpstat.tcps_sc_completed++;
   2268 	SYN_CACHE_PUT(sc);
   2269 	return (so);
   2270 
   2271 resetandabort:
   2272 	(void) tcp_respond(NULL, ti, m, ti->ti_seq+ti->ti_len,
   2273 	    (tcp_seq)0, TH_RST|TH_ACK);
   2274 abort:
   2275 	if (so != NULL)
   2276 		(void) soabort(so);
   2277 	SYN_CACHE_PUT(sc);
   2278 	tcpstat.tcps_sc_aborted++;
   2279 	return ((struct socket *)(-1));
   2280 }
   2281 
   2282 /*
   2283  * This function is called when we get a RST for a
   2284  * non-existant connection, so that we can see if the
   2285  * connection is in the syn cache.  If it is, zap it.
   2286  */
   2287 
   2288 void
   2289 syn_cache_reset(ti)
   2290 	register struct tcpiphdr *ti;
   2291 {
   2292 	struct syn_cache *sc;
   2293 	struct syn_cache_head *scp;
   2294 	int s = splsoftnet();
   2295 
   2296 	if ((sc = syn_cache_lookup(ti, &scp)) == NULL) {
   2297 		splx(s);
   2298 		return;
   2299 	}
   2300 	if (SEQ_LT(ti->ti_seq,sc->sc_irs) ||
   2301 	    SEQ_GT(ti->ti_seq, sc->sc_irs+1)) {
   2302 		splx(s);
   2303 		return;
   2304 	}
   2305 	SYN_CACHE_RM(sc);
   2306 	splx(s);
   2307 	tcpstat.tcps_sc_reset++;
   2308 	SYN_CACHE_PUT(sc);
   2309 }
   2310 
   2311 void
   2312 syn_cache_unreach(ip, th)
   2313 	struct ip *ip;
   2314 	struct tcphdr *th;
   2315 {
   2316 	struct syn_cache *sc;
   2317 	struct syn_cache_head *scp;
   2318 	struct tcpiphdr ti2;
   2319 	int s;
   2320 
   2321 	ti2.ti_src.s_addr = ip->ip_dst.s_addr;
   2322 	ti2.ti_dst.s_addr = ip->ip_src.s_addr;
   2323 	ti2.ti_sport = th->th_dport;
   2324 	ti2.ti_dport = th->th_sport;
   2325 
   2326 	s = splsoftnet();
   2327 	if ((sc = syn_cache_lookup(&ti2, &scp)) == NULL) {
   2328 		splx(s);
   2329 		return;
   2330 	}
   2331 	/* If the sequence number != sc_iss, then it's a bogus ICMP msg */
   2332 	if (ntohl (th->th_seq) != sc->sc_iss) {
   2333 		splx(s);
   2334 		return;
   2335 	}
   2336 
   2337 	/*
   2338 	 * If we've rertransmitted 3 times and this is our second error,
   2339 	 * we remove the entry.  Otherwise, we allow it to continue on.
   2340 	 * This prevents us from incorrectly nuking an entry during a
   2341 	 * spurious network outage.
   2342 	 *
   2343 	 * See tcp_notify().
   2344 	 */
   2345 	if ((sc->sc_flags & SCF_UNREACH) == 0 || sc->sc_rxtshift < 3) {
   2346 		sc->sc_flags |= SCF_UNREACH;
   2347 		splx(s);
   2348 		return;
   2349 	}
   2350 
   2351 	SYN_CACHE_RM(sc);
   2352 	splx(s);
   2353 	tcpstat.tcps_sc_unreach++;
   2354 	SYN_CACHE_PUT(sc);
   2355 }
   2356 
   2357 /*
   2358  * Given a LISTEN socket and an inbound SYN request, add
   2359  * this to the syn cache, and send back a segment:
   2360  *	<SEQ=ISS><ACK=RCV_NXT><CTL=SYN,ACK>
   2361  * to the source.
   2362  *
   2363  * IMPORTANT NOTE: We do _NOT_ ACK data that might accompany the SYN.
   2364  * Doing so would require that we hold onto the data and deliver it
   2365  * to the application.  However, if we are the target of a SYN-flood
   2366  * DoS attack, an attacker could send data which would eventually
   2367  * consume all available buffer space if it were ACKed.  By not ACKing
   2368  * the data, we avoid this DoS scenario.
   2369  */
   2370 
   2371 int
   2372 syn_cache_add(so, m, optp, optlen, oi)
   2373 	struct socket *so;
   2374 	struct mbuf *m;
   2375 	u_char *optp;
   2376 	int optlen;
   2377 	struct tcp_opt_info *oi;
   2378 {
   2379 	register struct tcpiphdr *ti;
   2380 	struct tcpcb tb, *tp;
   2381 	long win;
   2382 	struct syn_cache *sc;
   2383 	struct syn_cache_head *scp;
   2384 	struct mbuf *ipopts;
   2385 
   2386 	tp = sototcpcb(so);
   2387 	ti = mtod(m, struct tcpiphdr *);
   2388 
   2389 	/*
   2390 	 * RFC1122 4.2.3.10, p. 104: discard bcast/mcast SYN
   2391 	 * in_broadcast() should never return true on a received
   2392 	 * packet with M_BCAST not set.
   2393 	 */
   2394 	if (m->m_flags & (M_BCAST|M_MCAST) ||
   2395 	    IN_MULTICAST(ti->ti_src.s_addr) ||
   2396 	    IN_MULTICAST(ti->ti_dst.s_addr))
   2397 		return (0);
   2398 
   2399 	/*
   2400 	 * Initialize some local state.
   2401 	 */
   2402 	win = sbspace(&so->so_rcv);
   2403 	if (win > TCP_MAXWIN)
   2404 		win = TCP_MAXWIN;
   2405 
   2406 	/*
   2407 	 * Remember the IP options, if any.
   2408 	 */
   2409 	ipopts = ip_srcroute();
   2410 
   2411 	if (optp) {
   2412 		tb.t_flags = tcp_do_rfc1323 ? (TF_REQ_SCALE|TF_REQ_TSTMP) : 0;
   2413 		tcp_dooptions(&tb, optp, optlen, ti, oi);
   2414 	} else
   2415 		tb.t_flags = 0;
   2416 
   2417 	/*
   2418 	 * See if we already have an entry for this connection.
   2419 	 * If we do, resend the SYN,ACK.  We do not count this
   2420 	 * as a retransmission (XXX though maybe we should).
   2421 	 */
   2422 	if ((sc = syn_cache_lookup(ti, &scp)) != NULL) {
   2423 		tcpstat.tcps_sc_dupesyn++;
   2424 		if (ipopts) {
   2425 			/*
   2426 			 * If we were remembering a previous source route,
   2427 			 * forget it and use the new one we've been given.
   2428 			 */
   2429 			if (sc->sc_ipopts)
   2430 				(void) m_free(sc->sc_ipopts);
   2431 			sc->sc_ipopts = ipopts;
   2432 		}
   2433 		sc->sc_timestamp = tb.ts_recent;
   2434 		if (syn_cache_respond(sc, m) == 0) {
   2435 			tcpstat.tcps_sndacks++;
   2436 			tcpstat.tcps_sndtotal++;
   2437 		}
   2438 		return (1);
   2439 	}
   2440 
   2441 	sc = pool_get(&syn_cache_pool, PR_NOWAIT);
   2442 	if (sc == NULL) {
   2443 		if (ipopts)
   2444 			(void) m_free(ipopts);
   2445 		return (0);
   2446 	}
   2447 
   2448 	/*
   2449 	 * Fill in the cache, and put the necessary IP and TCP
   2450 	 * options into the reply.
   2451 	 */
   2452 	memset(&sc->sc_route, 0, sizeof(sc->sc_route));
   2453 	sc->sc_src.s_addr = ti->ti_src.s_addr;
   2454 	sc->sc_dst.s_addr = ti->ti_dst.s_addr;
   2455 	sc->sc_sport = ti->ti_sport;
   2456 	sc->sc_dport = ti->ti_dport;
   2457 	sc->sc_flags = 0;
   2458 	sc->sc_ipopts = ipopts;
   2459 	sc->sc_irs = ti->ti_seq;
   2460 	sc->sc_iss = tcp_new_iss(sc, sizeof(struct syn_cache), 0);
   2461 	sc->sc_peermaxseg = oi->maxseg;
   2462 	sc->sc_ourmaxseg = tcp_mss_to_advertise(m->m_flags & M_PKTHDR ?
   2463 						m->m_pkthdr.rcvif : NULL);
   2464 	sc->sc_win = win;
   2465 	sc->sc_timestamp = tb.ts_recent;
   2466 	if (tcp_do_rfc1323 && (tb.t_flags & TF_RCVD_TSTMP))
   2467 		sc->sc_flags |= SCF_TIMESTAMP;
   2468 	if ((tb.t_flags & (TF_RCVD_SCALE|TF_REQ_SCALE)) ==
   2469 	    (TF_RCVD_SCALE|TF_REQ_SCALE)) {
   2470 		sc->sc_requested_s_scale = tb.requested_s_scale;
   2471 		sc->sc_request_r_scale = 0;
   2472 		while (sc->sc_request_r_scale < TCP_MAX_WINSHIFT &&
   2473 		    TCP_MAXWIN << sc->sc_request_r_scale <
   2474 		    so->so_rcv.sb_hiwat)
   2475 			sc->sc_request_r_scale++;
   2476 	} else {
   2477 		sc->sc_requested_s_scale = 15;
   2478 		sc->sc_request_r_scale = 15;
   2479 	}
   2480 	if (syn_cache_respond(sc, m) == 0) {
   2481 		syn_cache_insert(sc);
   2482 		tcpstat.tcps_sndacks++;
   2483 		tcpstat.tcps_sndtotal++;
   2484 	} else {
   2485 		SYN_CACHE_PUT(sc);
   2486 		tcpstat.tcps_sc_dropped++;
   2487 	}
   2488 	return (1);
   2489 }
   2490 
   2491 int
   2492 syn_cache_respond(sc, m)
   2493 	struct syn_cache *sc;
   2494 	struct mbuf *m;
   2495 {
   2496 	struct route *ro = &sc->sc_route;
   2497 	struct rtentry *rt;
   2498 	struct sockaddr_in *dst;
   2499 	struct tcpiphdr *ti;
   2500 	u_int8_t *optp;
   2501 	int optlen, error;
   2502 	u_int16_t tlen;
   2503 
   2504 	/* Compute the size of the TCP options. */
   2505 	optlen = 4 + (sc->sc_request_r_scale != 15 ? 4 : 0) +
   2506 	    ((sc->sc_flags & SCF_TIMESTAMP) ? TCPOLEN_TSTAMP_APPA : 0);
   2507 
   2508 	tlen = sizeof(struct tcpiphdr) + optlen;
   2509 
   2510 	/*
   2511 	 * Create the IP+TCP header from scratch.  Reuse the received mbuf
   2512 	 * if possible.
   2513 	 */
   2514 	if (m != NULL) {
   2515 		m_freem(m->m_next);
   2516 		m->m_next = NULL;
   2517 		MRESETDATA(m);
   2518 	} else {
   2519 		MGETHDR(m, M_DONTWAIT, MT_DATA);
   2520 		if (m == NULL)
   2521 			return (ENOBUFS);
   2522 	}
   2523 
   2524 	/* Fixup the mbuf. */
   2525 	m->m_data += max_linkhdr;
   2526 	m->m_len = m->m_pkthdr.len = tlen;
   2527 	m->m_pkthdr.rcvif = NULL;
   2528 
   2529 	ti = mtod(m, struct tcpiphdr *);
   2530 	memset(ti, 0, tlen);
   2531 
   2532 	ti->ti_dst = sc->sc_src;
   2533 	ti->ti_src = sc->sc_dst;
   2534 	ti->ti_sport = sc->sc_dport;
   2535 	ti->ti_dport = sc->sc_sport;
   2536 	ti->ti_pr = IPPROTO_TCP;
   2537 	ti->ti_len = htons(tlen - sizeof(struct ip));
   2538 	/* ti_x1 already 0'd */
   2539 	ti->ti_seq = htonl(sc->sc_iss);
   2540 	ti->ti_ack = htonl(sc->sc_irs + 1);
   2541 	/* ti_x2 already 0 */
   2542 	ti->ti_off = (sizeof(struct tcphdr) + optlen) >> 2;
   2543 	ti->ti_flags = TH_SYN|TH_ACK;
   2544 	ti->ti_win = htons(sc->sc_win);
   2545 	/* ti_sum already 0 */
   2546 	/* ti_urp already 0 */
   2547 
   2548 	/* Tack on the TCP options. */
   2549 	optp = (u_int8_t *)(ti + 1);
   2550 	*optp++ = TCPOPT_MAXSEG;
   2551 	*optp++ = 4;
   2552 	*optp++ = (sc->sc_ourmaxseg >> 8) & 0xff;
   2553 	*optp++ = sc->sc_ourmaxseg & 0xff;
   2554 
   2555 	if (sc->sc_request_r_scale != 15) {
   2556 		*((u_int32_t *)optp) = htonl(TCPOPT_NOP << 24 |
   2557 		    TCPOPT_WINDOW << 16 | TCPOLEN_WINDOW << 8 |
   2558 		    sc->sc_request_r_scale);
   2559 		optp += 4;
   2560 	}
   2561 
   2562 	if (sc->sc_flags & SCF_TIMESTAMP) {
   2563 		u_int32_t *lp = (u_int32_t *)(optp);
   2564 		/* Form timestamp option as shown in appendix A of RFC 1323. */
   2565 		*lp++ = htonl(TCPOPT_TSTAMP_HDR);
   2566 		*lp++ = htonl(tcp_now);
   2567 		*lp   = htonl(sc->sc_timestamp);
   2568 		optp += TCPOLEN_TSTAMP_APPA;
   2569 	}
   2570 
   2571 	/* Compute the packet's checksum. */
   2572 	ti->ti_sum = in_cksum(m, tlen);
   2573 
   2574 	/*
   2575 	 * Fill in some straggling IP bits.  Note the stack expects
   2576 	 * ip_len to be in host order, for convenience.
   2577 	 */
   2578 	((struct ip *)ti)->ip_len = tlen;
   2579 	((struct ip *)ti)->ip_ttl = ip_defttl;
   2580 	/* XXX tos? */
   2581 
   2582 	/*
   2583 	 * If we're doing Path MTU discovery, we need to set DF unless
   2584 	 * the route's MTU is locked.  If we don't yet know the route,
   2585 	 * look it up now.  We will copy this reference to the inpcb
   2586 	 * when we finish creating the connection.
   2587 	 */
   2588 	if ((rt = ro->ro_rt) == NULL || (rt->rt_flags & RTF_UP) == 0) {
   2589 		if (ro->ro_rt != NULL) {
   2590 			RTFREE(ro->ro_rt);
   2591 			ro->ro_rt = NULL;
   2592 		}
   2593 		dst = satosin(&ro->ro_dst);
   2594 		dst->sin_family = AF_INET;
   2595 		dst->sin_len = sizeof(*dst);
   2596 		dst->sin_addr = ti->ti_dst;
   2597 		rtalloc(ro);
   2598 		if ((rt = ro->ro_rt) == NULL) {
   2599 			m_freem(m);
   2600 			ipstat.ips_noroute++;
   2601 			return (EHOSTUNREACH);
   2602 		}
   2603 	}
   2604 	if (ip_mtudisc != 0 && (rt->rt_rmx.rmx_locks & RTV_MTU) == 0)
   2605 		((struct ip *)ti)->ip_off |= IP_DF;
   2606 
   2607 	/* ...and send it off! */
   2608 	error = ip_output(m, sc->sc_ipopts, ro, 0, NULL);
   2609 
   2610 	return (error);
   2611 }
   2612