xref: /freebsd/sys/netinet/tcp_subr.c (revision 6adf353a56a161443406b44a45d00c688ca7b857)
1 /*
2  * Copyright (c) 1982, 1986, 1988, 1990, 1993, 1995
3  *	The Regents of the University of California.  All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  * 3. All advertising materials mentioning features or use of this software
14  *    must display the following acknowledgement:
15  *	This product includes software developed by the University of
16  *	California, Berkeley and its contributors.
17  * 4. Neither the name of the University nor the names of its contributors
18  *    may be used to endorse or promote products derived from this software
19  *    without specific prior written permission.
20  *
21  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
22  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
25  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31  * SUCH DAMAGE.
32  *
33  *	@(#)tcp_subr.c	8.2 (Berkeley) 5/24/95
34  * $FreeBSD$
35  */
36 
37 #include "opt_compat.h"
38 #include "opt_inet6.h"
39 #include "opt_ipsec.h"
40 #include "opt_tcpdebug.h"
41 
42 #include <sys/param.h>
43 #include <sys/systm.h>
44 #include <sys/callout.h>
45 #include <sys/kernel.h>
46 #include <sys/sysctl.h>
47 #include <sys/malloc.h>
48 #include <sys/mbuf.h>
49 #ifdef INET6
50 #include <sys/domain.h>
51 #endif
52 #include <sys/proc.h>
53 #include <sys/socket.h>
54 #include <sys/socketvar.h>
55 #include <sys/protosw.h>
56 #include <sys/random.h>
57 
58 #include <vm/vm_zone.h>
59 
60 #include <net/route.h>
61 #include <net/if.h>
62 
63 #define _IP_VHL
64 #include <netinet/in.h>
65 #include <netinet/in_systm.h>
66 #include <netinet/ip.h>
67 #ifdef INET6
68 #include <netinet/ip6.h>
69 #endif
70 #include <netinet/in_pcb.h>
71 #ifdef INET6
72 #include <netinet6/in6_pcb.h>
73 #endif
74 #include <netinet/in_var.h>
75 #include <netinet/ip_var.h>
76 #ifdef INET6
77 #include <netinet6/ip6_var.h>
78 #endif
79 #include <netinet/tcp.h>
80 #include <netinet/tcp_fsm.h>
81 #include <netinet/tcp_seq.h>
82 #include <netinet/tcp_timer.h>
83 #include <netinet/tcp_var.h>
84 #ifdef INET6
85 #include <netinet6/tcp6_var.h>
86 #endif
87 #include <netinet/tcpip.h>
88 #ifdef TCPDEBUG
89 #include <netinet/tcp_debug.h>
90 #endif
91 #include <netinet6/ip6protosw.h>
92 
93 #ifdef IPSEC
94 #include <netinet6/ipsec.h>
95 #ifdef INET6
96 #include <netinet6/ipsec6.h>
97 #endif
98 #endif /*IPSEC*/
99 
100 #include <machine/in_cksum.h>
101 
102 int 	tcp_mssdflt = TCP_MSS;
103 SYSCTL_INT(_net_inet_tcp, TCPCTL_MSSDFLT, mssdflt, CTLFLAG_RW,
104     &tcp_mssdflt , 0, "Default TCP Maximum Segment Size");
105 
106 #ifdef INET6
107 int	tcp_v6mssdflt = TCP6_MSS;
108 SYSCTL_INT(_net_inet_tcp, TCPCTL_V6MSSDFLT, v6mssdflt,
109 	CTLFLAG_RW, &tcp_v6mssdflt , 0,
110 	"Default TCP Maximum Segment Size for IPv6");
111 #endif
112 
113 #if 0
114 static int 	tcp_rttdflt = TCPTV_SRTTDFLT / PR_SLOWHZ;
115 SYSCTL_INT(_net_inet_tcp, TCPCTL_RTTDFLT, rttdflt, CTLFLAG_RW,
116     &tcp_rttdflt , 0, "Default maximum TCP Round Trip Time");
117 #endif
118 
119 static int	tcp_do_rfc1323 = 1;
120 SYSCTL_INT(_net_inet_tcp, TCPCTL_DO_RFC1323, rfc1323, CTLFLAG_RW,
121     &tcp_do_rfc1323 , 0, "Enable rfc1323 (high performance TCP) extensions");
122 
123 static int	tcp_do_rfc1644 = 0;
124 SYSCTL_INT(_net_inet_tcp, TCPCTL_DO_RFC1644, rfc1644, CTLFLAG_RW,
125     &tcp_do_rfc1644 , 0, "Enable rfc1644 (TTCP) extensions");
126 
127 static int	tcp_tcbhashsize = 0;
128 SYSCTL_INT(_net_inet_tcp, OID_AUTO, tcbhashsize, CTLFLAG_RD,
129      &tcp_tcbhashsize, 0, "Size of TCP control-block hashtable");
130 
131 static int	do_tcpdrain = 1;
132 SYSCTL_INT(_net_inet_tcp, OID_AUTO, do_tcpdrain, CTLFLAG_RW, &do_tcpdrain, 0,
133      "Enable tcp_drain routine for extra help when low on mbufs");
134 
135 SYSCTL_INT(_net_inet_tcp, OID_AUTO, pcbcount, CTLFLAG_RD,
136     &tcbinfo.ipi_count, 0, "Number of active PCBs");
137 
138 static int	icmp_may_rst = 1;
139 SYSCTL_INT(_net_inet_tcp, OID_AUTO, icmp_may_rst, CTLFLAG_RW, &icmp_may_rst, 0,
140     "Certain ICMP unreachable messages may abort connections in SYN_SENT");
141 
142 static int	tcp_seq_genscheme = 1;
143 SYSCTL_INT(_net_inet_tcp, OID_AUTO, tcp_seq_genscheme, CTLFLAG_RW,
144     &tcp_seq_genscheme, 0, "TCP ISN generation scheme");
145 
146 static void	tcp_cleartaocache __P((void));
147 static void	tcp_notify __P((struct inpcb *, int));
148 
149 /*
150  * Target size of TCP PCB hash tables. Must be a power of two.
151  *
152  * Note that this can be overridden by the kernel environment
153  * variable net.inet.tcp.tcbhashsize
154  */
155 #ifndef TCBHASHSIZE
156 #define TCBHASHSIZE	512
157 #endif
158 
159 /*
160  * This is the actual shape of what we allocate using the zone
161  * allocator.  Doing it this way allows us to protect both structures
162  * using the same generation count, and also eliminates the overhead
163  * of allocating tcpcbs separately.  By hiding the structure here,
164  * we avoid changing most of the rest of the code (although it needs
165  * to be changed, eventually, for greater efficiency).
166  */
167 #define	ALIGNMENT	32
168 #define	ALIGNM1		(ALIGNMENT - 1)
169 struct	inp_tp {
170 	union {
171 		struct	inpcb inp;
172 		char	align[(sizeof(struct inpcb) + ALIGNM1) & ~ALIGNM1];
173 	} inp_tp_u;
174 	struct	tcpcb tcb;
175 	struct	callout inp_tp_rexmt, inp_tp_persist, inp_tp_keep, inp_tp_2msl;
176 	struct	callout inp_tp_delack;
177 };
178 #undef ALIGNMENT
179 #undef ALIGNM1
180 
181 /*
182  * Tcp initialization
183  */
184 void
185 tcp_init()
186 {
187 	int hashsize = TCBHASHSIZE;
188 
189 	tcp_iss = arc4random();	/* wrong, but better than a constant */
190 	tcp_ccgen = 1;
191 	tcp_cleartaocache();
192 
193 	tcp_delacktime = TCPTV_DELACK;
194 	tcp_keepinit = TCPTV_KEEP_INIT;
195 	tcp_keepidle = TCPTV_KEEP_IDLE;
196 	tcp_keepintvl = TCPTV_KEEPINTVL;
197 	tcp_maxpersistidle = TCPTV_KEEP_IDLE;
198 	tcp_msl = TCPTV_MSL;
199 
200 	LIST_INIT(&tcb);
201 	tcbinfo.listhead = &tcb;
202 	TUNABLE_INT_FETCH("net.inet.tcp.tcbhashsize", &hashsize);
203 	if (!powerof2(hashsize)) {
204 		printf("WARNING: TCB hash size not a power of 2\n");
205 		hashsize = 512; /* safe default */
206 	}
207 	tcp_tcbhashsize = hashsize;
208 	tcbinfo.hashbase = hashinit(hashsize, M_PCB, &tcbinfo.hashmask);
209 	tcbinfo.porthashbase = hashinit(hashsize, M_PCB,
210 					&tcbinfo.porthashmask);
211 	tcbinfo.ipi_zone = zinit("tcpcb", sizeof(struct inp_tp), maxsockets,
212 				 ZONE_INTERRUPT, 0);
213 #ifdef INET6
214 #define TCP_MINPROTOHDR (sizeof(struct ip6_hdr) + sizeof(struct tcphdr))
215 #else /* INET6 */
216 #define TCP_MINPROTOHDR (sizeof(struct tcpiphdr))
217 #endif /* INET6 */
218 	if (max_protohdr < TCP_MINPROTOHDR)
219 		max_protohdr = TCP_MINPROTOHDR;
220 	if (max_linkhdr + TCP_MINPROTOHDR > MHLEN)
221 		panic("tcp_init");
222 #undef TCP_MINPROTOHDR
223 }
224 
225 /*
226  * Fill in the IP and TCP headers for an outgoing packet, given the tcpcb.
227  * tcp_template used to store this data in mbufs, but we now recopy it out
228  * of the tcpcb each time to conserve mbufs.
229  */
230 void
231 tcp_fillheaders(tp, ip_ptr, tcp_ptr)
232 	struct tcpcb *tp;
233 	void *ip_ptr;
234 	void *tcp_ptr;
235 {
236 	struct inpcb *inp = tp->t_inpcb;
237 	struct tcphdr *tcp_hdr = (struct tcphdr *)tcp_ptr;
238 
239 #ifdef INET6
240 	if ((inp->inp_vflag & INP_IPV6) != 0) {
241 		struct ip6_hdr *ip6;
242 
243 		ip6 = (struct ip6_hdr *)ip_ptr;
244 		ip6->ip6_flow = (ip6->ip6_flow & ~IPV6_FLOWINFO_MASK) |
245 			(inp->in6p_flowinfo & IPV6_FLOWINFO_MASK);
246 		ip6->ip6_vfc = (ip6->ip6_vfc & ~IPV6_VERSION_MASK) |
247 			(IPV6_VERSION & IPV6_VERSION_MASK);
248 		ip6->ip6_nxt = IPPROTO_TCP;
249 		ip6->ip6_plen = sizeof(struct tcphdr);
250 		ip6->ip6_src = inp->in6p_laddr;
251 		ip6->ip6_dst = inp->in6p_faddr;
252 		tcp_hdr->th_sum = 0;
253 	} else
254 #endif
255 	{
256 	struct ip *ip = (struct ip *) ip_ptr;
257 
258 	ip->ip_vhl = IP_VHL_BORING;
259 	ip->ip_tos = 0;
260 	ip->ip_len = 0;
261 	ip->ip_id = 0;
262 	ip->ip_off = 0;
263 	ip->ip_ttl = 0;
264 	ip->ip_sum = 0;
265 	ip->ip_p = IPPROTO_TCP;
266 	ip->ip_src = inp->inp_laddr;
267 	ip->ip_dst = inp->inp_faddr;
268 	tcp_hdr->th_sum = in_pseudo(ip->ip_src.s_addr, ip->ip_dst.s_addr,
269 		htons(sizeof(struct tcphdr) + IPPROTO_TCP));
270 	}
271 
272 	tcp_hdr->th_sport = inp->inp_lport;
273 	tcp_hdr->th_dport = inp->inp_fport;
274 	tcp_hdr->th_seq = 0;
275 	tcp_hdr->th_ack = 0;
276 	tcp_hdr->th_x2 = 0;
277 	tcp_hdr->th_off = 5;
278 	tcp_hdr->th_flags = 0;
279 	tcp_hdr->th_win = 0;
280 	tcp_hdr->th_urp = 0;
281 }
282 
283 /*
284  * Create template to be used to send tcp packets on a connection.
285  * Allocates an mbuf and fills in a skeletal tcp/ip header.  The only
286  * use for this function is in keepalives, which use tcp_respond.
287  */
288 struct tcptemp *
289 tcp_maketemplate(tp)
290 	struct tcpcb *tp;
291 {
292 	struct mbuf *m;
293 	struct tcptemp *n;
294 
295 	m = m_get(M_DONTWAIT, MT_HEADER);
296 	if (m == NULL)
297 		return (0);
298 	m->m_len = sizeof(struct tcptemp);
299 	n = mtod(m, struct tcptemp *);
300 
301 	tcp_fillheaders(tp, (void *)&n->tt_ipgen, (void *)&n->tt_t);
302 	return (n);
303 }
304 
305 /*
306  * Send a single message to the TCP at address specified by
307  * the given TCP/IP header.  If m == 0, then we make a copy
308  * of the tcpiphdr at ti and send directly to the addressed host.
309  * This is used to force keep alive messages out using the TCP
310  * template for a connection.  If flags are given then we send
311  * a message back to the TCP which originated the * segment ti,
312  * and discard the mbuf containing it and any other attached mbufs.
313  *
314  * In any case the ack and sequence number of the transmitted
315  * segment are as specified by the parameters.
316  *
317  * NOTE: If m != NULL, then ti must point to *inside* the mbuf.
318  */
319 void
320 tcp_respond(tp, ipgen, th, m, ack, seq, flags)
321 	struct tcpcb *tp;
322 	void *ipgen;
323 	register struct tcphdr *th;
324 	register struct mbuf *m;
325 	tcp_seq ack, seq;
326 	int flags;
327 {
328 	register int tlen;
329 	int win = 0;
330 	struct route *ro = 0;
331 	struct route sro;
332 	struct ip *ip;
333 	struct tcphdr *nth;
334 #ifdef INET6
335 	struct route_in6 *ro6 = 0;
336 	struct route_in6 sro6;
337 	struct ip6_hdr *ip6;
338 	int isipv6;
339 #endif /* INET6 */
340 	int ipflags = 0;
341 
342 #ifdef INET6
343 	isipv6 = IP_VHL_V(((struct ip *)ipgen)->ip_vhl) == 6;
344 	ip6 = ipgen;
345 #endif /* INET6 */
346 	ip = ipgen;
347 
348 	if (tp) {
349 		if (!(flags & TH_RST)) {
350 			win = sbspace(&tp->t_inpcb->inp_socket->so_rcv);
351 			if (win > (long)TCP_MAXWIN << tp->rcv_scale)
352 				win = (long)TCP_MAXWIN << tp->rcv_scale;
353 		}
354 #ifdef INET6
355 		if (isipv6)
356 			ro6 = &tp->t_inpcb->in6p_route;
357 		else
358 #endif /* INET6 */
359 		ro = &tp->t_inpcb->inp_route;
360 	} else {
361 #ifdef INET6
362 		if (isipv6) {
363 			ro6 = &sro6;
364 			bzero(ro6, sizeof *ro6);
365 		} else
366 #endif /* INET6 */
367 	      {
368 		ro = &sro;
369 		bzero(ro, sizeof *ro);
370 	      }
371 	}
372 	if (m == 0) {
373 		m = m_gethdr(M_DONTWAIT, MT_HEADER);
374 		if (m == NULL)
375 			return;
376 		tlen = 0;
377 		m->m_data += max_linkhdr;
378 #ifdef INET6
379 		if (isipv6) {
380 			bcopy((caddr_t)ip6, mtod(m, caddr_t),
381 			      sizeof(struct ip6_hdr));
382 			ip6 = mtod(m, struct ip6_hdr *);
383 			nth = (struct tcphdr *)(ip6 + 1);
384 		} else
385 #endif /* INET6 */
386 	      {
387 		bcopy((caddr_t)ip, mtod(m, caddr_t), sizeof(struct ip));
388 		ip = mtod(m, struct ip *);
389 		nth = (struct tcphdr *)(ip + 1);
390 	      }
391 		bcopy((caddr_t)th, (caddr_t)nth, sizeof(struct tcphdr));
392 		flags = TH_ACK;
393 	} else {
394 		m_freem(m->m_next);
395 		m->m_next = 0;
396 		m->m_data = (caddr_t)ipgen;
397 		/* m_len is set later */
398 		tlen = 0;
399 #define xchg(a,b,type) { type t; t=a; a=b; b=t; }
400 #ifdef INET6
401 		if (isipv6) {
402 			xchg(ip6->ip6_dst, ip6->ip6_src, struct in6_addr);
403 			nth = (struct tcphdr *)(ip6 + 1);
404 		} else
405 #endif /* INET6 */
406 	      {
407 		xchg(ip->ip_dst.s_addr, ip->ip_src.s_addr, n_long);
408 		nth = (struct tcphdr *)(ip + 1);
409 	      }
410 		if (th != nth) {
411 			/*
412 			 * this is usually a case when an extension header
413 			 * exists between the IPv6 header and the
414 			 * TCP header.
415 			 */
416 			nth->th_sport = th->th_sport;
417 			nth->th_dport = th->th_dport;
418 		}
419 		xchg(nth->th_dport, nth->th_sport, n_short);
420 #undef xchg
421 	}
422 #ifdef INET6
423 	if (isipv6) {
424 		ip6->ip6_plen = htons((u_short)(sizeof (struct tcphdr) +
425 						tlen));
426 		tlen += sizeof (struct ip6_hdr) + sizeof (struct tcphdr);
427 	} else
428 #endif
429       {
430 	tlen += sizeof (struct tcpiphdr);
431 	ip->ip_len = tlen;
432 	ip->ip_ttl = ip_defttl;
433       }
434 	m->m_len = tlen;
435 	m->m_pkthdr.len = tlen;
436 	m->m_pkthdr.rcvif = (struct ifnet *) 0;
437 	nth->th_seq = htonl(seq);
438 	nth->th_ack = htonl(ack);
439 	nth->th_x2 = 0;
440 	nth->th_off = sizeof (struct tcphdr) >> 2;
441 	nth->th_flags = flags;
442 	if (tp)
443 		nth->th_win = htons((u_short) (win >> tp->rcv_scale));
444 	else
445 		nth->th_win = htons((u_short)win);
446 	nth->th_urp = 0;
447 #ifdef INET6
448 	if (isipv6) {
449 		nth->th_sum = 0;
450 		nth->th_sum = in6_cksum(m, IPPROTO_TCP,
451 					sizeof(struct ip6_hdr),
452 					tlen - sizeof(struct ip6_hdr));
453 		ip6->ip6_hlim = in6_selecthlim(tp ? tp->t_inpcb : NULL,
454 					       ro6 && ro6->ro_rt ?
455 					       ro6->ro_rt->rt_ifp :
456 					       NULL);
457 	} else
458 #endif /* INET6 */
459       {
460         nth->th_sum = in_pseudo(ip->ip_src.s_addr, ip->ip_dst.s_addr,
461 	    htons((u_short)(tlen - sizeof(struct ip) + ip->ip_p)));
462         m->m_pkthdr.csum_flags = CSUM_TCP;
463         m->m_pkthdr.csum_data = offsetof(struct tcphdr, th_sum);
464       }
465 #ifdef TCPDEBUG
466 	if (tp == NULL || (tp->t_inpcb->inp_socket->so_options & SO_DEBUG))
467 		tcp_trace(TA_OUTPUT, 0, tp, mtod(m, void *), th, 0);
468 #endif
469 #ifdef IPSEC
470 	if (ipsec_setsocket(m, tp ? tp->t_inpcb->inp_socket : NULL) != 0) {
471 		m_freem(m);
472 		return;
473 	}
474 #endif
475 #ifdef INET6
476 	if (isipv6) {
477 		(void)ip6_output(m, NULL, ro6, ipflags, NULL, NULL);
478 		if (ro6 == &sro6 && ro6->ro_rt) {
479 			RTFREE(ro6->ro_rt);
480 			ro6->ro_rt = NULL;
481 		}
482 	} else
483 #endif /* INET6 */
484       {
485 	(void) ip_output(m, NULL, ro, ipflags, NULL);
486 	if (ro == &sro && ro->ro_rt) {
487 		RTFREE(ro->ro_rt);
488 		ro->ro_rt = NULL;
489 	}
490       }
491 }
492 
493 /*
494  * Create a new TCP control block, making an
495  * empty reassembly queue and hooking it to the argument
496  * protocol control block.  The `inp' parameter must have
497  * come from the zone allocator set up in tcp_init().
498  */
499 struct tcpcb *
500 tcp_newtcpcb(inp)
501 	struct inpcb *inp;
502 {
503 	struct inp_tp *it;
504 	register struct tcpcb *tp;
505 #ifdef INET6
506 	int isipv6 = (inp->inp_vflag & INP_IPV6) != 0;
507 #endif /* INET6 */
508 
509 	it = (struct inp_tp *)inp;
510 	tp = &it->tcb;
511 	bzero((char *) tp, sizeof(struct tcpcb));
512 	LIST_INIT(&tp->t_segq);
513 	tp->t_maxseg = tp->t_maxopd =
514 #ifdef INET6
515 		isipv6 ? tcp_v6mssdflt :
516 #endif /* INET6 */
517 		tcp_mssdflt;
518 
519 	/* Set up our timeouts. */
520 	callout_init(tp->tt_rexmt = &it->inp_tp_rexmt, 0);
521 	callout_init(tp->tt_persist = &it->inp_tp_persist, 0);
522 	callout_init(tp->tt_keep = &it->inp_tp_keep, 0);
523 	callout_init(tp->tt_2msl = &it->inp_tp_2msl, 0);
524 	callout_init(tp->tt_delack = &it->inp_tp_delack, 0);
525 
526 	if (tcp_do_rfc1323)
527 		tp->t_flags = (TF_REQ_SCALE|TF_REQ_TSTMP);
528 	if (tcp_do_rfc1644)
529 		tp->t_flags |= TF_REQ_CC;
530 	tp->t_inpcb = inp;	/* XXX */
531 	/*
532 	 * Init srtt to TCPTV_SRTTBASE (0), so we can tell that we have no
533 	 * rtt estimate.  Set rttvar so that srtt + 4 * rttvar gives
534 	 * reasonable initial retransmit time.
535 	 */
536 	tp->t_srtt = TCPTV_SRTTBASE;
537 	tp->t_rttvar = ((TCPTV_RTOBASE - TCPTV_SRTTBASE) << TCP_RTTVAR_SHIFT) / 4;
538 	tp->t_rttmin = TCPTV_MIN;
539 	tp->t_rxtcur = TCPTV_RTOBASE;
540 	tp->snd_cwnd = TCP_MAXWIN << TCP_MAX_WINSHIFT;
541 	tp->snd_ssthresh = TCP_MAXWIN << TCP_MAX_WINSHIFT;
542 	tp->t_rcvtime = ticks;
543         /*
544 	 * IPv4 TTL initialization is necessary for an IPv6 socket as well,
545 	 * because the socket may be bound to an IPv6 wildcard address,
546 	 * which may match an IPv4-mapped IPv6 address.
547 	 */
548 	inp->inp_ip_ttl = ip_defttl;
549 	inp->inp_ppcb = (caddr_t)tp;
550 	return (tp);		/* XXX */
551 }
552 
553 /*
554  * Drop a TCP connection, reporting
555  * the specified error.  If connection is synchronized,
556  * then send a RST to peer.
557  */
558 struct tcpcb *
559 tcp_drop(tp, errno)
560 	register struct tcpcb *tp;
561 	int errno;
562 {
563 	struct socket *so = tp->t_inpcb->inp_socket;
564 
565 	if (TCPS_HAVERCVDSYN(tp->t_state)) {
566 		tp->t_state = TCPS_CLOSED;
567 		(void) tcp_output(tp);
568 		tcpstat.tcps_drops++;
569 	} else
570 		tcpstat.tcps_conndrops++;
571 	if (errno == ETIMEDOUT && tp->t_softerror)
572 		errno = tp->t_softerror;
573 	so->so_error = errno;
574 	return (tcp_close(tp));
575 }
576 
577 /*
578  * Close a TCP control block:
579  *	discard all space held by the tcp
580  *	discard internet protocol block
581  *	wake up any sleepers
582  */
583 struct tcpcb *
584 tcp_close(tp)
585 	register struct tcpcb *tp;
586 {
587 	register struct tseg_qent *q;
588 	struct inpcb *inp = tp->t_inpcb;
589 	struct socket *so = inp->inp_socket;
590 #ifdef INET6
591 	int isipv6 = (inp->inp_vflag & INP_IPV6) != 0;
592 #endif /* INET6 */
593 	register struct rtentry *rt;
594 	int dosavessthresh;
595 
596 	/*
597 	 * Make sure that all of our timers are stopped before we
598 	 * delete the PCB.
599 	 */
600 	callout_stop(tp->tt_rexmt);
601 	callout_stop(tp->tt_persist);
602 	callout_stop(tp->tt_keep);
603 	callout_stop(tp->tt_2msl);
604 	callout_stop(tp->tt_delack);
605 
606 	/*
607 	 * If we got enough samples through the srtt filter,
608 	 * save the rtt and rttvar in the routing entry.
609 	 * 'Enough' is arbitrarily defined as the 16 samples.
610 	 * 16 samples is enough for the srtt filter to converge
611 	 * to within 5% of the correct value; fewer samples and
612 	 * we could save a very bogus rtt.
613 	 *
614 	 * Don't update the default route's characteristics and don't
615 	 * update anything that the user "locked".
616 	 */
617 	if (tp->t_rttupdated >= 16) {
618 		register u_long i = 0;
619 #ifdef INET6
620 		if (isipv6) {
621 			struct sockaddr_in6 *sin6;
622 
623 			if ((rt = inp->in6p_route.ro_rt) == NULL)
624 				goto no_valid_rt;
625 			sin6 = (struct sockaddr_in6 *)rt_key(rt);
626 			if (IN6_IS_ADDR_UNSPECIFIED(&sin6->sin6_addr))
627 				goto no_valid_rt;
628 		}
629 		else
630 #endif /* INET6 */
631 		if ((rt = inp->inp_route.ro_rt) == NULL ||
632 		    ((struct sockaddr_in *)rt_key(rt))->sin_addr.s_addr
633 		    == INADDR_ANY)
634 			goto no_valid_rt;
635 
636 		if ((rt->rt_rmx.rmx_locks & RTV_RTT) == 0) {
637 			i = tp->t_srtt *
638 			    (RTM_RTTUNIT / (hz * TCP_RTT_SCALE));
639 			if (rt->rt_rmx.rmx_rtt && i)
640 				/*
641 				 * filter this update to half the old & half
642 				 * the new values, converting scale.
643 				 * See route.h and tcp_var.h for a
644 				 * description of the scaling constants.
645 				 */
646 				rt->rt_rmx.rmx_rtt =
647 				    (rt->rt_rmx.rmx_rtt + i) / 2;
648 			else
649 				rt->rt_rmx.rmx_rtt = i;
650 			tcpstat.tcps_cachedrtt++;
651 		}
652 		if ((rt->rt_rmx.rmx_locks & RTV_RTTVAR) == 0) {
653 			i = tp->t_rttvar *
654 			    (RTM_RTTUNIT / (hz * TCP_RTTVAR_SCALE));
655 			if (rt->rt_rmx.rmx_rttvar && i)
656 				rt->rt_rmx.rmx_rttvar =
657 				    (rt->rt_rmx.rmx_rttvar + i) / 2;
658 			else
659 				rt->rt_rmx.rmx_rttvar = i;
660 			tcpstat.tcps_cachedrttvar++;
661 		}
662 		/*
663 		 * The old comment here said:
664 		 * update the pipelimit (ssthresh) if it has been updated
665 		 * already or if a pipesize was specified & the threshhold
666 		 * got below half the pipesize.  I.e., wait for bad news
667 		 * before we start updating, then update on both good
668 		 * and bad news.
669 		 *
670 		 * But we want to save the ssthresh even if no pipesize is
671 		 * specified explicitly in the route, because such
672 		 * connections still have an implicit pipesize specified
673 		 * by the global tcp_sendspace.  In the absence of a reliable
674 		 * way to calculate the pipesize, it will have to do.
675 		 */
676 		i = tp->snd_ssthresh;
677 		if (rt->rt_rmx.rmx_sendpipe != 0)
678 			dosavessthresh = (i < rt->rt_rmx.rmx_sendpipe / 2);
679 		else
680 			dosavessthresh = (i < so->so_snd.sb_hiwat / 2);
681 		if (((rt->rt_rmx.rmx_locks & RTV_SSTHRESH) == 0 &&
682 		     i != 0 && rt->rt_rmx.rmx_ssthresh != 0)
683 		    || dosavessthresh) {
684 			/*
685 			 * convert the limit from user data bytes to
686 			 * packets then to packet data bytes.
687 			 */
688 			i = (i + tp->t_maxseg / 2) / tp->t_maxseg;
689 			if (i < 2)
690 				i = 2;
691 			i *= (u_long)(tp->t_maxseg +
692 #ifdef INET6
693 				      (isipv6 ? sizeof (struct ip6_hdr) +
694 					       sizeof (struct tcphdr) :
695 #endif
696 				       sizeof (struct tcpiphdr)
697 #ifdef INET6
698 				       )
699 #endif
700 				      );
701 			if (rt->rt_rmx.rmx_ssthresh)
702 				rt->rt_rmx.rmx_ssthresh =
703 				    (rt->rt_rmx.rmx_ssthresh + i) / 2;
704 			else
705 				rt->rt_rmx.rmx_ssthresh = i;
706 			tcpstat.tcps_cachedssthresh++;
707 		}
708 	}
709 	rt = inp->inp_route.ro_rt;
710 	if (rt) {
711 		/*
712 		 * mark route for deletion if no information is
713 		 * cached.
714 		 */
715 		if ((tp->t_flags & TF_LQ_OVERFLOW) &&
716 		    ((rt->rt_rmx.rmx_locks & RTV_RTT) == 0)){
717 			if (rt->rt_rmx.rmx_rtt == 0)
718 				rt->rt_flags |= RTF_DELCLONE;
719 		}
720 	}
721     no_valid_rt:
722 	/* free the reassembly queue, if any */
723 	while((q = LIST_FIRST(&tp->t_segq)) != NULL) {
724 		LIST_REMOVE(q, tqe_q);
725 		m_freem(q->tqe_m);
726 		FREE(q, M_TSEGQ);
727 	}
728 	inp->inp_ppcb = NULL;
729 	soisdisconnected(so);
730 #ifdef INET6
731 	if (INP_CHECK_SOCKAF(so, AF_INET6))
732 		in6_pcbdetach(inp);
733 	else
734 #endif /* INET6 */
735 	in_pcbdetach(inp);
736 	tcpstat.tcps_closed++;
737 	return ((struct tcpcb *)0);
738 }
739 
740 void
741 tcp_drain()
742 {
743 	if (do_tcpdrain)
744 	{
745 		struct inpcb *inpb;
746 		struct tcpcb *tcpb;
747 		struct tseg_qent *te;
748 
749 	/*
750 	 * Walk the tcpbs, if existing, and flush the reassembly queue,
751 	 * if there is one...
752 	 * XXX: The "Net/3" implementation doesn't imply that the TCP
753 	 *      reassembly queue should be flushed, but in a situation
754 	 * 	where we're really low on mbufs, this is potentially
755 	 *  	usefull.
756 	 */
757 		LIST_FOREACH(inpb, tcbinfo.listhead, inp_list) {
758 			if ((tcpb = intotcpcb(inpb))) {
759 				while ((te = LIST_FIRST(&tcpb->t_segq))
760 			            != NULL) {
761 					LIST_REMOVE(te, tqe_q);
762 					m_freem(te->tqe_m);
763 					FREE(te, M_TSEGQ);
764 				}
765 			}
766 		}
767 	}
768 }
769 
770 /*
771  * Notify a tcp user of an asynchronous error;
772  * store error as soft error, but wake up user
773  * (for now, won't do anything until can select for soft error).
774  *
775  * Do not wake up user since there currently is no mechanism for
776  * reporting soft errors (yet - a kqueue filter may be added).
777  */
778 static void
779 tcp_notify(inp, error)
780 	struct inpcb *inp;
781 	int error;
782 {
783 	struct tcpcb *tp = (struct tcpcb *)inp->inp_ppcb;
784 
785 	/*
786 	 * Ignore some errors if we are hooked up.
787 	 * If connection hasn't completed, has retransmitted several times,
788 	 * and receives a second error, give up now.  This is better
789 	 * than waiting a long time to establish a connection that
790 	 * can never complete.
791 	 */
792 	if (tp->t_state == TCPS_ESTABLISHED &&
793 	     (error == EHOSTUNREACH || error == ENETUNREACH ||
794 	      error == EHOSTDOWN)) {
795 		return;
796 	} else if (tp->t_state < TCPS_ESTABLISHED && tp->t_rxtshift > 3 &&
797 	    tp->t_softerror)
798 		tcp_drop(tp, error);
799 	else
800 		tp->t_softerror = error;
801 #if 0
802 	wakeup((caddr_t) &so->so_timeo);
803 	sorwakeup(so);
804 	sowwakeup(so);
805 #endif
806 }
807 
808 static int
809 tcp_pcblist(SYSCTL_HANDLER_ARGS)
810 {
811 	int error, i, n, s;
812 	struct inpcb *inp, **inp_list;
813 	inp_gen_t gencnt;
814 	struct xinpgen xig;
815 
816 	/*
817 	 * The process of preparing the TCB list is too time-consuming and
818 	 * resource-intensive to repeat twice on every request.
819 	 */
820 	if (req->oldptr == 0) {
821 		n = tcbinfo.ipi_count;
822 		req->oldidx = 2 * (sizeof xig)
823 			+ (n + n/8) * sizeof(struct xtcpcb);
824 		return 0;
825 	}
826 
827 	if (req->newptr != 0)
828 		return EPERM;
829 
830 	/*
831 	 * OK, now we're committed to doing something.
832 	 */
833 	s = splnet();
834 	gencnt = tcbinfo.ipi_gencnt;
835 	n = tcbinfo.ipi_count;
836 	splx(s);
837 
838 	xig.xig_len = sizeof xig;
839 	xig.xig_count = n;
840 	xig.xig_gen = gencnt;
841 	xig.xig_sogen = so_gencnt;
842 	error = SYSCTL_OUT(req, &xig, sizeof xig);
843 	if (error)
844 		return error;
845 
846 	inp_list = malloc(n * sizeof *inp_list, M_TEMP, M_WAITOK);
847 	if (inp_list == 0)
848 		return ENOMEM;
849 
850 	s = splnet();
851 	for (inp = LIST_FIRST(tcbinfo.listhead), i = 0; inp && i < n;
852 	     inp = LIST_NEXT(inp, inp_list)) {
853 		if (inp->inp_gencnt <= gencnt && !prison_xinpcb(req->p, inp))
854 			inp_list[i++] = inp;
855 	}
856 	splx(s);
857 	n = i;
858 
859 	error = 0;
860 	for (i = 0; i < n; i++) {
861 		inp = inp_list[i];
862 		if (inp->inp_gencnt <= gencnt) {
863 			struct xtcpcb xt;
864 			caddr_t inp_ppcb;
865 			xt.xt_len = sizeof xt;
866 			/* XXX should avoid extra copy */
867 			bcopy(inp, &xt.xt_inp, sizeof *inp);
868 			inp_ppcb = inp->inp_ppcb;
869 			if (inp_ppcb != NULL)
870 				bcopy(inp_ppcb, &xt.xt_tp, sizeof xt.xt_tp);
871 			else
872 				bzero((char *) &xt.xt_tp, sizeof xt.xt_tp);
873 			if (inp->inp_socket)
874 				sotoxsocket(inp->inp_socket, &xt.xt_socket);
875 			error = SYSCTL_OUT(req, &xt, sizeof xt);
876 		}
877 	}
878 	if (!error) {
879 		/*
880 		 * Give the user an updated idea of our state.
881 		 * If the generation differs from what we told
882 		 * her before, she knows that something happened
883 		 * while we were processing this request, and it
884 		 * might be necessary to retry.
885 		 */
886 		s = splnet();
887 		xig.xig_gen = tcbinfo.ipi_gencnt;
888 		xig.xig_sogen = so_gencnt;
889 		xig.xig_count = tcbinfo.ipi_count;
890 		splx(s);
891 		error = SYSCTL_OUT(req, &xig, sizeof xig);
892 	}
893 	free(inp_list, M_TEMP);
894 	return error;
895 }
896 
897 SYSCTL_PROC(_net_inet_tcp, TCPCTL_PCBLIST, pcblist, CTLFLAG_RD, 0, 0,
898 	    tcp_pcblist, "S,xtcpcb", "List of active TCP connections");
899 
900 static int
901 tcp_getcred(SYSCTL_HANDLER_ARGS)
902 {
903 	struct xucred xuc;
904 	struct sockaddr_in addrs[2];
905 	struct inpcb *inp;
906 	int error, s;
907 
908 	error = suser_xxx(0, req->p, PRISON_ROOT);
909 	if (error)
910 		return (error);
911 	error = SYSCTL_IN(req, addrs, sizeof(addrs));
912 	if (error)
913 		return (error);
914 	s = splnet();
915 	inp = in_pcblookup_hash(&tcbinfo, addrs[1].sin_addr, addrs[1].sin_port,
916 	    addrs[0].sin_addr, addrs[0].sin_port, 0, NULL);
917 	if (inp == NULL || inp->inp_socket == NULL) {
918 		error = ENOENT;
919 		goto out;
920 	}
921 	error = u_cansee(req->p->p_ucred, inp->inp_socket->so_cred);
922 	if (error)
923 		goto out;
924 	bzero(&xuc, sizeof(xuc));
925 	xuc.cr_uid = inp->inp_socket->so_cred->cr_uid;
926 	xuc.cr_ngroups = inp->inp_socket->so_cred->cr_ngroups;
927 	bcopy(inp->inp_socket->so_cred->cr_groups, xuc.cr_groups,
928 	    sizeof(xuc.cr_groups));
929 	error = SYSCTL_OUT(req, &xuc, sizeof(struct xucred));
930 out:
931 	splx(s);
932 	return (error);
933 }
934 
935 SYSCTL_PROC(_net_inet_tcp, OID_AUTO, getcred,
936     CTLTYPE_OPAQUE|CTLFLAG_RW|CTLFLAG_PRISON, 0, 0,
937     tcp_getcred, "S,xucred", "Get the xucred of a TCP connection");
938 
939 #ifdef INET6
940 static int
941 tcp6_getcred(SYSCTL_HANDLER_ARGS)
942 {
943 	struct xucred xuc;
944 	struct sockaddr_in6 addrs[2];
945 	struct inpcb *inp;
946 	int error, s, mapped = 0;
947 
948 	error = suser_xxx(0, req->p, PRISON_ROOT);
949 	if (error)
950 		return (error);
951 	error = SYSCTL_IN(req, addrs, sizeof(addrs));
952 	if (error)
953 		return (error);
954 	if (IN6_IS_ADDR_V4MAPPED(&addrs[0].sin6_addr)) {
955 		if (IN6_IS_ADDR_V4MAPPED(&addrs[1].sin6_addr))
956 			mapped = 1;
957 		else
958 			return (EINVAL);
959 	}
960 	s = splnet();
961 	if (mapped == 1)
962 		inp = in_pcblookup_hash(&tcbinfo,
963 			*(struct in_addr *)&addrs[1].sin6_addr.s6_addr[12],
964 			addrs[1].sin6_port,
965 			*(struct in_addr *)&addrs[0].sin6_addr.s6_addr[12],
966 			addrs[0].sin6_port,
967 			0, NULL);
968 	else
969 		inp = in6_pcblookup_hash(&tcbinfo, &addrs[1].sin6_addr,
970 				 addrs[1].sin6_port,
971 				 &addrs[0].sin6_addr, addrs[0].sin6_port,
972 				 0, NULL);
973 	if (inp == NULL || inp->inp_socket == NULL) {
974 		error = ENOENT;
975 		goto out;
976 	}
977 	error = u_cansee(req->p->p_ucred, inp->inp_socket->so_cred);
978 	if (error)
979 		goto out;
980 	bzero(&xuc, sizeof(xuc));
981 	xuc.cr_uid = inp->inp_socket->so_cred->cr_uid;
982 	xuc.cr_ngroups = inp->inp_socket->so_cred->cr_ngroups;
983 	bcopy(inp->inp_socket->so_cred->cr_groups, xuc.cr_groups,
984 	    sizeof(xuc.cr_groups));
985 	error = SYSCTL_OUT(req, &xuc, sizeof(struct xucred));
986 out:
987 	splx(s);
988 	return (error);
989 }
990 
991 SYSCTL_PROC(_net_inet6_tcp6, OID_AUTO, getcred,
992     CTLTYPE_OPAQUE|CTLFLAG_RW|CTLFLAG_PRISON, 0, 0,
993     tcp6_getcred, "S,xucred", "Get the xucred of a TCP6 connection");
994 #endif
995 
996 
997 void
998 tcp_ctlinput(cmd, sa, vip)
999 	int cmd;
1000 	struct sockaddr *sa;
1001 	void *vip;
1002 {
1003 	struct ip *ip = vip;
1004 	struct tcphdr *th;
1005 	struct in_addr faddr;
1006 	struct inpcb *inp;
1007 	struct tcpcb *tp;
1008 	void (*notify) __P((struct inpcb *, int)) = tcp_notify;
1009 	tcp_seq icmp_seq;
1010 	int s;
1011 
1012 	faddr = ((struct sockaddr_in *)sa)->sin_addr;
1013 	if (sa->sa_family != AF_INET || faddr.s_addr == INADDR_ANY)
1014 		return;
1015 
1016 	if (cmd == PRC_QUENCH)
1017 		notify = tcp_quench;
1018 	else if (icmp_may_rst && (cmd == PRC_UNREACH_ADMIN_PROHIB ||
1019 		cmd == PRC_UNREACH_PORT) && ip)
1020 		notify = tcp_drop_syn_sent;
1021 	else if (cmd == PRC_MSGSIZE)
1022 		notify = tcp_mtudisc;
1023 	else if (PRC_IS_REDIRECT(cmd)) {
1024 		ip = 0;
1025 		notify = in_rtchange;
1026 	} else if (cmd == PRC_HOSTDEAD)
1027 		ip = 0;
1028 	else if ((unsigned)cmd > PRC_NCMDS || inetctlerrmap[cmd] == 0)
1029 		return;
1030 	if (ip) {
1031 		s = splnet();
1032 		th = (struct tcphdr *)((caddr_t)ip
1033 				       + (IP_VHL_HL(ip->ip_vhl) << 2));
1034 		inp = in_pcblookup_hash(&tcbinfo, faddr, th->th_dport,
1035 		    ip->ip_src, th->th_sport, 0, NULL);
1036 		if (inp != NULL && inp->inp_socket != NULL) {
1037 			icmp_seq = htonl(th->th_seq);
1038 			tp = intotcpcb(inp);
1039 			if (SEQ_GEQ(icmp_seq, tp->snd_una) &&
1040 			    SEQ_LT(icmp_seq, tp->snd_max))
1041 				(*notify)(inp, inetctlerrmap[cmd]);
1042 		}
1043 		splx(s);
1044 	} else
1045 		in_pcbnotifyall(&tcb, faddr, inetctlerrmap[cmd], notify);
1046 }
1047 
1048 #ifdef INET6
1049 void
1050 tcp6_ctlinput(cmd, sa, d)
1051 	int cmd;
1052 	struct sockaddr *sa;
1053 	void *d;
1054 {
1055 	struct tcphdr th;
1056 	void (*notify) __P((struct inpcb *, int)) = tcp_notify;
1057 	struct ip6_hdr *ip6;
1058 	struct mbuf *m;
1059 	struct ip6ctlparam *ip6cp = NULL;
1060 	const struct sockaddr_in6 *sa6_src = NULL;
1061 	int off;
1062 	struct tcp_portonly {
1063 		u_int16_t th_sport;
1064 		u_int16_t th_dport;
1065 	} *thp;
1066 
1067 	if (sa->sa_family != AF_INET6 ||
1068 	    sa->sa_len != sizeof(struct sockaddr_in6))
1069 		return;
1070 
1071 	if (cmd == PRC_QUENCH)
1072 		notify = tcp_quench;
1073 	else if (cmd == PRC_MSGSIZE)
1074 		notify = tcp_mtudisc;
1075 	else if (!PRC_IS_REDIRECT(cmd) &&
1076 		 ((unsigned)cmd > PRC_NCMDS || inet6ctlerrmap[cmd] == 0))
1077 		return;
1078 
1079 	/* if the parameter is from icmp6, decode it. */
1080 	if (d != NULL) {
1081 		ip6cp = (struct ip6ctlparam *)d;
1082 		m = ip6cp->ip6c_m;
1083 		ip6 = ip6cp->ip6c_ip6;
1084 		off = ip6cp->ip6c_off;
1085 		sa6_src = ip6cp->ip6c_src;
1086 	} else {
1087 		m = NULL;
1088 		ip6 = NULL;
1089 		off = 0;	/* fool gcc */
1090 		sa6_src = &sa6_any;
1091 	}
1092 
1093 	if (ip6) {
1094 		/*
1095 		 * XXX: We assume that when IPV6 is non NULL,
1096 		 * M and OFF are valid.
1097 		 */
1098 
1099 		/* check if we can safely examine src and dst ports */
1100 		if (m->m_pkthdr.len < off + sizeof(*thp))
1101 			return;
1102 
1103 		bzero(&th, sizeof(th));
1104 		m_copydata(m, off, sizeof(*thp), (caddr_t)&th);
1105 
1106 		in6_pcbnotify(&tcb, sa, th.th_dport,
1107 		    (struct sockaddr *)ip6cp->ip6c_src,
1108 		    th.th_sport, cmd, notify);
1109 	} else
1110 		in6_pcbnotify(&tcb, sa, 0, (struct sockaddr *)sa6_src,
1111 			      0, cmd, notify);
1112 }
1113 #endif /* INET6 */
1114 
1115 tcp_seq
1116 tcp_new_isn()
1117 {
1118 
1119 	if (tcp_seq_genscheme > 1 || tcp_seq_genscheme < 0)
1120 		tcp_seq_genscheme = 1;
1121 
1122 	switch (tcp_seq_genscheme) {
1123 	case 0:			/* Random positive increments */
1124 		tcp_iss += TCP_ISSINCR/2;
1125 		return tcp_iss;
1126 	case 1:			/* OpenBSD randomized scheme */
1127 		return tcp_rndiss_next();
1128 	default:
1129 		panic("cannot happen");
1130 	}
1131 }
1132 
1133 #define TCP_RNDISS_ROUNDS	16
1134 #define TCP_RNDISS_OUT	7200
1135 #define TCP_RNDISS_MAX	30000
1136 
1137 u_int8_t tcp_rndiss_sbox[128];
1138 u_int16_t tcp_rndiss_msb;
1139 u_int16_t tcp_rndiss_cnt;
1140 long tcp_rndiss_reseed;
1141 
1142 u_int16_t
1143 tcp_rndiss_encrypt(val)
1144 	u_int16_t val;
1145 {
1146 	u_int16_t sum = 0, i;
1147 
1148 	for (i = 0; i < TCP_RNDISS_ROUNDS; i++) {
1149 		sum += 0x79b9;
1150 		val ^= ((u_int16_t)tcp_rndiss_sbox[(val^sum) & 0x7f]) << 7;
1151 		val = ((val & 0xff) << 7) | (val >> 8);
1152 	}
1153 
1154 	return val;
1155 }
1156 
1157 void
1158 tcp_rndiss_init()
1159 {
1160 	struct timeval time;
1161 
1162 	getmicrotime(&time);
1163 	read_random(tcp_rndiss_sbox, sizeof(tcp_rndiss_sbox));
1164 
1165 	tcp_rndiss_reseed = time.tv_sec + TCP_RNDISS_OUT;
1166 	tcp_rndiss_msb = tcp_rndiss_msb == 0x8000 ? 0 : 0x8000;
1167 	tcp_rndiss_cnt = 0;
1168 }
1169 
1170 tcp_seq
1171 tcp_rndiss_next()
1172 {
1173 	u_int16_t tmp;
1174 	struct timeval time;
1175 
1176 	getmicrotime(&time);
1177 
1178         if (tcp_rndiss_cnt >= TCP_RNDISS_MAX ||
1179 	    time.tv_sec > tcp_rndiss_reseed)
1180                 tcp_rndiss_init();
1181 
1182 	read_random(&tmp, sizeof(tmp));
1183 
1184 	/* (tmp & 0x7fff) ensures a 32768 byte gap between ISS */
1185 	return ((tcp_rndiss_encrypt(tcp_rndiss_cnt++) | tcp_rndiss_msb) <<16) |
1186 		(tmp & 0x7fff);
1187 }
1188 
1189 
1190 /*
1191  * When a source quench is received, close congestion window
1192  * to one segment.  We will gradually open it again as we proceed.
1193  */
1194 void
1195 tcp_quench(inp, errno)
1196 	struct inpcb *inp;
1197 	int errno;
1198 {
1199 	struct tcpcb *tp = intotcpcb(inp);
1200 
1201 	if (tp)
1202 		tp->snd_cwnd = tp->t_maxseg;
1203 }
1204 
1205 /*
1206  * When a specific ICMP unreachable message is received and the
1207  * connection state is SYN-SENT, drop the connection.  This behavior
1208  * is controlled by the icmp_may_rst sysctl.
1209  */
1210 void
1211 tcp_drop_syn_sent(inp, errno)
1212 	struct inpcb *inp;
1213 	int errno;
1214 {
1215 	struct tcpcb *tp = intotcpcb(inp);
1216 
1217 	if (tp && tp->t_state == TCPS_SYN_SENT)
1218 		tcp_drop(tp, errno);
1219 }
1220 
1221 /*
1222  * When `need fragmentation' ICMP is received, update our idea of the MSS
1223  * based on the new value in the route.  Also nudge TCP to send something,
1224  * since we know the packet we just sent was dropped.
1225  * This duplicates some code in the tcp_mss() function in tcp_input.c.
1226  */
1227 void
1228 tcp_mtudisc(inp, errno)
1229 	struct inpcb *inp;
1230 	int errno;
1231 {
1232 	struct tcpcb *tp = intotcpcb(inp);
1233 	struct rtentry *rt;
1234 	struct rmxp_tao *taop;
1235 	struct socket *so = inp->inp_socket;
1236 	int offered;
1237 	int mss;
1238 #ifdef INET6
1239 	int isipv6 = (tp->t_inpcb->inp_vflag & INP_IPV6) != 0;
1240 #endif /* INET6 */
1241 
1242 	if (tp) {
1243 #ifdef INET6
1244 		if (isipv6)
1245 			rt = tcp_rtlookup6(inp);
1246 		else
1247 #endif /* INET6 */
1248 		rt = tcp_rtlookup(inp);
1249 		if (!rt || !rt->rt_rmx.rmx_mtu) {
1250 			tp->t_maxopd = tp->t_maxseg =
1251 #ifdef INET6
1252 				isipv6 ? tcp_v6mssdflt :
1253 #endif /* INET6 */
1254 				tcp_mssdflt;
1255 			return;
1256 		}
1257 		taop = rmx_taop(rt->rt_rmx);
1258 		offered = taop->tao_mssopt;
1259 		mss = rt->rt_rmx.rmx_mtu -
1260 #ifdef INET6
1261 			(isipv6 ?
1262 			 sizeof(struct ip6_hdr) + sizeof(struct tcphdr) :
1263 #endif /* INET6 */
1264 			 sizeof(struct tcpiphdr)
1265 #ifdef INET6
1266 			 )
1267 #endif /* INET6 */
1268 			;
1269 
1270 		if (offered)
1271 			mss = min(mss, offered);
1272 		/*
1273 		 * XXX - The above conditional probably violates the TCP
1274 		 * spec.  The problem is that, since we don't know the
1275 		 * other end's MSS, we are supposed to use a conservative
1276 		 * default.  But, if we do that, then MTU discovery will
1277 		 * never actually take place, because the conservative
1278 		 * default is much less than the MTUs typically seen
1279 		 * on the Internet today.  For the moment, we'll sweep
1280 		 * this under the carpet.
1281 		 *
1282 		 * The conservative default might not actually be a problem
1283 		 * if the only case this occurs is when sending an initial
1284 		 * SYN with options and data to a host we've never talked
1285 		 * to before.  Then, they will reply with an MSS value which
1286 		 * will get recorded and the new parameters should get
1287 		 * recomputed.  For Further Study.
1288 		 */
1289 		if (tp->t_maxopd <= mss)
1290 			return;
1291 		tp->t_maxopd = mss;
1292 
1293 		if ((tp->t_flags & (TF_REQ_TSTMP|TF_NOOPT)) == TF_REQ_TSTMP &&
1294 		    (tp->t_flags & TF_RCVD_TSTMP) == TF_RCVD_TSTMP)
1295 			mss -= TCPOLEN_TSTAMP_APPA;
1296 		if ((tp->t_flags & (TF_REQ_CC|TF_NOOPT)) == TF_REQ_CC &&
1297 		    (tp->t_flags & TF_RCVD_CC) == TF_RCVD_CC)
1298 			mss -= TCPOLEN_CC_APPA;
1299 #if	(MCLBYTES & (MCLBYTES - 1)) == 0
1300 		if (mss > MCLBYTES)
1301 			mss &= ~(MCLBYTES-1);
1302 #else
1303 		if (mss > MCLBYTES)
1304 			mss = mss / MCLBYTES * MCLBYTES;
1305 #endif
1306 		if (so->so_snd.sb_hiwat < mss)
1307 			mss = so->so_snd.sb_hiwat;
1308 
1309 		tp->t_maxseg = mss;
1310 
1311 		tcpstat.tcps_mturesent++;
1312 		tp->t_rtttime = 0;
1313 		tp->snd_nxt = tp->snd_una;
1314 		tcp_output(tp);
1315 	}
1316 }
1317 
1318 /*
1319  * Look-up the routing entry to the peer of this inpcb.  If no route
1320  * is found and it cannot be allocated the return NULL.  This routine
1321  * is called by TCP routines that access the rmx structure and by tcp_mss
1322  * to get the interface MTU.
1323  */
1324 struct rtentry *
1325 tcp_rtlookup(inp)
1326 	struct inpcb *inp;
1327 {
1328 	struct route *ro;
1329 	struct rtentry *rt;
1330 
1331 	ro = &inp->inp_route;
1332 	rt = ro->ro_rt;
1333 	if (rt == NULL || !(rt->rt_flags & RTF_UP)) {
1334 		/* No route yet, so try to acquire one */
1335 		if (inp->inp_faddr.s_addr != INADDR_ANY) {
1336 			ro->ro_dst.sa_family = AF_INET;
1337 			ro->ro_dst.sa_len = sizeof(struct sockaddr_in);
1338 			((struct sockaddr_in *) &ro->ro_dst)->sin_addr =
1339 				inp->inp_faddr;
1340 			rtalloc(ro);
1341 			rt = ro->ro_rt;
1342 		}
1343 	}
1344 	return rt;
1345 }
1346 
1347 #ifdef INET6
1348 struct rtentry *
1349 tcp_rtlookup6(inp)
1350 	struct inpcb *inp;
1351 {
1352 	struct route_in6 *ro6;
1353 	struct rtentry *rt;
1354 
1355 	ro6 = &inp->in6p_route;
1356 	rt = ro6->ro_rt;
1357 	if (rt == NULL || !(rt->rt_flags & RTF_UP)) {
1358 		/* No route yet, so try to acquire one */
1359 		if (!IN6_IS_ADDR_UNSPECIFIED(&inp->in6p_faddr)) {
1360 			struct sockaddr_in6 *dst6;
1361 
1362 			dst6 = (struct sockaddr_in6 *)&ro6->ro_dst;
1363 			dst6->sin6_family = AF_INET6;
1364 			dst6->sin6_len = sizeof(*dst6);
1365 			dst6->sin6_addr = inp->in6p_faddr;
1366 			rtalloc((struct route *)ro6);
1367 			rt = ro6->ro_rt;
1368 		}
1369 	}
1370 	return rt;
1371 }
1372 #endif /* INET6 */
1373 
1374 #ifdef IPSEC
1375 /* compute ESP/AH header size for TCP, including outer IP header. */
1376 size_t
1377 ipsec_hdrsiz_tcp(tp)
1378 	struct tcpcb *tp;
1379 {
1380 	struct inpcb *inp;
1381 	struct mbuf *m;
1382 	size_t hdrsiz;
1383 	struct ip *ip;
1384 #ifdef INET6
1385 	struct ip6_hdr *ip6;
1386 #endif /* INET6 */
1387 	struct tcphdr *th;
1388 
1389 	if ((tp == NULL) || ((inp = tp->t_inpcb) == NULL))
1390 		return 0;
1391 	MGETHDR(m, M_DONTWAIT, MT_DATA);
1392 	if (!m)
1393 		return 0;
1394 
1395 #ifdef INET6
1396 	if ((inp->inp_vflag & INP_IPV6) != 0) {
1397 		ip6 = mtod(m, struct ip6_hdr *);
1398 		th = (struct tcphdr *)(ip6 + 1);
1399 		m->m_pkthdr.len = m->m_len =
1400 			sizeof(struct ip6_hdr) + sizeof(struct tcphdr);
1401 		tcp_fillheaders(tp, ip6, th);
1402 		hdrsiz = ipsec6_hdrsiz(m, IPSEC_DIR_OUTBOUND, inp);
1403 	} else
1404 #endif /* INET6 */
1405       {
1406 	ip = mtod(m, struct ip *);
1407 	th = (struct tcphdr *)(ip + 1);
1408 	m->m_pkthdr.len = m->m_len = sizeof(struct tcpiphdr);
1409 	tcp_fillheaders(tp, ip, th);
1410 	hdrsiz = ipsec4_hdrsiz(m, IPSEC_DIR_OUTBOUND, inp);
1411       }
1412 
1413 	m_free(m);
1414 	return hdrsiz;
1415 }
1416 #endif /*IPSEC*/
1417 
1418 /*
1419  * Return a pointer to the cached information about the remote host.
1420  * The cached information is stored in the protocol specific part of
1421  * the route metrics.
1422  */
1423 struct rmxp_tao *
1424 tcp_gettaocache(inp)
1425 	struct inpcb *inp;
1426 {
1427 	struct rtentry *rt;
1428 
1429 #ifdef INET6
1430 	if ((inp->inp_vflag & INP_IPV6) != 0)
1431 		rt = tcp_rtlookup6(inp);
1432 	else
1433 #endif /* INET6 */
1434 	rt = tcp_rtlookup(inp);
1435 
1436 	/* Make sure this is a host route and is up. */
1437 	if (rt == NULL ||
1438 	    (rt->rt_flags & (RTF_UP|RTF_HOST)) != (RTF_UP|RTF_HOST))
1439 		return NULL;
1440 
1441 	return rmx_taop(rt->rt_rmx);
1442 }
1443 
1444 /*
1445  * Clear all the TAO cache entries, called from tcp_init.
1446  *
1447  * XXX
1448  * This routine is just an empty one, because we assume that the routing
1449  * routing tables are initialized at the same time when TCP, so there is
1450  * nothing in the cache left over.
1451  */
1452 static void
1453 tcp_cleartaocache()
1454 {
1455 }
1456