Home | History | Annotate | Line # | Download | only in netinet
tcp_subr.c revision 1.171
      1 /*	$NetBSD: tcp_subr.c,v 1.171 2004/05/01 02:20:43 matt Exp $	*/
      2 
      3 /*
      4  * Copyright (C) 1995, 1996, 1997, and 1998 WIDE Project.
      5  * All rights reserved.
      6  *
      7  * Redistribution and use in source and binary forms, with or without
      8  * modification, are permitted provided that the following conditions
      9  * are met:
     10  * 1. Redistributions of source code must retain the above copyright
     11  *    notice, this list of conditions and the following disclaimer.
     12  * 2. Redistributions in binary form must reproduce the above copyright
     13  *    notice, this list of conditions and the following disclaimer in the
     14  *    documentation and/or other materials provided with the distribution.
     15  * 3. Neither the name of the project nor the names of its contributors
     16  *    may be used to endorse or promote products derived from this software
     17  *    without specific prior written permission.
     18  *
     19  * THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND
     20  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     21  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     22  * ARE DISCLAIMED.  IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE
     23  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     24  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     25  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     26  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     27  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     28  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     29  * SUCH DAMAGE.
     30  */
     31 
     32 /*-
     33  * Copyright (c) 1997, 1998, 2000, 2001 The NetBSD Foundation, Inc.
     34  * All rights reserved.
     35  *
     36  * This code is derived from software contributed to The NetBSD Foundation
     37  * by Jason R. Thorpe and Kevin M. Lahey of the Numerical Aerospace Simulation
     38  * Facility, NASA Ames Research Center.
     39  *
     40  * Redistribution and use in source and binary forms, with or without
     41  * modification, are permitted provided that the following conditions
     42  * are met:
     43  * 1. Redistributions of source code must retain the above copyright
     44  *    notice, this list of conditions and the following disclaimer.
     45  * 2. Redistributions in binary form must reproduce the above copyright
     46  *    notice, this list of conditions and the following disclaimer in the
     47  *    documentation and/or other materials provided with the distribution.
     48  * 3. All advertising materials mentioning features or use of this software
     49  *    must display the following acknowledgement:
     50  *	This product includes software developed by the NetBSD
     51  *	Foundation, Inc. and its contributors.
     52  * 4. Neither the name of The NetBSD Foundation nor the names of its
     53  *    contributors may be used to endorse or promote products derived
     54  *    from this software without specific prior written permission.
     55  *
     56  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
     57  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
     58  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
     59  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
     60  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
     61  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
     62  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
     63  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
     64  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
     65  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
     66  * POSSIBILITY OF SUCH DAMAGE.
     67  */
     68 
     69 /*
     70  * Copyright (c) 1982, 1986, 1988, 1990, 1993, 1995
     71  *	The Regents of the University of California.  All rights reserved.
     72  *
     73  * Redistribution and use in source and binary forms, with or without
     74  * modification, are permitted provided that the following conditions
     75  * are met:
     76  * 1. Redistributions of source code must retain the above copyright
     77  *    notice, this list of conditions and the following disclaimer.
     78  * 2. Redistributions in binary form must reproduce the above copyright
     79  *    notice, this list of conditions and the following disclaimer in the
     80  *    documentation and/or other materials provided with the distribution.
     81  * 3. Neither the name of the University nor the names of its contributors
     82  *    may be used to endorse or promote products derived from this software
     83  *    without specific prior written permission.
     84  *
     85  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
     86  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     87  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     88  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
     89  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     90  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     91  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     92  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     93  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     94  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     95  * SUCH DAMAGE.
     96  *
     97  *	@(#)tcp_subr.c	8.2 (Berkeley) 5/24/95
     98  */
     99 
    100 #include <sys/cdefs.h>
    101 __KERNEL_RCSID(0, "$NetBSD: tcp_subr.c,v 1.171 2004/05/01 02:20:43 matt Exp $");
    102 
    103 #include "opt_inet.h"
    104 #include "opt_ipsec.h"
    105 #include "opt_tcp_compat_42.h"
    106 #include "opt_inet_csum.h"
    107 #include "opt_mbuftrace.h"
    108 #include "rnd.h"
    109 
    110 #include <sys/param.h>
    111 #include <sys/proc.h>
    112 #include <sys/systm.h>
    113 #include <sys/malloc.h>
    114 #include <sys/mbuf.h>
    115 #include <sys/socket.h>
    116 #include <sys/socketvar.h>
    117 #include <sys/protosw.h>
    118 #include <sys/errno.h>
    119 #include <sys/kernel.h>
    120 #include <sys/pool.h>
    121 #if NRND > 0
    122 #include <sys/md5.h>
    123 #include <sys/rnd.h>
    124 #endif
    125 
    126 #include <net/route.h>
    127 #include <net/if.h>
    128 
    129 #include <netinet/in.h>
    130 #include <netinet/in_systm.h>
    131 #include <netinet/ip.h>
    132 #include <netinet/in_pcb.h>
    133 #include <netinet/ip_var.h>
    134 #include <netinet/ip_icmp.h>
    135 
    136 #ifdef INET6
    137 #ifndef INET
    138 #include <netinet/in.h>
    139 #endif
    140 #include <netinet/ip6.h>
    141 #include <netinet6/in6_pcb.h>
    142 #include <netinet6/ip6_var.h>
    143 #include <netinet6/in6_var.h>
    144 #include <netinet6/ip6protosw.h>
    145 #include <netinet/icmp6.h>
    146 #include <netinet6/nd6.h>
    147 #endif
    148 
    149 #include <netinet/tcp.h>
    150 #include <netinet/tcp_fsm.h>
    151 #include <netinet/tcp_seq.h>
    152 #include <netinet/tcp_timer.h>
    153 #include <netinet/tcp_var.h>
    154 #include <netinet/tcpip.h>
    155 
    156 #ifdef IPSEC
    157 #include <netinet6/ipsec.h>
    158 #include <netkey/key.h>
    159 #endif /*IPSEC*/
    160 
    161 #ifdef FAST_IPSEC
    162 #include <netipsec/ipsec.h>
    163 #include <netipsec/xform.h>
    164 #ifdef INET6
    165 #include <netipsec/ipsec6.h>
    166 #endif
    167  #include <netipsec/key.h>
    168 #endif	/* FAST_IPSEC*/
    169 
    170 
    171 struct	inpcbtable tcbtable;	/* head of queue of active tcpcb's */
    172 struct	tcpstat tcpstat;	/* tcp statistics */
    173 u_int32_t tcp_now;		/* for RFC 1323 timestamps */
    174 
    175 /* patchable/settable parameters for tcp */
    176 int 	tcp_mssdflt = TCP_MSS;
    177 int 	tcp_rttdflt = TCPTV_SRTTDFLT / PR_SLOWHZ;
    178 int	tcp_do_rfc1323 = 1;	/* window scaling / timestamps (obsolete) */
    179 #if NRND > 0
    180 int	tcp_do_rfc1948 = 0;	/* ISS by cryptographic hash */
    181 #endif
    182 int	tcp_do_sack = 1;	/* selective acknowledgement */
    183 int	tcp_do_win_scale = 1;	/* RFC1323 window scaling */
    184 int	tcp_do_timestamps = 1;	/* RFC1323 timestamps */
    185 int	tcp_do_newreno = 1;	/* Use the New Reno algorithms */
    186 int	tcp_ack_on_push = 0;	/* set to enable immediate ACK-on-PUSH */
    187 #ifndef TCP_INIT_WIN
    188 #define	TCP_INIT_WIN	0	/* initial slow start window */
    189 #endif
    190 #ifndef TCP_INIT_WIN_LOCAL
    191 #define	TCP_INIT_WIN_LOCAL 4	/* initial slow start window for local nets */
    192 #endif
    193 int	tcp_init_win = TCP_INIT_WIN;
    194 int	tcp_init_win_local = TCP_INIT_WIN_LOCAL;
    195 int	tcp_mss_ifmtu = 0;
    196 #ifdef TCP_COMPAT_42
    197 int	tcp_compat_42 = 1;
    198 #else
    199 int	tcp_compat_42 = 0;
    200 #endif
    201 int	tcp_rst_ppslim = 100;	/* 100pps */
    202 int	tcp_ackdrop_ppslim = 100;	/* 100pps */
    203 
    204 /* tcb hash */
    205 #ifndef TCBHASHSIZE
    206 #define	TCBHASHSIZE	128
    207 #endif
    208 int	tcbhashsize = TCBHASHSIZE;
    209 
    210 /* syn hash parameters */
    211 #define	TCP_SYN_HASH_SIZE	293
    212 #define	TCP_SYN_BUCKET_SIZE	35
    213 int	tcp_syn_cache_size = TCP_SYN_HASH_SIZE;
    214 int	tcp_syn_cache_limit = TCP_SYN_HASH_SIZE*TCP_SYN_BUCKET_SIZE;
    215 int	tcp_syn_bucket_limit = 3*TCP_SYN_BUCKET_SIZE;
    216 struct	syn_cache_head tcp_syn_cache[TCP_SYN_HASH_SIZE];
    217 
    218 int	tcp_freeq __P((struct tcpcb *));
    219 
    220 #ifdef INET
    221 void	tcp_mtudisc_callback __P((struct in_addr));
    222 #endif
    223 #ifdef INET6
    224 void	tcp6_mtudisc_callback __P((struct in6_addr *));
    225 #endif
    226 
    227 void	tcp_mtudisc __P((struct inpcb *, int));
    228 #ifdef INET6
    229 void	tcp6_mtudisc __P((struct in6pcb *, int));
    230 #endif
    231 
    232 POOL_INIT(tcpcb_pool, sizeof(struct tcpcb), 0, 0, 0, "tcpcbpl", NULL);
    233 
    234 #ifdef TCP_CSUM_COUNTERS
    235 #include <sys/device.h>
    236 
    237 struct evcnt tcp_hwcsum_bad = EVCNT_INITIALIZER(EVCNT_TYPE_MISC,
    238     NULL, "tcp", "hwcsum bad");
    239 struct evcnt tcp_hwcsum_ok = EVCNT_INITIALIZER(EVCNT_TYPE_MISC,
    240     NULL, "tcp", "hwcsum ok");
    241 struct evcnt tcp_hwcsum_data = EVCNT_INITIALIZER(EVCNT_TYPE_MISC,
    242     NULL, "tcp", "hwcsum data");
    243 struct evcnt tcp_swcsum = EVCNT_INITIALIZER(EVCNT_TYPE_MISC,
    244     NULL, "tcp", "swcsum");
    245 
    246 EVCNT_ATTACH_STATIC(tcp_hwcsum_bad);
    247 EVCNT_ATTACH_STATIC(tcp_hwcsum_ok);
    248 EVCNT_ATTACH_STATIC(tcp_hwcsum_data);
    249 EVCNT_ATTACH_STATIC(tcp_swcsum);
    250 #endif /* TCP_CSUM_COUNTERS */
    251 
    252 
    253 #ifdef TCP_OUTPUT_COUNTERS
    254 #include <sys/device.h>
    255 
    256 struct evcnt tcp_output_bigheader = EVCNT_INITIALIZER(EVCNT_TYPE_MISC,
    257     NULL, "tcp", "output big header");
    258 struct evcnt tcp_output_predict_hit = EVCNT_INITIALIZER(EVCNT_TYPE_MISC,
    259     NULL, "tcp", "output predict hit");
    260 struct evcnt tcp_output_predict_miss = EVCNT_INITIALIZER(EVCNT_TYPE_MISC,
    261     NULL, "tcp", "output predict miss");
    262 struct evcnt tcp_output_copysmall = EVCNT_INITIALIZER(EVCNT_TYPE_MISC,
    263     NULL, "tcp", "output copy small");
    264 struct evcnt tcp_output_copybig = EVCNT_INITIALIZER(EVCNT_TYPE_MISC,
    265     NULL, "tcp", "output copy big");
    266 struct evcnt tcp_output_refbig = EVCNT_INITIALIZER(EVCNT_TYPE_MISC,
    267     NULL, "tcp", "output reference big");
    268 
    269 EVCNT_ATTACH_STATIC(tcp_output_bigheader);
    270 EVCNT_ATTACH_STATIC(tcp_output_predict_hit);
    271 EVCNT_ATTACH_STATIC(tcp_output_predict_miss);
    272 EVCNT_ATTACH_STATIC(tcp_output_copysmall);
    273 EVCNT_ATTACH_STATIC(tcp_output_copybig);
    274 EVCNT_ATTACH_STATIC(tcp_output_refbig);
    275 
    276 #endif /* TCP_OUTPUT_COUNTERS */
    277 
    278 #ifdef TCP_REASS_COUNTERS
    279 #include <sys/device.h>
    280 
    281 struct evcnt tcp_reass_ = EVCNT_INITIALIZER(EVCNT_TYPE_MISC,
    282     NULL, "tcp_reass", "calls");
    283 struct evcnt tcp_reass_empty = EVCNT_INITIALIZER(EVCNT_TYPE_MISC,
    284     &tcp_reass_, "tcp_reass", "insert into empty queue");
    285 struct evcnt tcp_reass_iteration[8] = {
    286     EVCNT_INITIALIZER(EVCNT_TYPE_MISC, &tcp_reass_, "tcp_reass", ">7 iterations"),
    287     EVCNT_INITIALIZER(EVCNT_TYPE_MISC, &tcp_reass_, "tcp_reass", "1 iteration"),
    288     EVCNT_INITIALIZER(EVCNT_TYPE_MISC, &tcp_reass_, "tcp_reass", "2 iterations"),
    289     EVCNT_INITIALIZER(EVCNT_TYPE_MISC, &tcp_reass_, "tcp_reass", "3 iterations"),
    290     EVCNT_INITIALIZER(EVCNT_TYPE_MISC, &tcp_reass_, "tcp_reass", "4 iterations"),
    291     EVCNT_INITIALIZER(EVCNT_TYPE_MISC, &tcp_reass_, "tcp_reass", "5 iterations"),
    292     EVCNT_INITIALIZER(EVCNT_TYPE_MISC, &tcp_reass_, "tcp_reass", "6 iterations"),
    293     EVCNT_INITIALIZER(EVCNT_TYPE_MISC, &tcp_reass_, "tcp_reass", "7 iterations"),
    294 };
    295 struct evcnt tcp_reass_prependfirst = EVCNT_INITIALIZER(EVCNT_TYPE_MISC,
    296     &tcp_reass_, "tcp_reass", "prepend to first");
    297 struct evcnt tcp_reass_prepend = EVCNT_INITIALIZER(EVCNT_TYPE_MISC,
    298     &tcp_reass_, "tcp_reass", "prepend");
    299 struct evcnt tcp_reass_insert = EVCNT_INITIALIZER(EVCNT_TYPE_MISC,
    300     &tcp_reass_, "tcp_reass", "insert");
    301 struct evcnt tcp_reass_inserttail = EVCNT_INITIALIZER(EVCNT_TYPE_MISC,
    302     &tcp_reass_, "tcp_reass", "insert at tail");
    303 struct evcnt tcp_reass_append = EVCNT_INITIALIZER(EVCNT_TYPE_MISC,
    304     &tcp_reass_, "tcp_reass", "append");
    305 struct evcnt tcp_reass_appendtail = EVCNT_INITIALIZER(EVCNT_TYPE_MISC,
    306     &tcp_reass_, "tcp_reass", "append to tail fragment");
    307 struct evcnt tcp_reass_overlaptail = EVCNT_INITIALIZER(EVCNT_TYPE_MISC,
    308     &tcp_reass_, "tcp_reass", "overlap at end");
    309 struct evcnt tcp_reass_overlapfront = EVCNT_INITIALIZER(EVCNT_TYPE_MISC,
    310     &tcp_reass_, "tcp_reass", "overlap at start");
    311 struct evcnt tcp_reass_segdup = EVCNT_INITIALIZER(EVCNT_TYPE_MISC,
    312     &tcp_reass_, "tcp_reass", "duplicate segment");
    313 struct evcnt tcp_reass_fragdup = EVCNT_INITIALIZER(EVCNT_TYPE_MISC,
    314     &tcp_reass_, "tcp_reass", "duplicate fragment");
    315 
    316 EVCNT_ATTACH_STATIC(tcp_reass_);
    317 EVCNT_ATTACH_STATIC(tcp_reass_empty);
    318 EVCNT_ATTACH_STATIC2(tcp_reass_iteration, 0);
    319 EVCNT_ATTACH_STATIC2(tcp_reass_iteration, 1);
    320 EVCNT_ATTACH_STATIC2(tcp_reass_iteration, 2);
    321 EVCNT_ATTACH_STATIC2(tcp_reass_iteration, 3);
    322 EVCNT_ATTACH_STATIC2(tcp_reass_iteration, 4);
    323 EVCNT_ATTACH_STATIC2(tcp_reass_iteration, 5);
    324 EVCNT_ATTACH_STATIC2(tcp_reass_iteration, 6);
    325 EVCNT_ATTACH_STATIC2(tcp_reass_iteration, 7);
    326 EVCNT_ATTACH_STATIC(tcp_reass_prependfirst);
    327 EVCNT_ATTACH_STATIC(tcp_reass_prepend);
    328 EVCNT_ATTACH_STATIC(tcp_reass_insert);
    329 EVCNT_ATTACH_STATIC(tcp_reass_inserttail);
    330 EVCNT_ATTACH_STATIC(tcp_reass_append);
    331 EVCNT_ATTACH_STATIC(tcp_reass_appendtail);
    332 EVCNT_ATTACH_STATIC(tcp_reass_overlaptail);
    333 EVCNT_ATTACH_STATIC(tcp_reass_overlapfront);
    334 EVCNT_ATTACH_STATIC(tcp_reass_segdup);
    335 EVCNT_ATTACH_STATIC(tcp_reass_fragdup);
    336 
    337 #endif /* TCP_REASS_COUNTERS */
    338 
    339 #ifdef MBUFTRACE
    340 struct mowner tcp_mowner = { "tcp" };
    341 struct mowner tcp_rx_mowner = { "tcp", "rx" };
    342 struct mowner tcp_tx_mowner = { "tcp", "tx" };
    343 #endif
    344 
    345 /*
    346  * Tcp initialization
    347  */
    348 void
    349 tcp_init()
    350 {
    351 	int hlen;
    352 
    353 	/* Initialize the TCPCB template. */
    354 	tcp_tcpcb_template();
    355 
    356 	in_pcbinit(&tcbtable, tcbhashsize, tcbhashsize);
    357 
    358 	hlen = sizeof(struct ip) + sizeof(struct tcphdr);
    359 #ifdef INET6
    360 	if (sizeof(struct ip) < sizeof(struct ip6_hdr))
    361 		hlen = sizeof(struct ip6_hdr) + sizeof(struct tcphdr);
    362 #endif
    363 	if (max_protohdr < hlen)
    364 		max_protohdr = hlen;
    365 	if (max_linkhdr + hlen > MHLEN)
    366 		panic("tcp_init");
    367 
    368 #ifdef INET
    369 	icmp_mtudisc_callback_register(tcp_mtudisc_callback);
    370 #endif
    371 #ifdef INET6
    372 	icmp6_mtudisc_callback_register(tcp6_mtudisc_callback);
    373 #endif
    374 
    375 	/* Initialize timer state. */
    376 	tcp_timer_init();
    377 
    378 	/* Initialize the compressed state engine. */
    379 	syn_cache_init();
    380 
    381 	MOWNER_ATTACH(&tcp_tx_mowner);
    382 	MOWNER_ATTACH(&tcp_rx_mowner);
    383 	MOWNER_ATTACH(&tcp_mowner);
    384 }
    385 
    386 /*
    387  * Create template to be used to send tcp packets on a connection.
    388  * Call after host entry created, allocates an mbuf and fills
    389  * in a skeletal tcp/ip header, minimizing the amount of work
    390  * necessary when the connection is used.
    391  */
    392 struct mbuf *
    393 tcp_template(tp)
    394 	struct tcpcb *tp;
    395 {
    396 	struct inpcb *inp = tp->t_inpcb;
    397 #ifdef INET6
    398 	struct in6pcb *in6p = tp->t_in6pcb;
    399 #endif
    400 	struct tcphdr *n;
    401 	struct mbuf *m;
    402 	int hlen;
    403 
    404 	switch (tp->t_family) {
    405 	case AF_INET:
    406 		hlen = sizeof(struct ip);
    407 		if (inp)
    408 			break;
    409 #ifdef INET6
    410 		if (in6p) {
    411 			/* mapped addr case */
    412 			if (IN6_IS_ADDR_V4MAPPED(&in6p->in6p_laddr)
    413 			 && IN6_IS_ADDR_V4MAPPED(&in6p->in6p_faddr))
    414 				break;
    415 		}
    416 #endif
    417 		return NULL;	/*EINVAL*/
    418 #ifdef INET6
    419 	case AF_INET6:
    420 		hlen = sizeof(struct ip6_hdr);
    421 		if (in6p) {
    422 			/* more sainty check? */
    423 			break;
    424 		}
    425 		return NULL;	/*EINVAL*/
    426 #endif
    427 	default:
    428 		hlen = 0;	/*pacify gcc*/
    429 		return NULL;	/*EAFNOSUPPORT*/
    430 	}
    431 #ifdef DIAGNOSTIC
    432 	if (hlen + sizeof(struct tcphdr) > MCLBYTES)
    433 		panic("mclbytes too small for t_template");
    434 #endif
    435 	m = tp->t_template;
    436 	if (m && m->m_len == hlen + sizeof(struct tcphdr))
    437 		;
    438 	else {
    439 		if (m)
    440 			m_freem(m);
    441 		m = tp->t_template = NULL;
    442 		MGETHDR(m, M_DONTWAIT, MT_HEADER);
    443 		if (m && hlen + sizeof(struct tcphdr) > MHLEN) {
    444 			MCLGET(m, M_DONTWAIT);
    445 			if ((m->m_flags & M_EXT) == 0) {
    446 				m_free(m);
    447 				m = NULL;
    448 			}
    449 		}
    450 		if (m == NULL)
    451 			return NULL;
    452 		MCLAIM(m, &tcp_mowner);
    453 		m->m_pkthdr.len = m->m_len = hlen + sizeof(struct tcphdr);
    454 	}
    455 
    456 	bzero(mtod(m, caddr_t), m->m_len);
    457 
    458 	n = (struct tcphdr *)(mtod(m, caddr_t) + hlen);
    459 
    460 	switch (tp->t_family) {
    461 	case AF_INET:
    462 	    {
    463 		struct ipovly *ipov;
    464 		mtod(m, struct ip *)->ip_v = 4;
    465 		mtod(m, struct ip *)->ip_hl = hlen >> 2;
    466 		ipov = mtod(m, struct ipovly *);
    467 		ipov->ih_pr = IPPROTO_TCP;
    468 		ipov->ih_len = htons(sizeof(struct tcphdr));
    469 		if (inp) {
    470 			ipov->ih_src = inp->inp_laddr;
    471 			ipov->ih_dst = inp->inp_faddr;
    472 		}
    473 #ifdef INET6
    474 		else if (in6p) {
    475 			/* mapped addr case */
    476 			bcopy(&in6p->in6p_laddr.s6_addr32[3], &ipov->ih_src,
    477 				sizeof(ipov->ih_src));
    478 			bcopy(&in6p->in6p_faddr.s6_addr32[3], &ipov->ih_dst,
    479 				sizeof(ipov->ih_dst));
    480 		}
    481 #endif
    482 		/*
    483 		 * Compute the pseudo-header portion of the checksum
    484 		 * now.  We incrementally add in the TCP option and
    485 		 * payload lengths later, and then compute the TCP
    486 		 * checksum right before the packet is sent off onto
    487 		 * the wire.
    488 		 */
    489 		n->th_sum = in_cksum_phdr(ipov->ih_src.s_addr,
    490 		    ipov->ih_dst.s_addr,
    491 		    htons(sizeof(struct tcphdr) + IPPROTO_TCP));
    492 		break;
    493 	    }
    494 #ifdef INET6
    495 	case AF_INET6:
    496 	    {
    497 		struct ip6_hdr *ip6;
    498 		mtod(m, struct ip *)->ip_v = 6;
    499 		ip6 = mtod(m, struct ip6_hdr *);
    500 		ip6->ip6_nxt = IPPROTO_TCP;
    501 		ip6->ip6_plen = htons(sizeof(struct tcphdr));
    502 		ip6->ip6_src = in6p->in6p_laddr;
    503 		ip6->ip6_dst = in6p->in6p_faddr;
    504 		ip6->ip6_flow = in6p->in6p_flowinfo & IPV6_FLOWINFO_MASK;
    505 		if (ip6_auto_flowlabel) {
    506 			ip6->ip6_flow &= ~IPV6_FLOWLABEL_MASK;
    507 			ip6->ip6_flow |=
    508 			    (htonl(ip6_randomflowlabel()) & IPV6_FLOWLABEL_MASK);
    509 		}
    510 		ip6->ip6_vfc &= ~IPV6_VERSION_MASK;
    511 		ip6->ip6_vfc |= IPV6_VERSION;
    512 
    513 		/*
    514 		 * Compute the pseudo-header portion of the checksum
    515 		 * now.  We incrementally add in the TCP option and
    516 		 * payload lengths later, and then compute the TCP
    517 		 * checksum right before the packet is sent off onto
    518 		 * the wire.
    519 		 */
    520 		n->th_sum = in6_cksum_phdr(&in6p->in6p_laddr,
    521 		    &in6p->in6p_faddr, htonl(sizeof(struct tcphdr)),
    522 		    htonl(IPPROTO_TCP));
    523 		break;
    524 	    }
    525 #endif
    526 	}
    527 	if (inp) {
    528 		n->th_sport = inp->inp_lport;
    529 		n->th_dport = inp->inp_fport;
    530 	}
    531 #ifdef INET6
    532 	else if (in6p) {
    533 		n->th_sport = in6p->in6p_lport;
    534 		n->th_dport = in6p->in6p_fport;
    535 	}
    536 #endif
    537 	n->th_seq = 0;
    538 	n->th_ack = 0;
    539 	n->th_x2 = 0;
    540 	n->th_off = 5;
    541 	n->th_flags = 0;
    542 	n->th_win = 0;
    543 	n->th_urp = 0;
    544 	return (m);
    545 }
    546 
    547 /*
    548  * Send a single message to the TCP at address specified by
    549  * the given TCP/IP header.  If m == 0, then we make a copy
    550  * of the tcpiphdr at ti and send directly to the addressed host.
    551  * This is used to force keep alive messages out using the TCP
    552  * template for a connection tp->t_template.  If flags are given
    553  * then we send a message back to the TCP which originated the
    554  * segment ti, and discard the mbuf containing it and any other
    555  * attached mbufs.
    556  *
    557  * In any case the ack and sequence number of the transmitted
    558  * segment are as specified by the parameters.
    559  */
    560 int
    561 tcp_respond(tp, template, m, th0, ack, seq, flags)
    562 	struct tcpcb *tp;
    563 	struct mbuf *template;
    564 	struct mbuf *m;
    565 	struct tcphdr *th0;
    566 	tcp_seq ack, seq;
    567 	int flags;
    568 {
    569 	struct route *ro;
    570 	int error, tlen, win = 0;
    571 	int hlen;
    572 	struct ip *ip;
    573 #ifdef INET6
    574 	struct ip6_hdr *ip6;
    575 #endif
    576 	int family;	/* family on packet, not inpcb/in6pcb! */
    577 	struct tcphdr *th;
    578 	struct socket *so;
    579 
    580 	if (tp != NULL && (flags & TH_RST) == 0) {
    581 #ifdef DIAGNOSTIC
    582 		if (tp->t_inpcb && tp->t_in6pcb)
    583 			panic("tcp_respond: both t_inpcb and t_in6pcb are set");
    584 #endif
    585 #ifdef INET
    586 		if (tp->t_inpcb)
    587 			win = sbspace(&tp->t_inpcb->inp_socket->so_rcv);
    588 #endif
    589 #ifdef INET6
    590 		if (tp->t_in6pcb)
    591 			win = sbspace(&tp->t_in6pcb->in6p_socket->so_rcv);
    592 #endif
    593 	}
    594 
    595 	th = NULL;	/* Quell uninitialized warning */
    596 	ip = NULL;
    597 #ifdef INET6
    598 	ip6 = NULL;
    599 #endif
    600 	if (m == 0) {
    601 		if (!template)
    602 			return EINVAL;
    603 
    604 		/* get family information from template */
    605 		switch (mtod(template, struct ip *)->ip_v) {
    606 		case 4:
    607 			family = AF_INET;
    608 			hlen = sizeof(struct ip);
    609 			break;
    610 #ifdef INET6
    611 		case 6:
    612 			family = AF_INET6;
    613 			hlen = sizeof(struct ip6_hdr);
    614 			break;
    615 #endif
    616 		default:
    617 			return EAFNOSUPPORT;
    618 		}
    619 
    620 		MGETHDR(m, M_DONTWAIT, MT_HEADER);
    621 		if (m) {
    622 			MCLAIM(m, &tcp_tx_mowner);
    623 			MCLGET(m, M_DONTWAIT);
    624 			if ((m->m_flags & M_EXT) == 0) {
    625 				m_free(m);
    626 				m = NULL;
    627 			}
    628 		}
    629 		if (m == NULL)
    630 			return (ENOBUFS);
    631 
    632 		if (tcp_compat_42)
    633 			tlen = 1;
    634 		else
    635 			tlen = 0;
    636 
    637 		m->m_data += max_linkhdr;
    638 		bcopy(mtod(template, caddr_t), mtod(m, caddr_t),
    639 			template->m_len);
    640 		switch (family) {
    641 		case AF_INET:
    642 			ip = mtod(m, struct ip *);
    643 			th = (struct tcphdr *)(ip + 1);
    644 			break;
    645 #ifdef INET6
    646 		case AF_INET6:
    647 			ip6 = mtod(m, struct ip6_hdr *);
    648 			th = (struct tcphdr *)(ip6 + 1);
    649 			break;
    650 #endif
    651 #if 0
    652 		default:
    653 			/* noone will visit here */
    654 			m_freem(m);
    655 			return EAFNOSUPPORT;
    656 #endif
    657 		}
    658 		flags = TH_ACK;
    659 	} else {
    660 
    661 		if ((m->m_flags & M_PKTHDR) == 0) {
    662 #if 0
    663 			printf("non PKTHDR to tcp_respond\n");
    664 #endif
    665 			m_freem(m);
    666 			return EINVAL;
    667 		}
    668 #ifdef DIAGNOSTIC
    669 		if (!th0)
    670 			panic("th0 == NULL in tcp_respond");
    671 #endif
    672 
    673 		/* get family information from m */
    674 		switch (mtod(m, struct ip *)->ip_v) {
    675 		case 4:
    676 			family = AF_INET;
    677 			hlen = sizeof(struct ip);
    678 			ip = mtod(m, struct ip *);
    679 			break;
    680 #ifdef INET6
    681 		case 6:
    682 			family = AF_INET6;
    683 			hlen = sizeof(struct ip6_hdr);
    684 			ip6 = mtod(m, struct ip6_hdr *);
    685 			break;
    686 #endif
    687 		default:
    688 			m_freem(m);
    689 			return EAFNOSUPPORT;
    690 		}
    691 		if ((flags & TH_SYN) == 0 || sizeof(*th0) > (th0->th_off << 2))
    692 			tlen = sizeof(*th0);
    693 		else
    694 			tlen = th0->th_off << 2;
    695 
    696 		if (m->m_len > hlen + tlen && (m->m_flags & M_EXT) == 0 &&
    697 		    mtod(m, caddr_t) + hlen == (caddr_t)th0) {
    698 			m->m_len = hlen + tlen;
    699 			m_freem(m->m_next);
    700 			m->m_next = NULL;
    701 		} else {
    702 			struct mbuf *n;
    703 
    704 #ifdef DIAGNOSTIC
    705 			if (max_linkhdr + hlen + tlen > MCLBYTES) {
    706 				m_freem(m);
    707 				return EMSGSIZE;
    708 			}
    709 #endif
    710 			MGETHDR(n, M_DONTWAIT, MT_HEADER);
    711 			if (n && max_linkhdr + hlen + tlen > MHLEN) {
    712 				MCLGET(n, M_DONTWAIT);
    713 				if ((n->m_flags & M_EXT) == 0) {
    714 					m_freem(n);
    715 					n = NULL;
    716 				}
    717 			}
    718 			if (!n) {
    719 				m_freem(m);
    720 				return ENOBUFS;
    721 			}
    722 
    723 			MCLAIM(n, &tcp_tx_mowner);
    724 			n->m_data += max_linkhdr;
    725 			n->m_len = hlen + tlen;
    726 			m_copyback(n, 0, hlen, mtod(m, caddr_t));
    727 			m_copyback(n, hlen, tlen, (caddr_t)th0);
    728 
    729 			m_freem(m);
    730 			m = n;
    731 			n = NULL;
    732 		}
    733 
    734 #define xchg(a,b,type) { type t; t=a; a=b; b=t; }
    735 		switch (family) {
    736 		case AF_INET:
    737 			ip = mtod(m, struct ip *);
    738 			th = (struct tcphdr *)(ip + 1);
    739 			ip->ip_p = IPPROTO_TCP;
    740 			xchg(ip->ip_dst, ip->ip_src, struct in_addr);
    741 			ip->ip_p = IPPROTO_TCP;
    742 			break;
    743 #ifdef INET6
    744 		case AF_INET6:
    745 			ip6 = mtod(m, struct ip6_hdr *);
    746 			th = (struct tcphdr *)(ip6 + 1);
    747 			ip6->ip6_nxt = IPPROTO_TCP;
    748 			xchg(ip6->ip6_dst, ip6->ip6_src, struct in6_addr);
    749 			ip6->ip6_nxt = IPPROTO_TCP;
    750 			break;
    751 #endif
    752 #if 0
    753 		default:
    754 			/* noone will visit here */
    755 			m_freem(m);
    756 			return EAFNOSUPPORT;
    757 #endif
    758 		}
    759 		xchg(th->th_dport, th->th_sport, u_int16_t);
    760 #undef xchg
    761 		tlen = 0;	/*be friendly with the following code*/
    762 	}
    763 	th->th_seq = htonl(seq);
    764 	th->th_ack = htonl(ack);
    765 	th->th_x2 = 0;
    766 	if ((flags & TH_SYN) == 0) {
    767 		if (tp)
    768 			win >>= tp->rcv_scale;
    769 		if (win > TCP_MAXWIN)
    770 			win = TCP_MAXWIN;
    771 		th->th_win = htons((u_int16_t)win);
    772 		th->th_off = sizeof (struct tcphdr) >> 2;
    773 		tlen += sizeof(*th);
    774 	} else
    775 		tlen += th->th_off << 2;
    776 	m->m_len = hlen + tlen;
    777 	m->m_pkthdr.len = hlen + tlen;
    778 	m->m_pkthdr.rcvif = (struct ifnet *) 0;
    779 	th->th_flags = flags;
    780 	th->th_urp = 0;
    781 
    782 	switch (family) {
    783 #ifdef INET
    784 	case AF_INET:
    785 	    {
    786 		struct ipovly *ipov = (struct ipovly *)ip;
    787 		bzero(ipov->ih_x1, sizeof ipov->ih_x1);
    788 		ipov->ih_len = htons((u_int16_t)tlen);
    789 
    790 		th->th_sum = 0;
    791 		th->th_sum = in_cksum(m, hlen + tlen);
    792 		ip->ip_len = htons(hlen + tlen);
    793 		ip->ip_ttl = ip_defttl;
    794 		break;
    795 	    }
    796 #endif
    797 #ifdef INET6
    798 	case AF_INET6:
    799 	    {
    800 		th->th_sum = 0;
    801 		th->th_sum = in6_cksum(m, IPPROTO_TCP, sizeof(struct ip6_hdr),
    802 				tlen);
    803 		ip6->ip6_plen = ntohs(tlen);
    804 		if (tp && tp->t_in6pcb) {
    805 			struct ifnet *oifp;
    806 			ro = (struct route *)&tp->t_in6pcb->in6p_route;
    807 			oifp = ro->ro_rt ? ro->ro_rt->rt_ifp : NULL;
    808 			ip6->ip6_hlim = in6_selecthlim(tp->t_in6pcb, oifp);
    809 		} else
    810 			ip6->ip6_hlim = ip6_defhlim;
    811 		ip6->ip6_flow &= ~IPV6_FLOWINFO_MASK;
    812 		if (ip6_auto_flowlabel) {
    813 			ip6->ip6_flow |=
    814 			    (htonl(ip6_randomflowlabel()) & IPV6_FLOWLABEL_MASK);
    815 		}
    816 		break;
    817 	    }
    818 #endif
    819 	}
    820 
    821 	if (tp && tp->t_inpcb)
    822 		so = tp->t_inpcb->inp_socket;
    823 #ifdef INET6
    824 	else if (tp && tp->t_in6pcb)
    825 		so = tp->t_in6pcb->in6p_socket;
    826 #endif
    827 	else
    828 		so = NULL;
    829 
    830 	if (tp != NULL && tp->t_inpcb != NULL) {
    831 		ro = &tp->t_inpcb->inp_route;
    832 #ifdef DIAGNOSTIC
    833 		if (family != AF_INET)
    834 			panic("tcp_respond: address family mismatch");
    835 		if (!in_hosteq(ip->ip_dst, tp->t_inpcb->inp_faddr)) {
    836 			panic("tcp_respond: ip_dst %x != inp_faddr %x",
    837 			    ntohl(ip->ip_dst.s_addr),
    838 			    ntohl(tp->t_inpcb->inp_faddr.s_addr));
    839 		}
    840 #endif
    841 	}
    842 #ifdef INET6
    843 	else if (tp != NULL && tp->t_in6pcb != NULL) {
    844 		ro = (struct route *)&tp->t_in6pcb->in6p_route;
    845 #ifdef DIAGNOSTIC
    846 		if (family == AF_INET) {
    847 			if (!IN6_IS_ADDR_V4MAPPED(&tp->t_in6pcb->in6p_faddr))
    848 				panic("tcp_respond: not mapped addr");
    849 			if (bcmp(&ip->ip_dst,
    850 			    &tp->t_in6pcb->in6p_faddr.s6_addr32[3],
    851 			    sizeof(ip->ip_dst)) != 0) {
    852 				panic("tcp_respond: ip_dst != in6p_faddr");
    853 			}
    854 		} else if (family == AF_INET6) {
    855 			if (!IN6_ARE_ADDR_EQUAL(&ip6->ip6_dst,
    856 			    &tp->t_in6pcb->in6p_faddr))
    857 				panic("tcp_respond: ip6_dst != in6p_faddr");
    858 		} else
    859 			panic("tcp_respond: address family mismatch");
    860 #endif
    861 	}
    862 #endif
    863 	else
    864 		ro = NULL;
    865 
    866 	switch (family) {
    867 #ifdef INET
    868 	case AF_INET:
    869 		error = ip_output(m, NULL, ro,
    870 		    (tp && tp->t_mtudisc ? IP_MTUDISC : 0),
    871 		    (struct ip_moptions *)0, so);
    872 		break;
    873 #endif
    874 #ifdef INET6
    875 	case AF_INET6:
    876 		error = ip6_output(m, NULL, (struct route_in6 *)ro, 0,
    877 		    (struct ip6_moptions *)0, so, NULL);
    878 		break;
    879 #endif
    880 	default:
    881 		error = EAFNOSUPPORT;
    882 		break;
    883 	}
    884 
    885 	return (error);
    886 }
    887 
    888 /*
    889  * Template TCPCB.  Rather than zeroing a new TCPCB and initializing
    890  * a bunch of members individually, we maintain this template for the
    891  * static and mostly-static components of the TCPCB, and copy it into
    892  * the new TCPCB instead.
    893  */
    894 static struct tcpcb tcpcb_template = {
    895 	/*
    896 	 * If TCP_NTIMERS ever changes, we'll need to update this
    897 	 * initializer.
    898 	 */
    899 	.t_timer = {
    900 		CALLOUT_INITIALIZER,
    901 		CALLOUT_INITIALIZER,
    902 		CALLOUT_INITIALIZER,
    903 		CALLOUT_INITIALIZER,
    904 	},
    905 	.t_delack_ch = CALLOUT_INITIALIZER,
    906 
    907 	.t_srtt = TCPTV_SRTTBASE,
    908 	.t_rttmin = TCPTV_MIN,
    909 
    910 	.snd_cwnd = TCP_MAXWIN << TCP_MAX_WINSHIFT,
    911 	.snd_ssthresh = TCP_MAXWIN << TCP_MAX_WINSHIFT,
    912 };
    913 
    914 /*
    915  * Updates the TCPCB template whenever a parameter that would affect
    916  * the template is changed.
    917  */
    918 void
    919 tcp_tcpcb_template(void)
    920 {
    921 	struct tcpcb *tp = &tcpcb_template;
    922 	int flags;
    923 
    924 	tp->t_peermss = tcp_mssdflt;
    925 	tp->t_ourmss = tcp_mssdflt;
    926 	tp->t_segsz = tcp_mssdflt;
    927 
    928 	flags = 0;
    929 	if (tcp_do_rfc1323 && tcp_do_win_scale)
    930 		flags |= TF_REQ_SCALE;
    931 	if (tcp_do_rfc1323 && tcp_do_timestamps)
    932 		flags |= TF_REQ_TSTMP;
    933 	if (tcp_do_sack == 2)
    934 		flags |= TF_WILL_SACK;
    935 	else if (tcp_do_sack == 1)
    936 		flags |= TF_WILL_SACK|TF_IGNR_RXSACK;
    937 	flags |= TF_CANT_TXSACK;
    938 	tp->t_flags = flags;
    939 
    940 	/*
    941 	 * Init srtt to TCPTV_SRTTBASE (0), so we can tell that we have no
    942 	 * rtt estimate.  Set rttvar so that srtt + 2 * rttvar gives
    943 	 * reasonable initial retransmit time.
    944 	 */
    945 	tp->t_rttvar = tcp_rttdflt * PR_SLOWHZ << (TCP_RTTVAR_SHIFT + 2 - 1);
    946 	TCPT_RANGESET(tp->t_rxtcur, TCP_REXMTVAL(tp),
    947 	    TCPTV_MIN, TCPTV_REXMTMAX);
    948 }
    949 
    950 /*
    951  * Create a new TCP control block, making an
    952  * empty reassembly queue and hooking it to the argument
    953  * protocol control block.
    954  */
    955 struct tcpcb *
    956 tcp_newtcpcb(family, aux)
    957 	int family;	/* selects inpcb, or in6pcb */
    958 	void *aux;
    959 {
    960 	struct tcpcb *tp;
    961 	int i;
    962 
    963 	/* XXX Consider using a pool_cache for speed. */
    964 	tp = pool_get(&tcpcb_pool, PR_NOWAIT);
    965 	if (tp == NULL)
    966 		return (NULL);
    967 	memcpy(tp, &tcpcb_template, sizeof(*tp));
    968 	TAILQ_INIT(&tp->segq);
    969 	TAILQ_INIT(&tp->timeq);
    970 	tp->t_family = family;		/* may be overridden later on */
    971 	LIST_INIT(&tp->t_sc);		/* XXX can template this */
    972 
    973 	/* Don't sweat this loop; hopefully the compiler will unroll it. */
    974 	for (i = 0; i < TCPT_NTIMERS; i++)
    975 		TCP_TIMER_INIT(tp, i);
    976 
    977 	switch (family) {
    978 	case AF_INET:
    979 	    {
    980 		struct inpcb *inp = (struct inpcb *)aux;
    981 
    982 		inp->inp_ip.ip_ttl = ip_defttl;
    983 		inp->inp_ppcb = (caddr_t)tp;
    984 
    985 		tp->t_inpcb = inp;
    986 		tp->t_mtudisc = ip_mtudisc;
    987 		break;
    988 	    }
    989 #ifdef INET6
    990 	case AF_INET6:
    991 	    {
    992 		struct in6pcb *in6p = (struct in6pcb *)aux;
    993 
    994 		in6p->in6p_ip6.ip6_hlim = in6_selecthlim(in6p,
    995 			in6p->in6p_route.ro_rt ? in6p->in6p_route.ro_rt->rt_ifp
    996 					       : NULL);
    997 		in6p->in6p_ppcb = (caddr_t)tp;
    998 
    999 		tp->t_in6pcb = in6p;
   1000 		/* for IPv6, always try to run path MTU discovery */
   1001 		tp->t_mtudisc = 1;
   1002 		break;
   1003 	    }
   1004 #endif /* INET6 */
   1005 	default:
   1006 		pool_put(&tcpcb_pool, tp);
   1007 		return (NULL);
   1008 	}
   1009 
   1010 	/*
   1011 	 * Initialize our timebase.  When we send timestamps, we take
   1012 	 * the delta from tcp_now -- this means each connection always
   1013 	 * gets a timebase of 0, which makes it, among other things,
   1014 	 * more difficult to determine how long a system has been up,
   1015 	 * and thus how many TCP sequence increments have occurred.
   1016 	 */
   1017 	tp->ts_timebase = tcp_now;
   1018 
   1019 	return (tp);
   1020 }
   1021 
   1022 /*
   1023  * Drop a TCP connection, reporting
   1024  * the specified error.  If connection is synchronized,
   1025  * then send a RST to peer.
   1026  */
   1027 struct tcpcb *
   1028 tcp_drop(tp, errno)
   1029 	struct tcpcb *tp;
   1030 	int errno;
   1031 {
   1032 	struct socket *so = NULL;
   1033 
   1034 #ifdef DIAGNOSTIC
   1035 	if (tp->t_inpcb && tp->t_in6pcb)
   1036 		panic("tcp_drop: both t_inpcb and t_in6pcb are set");
   1037 #endif
   1038 #ifdef INET
   1039 	if (tp->t_inpcb)
   1040 		so = tp->t_inpcb->inp_socket;
   1041 #endif
   1042 #ifdef INET6
   1043 	if (tp->t_in6pcb)
   1044 		so = tp->t_in6pcb->in6p_socket;
   1045 #endif
   1046 	if (!so)
   1047 		return NULL;
   1048 
   1049 	if (TCPS_HAVERCVDSYN(tp->t_state)) {
   1050 		tp->t_state = TCPS_CLOSED;
   1051 		(void) tcp_output(tp);
   1052 		tcpstat.tcps_drops++;
   1053 	} else
   1054 		tcpstat.tcps_conndrops++;
   1055 	if (errno == ETIMEDOUT && tp->t_softerror)
   1056 		errno = tp->t_softerror;
   1057 	so->so_error = errno;
   1058 	return (tcp_close(tp));
   1059 }
   1060 
   1061 /*
   1062  * Return whether this tcpcb is marked as dead, indicating
   1063  * to the calling timer function that no further action should
   1064  * be taken, as we are about to release this tcpcb.  The release
   1065  * of the storage will be done if this is the last timer running.
   1066  *
   1067  * This should be called from the callout handler function after
   1068  * callout_ack() is done, so that the number of invoking timer
   1069  * functions is 0.
   1070  */
   1071 int
   1072 tcp_isdead(tp)
   1073 	struct tcpcb *tp;
   1074 {
   1075 	int dead = (tp->t_flags & TF_DEAD);
   1076 
   1077 	if (__predict_false(dead)) {
   1078 		if (tcp_timers_invoking(tp) > 0)
   1079 				/* not quite there yet -- count separately? */
   1080 			return dead;
   1081 		tcpstat.tcps_delayed_free++;
   1082 		pool_put(&tcpcb_pool, tp);
   1083 	}
   1084 	return dead;
   1085 }
   1086 
   1087 /*
   1088  * Close a TCP control block:
   1089  *	discard all space held by the tcp
   1090  *	discard internet protocol block
   1091  *	wake up any sleepers
   1092  */
   1093 struct tcpcb *
   1094 tcp_close(tp)
   1095 	struct tcpcb *tp;
   1096 {
   1097 	struct inpcb *inp;
   1098 #ifdef INET6
   1099 	struct in6pcb *in6p;
   1100 #endif
   1101 	struct socket *so;
   1102 #ifdef RTV_RTT
   1103 	struct rtentry *rt;
   1104 #endif
   1105 	struct route *ro;
   1106 
   1107 	inp = tp->t_inpcb;
   1108 #ifdef INET6
   1109 	in6p = tp->t_in6pcb;
   1110 #endif
   1111 	so = NULL;
   1112 	ro = NULL;
   1113 	if (inp) {
   1114 		so = inp->inp_socket;
   1115 		ro = &inp->inp_route;
   1116 	}
   1117 #ifdef INET6
   1118 	else if (in6p) {
   1119 		so = in6p->in6p_socket;
   1120 		ro = (struct route *)&in6p->in6p_route;
   1121 	}
   1122 #endif
   1123 
   1124 #ifdef RTV_RTT
   1125 	/*
   1126 	 * If we sent enough data to get some meaningful characteristics,
   1127 	 * save them in the routing entry.  'Enough' is arbitrarily
   1128 	 * defined as the sendpipesize (default 4K) * 16.  This would
   1129 	 * give us 16 rtt samples assuming we only get one sample per
   1130 	 * window (the usual case on a long haul net).  16 samples is
   1131 	 * enough for the srtt filter to converge to within 5% of the correct
   1132 	 * value; fewer samples and we could save a very bogus rtt.
   1133 	 *
   1134 	 * Don't update the default route's characteristics and don't
   1135 	 * update anything that the user "locked".
   1136 	 */
   1137 	if (SEQ_LT(tp->iss + so->so_snd.sb_hiwat * 16, tp->snd_max) &&
   1138 	    ro && (rt = ro->ro_rt) &&
   1139 	    !in_nullhost(satosin(rt_key(rt))->sin_addr)) {
   1140 		u_long i = 0;
   1141 
   1142 		if ((rt->rt_rmx.rmx_locks & RTV_RTT) == 0) {
   1143 			i = tp->t_srtt *
   1144 			    ((RTM_RTTUNIT / PR_SLOWHZ) >> (TCP_RTT_SHIFT + 2));
   1145 			if (rt->rt_rmx.rmx_rtt && i)
   1146 				/*
   1147 				 * filter this update to half the old & half
   1148 				 * the new values, converting scale.
   1149 				 * See route.h and tcp_var.h for a
   1150 				 * description of the scaling constants.
   1151 				 */
   1152 				rt->rt_rmx.rmx_rtt =
   1153 				    (rt->rt_rmx.rmx_rtt + i) / 2;
   1154 			else
   1155 				rt->rt_rmx.rmx_rtt = i;
   1156 		}
   1157 		if ((rt->rt_rmx.rmx_locks & RTV_RTTVAR) == 0) {
   1158 			i = tp->t_rttvar *
   1159 			    ((RTM_RTTUNIT / PR_SLOWHZ) >> (TCP_RTTVAR_SHIFT + 2));
   1160 			if (rt->rt_rmx.rmx_rttvar && i)
   1161 				rt->rt_rmx.rmx_rttvar =
   1162 				    (rt->rt_rmx.rmx_rttvar + i) / 2;
   1163 			else
   1164 				rt->rt_rmx.rmx_rttvar = i;
   1165 		}
   1166 		/*
   1167 		 * update the pipelimit (ssthresh) if it has been updated
   1168 		 * already or if a pipesize was specified & the threshhold
   1169 		 * got below half the pipesize.  I.e., wait for bad news
   1170 		 * before we start updating, then update on both good
   1171 		 * and bad news.
   1172 		 */
   1173 		if (((rt->rt_rmx.rmx_locks & RTV_SSTHRESH) == 0 &&
   1174 		    (i = tp->snd_ssthresh) && rt->rt_rmx.rmx_ssthresh) ||
   1175 		    i < (rt->rt_rmx.rmx_sendpipe / 2)) {
   1176 			/*
   1177 			 * convert the limit from user data bytes to
   1178 			 * packets then to packet data bytes.
   1179 			 */
   1180 			i = (i + tp->t_segsz / 2) / tp->t_segsz;
   1181 			if (i < 2)
   1182 				i = 2;
   1183 			i *= (u_long)(tp->t_segsz + sizeof (struct tcpiphdr));
   1184 			if (rt->rt_rmx.rmx_ssthresh)
   1185 				rt->rt_rmx.rmx_ssthresh =
   1186 				    (rt->rt_rmx.rmx_ssthresh + i) / 2;
   1187 			else
   1188 				rt->rt_rmx.rmx_ssthresh = i;
   1189 		}
   1190 	}
   1191 #endif /* RTV_RTT */
   1192 	/* free the reassembly queue, if any */
   1193 	TCP_REASS_LOCK(tp);
   1194 	(void) tcp_freeq(tp);
   1195 	TCP_REASS_UNLOCK(tp);
   1196 
   1197 	tcp_canceltimers(tp);
   1198 	TCP_CLEAR_DELACK(tp);
   1199 	syn_cache_cleanup(tp);
   1200 
   1201 	if (tp->t_template) {
   1202 		m_free(tp->t_template);
   1203 		tp->t_template = NULL;
   1204 	}
   1205 	if (tcp_timers_invoking(tp))
   1206 		tp->t_flags |= TF_DEAD;
   1207 	else
   1208 		pool_put(&tcpcb_pool, tp);
   1209 
   1210 	if (inp) {
   1211 		inp->inp_ppcb = 0;
   1212 		soisdisconnected(so);
   1213 		in_pcbdetach(inp);
   1214 	}
   1215 #ifdef INET6
   1216 	else if (in6p) {
   1217 		in6p->in6p_ppcb = 0;
   1218 		soisdisconnected(so);
   1219 		in6_pcbdetach(in6p);
   1220 	}
   1221 #endif
   1222 	tcpstat.tcps_closed++;
   1223 	return ((struct tcpcb *)0);
   1224 }
   1225 
   1226 int
   1227 tcp_freeq(tp)
   1228 	struct tcpcb *tp;
   1229 {
   1230 	struct ipqent *qe;
   1231 	int rv = 0;
   1232 #ifdef TCPREASS_DEBUG
   1233 	int i = 0;
   1234 #endif
   1235 
   1236 	TCP_REASS_LOCK_CHECK(tp);
   1237 
   1238 	while ((qe = TAILQ_FIRST(&tp->segq)) != NULL) {
   1239 #ifdef TCPREASS_DEBUG
   1240 		printf("tcp_freeq[%p,%d]: %u:%u(%u) 0x%02x\n",
   1241 			tp, i++, qe->ipqe_seq, qe->ipqe_seq + qe->ipqe_len,
   1242 			qe->ipqe_len, qe->ipqe_flags & (TH_SYN|TH_FIN|TH_RST));
   1243 #endif
   1244 		TAILQ_REMOVE(&tp->segq, qe, ipqe_q);
   1245 		TAILQ_REMOVE(&tp->timeq, qe, ipqe_timeq);
   1246 		m_freem(qe->ipqe_m);
   1247 		pool_put(&ipqent_pool, qe);
   1248 		rv = 1;
   1249 	}
   1250 	return (rv);
   1251 }
   1252 
   1253 /*
   1254  * Protocol drain routine.  Called when memory is in short supply.
   1255  */
   1256 void
   1257 tcp_drain()
   1258 {
   1259 	struct inpcb_hdr *inph;
   1260 	struct tcpcb *tp;
   1261 
   1262 	/*
   1263 	 * Free the sequence queue of all TCP connections.
   1264 	 */
   1265 	CIRCLEQ_FOREACH(inph, &tcbtable.inpt_queue, inph_queue) {
   1266 		switch (inph->inph_af) {
   1267 		case AF_INET:
   1268 			tp = intotcpcb((struct inpcb *)inph);
   1269 			break;
   1270 #ifdef INET6
   1271 		case AF_INET6:
   1272 			tp = in6totcpcb((struct in6pcb *)inph);
   1273 			break;
   1274 #endif
   1275 		default:
   1276 			tp = NULL;
   1277 			break;
   1278 		}
   1279 		if (tp != NULL) {
   1280 			/*
   1281 			 * We may be called from a device's interrupt
   1282 			 * context.  If the tcpcb is already busy,
   1283 			 * just bail out now.
   1284 			 */
   1285 			if (tcp_reass_lock_try(tp) == 0)
   1286 				continue;
   1287 			if (tcp_freeq(tp))
   1288 				tcpstat.tcps_connsdrained++;
   1289 			TCP_REASS_UNLOCK(tp);
   1290 		}
   1291 	}
   1292 }
   1293 
   1294 /*
   1295  * Notify a tcp user of an asynchronous error;
   1296  * store error as soft error, but wake up user
   1297  * (for now, won't do anything until can select for soft error).
   1298  */
   1299 void
   1300 tcp_notify(inp, error)
   1301 	struct inpcb *inp;
   1302 	int error;
   1303 {
   1304 	struct tcpcb *tp = (struct tcpcb *)inp->inp_ppcb;
   1305 	struct socket *so = inp->inp_socket;
   1306 
   1307 	/*
   1308 	 * Ignore some errors if we are hooked up.
   1309 	 * If connection hasn't completed, has retransmitted several times,
   1310 	 * and receives a second error, give up now.  This is better
   1311 	 * than waiting a long time to establish a connection that
   1312 	 * can never complete.
   1313 	 */
   1314 	if (tp->t_state == TCPS_ESTABLISHED &&
   1315 	     (error == EHOSTUNREACH || error == ENETUNREACH ||
   1316 	      error == EHOSTDOWN)) {
   1317 		return;
   1318 	} else if (TCPS_HAVEESTABLISHED(tp->t_state) == 0 &&
   1319 	    tp->t_rxtshift > 3 && tp->t_softerror)
   1320 		so->so_error = error;
   1321 	else
   1322 		tp->t_softerror = error;
   1323 	wakeup((caddr_t) &so->so_timeo);
   1324 	sorwakeup(so);
   1325 	sowwakeup(so);
   1326 }
   1327 
   1328 #ifdef INET6
   1329 void
   1330 tcp6_notify(in6p, error)
   1331 	struct in6pcb *in6p;
   1332 	int error;
   1333 {
   1334 	struct tcpcb *tp = (struct tcpcb *)in6p->in6p_ppcb;
   1335 	struct socket *so = in6p->in6p_socket;
   1336 
   1337 	/*
   1338 	 * Ignore some errors if we are hooked up.
   1339 	 * If connection hasn't completed, has retransmitted several times,
   1340 	 * and receives a second error, give up now.  This is better
   1341 	 * than waiting a long time to establish a connection that
   1342 	 * can never complete.
   1343 	 */
   1344 	if (tp->t_state == TCPS_ESTABLISHED &&
   1345 	     (error == EHOSTUNREACH || error == ENETUNREACH ||
   1346 	      error == EHOSTDOWN)) {
   1347 		return;
   1348 	} else if (TCPS_HAVEESTABLISHED(tp->t_state) == 0 &&
   1349 	    tp->t_rxtshift > 3 && tp->t_softerror)
   1350 		so->so_error = error;
   1351 	else
   1352 		tp->t_softerror = error;
   1353 	wakeup((caddr_t) &so->so_timeo);
   1354 	sorwakeup(so);
   1355 	sowwakeup(so);
   1356 }
   1357 #endif
   1358 
   1359 #ifdef INET6
   1360 void
   1361 tcp6_ctlinput(cmd, sa, d)
   1362 	int cmd;
   1363 	struct sockaddr *sa;
   1364 	void *d;
   1365 {
   1366 	struct tcphdr th;
   1367 	void (*notify) __P((struct in6pcb *, int)) = tcp6_notify;
   1368 	int nmatch;
   1369 	struct ip6_hdr *ip6;
   1370 	const struct sockaddr_in6 *sa6_src = NULL;
   1371 	struct sockaddr_in6 *sa6 = (struct sockaddr_in6 *)sa;
   1372 	struct mbuf *m;
   1373 	int off;
   1374 
   1375 	if (sa->sa_family != AF_INET6 ||
   1376 	    sa->sa_len != sizeof(struct sockaddr_in6))
   1377 		return;
   1378 	if ((unsigned)cmd >= PRC_NCMDS)
   1379 		return;
   1380 	else if (cmd == PRC_QUENCH) {
   1381 		/* XXX there's no PRC_QUENCH in IPv6 */
   1382 		notify = tcp6_quench;
   1383 	} else if (PRC_IS_REDIRECT(cmd))
   1384 		notify = in6_rtchange, d = NULL;
   1385 	else if (cmd == PRC_MSGSIZE)
   1386 		; /* special code is present, see below */
   1387 	else if (cmd == PRC_HOSTDEAD)
   1388 		d = NULL;
   1389 	else if (inet6ctlerrmap[cmd] == 0)
   1390 		return;
   1391 
   1392 	/* if the parameter is from icmp6, decode it. */
   1393 	if (d != NULL) {
   1394 		struct ip6ctlparam *ip6cp = (struct ip6ctlparam *)d;
   1395 		m = ip6cp->ip6c_m;
   1396 		ip6 = ip6cp->ip6c_ip6;
   1397 		off = ip6cp->ip6c_off;
   1398 		sa6_src = ip6cp->ip6c_src;
   1399 	} else {
   1400 		m = NULL;
   1401 		ip6 = NULL;
   1402 		sa6_src = &sa6_any;
   1403 		off = 0;
   1404 	}
   1405 
   1406 	if (ip6) {
   1407 		/*
   1408 		 * XXX: We assume that when ip6 is non NULL,
   1409 		 * M and OFF are valid.
   1410 		 */
   1411 
   1412 		/* check if we can safely examine src and dst ports */
   1413 		if (m->m_pkthdr.len < off + sizeof(th)) {
   1414 			if (cmd == PRC_MSGSIZE)
   1415 				icmp6_mtudisc_update((struct ip6ctlparam *)d, 0);
   1416 			return;
   1417 		}
   1418 
   1419 		bzero(&th, sizeof(th));
   1420 		m_copydata(m, off, sizeof(th), (caddr_t)&th);
   1421 
   1422 		if (cmd == PRC_MSGSIZE) {
   1423 			int valid = 0;
   1424 
   1425 			/*
   1426 			 * Check to see if we have a valid TCP connection
   1427 			 * corresponding to the address in the ICMPv6 message
   1428 			 * payload.
   1429 			 */
   1430 			if (in6_pcblookup_connect(&tcbtable, &sa6->sin6_addr,
   1431 			    th.th_dport, (struct in6_addr *)&sa6_src->sin6_addr,
   1432 			    th.th_sport, 0))
   1433 				valid++;
   1434 
   1435 			/*
   1436 			 * Depending on the value of "valid" and routing table
   1437 			 * size (mtudisc_{hi,lo}wat), we will:
   1438 			 * - recalcurate the new MTU and create the
   1439 			 *   corresponding routing entry, or
   1440 			 * - ignore the MTU change notification.
   1441 			 */
   1442 			icmp6_mtudisc_update((struct ip6ctlparam *)d, valid);
   1443 
   1444 			/*
   1445 			 * no need to call in6_pcbnotify, it should have been
   1446 			 * called via callback if necessary
   1447 			 */
   1448 			return;
   1449 		}
   1450 
   1451 		nmatch = in6_pcbnotify(&tcbtable, sa, th.th_dport,
   1452 		    (struct sockaddr *)sa6_src, th.th_sport, cmd, NULL, notify);
   1453 		if (nmatch == 0 && syn_cache_count &&
   1454 		    (inet6ctlerrmap[cmd] == EHOSTUNREACH ||
   1455 		     inet6ctlerrmap[cmd] == ENETUNREACH ||
   1456 		     inet6ctlerrmap[cmd] == EHOSTDOWN))
   1457 			syn_cache_unreach((struct sockaddr *)sa6_src,
   1458 					  sa, &th);
   1459 	} else {
   1460 		(void) in6_pcbnotify(&tcbtable, sa, 0,
   1461 		    (struct sockaddr *)sa6_src, 0, cmd, NULL, notify);
   1462 	}
   1463 }
   1464 #endif
   1465 
   1466 #ifdef INET
   1467 /* assumes that ip header and tcp header are contiguous on mbuf */
   1468 void *
   1469 tcp_ctlinput(cmd, sa, v)
   1470 	int cmd;
   1471 	struct sockaddr *sa;
   1472 	void *v;
   1473 {
   1474 	struct ip *ip = v;
   1475 	struct tcphdr *th;
   1476 	struct icmp *icp;
   1477 	extern const int inetctlerrmap[];
   1478 	void (*notify) __P((struct inpcb *, int)) = tcp_notify;
   1479 	int errno;
   1480 	int nmatch;
   1481 #ifdef INET6
   1482 	struct in6_addr src6, dst6;
   1483 #endif
   1484 
   1485 	if (sa->sa_family != AF_INET ||
   1486 	    sa->sa_len != sizeof(struct sockaddr_in))
   1487 		return NULL;
   1488 	if ((unsigned)cmd >= PRC_NCMDS)
   1489 		return NULL;
   1490 	errno = inetctlerrmap[cmd];
   1491 	if (cmd == PRC_QUENCH)
   1492 		notify = tcp_quench;
   1493 	else if (PRC_IS_REDIRECT(cmd))
   1494 		notify = in_rtchange, ip = 0;
   1495 	else if (cmd == PRC_MSGSIZE && ip && ip->ip_v == 4) {
   1496 		/*
   1497 		 * Check to see if we have a valid TCP connection
   1498 		 * corresponding to the address in the ICMP message
   1499 		 * payload.
   1500 		 *
   1501 		 * Boundary check is made in icmp_input(), with ICMP_ADVLENMIN.
   1502 		 */
   1503 		th = (struct tcphdr *)((caddr_t)ip + (ip->ip_hl << 2));
   1504 #ifdef INET6
   1505 		memset(&src6, 0, sizeof(src6));
   1506 		memset(&dst6, 0, sizeof(dst6));
   1507 		src6.s6_addr16[5] = dst6.s6_addr16[5] = 0xffff;
   1508 		memcpy(&src6.s6_addr32[3], &ip->ip_src, sizeof(struct in_addr));
   1509 		memcpy(&dst6.s6_addr32[3], &ip->ip_dst, sizeof(struct in_addr));
   1510 #endif
   1511 		if (in_pcblookup_connect(&tcbtable, ip->ip_dst, th->th_dport,
   1512 		    ip->ip_src, th->th_sport) != NULL)
   1513 			;
   1514 #ifdef INET6
   1515 		else if (in6_pcblookup_connect(&tcbtable, &dst6,
   1516 		    th->th_dport, &src6, th->th_sport, 0) != NULL)
   1517 			;
   1518 #endif
   1519 		else
   1520 			return NULL;
   1521 
   1522 		/*
   1523 		 * Now that we've validated that we are actually communicating
   1524 		 * with the host indicated in the ICMP message, locate the
   1525 		 * ICMP header, recalculate the new MTU, and create the
   1526 		 * corresponding routing entry.
   1527 		 */
   1528 		icp = (struct icmp *)((caddr_t)ip -
   1529 		    offsetof(struct icmp, icmp_ip));
   1530 		icmp_mtudisc(icp, ip->ip_dst);
   1531 
   1532 		return NULL;
   1533 	} else if (cmd == PRC_HOSTDEAD)
   1534 		ip = 0;
   1535 	else if (errno == 0)
   1536 		return NULL;
   1537 	if (ip && ip->ip_v == 4 && sa->sa_family == AF_INET) {
   1538 		th = (struct tcphdr *)((caddr_t)ip + (ip->ip_hl << 2));
   1539 		nmatch = in_pcbnotify(&tcbtable, satosin(sa)->sin_addr,
   1540 		    th->th_dport, ip->ip_src, th->th_sport, errno, notify);
   1541 		if (nmatch == 0 && syn_cache_count &&
   1542 		    (inetctlerrmap[cmd] == EHOSTUNREACH ||
   1543 		    inetctlerrmap[cmd] == ENETUNREACH ||
   1544 		    inetctlerrmap[cmd] == EHOSTDOWN)) {
   1545 			struct sockaddr_in sin;
   1546 			bzero(&sin, sizeof(sin));
   1547 			sin.sin_len = sizeof(sin);
   1548 			sin.sin_family = AF_INET;
   1549 			sin.sin_port = th->th_sport;
   1550 			sin.sin_addr = ip->ip_src;
   1551 			syn_cache_unreach((struct sockaddr *)&sin, sa, th);
   1552 		}
   1553 
   1554 		/* XXX mapped address case */
   1555 	} else
   1556 		in_pcbnotifyall(&tcbtable, satosin(sa)->sin_addr, errno,
   1557 		    notify);
   1558 	return NULL;
   1559 }
   1560 
   1561 /*
   1562  * When a source quence is received, we are being notifed of congestion.
   1563  * Close the congestion window down to the Loss Window (one segment).
   1564  * We will gradually open it again as we proceed.
   1565  */
   1566 void
   1567 tcp_quench(inp, errno)
   1568 	struct inpcb *inp;
   1569 	int errno;
   1570 {
   1571 	struct tcpcb *tp = intotcpcb(inp);
   1572 
   1573 	if (tp)
   1574 		tp->snd_cwnd = tp->t_segsz;
   1575 }
   1576 #endif
   1577 
   1578 #ifdef INET6
   1579 void
   1580 tcp6_quench(in6p, errno)
   1581 	struct in6pcb *in6p;
   1582 	int errno;
   1583 {
   1584 	struct tcpcb *tp = in6totcpcb(in6p);
   1585 
   1586 	if (tp)
   1587 		tp->snd_cwnd = tp->t_segsz;
   1588 }
   1589 #endif
   1590 
   1591 #ifdef INET
   1592 /*
   1593  * Path MTU Discovery handlers.
   1594  */
   1595 void
   1596 tcp_mtudisc_callback(faddr)
   1597 	struct in_addr faddr;
   1598 {
   1599 #ifdef INET6
   1600 	struct in6_addr in6;
   1601 #endif
   1602 
   1603 	in_pcbnotifyall(&tcbtable, faddr, EMSGSIZE, tcp_mtudisc);
   1604 #ifdef INET6
   1605 	memset(&in6, 0, sizeof(in6));
   1606 	in6.s6_addr16[5] = 0xffff;
   1607 	memcpy(&in6.s6_addr32[3], &faddr, sizeof(struct in_addr));
   1608 	tcp6_mtudisc_callback(&in6);
   1609 #endif
   1610 }
   1611 
   1612 #ifdef TCP_SIGNATURE
   1613 /*
   1614  * Callback function invoked by m_apply() to digest TCP segment data
   1615  * contained within an mbuf chain.
   1616  */
   1617 static int
   1618 tcp_signature_apply(void *fstate, caddr_t data, u_int len)
   1619 {
   1620 
   1621 	MD5Update(fstate, (u_char *)data, len);
   1622 	return (0);
   1623 }
   1624 
   1625 /*
   1626  * Compute TCP-MD5 hash of a TCPv4 segment. (RFC2385)
   1627  *
   1628  * Parameters:
   1629  * m		pointer to head of mbuf chain
   1630  * th		pointer to tcp header
   1631  * thoff	offset to TCP header within the mbuf chain
   1632  *		(if you don't know the value, set to -1)
   1633  * len		length of TCP segment data, excluding options
   1634  * optlen	length of TCP segment options
   1635  * buf		pointer to storage for computed MD5 digest
   1636  * direction	direction of flow (IPSEC_DIR_INBOUND or OUTBOUND)
   1637  *
   1638  * We do this over ip, tcphdr, segment data, and the key in the SADB.
   1639  * When called from tcp_input(), we can be sure that th_sum has been
   1640  * zeroed out and verified already.
   1641  *
   1642  * Return 0 if successful, otherwise return -1.
   1643  *
   1644  * XXX The key is retrieved from the system's PF_KEY SADB, by keying a
   1645  * search with the destination IP address, and a 'magic SPI' of 0x1000.
   1646  * Another branch of this code exists which uses the SPD to specify
   1647  * per-application flows, but it is unstable.
   1648  */
   1649 int
   1650 tcp_signature_compute(struct mbuf *m, struct tcphdr *th, int thoff,
   1651     int len, int optlen, u_char *buf, u_int direction)
   1652 {
   1653 #ifdef FAST_IPSEC
   1654 	union sockaddr_union dst;
   1655 #endif
   1656 	MD5_CTX ctx;
   1657 	int doff;
   1658 	struct ip *ip;
   1659 	struct ipovly *ipovly;
   1660 	struct ip6_hdr *ip6;
   1661 	struct secasvar *sav;
   1662 	u_int16_t savecsum;
   1663 	struct ippseudo ippseudo;
   1664 	struct ip6_ext ip6e;
   1665 	struct ip6_hdr_pseudo ip6pseudo;
   1666 	u_int8_t nxt;
   1667 
   1668 	KASSERT(m != NULL /*, ("NULL mbuf chain")*/);
   1669 	KASSERT(buf != NULL /*, ("NULL signature pointer")*/);
   1670 
   1671 	ip = mtod(m, struct ip *);
   1672 	ip6 = NULL;
   1673 	if (ip->ip_v == 6) {
   1674 		ip = NULL;
   1675 		ip6 = mtod(m, struct ip6_hdr *);
   1676 	}
   1677 
   1678 	/* look for TCP header offset - it won't take too long */
   1679 	if (thoff >= 0) {
   1680 		nxt = IPPROTO_TCP;
   1681 		goto found;
   1682 	}
   1683 
   1684 	thoff = ip ? sizeof(*ip) : sizeof(*ip6);
   1685 	nxt = ip ? ip->ip_p : ip6->ip6_nxt;
   1686 
   1687 	while (1) {
   1688 		switch (nxt) {
   1689 		case IPPROTO_TCP:
   1690 			goto found;
   1691 		case IPPROTO_AH:
   1692 			m_copydata(m, thoff, sizeof(ip6e), (caddr_t)&ip6e);
   1693 			thoff += (ip6e.ip6e_len + 2) << 2;
   1694 			break;
   1695 		case IPPROTO_DSTOPTS:
   1696 		case IPPROTO_ROUTING:
   1697 		case IPPROTO_HOPOPTS:
   1698 			m_copydata(m, thoff, sizeof(ip6e), (caddr_t)&ip6e);
   1699 			thoff += (ip6e.ip6e_len + 1) << 3;
   1700 			break;
   1701 		default:
   1702 			return EINVAL;
   1703 		}
   1704 
   1705 		nxt = ip6e.ip6e_nxt;
   1706 	}
   1707 
   1708 found:
   1709 
   1710 #ifdef FAST_IPSEC
   1711 	/* Extract the destination from the IP header in the mbuf. */
   1712 	bzero(&dst, sizeof(union sockaddr_union));
   1713 	dst.sa.sa_len = sizeof(struct sockaddr_in);
   1714 	dst.sa.sa_family = AF_INET;
   1715 	dst.sin.sin_addr = (direction == IPSEC_DIR_INBOUND) ?
   1716 	    ip->ip_src : ip->ip_dst;
   1717 
   1718 	/* Look up an SADB entry which matches the address of the peer. */
   1719 	sav = KEY_ALLOCSA(&dst, IPPROTO_TCP, htonl(TCP_SIG_SPI));
   1720 #else
   1721 	if (ip)
   1722 		sav = key_allocsa(AF_INET, (caddr_t)&ip->ip_src,
   1723 		    (caddr_t)&ip->ip_dst, IPPROTO_TCP, htonl(TCP_SIG_SPI));
   1724 	else
   1725 		sav = key_allocsa(AF_INET6, (caddr_t)&ip6->ip6_src,
   1726 		    (caddr_t)&ip6->ip6_dst, IPPROTO_TCP, htonl(TCP_SIG_SPI));
   1727 #endif
   1728 	if (sav == NULL) {
   1729 		printf("%s: SADB lookup failed\n", __func__);
   1730 		return (EINVAL);
   1731 	}
   1732 
   1733 	MD5Init(&ctx);
   1734 	doff = thoff + sizeof(struct tcphdr) + optlen;
   1735 
   1736 	/*
   1737 	 * Step 1: Update MD5 hash with IP pseudo-header.
   1738 	 *
   1739 	 * XXX The ippseudo header MUST be digested in network byte order,
   1740 	 * or else we'll fail the regression test. Assume all fields we've
   1741 	 * been doing arithmetic on have been in host byte order.
   1742 	 * XXX One cannot depend on ipovly->ih_len here. When called from
   1743 	 * tcp_output(), the underlying ip_len member has not yet been set.
   1744 	 */
   1745 	if (ip) {
   1746 		memset(&ippseudo, 0, sizeof(ippseudo));
   1747 		ipovly = (struct ipovly *)ip;
   1748 		ippseudo.ippseudo_src = ipovly->ih_src;
   1749 		ippseudo.ippseudo_dst = ipovly->ih_dst;
   1750 		ippseudo.ippseudo_pad = 0;
   1751 		ippseudo.ippseudo_p = IPPROTO_TCP;
   1752 		ippseudo.ippseudo_len =
   1753 		    htons(len + sizeof(struct tcphdr) + optlen);
   1754 		MD5Update(&ctx, (char *)&ippseudo, sizeof(ippseudo));
   1755 	} else {
   1756 		memset(&ip6pseudo, 0, sizeof(ip6pseudo));
   1757 		ip6pseudo.ip6ph_src = ip6->ip6_src;
   1758 		in6_clearscope(&ip6pseudo.ip6ph_src);
   1759 		ip6pseudo.ip6ph_dst = ip6->ip6_dst;
   1760 		in6_clearscope(&ip6pseudo.ip6ph_dst);
   1761 		ip6pseudo.ip6ph_len =
   1762 		    htonl(len + sizeof(struct tcphdr) + optlen);
   1763 		ip6pseudo.ip6ph_nxt = IPPROTO_TCP;
   1764 		MD5Update(&ctx, (char *)&ip6pseudo, sizeof(ip6pseudo));
   1765 	}
   1766 
   1767 	/*
   1768 	 * Step 2: Update MD5 hash with TCP header, excluding options.
   1769 	 * The TCP checksum must be set to zero.
   1770 	 */
   1771 	savecsum = th->th_sum;
   1772 	th->th_sum = 0;
   1773 	MD5Update(&ctx, (char *)th, sizeof(struct tcphdr));
   1774 	th->th_sum = savecsum;
   1775 
   1776 	/*
   1777 	 * Step 3: Update MD5 hash with TCP segment data.
   1778 	 *         Use m_apply() to avoid an early m_pullup().
   1779 	 */
   1780 	if (len > 0)
   1781 		m_apply(m, doff, len, tcp_signature_apply, &ctx);
   1782 
   1783 	/*
   1784 	 * Step 4: Update MD5 hash with shared secret.
   1785 	 */
   1786 	MD5Update(&ctx, _KEYBUF(sav->key_auth), _KEYLEN(sav->key_auth));
   1787 	MD5Final(buf, &ctx);
   1788 
   1789 	key_sa_recordxfer(sav, m);
   1790 #ifdef FAST_IPSEC
   1791 	KEY_FREESAV(&sav);
   1792 #else
   1793 	key_freesav(sav);
   1794 #endif
   1795 	return (0);
   1796 }
   1797 #endif /* TCP_SIGNATURE */
   1798 
   1799 /*
   1800  * On receipt of path MTU corrections, flush old route and replace it
   1801  * with the new one.  Retransmit all unacknowledged packets, to ensure
   1802  * that all packets will be received.
   1803  */
   1804 void
   1805 tcp_mtudisc(inp, errno)
   1806 	struct inpcb *inp;
   1807 	int errno;
   1808 {
   1809 	struct tcpcb *tp = intotcpcb(inp);
   1810 	struct rtentry *rt = in_pcbrtentry(inp);
   1811 
   1812 	if (tp != 0) {
   1813 		if (rt != 0) {
   1814 			/*
   1815 			 * If this was not a host route, remove and realloc.
   1816 			 */
   1817 			if ((rt->rt_flags & RTF_HOST) == 0) {
   1818 				in_rtchange(inp, errno);
   1819 				if ((rt = in_pcbrtentry(inp)) == 0)
   1820 					return;
   1821 			}
   1822 
   1823 			/*
   1824 			 * Slow start out of the error condition.  We
   1825 			 * use the MTU because we know it's smaller
   1826 			 * than the previously transmitted segment.
   1827 			 *
   1828 			 * Note: This is more conservative than the
   1829 			 * suggestion in draft-floyd-incr-init-win-03.
   1830 			 */
   1831 			if (rt->rt_rmx.rmx_mtu != 0)
   1832 				tp->snd_cwnd =
   1833 				    TCP_INITIAL_WINDOW(tcp_init_win,
   1834 				    rt->rt_rmx.rmx_mtu);
   1835 		}
   1836 
   1837 		/*
   1838 		 * Resend unacknowledged packets.
   1839 		 */
   1840 		tp->snd_nxt = tp->snd_una;
   1841 		tcp_output(tp);
   1842 	}
   1843 }
   1844 #endif
   1845 
   1846 #ifdef INET6
   1847 /*
   1848  * Path MTU Discovery handlers.
   1849  */
   1850 void
   1851 tcp6_mtudisc_callback(faddr)
   1852 	struct in6_addr *faddr;
   1853 {
   1854 	struct sockaddr_in6 sin6;
   1855 
   1856 	bzero(&sin6, sizeof(sin6));
   1857 	sin6.sin6_family = AF_INET6;
   1858 	sin6.sin6_len = sizeof(struct sockaddr_in6);
   1859 	sin6.sin6_addr = *faddr;
   1860 	(void) in6_pcbnotify(&tcbtable, (struct sockaddr *)&sin6, 0,
   1861 	    (struct sockaddr *)&sa6_any, 0, PRC_MSGSIZE, NULL, tcp6_mtudisc);
   1862 }
   1863 
   1864 void
   1865 tcp6_mtudisc(in6p, errno)
   1866 	struct in6pcb *in6p;
   1867 	int errno;
   1868 {
   1869 	struct tcpcb *tp = in6totcpcb(in6p);
   1870 	struct rtentry *rt = in6_pcbrtentry(in6p);
   1871 
   1872 	if (tp != 0) {
   1873 		if (rt != 0) {
   1874 			/*
   1875 			 * If this was not a host route, remove and realloc.
   1876 			 */
   1877 			if ((rt->rt_flags & RTF_HOST) == 0) {
   1878 				in6_rtchange(in6p, errno);
   1879 				if ((rt = in6_pcbrtentry(in6p)) == 0)
   1880 					return;
   1881 			}
   1882 
   1883 			/*
   1884 			 * Slow start out of the error condition.  We
   1885 			 * use the MTU because we know it's smaller
   1886 			 * than the previously transmitted segment.
   1887 			 *
   1888 			 * Note: This is more conservative than the
   1889 			 * suggestion in draft-floyd-incr-init-win-03.
   1890 			 */
   1891 			if (rt->rt_rmx.rmx_mtu != 0)
   1892 				tp->snd_cwnd =
   1893 				    TCP_INITIAL_WINDOW(tcp_init_win,
   1894 				    rt->rt_rmx.rmx_mtu);
   1895 		}
   1896 
   1897 		/*
   1898 		 * Resend unacknowledged packets.
   1899 		 */
   1900 		tp->snd_nxt = tp->snd_una;
   1901 		tcp_output(tp);
   1902 	}
   1903 }
   1904 #endif /* INET6 */
   1905 
   1906 /*
   1907  * Compute the MSS to advertise to the peer.  Called only during
   1908  * the 3-way handshake.  If we are the server (peer initiated
   1909  * connection), we are called with a pointer to the interface
   1910  * on which the SYN packet arrived.  If we are the client (we
   1911  * initiated connection), we are called with a pointer to the
   1912  * interface out which this connection should go.
   1913  *
   1914  * NOTE: Do not subtract IP option/extension header size nor IPsec
   1915  * header size from MSS advertisement.  MSS option must hold the maximum
   1916  * segment size we can accept, so it must always be:
   1917  *	 max(if mtu) - ip header - tcp header
   1918  */
   1919 u_long
   1920 tcp_mss_to_advertise(ifp, af)
   1921 	const struct ifnet *ifp;
   1922 	int af;
   1923 {
   1924 	extern u_long in_maxmtu;
   1925 	u_long mss = 0;
   1926 	u_long hdrsiz;
   1927 
   1928 	/*
   1929 	 * In order to avoid defeating path MTU discovery on the peer,
   1930 	 * we advertise the max MTU of all attached networks as our MSS,
   1931 	 * per RFC 1191, section 3.1.
   1932 	 *
   1933 	 * We provide the option to advertise just the MTU of
   1934 	 * the interface on which we hope this connection will
   1935 	 * be receiving.  If we are responding to a SYN, we
   1936 	 * will have a pretty good idea about this, but when
   1937 	 * initiating a connection there is a bit more doubt.
   1938 	 *
   1939 	 * We also need to ensure that loopback has a large enough
   1940 	 * MSS, as the loopback MTU is never included in in_maxmtu.
   1941 	 */
   1942 
   1943 	if (ifp != NULL)
   1944 		switch (af) {
   1945 		case AF_INET:
   1946 			mss = ifp->if_mtu;
   1947 			break;
   1948 #ifdef INET6
   1949 		case AF_INET6:
   1950 			mss = IN6_LINKMTU(ifp);
   1951 			break;
   1952 #endif
   1953 		}
   1954 
   1955 	if (tcp_mss_ifmtu == 0)
   1956 		switch (af) {
   1957 		case AF_INET:
   1958 			mss = max(in_maxmtu, mss);
   1959 			break;
   1960 #ifdef INET6
   1961 		case AF_INET6:
   1962 			mss = max(in6_maxmtu, mss);
   1963 			break;
   1964 #endif
   1965 		}
   1966 
   1967 	switch (af) {
   1968 	case AF_INET:
   1969 		hdrsiz = sizeof(struct ip);
   1970 		break;
   1971 #ifdef INET6
   1972 	case AF_INET6:
   1973 		hdrsiz = sizeof(struct ip6_hdr);
   1974 		break;
   1975 #endif
   1976 	default:
   1977 		hdrsiz = 0;
   1978 		break;
   1979 	}
   1980 	hdrsiz += sizeof(struct tcphdr);
   1981 	if (mss > hdrsiz)
   1982 		mss -= hdrsiz;
   1983 
   1984 	mss = max(tcp_mssdflt, mss);
   1985 	return (mss);
   1986 }
   1987 
   1988 /*
   1989  * Set connection variables based on the peer's advertised MSS.
   1990  * We are passed the TCPCB for the actual connection.  If we
   1991  * are the server, we are called by the compressed state engine
   1992  * when the 3-way handshake is complete.  If we are the client,
   1993  * we are called when we receive the SYN,ACK from the server.
   1994  *
   1995  * NOTE: Our advertised MSS value must be initialized in the TCPCB
   1996  * before this routine is called!
   1997  */
   1998 void
   1999 tcp_mss_from_peer(tp, offer)
   2000 	struct tcpcb *tp;
   2001 	int offer;
   2002 {
   2003 	struct socket *so;
   2004 #if defined(RTV_SPIPE) || defined(RTV_SSTHRESH)
   2005 	struct rtentry *rt;
   2006 #endif
   2007 	u_long bufsize;
   2008 	int mss;
   2009 
   2010 #ifdef DIAGNOSTIC
   2011 	if (tp->t_inpcb && tp->t_in6pcb)
   2012 		panic("tcp_mss_from_peer: both t_inpcb and t_in6pcb are set");
   2013 #endif
   2014 	so = NULL;
   2015 	rt = NULL;
   2016 #ifdef INET
   2017 	if (tp->t_inpcb) {
   2018 		so = tp->t_inpcb->inp_socket;
   2019 #if defined(RTV_SPIPE) || defined(RTV_SSTHRESH)
   2020 		rt = in_pcbrtentry(tp->t_inpcb);
   2021 #endif
   2022 	}
   2023 #endif
   2024 #ifdef INET6
   2025 	if (tp->t_in6pcb) {
   2026 		so = tp->t_in6pcb->in6p_socket;
   2027 #if defined(RTV_SPIPE) || defined(RTV_SSTHRESH)
   2028 		rt = in6_pcbrtentry(tp->t_in6pcb);
   2029 #endif
   2030 	}
   2031 #endif
   2032 
   2033 	/*
   2034 	 * As per RFC1122, use the default MSS value, unless they
   2035 	 * sent us an offer.  Do not accept offers less than 256 bytes.
   2036 	 */
   2037 	mss = tcp_mssdflt;
   2038 	if (offer)
   2039 		mss = offer;
   2040 	mss = max(mss, 256);		/* sanity */
   2041 	tp->t_peermss = mss;
   2042 	mss -= tcp_optlen(tp);
   2043 #ifdef INET
   2044 	if (tp->t_inpcb)
   2045 		mss -= ip_optlen(tp->t_inpcb);
   2046 #endif
   2047 #ifdef INET6
   2048 	if (tp->t_in6pcb)
   2049 		mss -= ip6_optlen(tp->t_in6pcb);
   2050 #endif
   2051 
   2052 	/*
   2053 	 * If there's a pipesize, change the socket buffer to that size.
   2054 	 * Make the socket buffer an integral number of MSS units.  If
   2055 	 * the MSS is larger than the socket buffer, artificially decrease
   2056 	 * the MSS.
   2057 	 */
   2058 #ifdef RTV_SPIPE
   2059 	if (rt != NULL && rt->rt_rmx.rmx_sendpipe != 0)
   2060 		bufsize = rt->rt_rmx.rmx_sendpipe;
   2061 	else
   2062 #endif
   2063 		bufsize = so->so_snd.sb_hiwat;
   2064 	if (bufsize < mss)
   2065 		mss = bufsize;
   2066 	else {
   2067 		bufsize = roundup(bufsize, mss);
   2068 		if (bufsize > sb_max)
   2069 			bufsize = sb_max;
   2070 		(void) sbreserve(&so->so_snd, bufsize, so);
   2071 	}
   2072 	tp->t_segsz = mss;
   2073 
   2074 #ifdef RTV_SSTHRESH
   2075 	if (rt != NULL && rt->rt_rmx.rmx_ssthresh) {
   2076 		/*
   2077 		 * There's some sort of gateway or interface buffer
   2078 		 * limit on the path.  Use this to set the slow
   2079 		 * start threshold, but set the threshold to no less
   2080 		 * than 2 * MSS.
   2081 		 */
   2082 		tp->snd_ssthresh = max(2 * mss, rt->rt_rmx.rmx_ssthresh);
   2083 	}
   2084 #endif
   2085 }
   2086 
   2087 /*
   2088  * Processing necessary when a TCP connection is established.
   2089  */
   2090 void
   2091 tcp_established(tp)
   2092 	struct tcpcb *tp;
   2093 {
   2094 	struct socket *so;
   2095 #ifdef RTV_RPIPE
   2096 	struct rtentry *rt;
   2097 #endif
   2098 	u_long bufsize;
   2099 
   2100 #ifdef DIAGNOSTIC
   2101 	if (tp->t_inpcb && tp->t_in6pcb)
   2102 		panic("tcp_established: both t_inpcb and t_in6pcb are set");
   2103 #endif
   2104 	so = NULL;
   2105 	rt = NULL;
   2106 #ifdef INET
   2107 	if (tp->t_inpcb) {
   2108 		so = tp->t_inpcb->inp_socket;
   2109 #if defined(RTV_RPIPE)
   2110 		rt = in_pcbrtentry(tp->t_inpcb);
   2111 #endif
   2112 	}
   2113 #endif
   2114 #ifdef INET6
   2115 	if (tp->t_in6pcb) {
   2116 		so = tp->t_in6pcb->in6p_socket;
   2117 #if defined(RTV_RPIPE)
   2118 		rt = in6_pcbrtentry(tp->t_in6pcb);
   2119 #endif
   2120 	}
   2121 #endif
   2122 
   2123 	tp->t_state = TCPS_ESTABLISHED;
   2124 	TCP_TIMER_ARM(tp, TCPT_KEEP, tcp_keepidle);
   2125 
   2126 #ifdef RTV_RPIPE
   2127 	if (rt != NULL && rt->rt_rmx.rmx_recvpipe != 0)
   2128 		bufsize = rt->rt_rmx.rmx_recvpipe;
   2129 	else
   2130 #endif
   2131 		bufsize = so->so_rcv.sb_hiwat;
   2132 	if (bufsize > tp->t_ourmss) {
   2133 		bufsize = roundup(bufsize, tp->t_ourmss);
   2134 		if (bufsize > sb_max)
   2135 			bufsize = sb_max;
   2136 		(void) sbreserve(&so->so_rcv, bufsize, so);
   2137 	}
   2138 }
   2139 
   2140 /*
   2141  * Check if there's an initial rtt or rttvar.  Convert from the
   2142  * route-table units to scaled multiples of the slow timeout timer.
   2143  * Called only during the 3-way handshake.
   2144  */
   2145 void
   2146 tcp_rmx_rtt(tp)
   2147 	struct tcpcb *tp;
   2148 {
   2149 #ifdef RTV_RTT
   2150 	struct rtentry *rt = NULL;
   2151 	int rtt;
   2152 
   2153 #ifdef DIAGNOSTIC
   2154 	if (tp->t_inpcb && tp->t_in6pcb)
   2155 		panic("tcp_rmx_rtt: both t_inpcb and t_in6pcb are set");
   2156 #endif
   2157 #ifdef INET
   2158 	if (tp->t_inpcb)
   2159 		rt = in_pcbrtentry(tp->t_inpcb);
   2160 #endif
   2161 #ifdef INET6
   2162 	if (tp->t_in6pcb)
   2163 		rt = in6_pcbrtentry(tp->t_in6pcb);
   2164 #endif
   2165 	if (rt == NULL)
   2166 		return;
   2167 
   2168 	if (tp->t_srtt == 0 && (rtt = rt->rt_rmx.rmx_rtt)) {
   2169 		/*
   2170 		 * XXX The lock bit for MTU indicates that the value
   2171 		 * is also a minimum value; this is subject to time.
   2172 		 */
   2173 		if (rt->rt_rmx.rmx_locks & RTV_RTT)
   2174 			TCPT_RANGESET(tp->t_rttmin,
   2175 			    rtt / (RTM_RTTUNIT / PR_SLOWHZ),
   2176 			    TCPTV_MIN, TCPTV_REXMTMAX);
   2177 		tp->t_srtt = rtt /
   2178 		    ((RTM_RTTUNIT / PR_SLOWHZ) >> (TCP_RTT_SHIFT + 2));
   2179 		if (rt->rt_rmx.rmx_rttvar) {
   2180 			tp->t_rttvar = rt->rt_rmx.rmx_rttvar /
   2181 			    ((RTM_RTTUNIT / PR_SLOWHZ) >>
   2182 				(TCP_RTTVAR_SHIFT + 2));
   2183 		} else {
   2184 			/* Default variation is +- 1 rtt */
   2185 			tp->t_rttvar =
   2186 			    tp->t_srtt >> (TCP_RTT_SHIFT - TCP_RTTVAR_SHIFT);
   2187 		}
   2188 		TCPT_RANGESET(tp->t_rxtcur,
   2189 		    ((tp->t_srtt >> 2) + tp->t_rttvar) >> (1 + 2),
   2190 		    tp->t_rttmin, TCPTV_REXMTMAX);
   2191 	}
   2192 #endif
   2193 }
   2194 
   2195 tcp_seq	 tcp_iss_seq = 0;	/* tcp initial seq # */
   2196 #if NRND > 0
   2197 u_int8_t tcp_iss_secret[16];	/* 128 bits; should be plenty */
   2198 #endif
   2199 
   2200 /*
   2201  * Get a new sequence value given a tcp control block
   2202  */
   2203 tcp_seq
   2204 tcp_new_iss(struct tcpcb *tp, tcp_seq addin)
   2205 {
   2206 
   2207 #ifdef INET
   2208 	if (tp->t_inpcb != NULL) {
   2209 		return (tcp_new_iss1(&tp->t_inpcb->inp_laddr,
   2210 		    &tp->t_inpcb->inp_faddr, tp->t_inpcb->inp_lport,
   2211 		    tp->t_inpcb->inp_fport, sizeof(tp->t_inpcb->inp_laddr),
   2212 		    addin));
   2213 	}
   2214 #endif
   2215 #ifdef INET6
   2216 	if (tp->t_in6pcb != NULL) {
   2217 		return (tcp_new_iss1(&tp->t_in6pcb->in6p_laddr,
   2218 		    &tp->t_in6pcb->in6p_faddr, tp->t_in6pcb->in6p_lport,
   2219 		    tp->t_in6pcb->in6p_fport, sizeof(tp->t_in6pcb->in6p_laddr),
   2220 		    addin));
   2221 	}
   2222 #endif
   2223 	/* Not possible. */
   2224 	panic("tcp_new_iss");
   2225 }
   2226 
   2227 /*
   2228  * This routine actually generates a new TCP initial sequence number.
   2229  */
   2230 tcp_seq
   2231 tcp_new_iss1(void *laddr, void *faddr, u_int16_t lport, u_int16_t fport,
   2232     size_t addrsz, tcp_seq addin)
   2233 {
   2234 	tcp_seq tcp_iss;
   2235 
   2236 #if NRND > 0
   2237 	static int beenhere;
   2238 
   2239 	/*
   2240 	 * If we haven't been here before, initialize our cryptographic
   2241 	 * hash secret.
   2242 	 */
   2243 	if (beenhere == 0) {
   2244 		rnd_extract_data(tcp_iss_secret, sizeof(tcp_iss_secret),
   2245 		    RND_EXTRACT_ANY);
   2246 		beenhere = 1;
   2247 	}
   2248 
   2249 	if (tcp_do_rfc1948) {
   2250 		MD5_CTX ctx;
   2251 		u_int8_t hash[16];	/* XXX MD5 knowledge */
   2252 
   2253 		/*
   2254 		 * Compute the base value of the ISS.  It is a hash
   2255 		 * of (saddr, sport, daddr, dport, secret).
   2256 		 */
   2257 		MD5Init(&ctx);
   2258 
   2259 		MD5Update(&ctx, (u_char *) laddr, addrsz);
   2260 		MD5Update(&ctx, (u_char *) &lport, sizeof(lport));
   2261 
   2262 		MD5Update(&ctx, (u_char *) faddr, addrsz);
   2263 		MD5Update(&ctx, (u_char *) &fport, sizeof(fport));
   2264 
   2265 		MD5Update(&ctx, tcp_iss_secret, sizeof(tcp_iss_secret));
   2266 
   2267 		MD5Final(hash, &ctx);
   2268 
   2269 		memcpy(&tcp_iss, hash, sizeof(tcp_iss));
   2270 
   2271 		/*
   2272 		 * Now increment our "timer", and add it in to
   2273 		 * the computed value.
   2274 		 *
   2275 		 * XXX Use `addin'?
   2276 		 * XXX TCP_ISSINCR too large to use?
   2277 		 */
   2278 		tcp_iss_seq += TCP_ISSINCR;
   2279 #ifdef TCPISS_DEBUG
   2280 		printf("ISS hash 0x%08x, ", tcp_iss);
   2281 #endif
   2282 		tcp_iss += tcp_iss_seq + addin;
   2283 #ifdef TCPISS_DEBUG
   2284 		printf("new ISS 0x%08x\n", tcp_iss);
   2285 #endif
   2286 	} else
   2287 #endif /* NRND > 0 */
   2288 	{
   2289 		/*
   2290 		 * Randomize.
   2291 		 */
   2292 #if NRND > 0
   2293 		rnd_extract_data(&tcp_iss, sizeof(tcp_iss), RND_EXTRACT_ANY);
   2294 #else
   2295 		tcp_iss = arc4random();
   2296 #endif
   2297 
   2298 		/*
   2299 		 * If we were asked to add some amount to a known value,
   2300 		 * we will take a random value obtained above, mask off
   2301 		 * the upper bits, and add in the known value.  We also
   2302 		 * add in a constant to ensure that we are at least a
   2303 		 * certain distance from the original value.
   2304 		 *
   2305 		 * This is used when an old connection is in timed wait
   2306 		 * and we have a new one coming in, for instance.
   2307 		 */
   2308 		if (addin != 0) {
   2309 #ifdef TCPISS_DEBUG
   2310 			printf("Random %08x, ", tcp_iss);
   2311 #endif
   2312 			tcp_iss &= TCP_ISS_RANDOM_MASK;
   2313 			tcp_iss += addin + TCP_ISSINCR;
   2314 #ifdef TCPISS_DEBUG
   2315 			printf("Old ISS %08x, ISS %08x\n", addin, tcp_iss);
   2316 #endif
   2317 		} else {
   2318 			tcp_iss &= TCP_ISS_RANDOM_MASK;
   2319 			tcp_iss += tcp_iss_seq;
   2320 			tcp_iss_seq += TCP_ISSINCR;
   2321 #ifdef TCPISS_DEBUG
   2322 			printf("ISS %08x\n", tcp_iss);
   2323 #endif
   2324 		}
   2325 	}
   2326 
   2327 	if (tcp_compat_42) {
   2328 		/*
   2329 		 * Limit it to the positive range for really old TCP
   2330 		 * implementations.
   2331 		 * Just AND off the top bit instead of checking if
   2332 		 * is set first - saves a branch 50% of the time.
   2333 		 */
   2334 		tcp_iss &= 0x7fffffff;		/* XXX */
   2335 	}
   2336 
   2337 	return (tcp_iss);
   2338 }
   2339 
   2340 #if defined(IPSEC) || defined(FAST_IPSEC)
   2341 /* compute ESP/AH header size for TCP, including outer IP header. */
   2342 size_t
   2343 ipsec4_hdrsiz_tcp(tp)
   2344 	struct tcpcb *tp;
   2345 {
   2346 	struct inpcb *inp;
   2347 	size_t hdrsiz;
   2348 
   2349 	/* XXX mapped addr case (tp->t_in6pcb) */
   2350 	if (!tp || !tp->t_template || !(inp = tp->t_inpcb))
   2351 		return 0;
   2352 	switch (tp->t_family) {
   2353 	case AF_INET:
   2354 		/* XXX: should use currect direction. */
   2355 		hdrsiz = ipsec4_hdrsiz(tp->t_template, IPSEC_DIR_OUTBOUND, inp);
   2356 		break;
   2357 	default:
   2358 		hdrsiz = 0;
   2359 		break;
   2360 	}
   2361 
   2362 	return hdrsiz;
   2363 }
   2364 
   2365 #ifdef INET6
   2366 size_t
   2367 ipsec6_hdrsiz_tcp(tp)
   2368 	struct tcpcb *tp;
   2369 {
   2370 	struct in6pcb *in6p;
   2371 	size_t hdrsiz;
   2372 
   2373 	if (!tp || !tp->t_template || !(in6p = tp->t_in6pcb))
   2374 		return 0;
   2375 	switch (tp->t_family) {
   2376 	case AF_INET6:
   2377 		/* XXX: should use currect direction. */
   2378 		hdrsiz = ipsec6_hdrsiz(tp->t_template, IPSEC_DIR_OUTBOUND, in6p);
   2379 		break;
   2380 	case AF_INET:
   2381 		/* mapped address case - tricky */
   2382 	default:
   2383 		hdrsiz = 0;
   2384 		break;
   2385 	}
   2386 
   2387 	return hdrsiz;
   2388 }
   2389 #endif
   2390 #endif /*IPSEC*/
   2391 
   2392 /*
   2393  * Determine the length of the TCP options for this connection.
   2394  *
   2395  * XXX:  What do we do for SACK, when we add that?  Just reserve
   2396  *       all of the space?  Otherwise we can't exactly be incrementing
   2397  *       cwnd by an amount that varies depending on the amount we last
   2398  *       had to SACK!
   2399  */
   2400 
   2401 u_int
   2402 tcp_optlen(tp)
   2403 	struct tcpcb *tp;
   2404 {
   2405 	u_int optlen;
   2406 
   2407 	optlen = 0;
   2408 	if ((tp->t_flags & (TF_REQ_TSTMP|TF_RCVD_TSTMP|TF_NOOPT)) ==
   2409 	    (TF_REQ_TSTMP | TF_RCVD_TSTMP))
   2410 		optlen += TCPOLEN_TSTAMP_APPA;
   2411 
   2412 #ifdef TCP_SIGNATURE
   2413 #if defined(INET6) && defined(FAST_IPSEC)
   2414 	if (tp->t_family == AF_INET)
   2415 #endif
   2416 	if (tp->t_flags & TF_SIGNATURE)
   2417 		optlen += TCPOLEN_SIGNATURE + 2;
   2418 #endif /* TCP_SIGNATURE */
   2419 
   2420 	return optlen;
   2421 }
   2422