Home | History | Annotate | Line # | Download | only in netinet
tcp_subr.c revision 1.70
      1 /*	$NetBSD: tcp_subr.c,v 1.70 1999/07/09 22:57:22 thorpej 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 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. All advertising materials mentioning features or use of this software
     82  *    must display the following acknowledgement:
     83  *	This product includes software developed by the University of
     84  *	California, Berkeley and its contributors.
     85  * 4. Neither the name of the University nor the names of its contributors
     86  *    may be used to endorse or promote products derived from this software
     87  *    without specific prior written permission.
     88  *
     89  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
     90  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     91  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     92  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
     93  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     94  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     95  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     96  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     97  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     98  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     99  * SUCH DAMAGE.
    100  *
    101  *	@(#)tcp_subr.c	8.2 (Berkeley) 5/24/95
    102  */
    103 
    104 #include "opt_inet.h"
    105 #include "opt_ipsec.h"
    106 #include "opt_tcp_compat_42.h"
    107 #include "rnd.h"
    108 
    109 #include <sys/param.h>
    110 #include <sys/proc.h>
    111 #include <sys/systm.h>
    112 #include <sys/malloc.h>
    113 #include <sys/mbuf.h>
    114 #include <sys/socket.h>
    115 #include <sys/socketvar.h>
    116 #include <sys/protosw.h>
    117 #include <sys/errno.h>
    118 #include <sys/kernel.h>
    119 #include <sys/pool.h>
    120 #if NRND > 0
    121 #include <sys/rnd.h>
    122 #endif
    123 
    124 #include <net/route.h>
    125 #include <net/if.h>
    126 
    127 #include <netinet/in.h>
    128 #include <netinet/in_systm.h>
    129 #include <netinet/ip.h>
    130 #include <netinet/in_pcb.h>
    131 #include <netinet/ip_var.h>
    132 #include <netinet/ip_icmp.h>
    133 
    134 #ifdef INET6
    135 #ifndef INET
    136 #include <netinet/in.h>
    137 #endif
    138 #include <netinet/ip6.h>
    139 #include <netinet6/in6_pcb.h>
    140 #include <netinet6/ip6_var.h>
    141 #endif
    142 
    143 #include <netinet/tcp.h>
    144 #include <netinet/tcp_fsm.h>
    145 #include <netinet/tcp_seq.h>
    146 #include <netinet/tcp_timer.h>
    147 #include <netinet/tcp_var.h>
    148 #include <netinet/tcpip.h>
    149 
    150 #ifdef IPSEC
    151 #include <netinet6/ipsec.h>
    152 #include <netinet6/ah.h>
    153 #ifdef IPSEC_ESP
    154 #include <netinet6/esp.h>
    155 #endif
    156 #endif /*IPSEC*/
    157 
    158 #ifdef INET6
    159 struct in6pcb tcb6;
    160 #endif
    161 
    162 /* patchable/settable parameters for tcp */
    163 int 	tcp_mssdflt = TCP_MSS;
    164 int 	tcp_rttdflt = TCPTV_SRTTDFLT / PR_SLOWHZ;
    165 int	tcp_do_rfc1323 = 1;	/* window scaling / timestamps (obsolete) */
    166 int	tcp_do_sack = 1;	/* selective acknowledgement */
    167 int	tcp_do_win_scale = 1;	/* RFC1323 window scaling */
    168 int	tcp_do_timestamps = 1;	/* RFC1323 timestamps */
    169 int	tcp_do_newreno = 0;	/* Use the New Reno algorithms */
    170 int	tcp_ack_on_push = 0;	/* set to enable immediate ACK-on-PUSH */
    171 int	tcp_init_win = 1;
    172 int	tcp_mss_ifmtu = 0;
    173 #ifdef TCP_COMPAT_42
    174 int	tcp_compat_42 = 1;
    175 #else
    176 int	tcp_compat_42 = 0;
    177 #endif
    178 
    179 #ifndef TCBHASHSIZE
    180 #define	TCBHASHSIZE	128
    181 #endif
    182 int	tcbhashsize = TCBHASHSIZE;
    183 
    184 int	tcp_freeq __P((struct tcpcb *));
    185 
    186 struct pool tcpcb_pool;
    187 
    188 /*
    189  * Tcp initialization
    190  */
    191 void
    192 tcp_init()
    193 {
    194 	int hlen;
    195 
    196 	pool_init(&tcpcb_pool, sizeof(struct tcpcb), 0, 0, 0, "tcpcbpl",
    197 	    0, NULL, NULL, M_PCB);
    198 	in_pcbinit(&tcbtable, tcbhashsize, tcbhashsize);
    199 #ifdef INET6
    200 	tcb6.in6p_next = tcb6.in6p_prev = &tcb6;
    201 #endif
    202 	LIST_INIT(&tcp_delacks);
    203 
    204 	hlen = sizeof(struct ip) + sizeof(struct tcphdr);
    205 #ifdef INET6
    206 	if (sizeof(struct ip) < sizeof(struct ip6_hdr))
    207 		hlen = sizeof(struct ip6_hdr) + sizeof(struct tcphdr);
    208 #endif
    209 	if (max_protohdr < hlen)
    210 		max_protohdr = hlen;
    211 	if (max_linkhdr + hlen > MHLEN)
    212 		panic("tcp_init");
    213 
    214 	/* Initialize the compressed state engine. */
    215 	syn_cache_init();
    216 }
    217 
    218 /*
    219  * Create template to be used to send tcp packets on a connection.
    220  * Call after host entry created, allocates an mbuf and fills
    221  * in a skeletal tcp/ip header, minimizing the amount of work
    222  * necessary when the connection is used.
    223  */
    224 struct mbuf *
    225 tcp_template(tp)
    226 	struct tcpcb *tp;
    227 {
    228 	register struct inpcb *inp = tp->t_inpcb;
    229 #ifdef INET6
    230 	register struct in6pcb *in6p = tp->t_in6pcb;
    231 #endif
    232 	register struct tcphdr *n;
    233 	register struct mbuf *m;
    234 	int hlen;
    235 
    236 	switch (tp->t_family) {
    237 	case AF_INET:
    238 		hlen = sizeof(struct ip);
    239 		if (inp)
    240 			break;
    241 #ifdef INET6
    242 		if (in6p) {
    243 			/* mapped addr case */
    244 			if (IN6_IS_ADDR_V4MAPPED(&in6p->in6p_laddr)
    245 			 && IN6_IS_ADDR_V4MAPPED(&in6p->in6p_faddr))
    246 				break;
    247 		}
    248 #endif
    249 		return NULL;	/*EINVAL*/
    250 #ifdef INET6
    251 	case AF_INET6:
    252 		hlen = sizeof(struct ip6_hdr);
    253 		if (in6p) {
    254 			/* more sainty check? */
    255 			break;
    256 		}
    257 		return NULL;	/*EINVAL*/
    258 #endif
    259 	default:
    260 		hlen = 0;	/*pacify gcc*/
    261 		return NULL;	/*EAFNOSUPPORT*/
    262 	}
    263 	if ((m = tp->t_template) == 0) {
    264 		MGETHDR(m, M_DONTWAIT, MT_HEADER);
    265 		if (m) {
    266 			MCLGET(m, M_DONTWAIT);
    267 			if ((m->m_flags & M_EXT) == 0) {
    268 				m_free(m);
    269 				m = NULL;
    270 			}
    271 		}
    272 		if (m == NULL)
    273 			return NULL;
    274 		m->m_len = hlen + sizeof(struct tcphdr);
    275 	}
    276 	bzero(mtod(m, caddr_t), m->m_len);
    277 	switch (tp->t_family) {
    278 	case AF_INET:
    279 	    {
    280 		struct ipovly *ipov;
    281 		mtod(m, struct ip *)->ip_v = 4;
    282 		ipov = mtod(m, struct ipovly *);
    283 		ipov->ih_pr = IPPROTO_TCP;
    284 		ipov->ih_len = htons(sizeof(struct tcphdr));
    285 		if (inp) {
    286 			ipov->ih_src = inp->inp_laddr;
    287 			ipov->ih_dst = inp->inp_faddr;
    288 		}
    289 #ifdef INET6
    290 		else if (in6p) {
    291 			/* mapped addr case */
    292 			bcopy(&in6p->in6p_laddr.s6_addr32[3], &ipov->ih_src,
    293 				sizeof(ipov->ih_src));
    294 			bcopy(&in6p->in6p_faddr.s6_addr32[3], &ipov->ih_dst,
    295 				sizeof(ipov->ih_dst));
    296 		}
    297 #endif
    298 		break;
    299 	    }
    300 #ifdef INET6
    301 	case AF_INET6:
    302 	    {
    303 		struct ip6_hdr *ip6;
    304 		mtod(m, struct ip *)->ip_v = 6;
    305 		ip6 = mtod(m, struct ip6_hdr *);
    306 		ip6->ip6_nxt = IPPROTO_TCP;
    307 		ip6->ip6_plen = htons(sizeof(struct tcphdr));
    308 		ip6->ip6_src = in6p->in6p_laddr;
    309 		ip6->ip6_dst = in6p->in6p_faddr;
    310 		ip6->ip6_flow = in6p->in6p_flowinfo & IPV6_FLOWINFO_MASK;
    311 		if (ip6_auto_flowlabel) {
    312 			ip6->ip6_flow &= ~IPV6_FLOWLABEL_MASK;
    313 			ip6->ip6_flow |=
    314 				(htonl(ip6_flow_seq++) & IPV6_FLOWLABEL_MASK);
    315 		}
    316 		ip6->ip6_vfc = IPV6_VERSION;
    317 		break;
    318 	    }
    319 #endif
    320 	}
    321 	n = (struct tcphdr *)(mtod(m, caddr_t) + hlen);
    322 	if (inp) {
    323 		n->th_sport = inp->inp_lport;
    324 		n->th_dport = inp->inp_fport;
    325 	}
    326 #ifdef INET6
    327 	else if (in6p) {
    328 		n->th_sport = in6p->in6p_lport;
    329 		n->th_dport = in6p->in6p_fport;
    330 	}
    331 #endif
    332 	n->th_seq = 0;
    333 	n->th_ack = 0;
    334 	n->th_x2 = 0;
    335 	n->th_off = 5;
    336 	n->th_flags = 0;
    337 	n->th_win = 0;
    338 	n->th_sum = 0;
    339 	n->th_urp = 0;
    340 	return (m);
    341 }
    342 
    343 /*
    344  * Send a single message to the TCP at address specified by
    345  * the given TCP/IP header.  If m == 0, then we make a copy
    346  * of the tcpiphdr at ti and send directly to the addressed host.
    347  * This is used to force keep alive messages out using the TCP
    348  * template for a connection tp->t_template.  If flags are given
    349  * then we send a message back to the TCP which originated the
    350  * segment ti, and discard the mbuf containing it and any other
    351  * attached mbufs.
    352  *
    353  * In any case the ack and sequence number of the transmitted
    354  * segment are as specified by the parameters.
    355  */
    356 int
    357 tcp_respond(tp, template, m, ack, seq, flags)
    358 	struct tcpcb *tp;
    359 	struct mbuf *template;		/* XXX should be struct mbuf? */
    360 	register struct mbuf *m;
    361 	tcp_seq ack, seq;
    362 	int flags;
    363 {
    364 #ifndef INET6
    365 	struct route iproute;
    366 #else
    367 	struct route_in6 iproute;	/* sizeof(route_in6) > sizeof(route) */
    368 #endif
    369 	struct route *ro;
    370 	struct rtentry *rt;
    371 	int error, tlen, win = 0;
    372 	int hlen;
    373 	struct ip *ip;
    374 #ifdef INET6
    375 	struct ip6_hdr *ip6;
    376 #endif
    377 	int family;	/* family on packet, not inpcb/in6pcb! */
    378 	struct tcphdr *th;
    379 
    380 	if (tp != NULL && (flags & TH_RST) == 0) {
    381 		if (tp->t_inpcb)
    382 			win = sbspace(&tp->t_inpcb->inp_socket->so_rcv);
    383 #ifdef INET6
    384 		else if (tp->t_in6pcb)
    385 			win = sbspace(&tp->t_in6pcb->in6p_socket->so_rcv);
    386 #endif
    387 	}
    388 
    389 	ip = NULL;
    390 #ifdef INET6
    391 	ip6 = NULL;
    392 #endif
    393 	if (m == 0) {
    394 		if (template
    395 		 && template->m_len < hlen + sizeof(struct tcphdr)) {
    396 			if (m)
    397 				m_freem(m);
    398 			return EINVAL;
    399 		}
    400 
    401 		/* get family information from template */
    402 		switch (mtod(template, struct ip *)->ip_v) {
    403 		case 4:
    404 			family = AF_INET;
    405 			hlen = sizeof(struct ip);
    406 			break;
    407 #ifdef INET6
    408 		case 6:
    409 			family = AF_INET6;
    410 			hlen = sizeof(struct ip6_hdr);
    411 			break;
    412 #endif
    413 		default:
    414 			if (m)
    415 				m_freem(m);
    416 			return EAFNOSUPPORT;
    417 		}
    418 
    419 		MGETHDR(m, M_DONTWAIT, MT_HEADER);
    420 		if (m) {
    421 			MCLGET(m, M_DONTWAIT);
    422 			if ((m->m_flags & M_EXT)) {
    423 				m_free(m);
    424 				m = NULL;
    425 			}
    426 		}
    427 		if (m == NULL)
    428 			return (ENOBUFS);
    429 
    430 		if (tcp_compat_42)
    431 			tlen = 1;
    432 		else
    433 			tlen = 0;
    434 
    435 		m->m_data += max_linkhdr;
    436 		bcopy(mtod(template, caddr_t), mtod(m, caddr_t),
    437 			template->m_len);
    438 		switch (family) {
    439 		case AF_INET:
    440 			ip = mtod(m, struct ip *);
    441 			th = (struct tcphdr *)(ip + 1);
    442 			break;
    443 #ifdef INET6
    444 		case AF_INET6:
    445 			ip6 = mtod(m, struct ip6_hdr *);
    446 			th = (struct tcphdr *)(ip6 + 1);
    447 			break;
    448 #endif
    449 		default:	/*pacify gcc*/
    450 			ip = NULL;
    451 #ifdef INET6
    452 			ip6 = NULL;
    453 #endif
    454 			th = NULL;
    455 			break;
    456 		}
    457 		flags = TH_ACK;
    458 	} else {
    459 		/* get family information from m */
    460 		switch (mtod(m, struct ip *)->ip_v) {
    461 		case 4:
    462 			family = AF_INET;
    463 			hlen = sizeof(struct ip);
    464 			break;
    465 #ifdef INET6
    466 		case 6:
    467 			family = AF_INET6;
    468 			hlen = sizeof(struct ip6_hdr);
    469 			break;
    470 #endif
    471 		default:
    472 			if (m)
    473 				m_freem(m);
    474 			return EAFNOSUPPORT;
    475 		}
    476 
    477 		/* template pointer almost has no meaning */
    478 		m_freem(m->m_next);
    479 		m->m_next = 0;
    480 		m->m_len = hlen + sizeof(struct tcphdr);
    481 		if ((m->m_flags & M_PKTHDR) == 0) {
    482 			printf("non PKTHDR to tcp_respond\n");
    483 			m_freem(m);
    484 			return EINVAL;
    485 		}
    486 
    487 		tlen = 0;
    488 #define xchg(a,b,type) { type t; t=a; a=b; b=t; }
    489 		switch (family) {
    490 		case AF_INET:
    491 			ip = mtod(m, struct ip *);
    492 			th = (struct tcphdr *)(ip + 1);
    493 			xchg(ip->ip_dst, ip->ip_src, struct in_addr);
    494 			break;
    495 #ifdef INET6
    496 		case AF_INET6:
    497 			ip6 = mtod(m, struct ip6_hdr *);
    498 			th = (struct tcphdr *)(ip6 + 1);
    499 			xchg(ip6->ip6_dst, ip6->ip6_src, struct in6_addr);
    500 			break;
    501 #endif
    502 		}
    503 		xchg(th->th_dport, th->th_sport, u_int16_t);
    504 #undef xchg
    505 	}
    506 	th->th_seq = htonl(seq);
    507 	th->th_ack = htonl(ack);
    508 	th->th_x2 = 0;
    509 	if ((flags & TH_SYN) == 0) {
    510 		if (tp)
    511 			th->th_win = htons((u_int16_t) (win >> tp->rcv_scale));
    512 		else
    513 			th->th_win = htons((u_int16_t)win);
    514 		th->th_off = sizeof (struct tcphdr) >> 2;
    515 		tlen += sizeof (struct tcphdr);
    516 	} else
    517 		tlen += th->th_off << 2;
    518 	m->m_len = hlen + tlen;
    519 	m->m_pkthdr.len = hlen + tlen;
    520 	m->m_pkthdr.rcvif = (struct ifnet *) 0;
    521 	th->th_flags = flags;
    522 	th->th_urp = 0;
    523 
    524 	switch (family) {
    525 	case AF_INET:
    526 	    {
    527 		struct ipovly *ipov = (struct ipovly *)ip;
    528 		bzero(ipov->ih_x1, sizeof ipov->ih_x1);
    529 		ipov->ih_len = htons((u_int16_t)tlen);
    530 
    531 		th->th_sum = 0;
    532 		th->th_sum = in_cksum(m, hlen + tlen);
    533 		ip->ip_len = hlen + tlen;	/*will be flipped on output*/
    534 		ip->ip_ttl = ip_defttl;
    535 		break;
    536 	    }
    537 #ifdef INET6
    538 	case AF_INET6:
    539 	    {
    540 		th->th_sum = 0;
    541 		th->th_sum = in6_cksum(m, IPPROTO_TCP, sizeof(struct ip6_hdr),
    542 				tlen);
    543 		ip6->ip6_plen = ntohs(tlen);
    544 		ip6->ip6_hlim = ip6_defhlim;
    545 		ip6->ip6_flow &= ~IPV6_FLOWINFO_MASK;
    546 		if (ip6_auto_flowlabel) {
    547 			ip6->ip6_flow |=
    548 				(htonl(ip6_flow_seq++) & IPV6_FLOWLABEL_MASK);
    549 		}
    550 		break;
    551 	    }
    552 #endif
    553 	}
    554 
    555 #ifdef IPSEC
    556 	m->m_pkthdr.rcvif = NULL;
    557 #endif /*IPSEC*/
    558 
    559 	/*
    560 	 * If we're doing Path MTU discovery, we need to set DF unless
    561 	 * the route's MTU is locked.  If we lack a route, we need to
    562 	 * look it up now.
    563 	 *
    564 	 * ip_output() could do this for us, but it's convenient to just
    565 	 * do it here unconditionally.
    566 	 */
    567 	if (tp != NULL && tp->t_inpcb != NULL) {
    568 		ro = &tp->t_inpcb->inp_route;
    569 #ifdef IPSEC
    570 		m->m_pkthdr.rcvif = (struct ifnet *)tp->t_inpcb->inp_socket;
    571 #endif
    572 #ifdef DIAGNOSTIC
    573 		if (family != AF_INET)
    574 			panic("tcp_respond: address family mismatch");
    575 		if (!in_hosteq(ip->ip_dst, tp->t_inpcb->inp_faddr)) {
    576 			panic("tcp_respond: ip_dst %x != inp_faddr %x",
    577 			    ntohl(ip->ip_dst.s_addr),
    578 			    ntohl(tp->t_inpcb->inp_faddr.s_addr));
    579 		}
    580 #endif
    581 	}
    582 #ifdef INET6
    583 	else if (tp != NULL && tp->t_in6pcb != NULL) {
    584 		ro = (struct route *)&tp->t_in6pcb->in6p_route;
    585 #ifdef IPSEC
    586 		m->m_pkthdr.rcvif = (struct ifnet *)tp->t_in6pcb->in6p_socket;
    587 #endif
    588 #ifdef DIAGNOSTIC
    589 		if (family == AF_INET) {
    590 			if (!IN6_IS_ADDR_V4MAPPED(&tp->t_in6pcb->in6p_faddr))
    591 				panic("tcp_respond: not mapped addr");
    592 			if (bcmp(&ip->ip_dst,
    593 					&tp->t_in6pcb->in6p_faddr.s6_addr32[3],
    594 					sizeof(ip->ip_dst)) != 0) {
    595 				panic("tcp_respond: ip_dst != in6p_faddr");
    596 			}
    597 		} else if (family == AF_INET6) {
    598 			if (!IN6_ARE_ADDR_EQUAL(&ip6->ip6_dst, &tp->t_in6pcb->in6p_faddr))
    599 				panic("tcp_respond: ip6_dst != in6p_faddr");
    600 		} else
    601 			panic("tcp_respond: address family mismatch");
    602 #endif
    603 	}
    604 #endif
    605 	else {
    606 		ro = (struct route *)&iproute;
    607 		bzero(ro, sizeof(iproute));
    608 	}
    609 	if ((rt = ro->ro_rt) == NULL || (rt->rt_flags & RTF_UP) == 0) {
    610 		if (ro->ro_rt != NULL) {
    611 			RTFREE(ro->ro_rt);
    612 			ro->ro_rt = NULL;
    613 		}
    614 		switch (family) {
    615 		case AF_INET:
    616 		    {
    617 			struct sockaddr_in *dst;
    618 			dst = satosin(&ro->ro_dst);
    619 			dst->sin_family = AF_INET;
    620 			dst->sin_len = sizeof(*dst);
    621 			dst->sin_addr = ip->ip_dst;
    622 			break;
    623 		    }
    624 #ifdef INET6
    625 		case AF_INET6:
    626 		    {
    627 			struct sockaddr_in6 *dst;
    628 			dst = satosin6(&ro->ro_dst);
    629 			bzero(dst, sizeof(*dst));
    630 			dst->sin6_family = AF_INET6;
    631 			dst->sin6_len = sizeof(*dst);
    632 			dst->sin6_addr = ip6->ip6_dst;
    633 			break;
    634 		    }
    635 #endif
    636 		}
    637 		rtalloc(ro);
    638 		if ((rt = ro->ro_rt) == NULL) {
    639 			m_freem(m);
    640 			switch (family) {
    641 			case AF_INET:
    642 				ipstat.ips_noroute++;
    643 				break;
    644 #ifdef INET6
    645 			case AF_INET6:
    646 				ip6stat.ip6s_noroute++;
    647 				break;
    648 #endif
    649 			}
    650 			return (EHOSTUNREACH);
    651 		}
    652 	}
    653 	switch (family) {
    654 	case AF_INET:
    655 		if (ip_mtudisc != 0 && (rt->rt_rmx.rmx_locks & RTV_MTU) == 0)
    656 			ip->ip_off |= IP_DF;
    657 
    658 		error = ip_output(m, NULL, ro, 0, NULL);
    659 		break;
    660 #ifdef INET6
    661 	case AF_INET6:
    662 		error = ip6_output(m, NULL, (struct route_in6 *)ro, 0, NULL);
    663 		break;
    664 #endif
    665 	default:
    666 		error = EAFNOSUPPORT;
    667 		break;
    668 	}
    669 
    670 	if (ro == (struct route *)&iproute) {
    671 		RTFREE(ro->ro_rt);
    672 		ro->ro_rt = NULL;
    673 	}
    674 
    675 	return (error);
    676 }
    677 
    678 /*
    679  * Create a new TCP control block, making an
    680  * empty reassembly queue and hooking it to the argument
    681  * protocol control block.
    682  */
    683 struct tcpcb *
    684 tcp_newtcpcb(family, aux)
    685 	int family;	/* selects inpcb, or in6pcb */
    686 	void *aux;
    687 {
    688 	register struct tcpcb *tp;
    689 
    690 	switch (family) {
    691 	case PF_INET:
    692 		break;
    693 #ifdef INET6
    694 	case PF_INET6:
    695 		break;
    696 #endif
    697 	default:
    698 		return NULL;
    699 	}
    700 
    701 	tp = pool_get(&tcpcb_pool, PR_NOWAIT);
    702 	if (tp == NULL)
    703 		return (NULL);
    704 	bzero((caddr_t)tp, sizeof(struct tcpcb));
    705 	LIST_INIT(&tp->segq);
    706 	LIST_INIT(&tp->timeq);
    707 	tp->t_family = family;		/* may be overridden later on */
    708 	tp->t_peermss = tcp_mssdflt;
    709 	tp->t_ourmss = tcp_mssdflt;
    710 	tp->t_segsz = tcp_mssdflt;
    711 
    712 	tp->t_flags = 0;
    713 	if (tcp_do_rfc1323 && tcp_do_win_scale)
    714 		tp->t_flags |= TF_REQ_SCALE;
    715 	if (tcp_do_rfc1323 && tcp_do_timestamps)
    716 		tp->t_flags |= TF_REQ_TSTMP;
    717 	if (tcp_do_sack == 2)
    718 		tp->t_flags |= TF_WILL_SACK;
    719 	else if (tcp_do_sack == 1)
    720 		tp->t_flags |= TF_WILL_SACK|TF_IGNR_RXSACK;
    721 	tp->t_flags |= TF_CANT_TXSACK;
    722 	switch (family) {
    723 	case PF_INET:
    724 		tp->t_inpcb = (struct inpcb *)aux;
    725 		break;
    726 #ifdef INET6
    727 	case PF_INET6:
    728 		tp->t_in6pcb = (struct in6pcb *)aux;
    729 		break;
    730 #endif
    731 	}
    732 	/*
    733 	 * Init srtt to TCPTV_SRTTBASE (0), so we can tell that we have no
    734 	 * rtt estimate.  Set rttvar so that srtt + 2 * rttvar gives
    735 	 * reasonable initial retransmit time.
    736 	 */
    737 	tp->t_srtt = TCPTV_SRTTBASE;
    738 	tp->t_rttvar = tcp_rttdflt * PR_SLOWHZ << (TCP_RTTVAR_SHIFT + 2 - 1);
    739 	tp->t_rttmin = TCPTV_MIN;
    740 	TCPT_RANGESET(tp->t_rxtcur, TCP_REXMTVAL(tp),
    741 	    TCPTV_MIN, TCPTV_REXMTMAX);
    742 	tp->snd_cwnd = TCP_MAXWIN << TCP_MAX_WINSHIFT;
    743 	tp->snd_ssthresh = TCP_MAXWIN << TCP_MAX_WINSHIFT;
    744 	if (family == AF_INET) {
    745 		struct inpcb *inp = (struct inpcb *)aux;
    746 		inp->inp_ip.ip_ttl = ip_defttl;
    747 		inp->inp_ppcb = (caddr_t)tp;
    748 	}
    749 #ifdef INET6
    750 	else if (family == AF_INET6) {
    751 		struct in6pcb *in6p = (struct in6pcb *)aux;
    752 		in6p->in6p_ip6.ip6_hlim = ip6_defhlim;
    753 		in6p->in6p_ppcb = (caddr_t)tp;
    754 	}
    755 #endif
    756 	return (tp);
    757 }
    758 
    759 /*
    760  * Drop a TCP connection, reporting
    761  * the specified error.  If connection is synchronized,
    762  * then send a RST to peer.
    763  */
    764 struct tcpcb *
    765 tcp_drop(tp, errno)
    766 	register struct tcpcb *tp;
    767 	int errno;
    768 {
    769 	struct socket *so;
    770 
    771 	if (tp->t_inpcb)
    772 		so = tp->t_inpcb->inp_socket;
    773 #ifdef INET6
    774 	else if (tp->t_in6pcb)
    775 		so = tp->t_in6pcb->in6p_socket;
    776 #endif
    777 	else
    778 		return NULL;
    779 
    780 	if (TCPS_HAVERCVDSYN(tp->t_state)) {
    781 		tp->t_state = TCPS_CLOSED;
    782 		(void) tcp_output(tp);
    783 		tcpstat.tcps_drops++;
    784 	} else
    785 		tcpstat.tcps_conndrops++;
    786 	if (errno == ETIMEDOUT && tp->t_softerror)
    787 		errno = tp->t_softerror;
    788 	so->so_error = errno;
    789 	return (tcp_close(tp));
    790 }
    791 
    792 /*
    793  * Close a TCP control block:
    794  *	discard all space held by the tcp
    795  *	discard internet protocol block
    796  *	wake up any sleepers
    797  */
    798 struct tcpcb *
    799 tcp_close(tp)
    800 	register struct tcpcb *tp;
    801 {
    802 	struct inpcb *inp;
    803 #ifdef INET6
    804 	struct in6pcb *in6p;
    805 #endif
    806 	struct socket *so;
    807 #ifdef RTV_RTT
    808 	register struct rtentry *rt;
    809 #endif
    810 	struct route *ro;
    811 
    812 	inp = tp->t_inpcb;
    813 #ifdef INET6
    814 	in6p = tp->t_in6pcb;
    815 #endif
    816 	so = NULL;
    817 	ro = NULL;
    818 	if (inp) {
    819 		so = inp->inp_socket;
    820 		ro = &inp->inp_route;
    821 	}
    822 #ifdef INET6
    823 	else if (in6p) {
    824 		so = in6p->in6p_socket;
    825 		ro = (struct route *)&in6p->in6p_route;
    826 	}
    827 #endif
    828 
    829 #ifdef RTV_RTT
    830 	/*
    831 	 * If we sent enough data to get some meaningful characteristics,
    832 	 * save them in the routing entry.  'Enough' is arbitrarily
    833 	 * defined as the sendpipesize (default 4K) * 16.  This would
    834 	 * give us 16 rtt samples assuming we only get one sample per
    835 	 * window (the usual case on a long haul net).  16 samples is
    836 	 * enough for the srtt filter to converge to within 5% of the correct
    837 	 * value; fewer samples and we could save a very bogus rtt.
    838 	 *
    839 	 * Don't update the default route's characteristics and don't
    840 	 * update anything that the user "locked".
    841 	 */
    842 	if (SEQ_LT(tp->iss + so->so_snd.sb_hiwat * 16, tp->snd_max) &&
    843 	    ro && (rt = ro->ro_rt) &&
    844 	    !in_nullhost(satosin(rt_key(rt))->sin_addr)) {
    845 		register u_long i = 0;
    846 
    847 		if ((rt->rt_rmx.rmx_locks & RTV_RTT) == 0) {
    848 			i = tp->t_srtt *
    849 			    ((RTM_RTTUNIT / PR_SLOWHZ) >> (TCP_RTT_SHIFT + 2));
    850 			if (rt->rt_rmx.rmx_rtt && i)
    851 				/*
    852 				 * filter this update to half the old & half
    853 				 * the new values, converting scale.
    854 				 * See route.h and tcp_var.h for a
    855 				 * description of the scaling constants.
    856 				 */
    857 				rt->rt_rmx.rmx_rtt =
    858 				    (rt->rt_rmx.rmx_rtt + i) / 2;
    859 			else
    860 				rt->rt_rmx.rmx_rtt = i;
    861 		}
    862 		if ((rt->rt_rmx.rmx_locks & RTV_RTTVAR) == 0) {
    863 			i = tp->t_rttvar *
    864 			    ((RTM_RTTUNIT / PR_SLOWHZ) >> (TCP_RTTVAR_SHIFT + 2));
    865 			if (rt->rt_rmx.rmx_rttvar && i)
    866 				rt->rt_rmx.rmx_rttvar =
    867 				    (rt->rt_rmx.rmx_rttvar + i) / 2;
    868 			else
    869 				rt->rt_rmx.rmx_rttvar = i;
    870 		}
    871 		/*
    872 		 * update the pipelimit (ssthresh) if it has been updated
    873 		 * already or if a pipesize was specified & the threshhold
    874 		 * got below half the pipesize.  I.e., wait for bad news
    875 		 * before we start updating, then update on both good
    876 		 * and bad news.
    877 		 */
    878 		if (((rt->rt_rmx.rmx_locks & RTV_SSTHRESH) == 0 &&
    879 		    (i = tp->snd_ssthresh) && rt->rt_rmx.rmx_ssthresh) ||
    880 		    i < (rt->rt_rmx.rmx_sendpipe / 2)) {
    881 			/*
    882 			 * convert the limit from user data bytes to
    883 			 * packets then to packet data bytes.
    884 			 */
    885 			i = (i + tp->t_segsz / 2) / tp->t_segsz;
    886 			if (i < 2)
    887 				i = 2;
    888 			i *= (u_long)(tp->t_segsz + sizeof (struct tcpiphdr));
    889 			if (rt->rt_rmx.rmx_ssthresh)
    890 				rt->rt_rmx.rmx_ssthresh =
    891 				    (rt->rt_rmx.rmx_ssthresh + i) / 2;
    892 			else
    893 				rt->rt_rmx.rmx_ssthresh = i;
    894 		}
    895 	}
    896 #endif /* RTV_RTT */
    897 	/* free the reassembly queue, if any */
    898 	TCP_REASS_LOCK(tp);
    899 	(void) tcp_freeq(tp);
    900 	TCP_REASS_UNLOCK(tp);
    901 
    902 	TCP_CLEAR_DELACK(tp);
    903 
    904 	if (tp->t_template) {
    905 		m_free(tp->t_template);
    906 		tp->t_template = NULL;
    907 	}
    908 	pool_put(&tcpcb_pool, tp);
    909 	if (inp) {
    910 		inp->inp_ppcb = 0;
    911 		soisdisconnected(so);
    912 		in_pcbdetach(inp);
    913 	}
    914 #ifdef INET6
    915 	else if (in6p) {
    916 		in6p->in6p_ppcb = 0;
    917 		soisdisconnected(so);
    918 		in6_pcbdetach(in6p);
    919 	}
    920 #endif
    921 	tcpstat.tcps_closed++;
    922 	return ((struct tcpcb *)0);
    923 }
    924 
    925 int
    926 tcp_freeq(tp)
    927 	struct tcpcb *tp;
    928 {
    929 	register struct ipqent *qe;
    930 	int rv = 0;
    931 #ifdef TCPREASS_DEBUG
    932 	int i = 0;
    933 #endif
    934 
    935 	TCP_REASS_LOCK_CHECK(tp);
    936 
    937 	while ((qe = tp->segq.lh_first) != NULL) {
    938 #ifdef TCPREASS_DEBUG
    939 		printf("tcp_freeq[%p,%d]: %u:%u(%u) 0x%02x\n",
    940 			tp, i++, qe->ipqe_seq, qe->ipqe_seq + qe->ipqe_len,
    941 			qe->ipqe_len, qe->ipqe_flags & (TH_SYN|TH_FIN|TH_RST));
    942 #endif
    943 		LIST_REMOVE(qe, ipqe_q);
    944 		LIST_REMOVE(qe, ipqe_timeq);
    945 		m_freem(qe->ipqe_m);
    946 		pool_put(&ipqent_pool, qe);
    947 		rv = 1;
    948 	}
    949 	return (rv);
    950 }
    951 
    952 /*
    953  * Protocol drain routine.  Called when memory is in short supply.
    954  */
    955 void
    956 tcp_drain()
    957 {
    958 	register struct inpcb *inp;
    959 	register struct tcpcb *tp;
    960 
    961 	/*
    962 	 * Free the sequence queue of all TCP connections.
    963 	 */
    964 	inp = tcbtable.inpt_queue.cqh_first;
    965 	if (inp)						/* XXX */
    966 	for (; inp != (struct inpcb *)&tcbtable.inpt_queue;
    967 	    inp = inp->inp_queue.cqe_next) {
    968 		if ((tp = intotcpcb(inp)) != NULL) {
    969 			/*
    970 			 * We may be called from a device's interrupt
    971 			 * context.  If the tcpcb is already busy,
    972 			 * just bail out now.
    973 			 */
    974 			if (tcp_reass_lock_try(tp) == 0)
    975 				continue;
    976 			if (tcp_freeq(tp))
    977 				tcpstat.tcps_connsdrained++;
    978 			TCP_REASS_UNLOCK(tp);
    979 		}
    980 	}
    981 }
    982 
    983 /*
    984  * Notify a tcp user of an asynchronous error;
    985  * store error as soft error, but wake up user
    986  * (for now, won't do anything until can select for soft error).
    987  */
    988 void
    989 tcp_notify(inp, error)
    990 	struct inpcb *inp;
    991 	int error;
    992 {
    993 	register struct tcpcb *tp = (struct tcpcb *)inp->inp_ppcb;
    994 	register struct socket *so = inp->inp_socket;
    995 
    996 	/*
    997 	 * Ignore some errors if we are hooked up.
    998 	 * If connection hasn't completed, has retransmitted several times,
    999 	 * and receives a second error, give up now.  This is better
   1000 	 * than waiting a long time to establish a connection that
   1001 	 * can never complete.
   1002 	 */
   1003 	if (tp->t_state == TCPS_ESTABLISHED &&
   1004 	     (error == EHOSTUNREACH || error == ENETUNREACH ||
   1005 	      error == EHOSTDOWN)) {
   1006 		return;
   1007 	} else if (TCPS_HAVEESTABLISHED(tp->t_state) == 0 &&
   1008 	    tp->t_rxtshift > 3 && tp->t_softerror)
   1009 		so->so_error = error;
   1010 	else
   1011 		tp->t_softerror = error;
   1012 	wakeup((caddr_t) &so->so_timeo);
   1013 	sorwakeup(so);
   1014 	sowwakeup(so);
   1015 }
   1016 
   1017 #if defined(INET6) && !defined(TCP6)
   1018 void
   1019 tcp6_ctlinput(cmd, sa, ip6, m, off)
   1020 	int cmd;
   1021 	struct sockaddr *sa;
   1022 	register struct ip6_hdr *ip6;
   1023 	struct mbuf *m;
   1024 	int off;
   1025 {
   1026 	(void)tcp_ctlinput(cmd, sa, (void *)ip6);
   1027 }
   1028 #endif
   1029 
   1030 /* assumes that ip header and tcp header are contiguous on mbuf */
   1031 void *
   1032 tcp_ctlinput(cmd, sa, v)
   1033 	int cmd;
   1034 	struct sockaddr *sa;
   1035 	register void *v;
   1036 {
   1037 	register struct ip *ip = v;
   1038 	register struct tcphdr *th;
   1039 	extern int inetctlerrmap[];
   1040 	void (*notify) __P((struct inpcb *, int)) = tcp_notify;
   1041 	int errno;
   1042 	int nmatch;
   1043 
   1044 	if ((unsigned)cmd >= PRC_NCMDS)
   1045 		return NULL;
   1046 	errno = inetctlerrmap[cmd];
   1047 	if (cmd == PRC_QUENCH)
   1048 		notify = tcp_quench;
   1049 	else if (PRC_IS_REDIRECT(cmd))
   1050 		notify = in_rtchange, ip = 0;
   1051 	else if (cmd == PRC_MSGSIZE && ip_mtudisc)
   1052 		notify = tcp_mtudisc, ip = 0;
   1053 	else if (cmd == PRC_HOSTDEAD)
   1054 		ip = 0;
   1055 	else if (errno == 0)
   1056 		return NULL;
   1057 	if (ip && ip->ip_v == 4 && sa->sa_family == AF_INET) {
   1058 		th = (struct tcphdr *)((caddr_t)ip + (ip->ip_hl << 2));
   1059 		nmatch = in_pcbnotify(&tcbtable, satosin(sa)->sin_addr,
   1060 		    th->th_dport, ip->ip_src, th->th_sport, errno, notify);
   1061 		if (nmatch == 0 && syn_cache_count &&
   1062 		    (inetctlerrmap[cmd] == EHOSTUNREACH ||
   1063 		    inetctlerrmap[cmd] == ENETUNREACH ||
   1064 		    inetctlerrmap[cmd] == EHOSTDOWN)) {
   1065 			struct sockaddr_in sin;
   1066 			bzero(&sin, sizeof(sin));
   1067 			sin.sin_len = sizeof(sin);
   1068 			sin.sin_family = AF_INET;
   1069 			sin.sin_port = th->th_sport;
   1070 			sin.sin_addr = ip->ip_src;
   1071 			syn_cache_unreach((struct sockaddr *)&sin, sa, th);
   1072 		}
   1073 
   1074 		/* XXX mapped address case */
   1075 	}
   1076 #ifdef INET6
   1077 	else if (ip && ip->ip_v == 6 && sa->sa_family == AF_INET6) {
   1078 		/* XXX do something for ip6 */
   1079 	}
   1080 #endif
   1081 	else {
   1082 		(void)in_pcbnotifyall(&tcbtable, satosin(sa)->sin_addr, errno,
   1083 		    notify);
   1084 #ifdef INET6
   1085 		/* XXX do something for ip6 */
   1086 #endif
   1087 	}
   1088 	return NULL;
   1089 }
   1090 
   1091 /*
   1092  * When a source quence is received, we are being notifed of congestion.
   1093  * Close the congestion window down to the Loss Window (one segment).
   1094  * We will gradually open it again as we proceed.
   1095  */
   1096 void
   1097 tcp_quench(inp, errno)
   1098 	struct inpcb *inp;
   1099 	int errno;
   1100 {
   1101 	struct tcpcb *tp = intotcpcb(inp);
   1102 
   1103 	if (tp)
   1104 		tp->snd_cwnd = tp->t_segsz;
   1105 }
   1106 
   1107 /*
   1108  * On receipt of path MTU corrections, flush old route and replace it
   1109  * with the new one.  Retransmit all unacknowledged packets, to ensure
   1110  * that all packets will be received.
   1111  */
   1112 void
   1113 tcp_mtudisc(inp, errno)
   1114 	struct inpcb *inp;
   1115 	int errno;
   1116 {
   1117 	struct tcpcb *tp = intotcpcb(inp);
   1118 	struct rtentry *rt = in_pcbrtentry(inp);
   1119 
   1120 	if (tp != 0) {
   1121 		if (rt != 0) {
   1122 			/*
   1123 			 * If this was not a host route, remove and realloc.
   1124 			 */
   1125 			if ((rt->rt_flags & RTF_HOST) == 0) {
   1126 				in_rtchange(inp, errno);
   1127 				if ((rt = in_pcbrtentry(inp)) == 0)
   1128 					return;
   1129 			}
   1130 
   1131 			/*
   1132 			 * Slow start out of the error condition.  We
   1133 			 * use the MTU because we know it's smaller
   1134 			 * than the previously transmitted segment.
   1135 			 *
   1136 			 * Note: This is more conservative than the
   1137 			 * suggestion in draft-floyd-incr-init-win-03.
   1138 			 */
   1139 			if (rt->rt_rmx.rmx_mtu != 0)
   1140 				tp->snd_cwnd =
   1141 				    TCP_INITIAL_WINDOW(tcp_init_win,
   1142 				    rt->rt_rmx.rmx_mtu);
   1143 		}
   1144 
   1145 		/*
   1146 		 * Resend unacknowledged packets.
   1147 		 */
   1148 		tp->snd_nxt = tp->snd_una;
   1149 		tcp_output(tp);
   1150 	}
   1151 }
   1152 
   1153 
   1154 /*
   1155  * Compute the MSS to advertise to the peer.  Called only during
   1156  * the 3-way handshake.  If we are the server (peer initiated
   1157  * connection), we are called with a pointer to the interface
   1158  * on which the SYN packet arrived.  If we are the client (we
   1159  * initiated connection), we are called with a pointer to the
   1160  * interface out which this connection should go.
   1161  */
   1162 u_long
   1163 tcp_mss_to_advertise(ifp)
   1164 	const struct ifnet *ifp;
   1165 {
   1166 	extern u_long in_maxmtu;
   1167 	u_long mss = 0;
   1168 
   1169 	/*
   1170 	 * In order to avoid defeating path MTU discovery on the peer,
   1171 	 * we advertise the max MTU of all attached networks as our MSS,
   1172 	 * per RFC 1191, section 3.1.
   1173 	 *
   1174 	 * We provide the option to advertise just the MTU of
   1175 	 * the interface on which we hope this connection will
   1176 	 * be receiving.  If we are responding to a SYN, we
   1177 	 * will have a pretty good idea about this, but when
   1178 	 * initiating a connection there is a bit more doubt.
   1179 	 *
   1180 	 * We also need to ensure that loopback has a large enough
   1181 	 * MSS, as the loopback MTU is never included in in_maxmtu.
   1182 	 */
   1183 
   1184 	if (ifp != NULL)
   1185 		mss = ifp->if_mtu;
   1186 
   1187 	if (tcp_mss_ifmtu == 0)
   1188 		mss = max(in_maxmtu, mss);
   1189 
   1190 	if (mss > sizeof(struct tcpiphdr))
   1191 		mss -= sizeof(struct tcpiphdr);
   1192 
   1193 	mss = max(tcp_mssdflt, mss);
   1194 	return (mss);
   1195 }
   1196 
   1197 /*
   1198  * Set connection variables based on the peer's advertised MSS.
   1199  * We are passed the TCPCB for the actual connection.  If we
   1200  * are the server, we are called by the compressed state engine
   1201  * when the 3-way handshake is complete.  If we are the client,
   1202  * we are called when we recieve the SYN,ACK from the server.
   1203  *
   1204  * NOTE: Our advertised MSS value must be initialized in the TCPCB
   1205  * before this routine is called!
   1206  */
   1207 void
   1208 tcp_mss_from_peer(tp, offer)
   1209 	struct tcpcb *tp;
   1210 	int offer;
   1211 {
   1212 	struct socket *so;
   1213 #if defined(RTV_SPIPE) || defined(RTV_SSTHRESH)
   1214 	struct rtentry *rt;
   1215 #endif
   1216 	u_long bufsize;
   1217 	int mss;
   1218 
   1219 	so = NULL;
   1220 	rt = NULL;
   1221 	if (tp->t_inpcb) {
   1222 		so = tp->t_inpcb->inp_socket;
   1223 #if defined(RTV_SPIPE) || defined(RTV_SSTHRESH)
   1224 		rt = in_pcbrtentry(tp->t_inpcb);
   1225 #endif
   1226 	}
   1227 #ifdef INET6
   1228 	else if (tp->t_in6pcb) {
   1229 		so = tp->t_in6pcb->in6p_socket;
   1230 #if defined(RTV_SPIPE) || defined(RTV_SSTHRESH)
   1231 #ifdef TCP6
   1232 		rt = NULL;
   1233 #else
   1234 		rt = in6_pcbrtentry(tp->t_in6pcb);
   1235 #endif
   1236 #endif
   1237 	}
   1238 #endif
   1239 
   1240 	/*
   1241 	 * As per RFC1122, use the default MSS value, unless they
   1242 	 * sent us an offer.  Do not accept offers less than 32 bytes.
   1243 	 */
   1244 	mss = tcp_mssdflt;
   1245 	if (offer)
   1246 		mss = offer;
   1247 	mss = max(mss, 32);		/* sanity */
   1248 	tp->t_peermss = mss;
   1249 	mss -= tcp_optlen(tp);
   1250 	if (tp->t_inpcb)
   1251 		mss -= ip_optlen(tp->t_inpcb);
   1252 #ifdef INET6
   1253 	else if (tp->t_in6pcb)
   1254 		mss -= ip6_optlen(tp->t_in6pcb);
   1255 #endif
   1256 
   1257 	/*
   1258 	 * If there's a pipesize, change the socket buffer to that size.
   1259 	 * Make the socket buffer an integral number of MSS units.  If
   1260 	 * the MSS is larger than the socket buffer, artificially decrease
   1261 	 * the MSS.
   1262 	 */
   1263 #ifdef RTV_SPIPE
   1264 	if (rt != NULL && rt->rt_rmx.rmx_sendpipe != 0)
   1265 		bufsize = rt->rt_rmx.rmx_sendpipe;
   1266 	else
   1267 #endif
   1268 		bufsize = so->so_snd.sb_hiwat;
   1269 	if (bufsize < mss)
   1270 		mss = bufsize;
   1271 	else {
   1272 		bufsize = roundup(bufsize, mss);
   1273 		if (bufsize > sb_max)
   1274 			bufsize = sb_max;
   1275 		(void) sbreserve(&so->so_snd, bufsize);
   1276 	}
   1277 	tp->t_segsz = mss;
   1278 
   1279 #ifdef RTV_SSTHRESH
   1280 	if (rt != NULL && rt->rt_rmx.rmx_ssthresh) {
   1281 		/*
   1282 		 * There's some sort of gateway or interface buffer
   1283 		 * limit on the path.  Use this to set the slow
   1284 		 * start threshold, but set the threshold to no less
   1285 		 * than 2 * MSS.
   1286 		 */
   1287 		tp->snd_ssthresh = max(2 * mss, rt->rt_rmx.rmx_ssthresh);
   1288 	}
   1289 #endif
   1290 }
   1291 
   1292 /*
   1293  * Processing necessary when a TCP connection is established.
   1294  */
   1295 void
   1296 tcp_established(tp)
   1297 	struct tcpcb *tp;
   1298 {
   1299 	struct socket *so;
   1300 #ifdef RTV_RPIPE
   1301 	struct rtentry *rt;
   1302 #endif
   1303 	u_long bufsize;
   1304 
   1305 	so = NULL;
   1306 	rt = NULL;
   1307 	if (tp->t_inpcb) {
   1308 		so = tp->t_inpcb->inp_socket;
   1309 #if defined(RTV_RPIPE)
   1310 		rt = in_pcbrtentry(tp->t_inpcb);
   1311 #endif
   1312 	}
   1313 #ifdef INET6
   1314 	else if (tp->t_in6pcb) {
   1315 		so = tp->t_in6pcb->in6p_socket;
   1316 #if defined(RTV_RPIPE)
   1317 #ifdef TCP6
   1318 		rt = NULL;
   1319 #else
   1320 		rt = in6_pcbrtentry(tp->t_in6pcb);
   1321 #endif
   1322 #endif
   1323 	}
   1324 #endif
   1325 
   1326 	tp->t_state = TCPS_ESTABLISHED;
   1327 	TCP_TIMER_ARM(tp, TCPT_KEEP, tcp_keepidle);
   1328 
   1329 #ifdef RTV_RPIPE
   1330 	if (rt != NULL && rt->rt_rmx.rmx_recvpipe != 0)
   1331 		bufsize = rt->rt_rmx.rmx_recvpipe;
   1332 	else
   1333 #endif
   1334 		bufsize = so->so_rcv.sb_hiwat;
   1335 	if (bufsize > tp->t_ourmss) {
   1336 		bufsize = roundup(bufsize, tp->t_ourmss);
   1337 		if (bufsize > sb_max)
   1338 			bufsize = sb_max;
   1339 		(void) sbreserve(&so->so_rcv, bufsize);
   1340 	}
   1341 }
   1342 
   1343 /*
   1344  * Check if there's an initial rtt or rttvar.  Convert from the
   1345  * route-table units to scaled multiples of the slow timeout timer.
   1346  * Called only during the 3-way handshake.
   1347  */
   1348 void
   1349 tcp_rmx_rtt(tp)
   1350 	struct tcpcb *tp;
   1351 {
   1352 #ifdef RTV_RTT
   1353 	struct rtentry *rt = NULL;
   1354 	int rtt;
   1355 
   1356 	if (tp->t_inpcb)
   1357 		rt = in_pcbrtentry(tp->t_inpcb);
   1358 #ifdef INET6
   1359 	else if (tp->t_in6pcb) {
   1360 #ifdef TCP6
   1361 		rt = NULL;
   1362 #else
   1363 		rt = in6_pcbrtentry(tp->t_in6pcb);
   1364 #endif
   1365 	}
   1366 #endif
   1367 	if (rt == NULL)
   1368 		return;
   1369 
   1370 	if (tp->t_srtt == 0 && (rtt = rt->rt_rmx.rmx_rtt)) {
   1371 		/*
   1372 		 * XXX The lock bit for MTU indicates that the value
   1373 		 * is also a minimum value; this is subject to time.
   1374 		 */
   1375 		if (rt->rt_rmx.rmx_locks & RTV_RTT)
   1376 			TCPT_RANGESET(tp->t_rttmin,
   1377 			    rtt / (RTM_RTTUNIT / PR_SLOWHZ),
   1378 			    TCPTV_MIN, TCPTV_REXMTMAX);
   1379 		tp->t_srtt = rtt /
   1380 		    ((RTM_RTTUNIT / PR_SLOWHZ) >> (TCP_RTT_SHIFT + 2));
   1381 		if (rt->rt_rmx.rmx_rttvar) {
   1382 			tp->t_rttvar = rt->rt_rmx.rmx_rttvar /
   1383 			    ((RTM_RTTUNIT / PR_SLOWHZ) >>
   1384 				(TCP_RTTVAR_SHIFT + 2));
   1385 		} else {
   1386 			/* Default variation is +- 1 rtt */
   1387 			tp->t_rttvar =
   1388 			    tp->t_srtt >> (TCP_RTT_SHIFT - TCP_RTTVAR_SHIFT);
   1389 		}
   1390 		TCPT_RANGESET(tp->t_rxtcur,
   1391 		    ((tp->t_srtt >> 2) + tp->t_rttvar) >> (1 + 2),
   1392 		    tp->t_rttmin, TCPTV_REXMTMAX);
   1393 	}
   1394 #endif
   1395 }
   1396 
   1397 tcp_seq	 tcp_iss_seq = 0;	/* tcp initial seq # */
   1398 
   1399 /*
   1400  * Get a new sequence value given a tcp control block
   1401  */
   1402 tcp_seq
   1403 tcp_new_iss(tp, len, addin)
   1404 	void            *tp;
   1405 	u_long           len;
   1406 	tcp_seq		 addin;
   1407 {
   1408 	tcp_seq          tcp_iss;
   1409 
   1410 	/*
   1411 	 * Randomize.
   1412 	 */
   1413 #if NRND > 0
   1414 	rnd_extract_data(&tcp_iss, sizeof(tcp_iss), RND_EXTRACT_ANY);
   1415 #else
   1416 	tcp_iss = random();
   1417 #endif
   1418 
   1419 	/*
   1420 	 * If we were asked to add some amount to a known value,
   1421 	 * we will take a random value obtained above, mask off the upper
   1422 	 * bits, and add in the known value.  We also add in a constant to
   1423 	 * ensure that we are at least a certain distance from the original
   1424 	 * value.
   1425 	 *
   1426 	 * This is used when an old connection is in timed wait
   1427 	 * and we have a new one coming in, for instance.
   1428 	 */
   1429 	if (addin != 0) {
   1430 #ifdef TCPISS_DEBUG
   1431 		printf("Random %08x, ", tcp_iss);
   1432 #endif
   1433 		tcp_iss &= TCP_ISS_RANDOM_MASK;
   1434 		tcp_iss += addin + TCP_ISSINCR;
   1435 #ifdef TCPISS_DEBUG
   1436 		printf("Old ISS %08x, ISS %08x\n", addin, tcp_iss);
   1437 #endif
   1438 	} else {
   1439 		tcp_iss &= TCP_ISS_RANDOM_MASK;
   1440 		tcp_iss += tcp_iss_seq;
   1441 		tcp_iss_seq += TCP_ISSINCR;
   1442 #ifdef TCPISS_DEBUG
   1443 		printf("ISS %08x\n", tcp_iss);
   1444 #endif
   1445 	}
   1446 
   1447 	if (tcp_compat_42) {
   1448 		/*
   1449 		 * Limit it to the positive range for really old TCP
   1450 		 * implementations.
   1451 		 */
   1452 		if (tcp_iss >= 0x80000000)
   1453 			tcp_iss &= 0x7fffffff;		/* XXX */
   1454 	}
   1455 
   1456 	return tcp_iss;
   1457 }
   1458 
   1459 #ifdef IPSEC
   1460 /* compute ESP/AH header size for TCP, including outer IP header. */
   1461 size_t
   1462 ipsec4_hdrsiz_tcp(tp)
   1463 	struct tcpcb *tp;
   1464 {
   1465 	struct inpcb *inp;
   1466 	size_t hdrsiz;
   1467 
   1468 	/* XXX mapped addr case (tp->t_in6pcb) */
   1469 	if (!tp || !tp->t_template || !(inp = tp->t_inpcb))
   1470 		return 0;
   1471 	switch (tp->t_family) {
   1472 	case AF_INET:
   1473 		hdrsiz = ipsec4_hdrsiz(tp->t_template, inp);
   1474 		break;
   1475 	default:
   1476 		hdrsiz = 0;
   1477 		break;
   1478 	}
   1479 
   1480 	return hdrsiz;
   1481 }
   1482 
   1483 #if defined(INET6) && !defined(TCP6)
   1484 size_t
   1485 ipsec6_hdrsiz_tcp(tp)
   1486 	struct tcpcb *tp;
   1487 {
   1488 	struct in6pcb *in6p;
   1489 	size_t hdrsiz;
   1490 
   1491 	if (!tp || !tp->t_template || !(in6p = tp->t_in6pcb))
   1492 		return 0;
   1493 	switch (tp->t_family) {
   1494 	case AF_INET6:
   1495 		hdrsiz = ipsec6_hdrsiz(tp->t_template, in6p);
   1496 		break;
   1497 	case AF_INET:
   1498 		/* mapped address case - tricky */
   1499 	default:
   1500 		hdrsiz = 0;
   1501 		break;
   1502 	}
   1503 
   1504 	return hdrsiz;
   1505 }
   1506 #endif
   1507 #endif /*IPSEC*/
   1508 
   1509 /*
   1510  * Determine the length of the TCP options for this connection.
   1511  *
   1512  * XXX:  What do we do for SACK, when we add that?  Just reserve
   1513  *       all of the space?  Otherwise we can't exactly be incrementing
   1514  *       cwnd by an amount that varies depending on the amount we last
   1515  *       had to SACK!
   1516  */
   1517 
   1518 u_int
   1519 tcp_optlen(tp)
   1520 	struct tcpcb *tp;
   1521 {
   1522 	if ((tp->t_flags & (TF_REQ_TSTMP|TF_RCVD_TSTMP|TF_NOOPT)) ==
   1523 	    (TF_REQ_TSTMP | TF_RCVD_TSTMP))
   1524 		return TCPOLEN_TSTAMP_APPA;
   1525 	else
   1526 		return 0;
   1527 }
   1528