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