xref: /freebsd/sys/netinet/tcp_timewait.c (revision 6b3455a7665208c366849f0b2b3bc916fb97516e)
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  * 4. Neither the name of the University nor the names of its contributors
14  *    may be used to endorse or promote products derived from this software
15  *    without specific prior written permission.
16  *
17  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
18  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
21  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
27  * SUCH DAMAGE.
28  *
29  *	@(#)tcp_subr.c	8.2 (Berkeley) 5/24/95
30  * $FreeBSD$
31  */
32 
33 #include "opt_compat.h"
34 #include "opt_inet.h"
35 #include "opt_inet6.h"
36 #include "opt_ipsec.h"
37 #include "opt_mac.h"
38 #include "opt_tcpdebug.h"
39 #include "opt_tcp_sack.h"
40 
41 #include <sys/param.h>
42 #include <sys/systm.h>
43 #include <sys/callout.h>
44 #include <sys/kernel.h>
45 #include <sys/sysctl.h>
46 #include <sys/mac.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/uma.h>
59 
60 #include <net/route.h>
61 #include <net/if.h>
62 
63 #include <netinet/in.h>
64 #include <netinet/in_systm.h>
65 #include <netinet/ip.h>
66 #ifdef INET6
67 #include <netinet/ip6.h>
68 #endif
69 #include <netinet/in_pcb.h>
70 #ifdef INET6
71 #include <netinet6/in6_pcb.h>
72 #endif
73 #include <netinet/in_var.h>
74 #include <netinet/ip_var.h>
75 #ifdef INET6
76 #include <netinet6/ip6_var.h>
77 #include <netinet6/nd6.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 #ifdef FAST_IPSEC
101 #include <netipsec/ipsec.h>
102 #include <netipsec/xform.h>
103 #ifdef INET6
104 #include <netipsec/ipsec6.h>
105 #endif
106 #include <netipsec/key.h>
107 #define	IPSEC
108 #endif /*FAST_IPSEC*/
109 
110 #include <machine/in_cksum.h>
111 #include <sys/md5.h>
112 
113 int 	tcp_mssdflt = TCP_MSS;
114 SYSCTL_INT(_net_inet_tcp, TCPCTL_MSSDFLT, mssdflt, CTLFLAG_RW,
115     &tcp_mssdflt , 0, "Default TCP Maximum Segment Size");
116 
117 #ifdef INET6
118 int	tcp_v6mssdflt = TCP6_MSS;
119 SYSCTL_INT(_net_inet_tcp, TCPCTL_V6MSSDFLT, v6mssdflt,
120 	CTLFLAG_RW, &tcp_v6mssdflt , 0,
121 	"Default TCP Maximum Segment Size for IPv6");
122 #endif
123 
124 /*
125  * Minimum MSS we accept and use. This prevents DoS attacks where
126  * we are forced to a ridiculous low MSS like 20 and send hundreds
127  * of packets instead of one. The effect scales with the available
128  * bandwidth and quickly saturates the CPU and network interface
129  * with packet generation and sending. Set to zero to disable MINMSS
130  * checking. This setting prevents us from sending too small packets.
131  */
132 int	tcp_minmss = TCP_MINMSS;
133 SYSCTL_INT(_net_inet_tcp, OID_AUTO, minmss, CTLFLAG_RW,
134     &tcp_minmss , 0, "Minmum TCP Maximum Segment Size");
135 /*
136  * Number of TCP segments per second we accept from remote host
137  * before we start to calculate average segment size. If average
138  * segment size drops below the minimum TCP MSS we assume a DoS
139  * attack and reset+drop the connection. Care has to be taken not to
140  * set this value too small to not kill interactive type connections
141  * (telnet, SSH) which send many small packets.
142  */
143 int     tcp_minmssoverload = TCP_MINMSSOVERLOAD;
144 SYSCTL_INT(_net_inet_tcp, OID_AUTO, minmssoverload, CTLFLAG_RW,
145     &tcp_minmssoverload , 0, "Number of TCP Segments per Second allowed to"
146     "be under the MINMSS Size");
147 
148 #if 0
149 static int 	tcp_rttdflt = TCPTV_SRTTDFLT / PR_SLOWHZ;
150 SYSCTL_INT(_net_inet_tcp, TCPCTL_RTTDFLT, rttdflt, CTLFLAG_RW,
151     &tcp_rttdflt , 0, "Default maximum TCP Round Trip Time");
152 #endif
153 
154 int	tcp_do_rfc1323 = 1;
155 SYSCTL_INT(_net_inet_tcp, TCPCTL_DO_RFC1323, rfc1323, CTLFLAG_RW,
156     &tcp_do_rfc1323 , 0, "Enable rfc1323 (high performance TCP) extensions");
157 
158 int	tcp_do_rfc1644 = 0;
159 SYSCTL_INT(_net_inet_tcp, TCPCTL_DO_RFC1644, rfc1644, CTLFLAG_RW,
160     &tcp_do_rfc1644 , 0, "Enable rfc1644 (TTCP) extensions");
161 
162 static int	tcp_tcbhashsize = 0;
163 SYSCTL_INT(_net_inet_tcp, OID_AUTO, tcbhashsize, CTLFLAG_RDTUN,
164      &tcp_tcbhashsize, 0, "Size of TCP control-block hashtable");
165 
166 static int	do_tcpdrain = 1;
167 SYSCTL_INT(_net_inet_tcp, OID_AUTO, do_tcpdrain, CTLFLAG_RW, &do_tcpdrain, 0,
168      "Enable tcp_drain routine for extra help when low on mbufs");
169 
170 SYSCTL_INT(_net_inet_tcp, OID_AUTO, pcbcount, CTLFLAG_RD,
171     &tcbinfo.ipi_count, 0, "Number of active PCBs");
172 
173 static int	icmp_may_rst = 1;
174 SYSCTL_INT(_net_inet_tcp, OID_AUTO, icmp_may_rst, CTLFLAG_RW, &icmp_may_rst, 0,
175     "Certain ICMP unreachable messages may abort connections in SYN_SENT");
176 
177 static int	tcp_isn_reseed_interval = 0;
178 SYSCTL_INT(_net_inet_tcp, OID_AUTO, isn_reseed_interval, CTLFLAG_RW,
179     &tcp_isn_reseed_interval, 0, "Seconds between reseeding of ISN secret");
180 
181 /*
182  * TCP bandwidth limiting sysctls.  Note that the default lower bound of
183  * 1024 exists only for debugging.  A good production default would be
184  * something like 6100.
185  */
186 static int	tcp_inflight_enable = 1;
187 SYSCTL_INT(_net_inet_tcp, OID_AUTO, inflight_enable, CTLFLAG_RW,
188     &tcp_inflight_enable, 0, "Enable automatic TCP inflight data limiting");
189 
190 static int	tcp_inflight_debug = 0;
191 SYSCTL_INT(_net_inet_tcp, OID_AUTO, inflight_debug, CTLFLAG_RW,
192     &tcp_inflight_debug, 0, "Debug TCP inflight calculations");
193 
194 static int	tcp_inflight_min = 6144;
195 SYSCTL_INT(_net_inet_tcp, OID_AUTO, inflight_min, CTLFLAG_RW,
196     &tcp_inflight_min, 0, "Lower-bound for TCP inflight window");
197 
198 static int	tcp_inflight_max = TCP_MAXWIN << TCP_MAX_WINSHIFT;
199 SYSCTL_INT(_net_inet_tcp, OID_AUTO, inflight_max, CTLFLAG_RW,
200     &tcp_inflight_max, 0, "Upper-bound for TCP inflight window");
201 static int	tcp_inflight_stab = 20;
202 SYSCTL_INT(_net_inet_tcp, OID_AUTO, inflight_stab, CTLFLAG_RW,
203     &tcp_inflight_stab, 0, "Inflight Algorithm Stabilization 20 = 2 packets");
204 
205 SYSCTL_NODE(_net_inet_tcp, OID_AUTO, sack, CTLFLAG_RW, 0, "TCP SACK");
206 int tcp_do_sack = 1;
207 SYSCTL_INT(_net_inet_tcp_sack, OID_AUTO, enable, CTLFLAG_RW,
208     &tcp_do_sack, 0, "Enable/Disable TCP SACK support");
209 
210 uma_zone_t sack_hole_zone;
211 
212 static struct inpcb *tcp_notify(struct inpcb *, int);
213 static void	tcp_discardcb(struct tcpcb *);
214 static void	tcp_isn_tick(void *);
215 
216 /*
217  * Target size of TCP PCB hash tables. Must be a power of two.
218  *
219  * Note that this can be overridden by the kernel environment
220  * variable net.inet.tcp.tcbhashsize
221  */
222 #ifndef TCBHASHSIZE
223 #define TCBHASHSIZE	512
224 #endif
225 
226 /*
227  * XXX
228  * Callouts should be moved into struct tcp directly.  They are currently
229  * separate because the tcpcb structure is exported to userland for sysctl
230  * parsing purposes, which do not know about callouts.
231  */
232 struct	tcpcb_mem {
233 	struct	tcpcb tcb;
234 	struct	callout tcpcb_mem_rexmt, tcpcb_mem_persist, tcpcb_mem_keep;
235 	struct	callout tcpcb_mem_2msl, tcpcb_mem_delack;
236 };
237 
238 static uma_zone_t tcpcb_zone;
239 static uma_zone_t tcptw_zone;
240 struct callout isn_callout;
241 
242 /*
243  * Tcp initialization
244  */
245 void
246 tcp_init()
247 {
248 	int hashsize = TCBHASHSIZE;
249 
250 	tcp_ccgen = 1;
251 
252 	tcp_delacktime = TCPTV_DELACK;
253 	tcp_keepinit = TCPTV_KEEP_INIT;
254 	tcp_keepidle = TCPTV_KEEP_IDLE;
255 	tcp_keepintvl = TCPTV_KEEPINTVL;
256 	tcp_maxpersistidle = TCPTV_KEEP_IDLE;
257 	tcp_msl = TCPTV_MSL;
258 	tcp_rexmit_min = TCPTV_MIN;
259 	tcp_rexmit_slop = TCPTV_CPU_VAR;
260 
261 	INP_INFO_LOCK_INIT(&tcbinfo, "tcp");
262 	LIST_INIT(&tcb);
263 	tcbinfo.listhead = &tcb;
264 	TUNABLE_INT_FETCH("net.inet.tcp.tcbhashsize", &hashsize);
265 	if (!powerof2(hashsize)) {
266 		printf("WARNING: TCB hash size not a power of 2\n");
267 		hashsize = 512; /* safe default */
268 	}
269 	tcp_tcbhashsize = hashsize;
270 	tcbinfo.hashbase = hashinit(hashsize, M_PCB, &tcbinfo.hashmask);
271 	tcbinfo.porthashbase = hashinit(hashsize, M_PCB,
272 					&tcbinfo.porthashmask);
273 	tcbinfo.ipi_zone = uma_zcreate("inpcb", sizeof(struct inpcb),
274 	    NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, UMA_ZONE_NOFREE);
275 	uma_zone_set_max(tcbinfo.ipi_zone, maxsockets);
276 #ifdef INET6
277 #define TCP_MINPROTOHDR (sizeof(struct ip6_hdr) + sizeof(struct tcphdr))
278 #else /* INET6 */
279 #define TCP_MINPROTOHDR (sizeof(struct tcpiphdr))
280 #endif /* INET6 */
281 	if (max_protohdr < TCP_MINPROTOHDR)
282 		max_protohdr = TCP_MINPROTOHDR;
283 	if (max_linkhdr + TCP_MINPROTOHDR > MHLEN)
284 		panic("tcp_init");
285 #undef TCP_MINPROTOHDR
286 	/*
287 	 * These have to be type stable for the benefit of the timers.
288 	 */
289 	tcpcb_zone = uma_zcreate("tcpcb", sizeof(struct tcpcb_mem),
290 	    NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, UMA_ZONE_NOFREE);
291 	uma_zone_set_max(tcpcb_zone, maxsockets);
292 	tcptw_zone = uma_zcreate("tcptw", sizeof(struct tcptw),
293 	    NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, UMA_ZONE_NOFREE);
294 	uma_zone_set_max(tcptw_zone, maxsockets / 5);
295 	tcp_timer_init();
296 	syncache_init();
297 	tcp_hc_init();
298 	tcp_reass_init();
299 	callout_init(&isn_callout, CALLOUT_MPSAFE);
300 	tcp_isn_tick(NULL);
301 	EVENTHANDLER_REGISTER(shutdown_pre_sync, tcp_fini, NULL,
302 		SHUTDOWN_PRI_DEFAULT);
303 	sack_hole_zone = uma_zcreate("sackhole", sizeof(struct sackhole),
304 	    NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, UMA_ZONE_NOFREE);
305 }
306 
307 void
308 tcp_fini(xtp)
309 	void *xtp;
310 {
311 	callout_stop(&isn_callout);
312 
313 }
314 
315 /*
316  * Fill in the IP and TCP headers for an outgoing packet, given the tcpcb.
317  * tcp_template used to store this data in mbufs, but we now recopy it out
318  * of the tcpcb each time to conserve mbufs.
319  */
320 void
321 tcpip_fillheaders(inp, ip_ptr, tcp_ptr)
322 	struct inpcb *inp;
323 	void *ip_ptr;
324 	void *tcp_ptr;
325 {
326 	struct tcphdr *th = (struct tcphdr *)tcp_ptr;
327 
328 #ifdef INET6
329 	if ((inp->inp_vflag & INP_IPV6) != 0) {
330 		struct ip6_hdr *ip6;
331 
332 		ip6 = (struct ip6_hdr *)ip_ptr;
333 		ip6->ip6_flow = (ip6->ip6_flow & ~IPV6_FLOWINFO_MASK) |
334 			(inp->in6p_flowinfo & IPV6_FLOWINFO_MASK);
335 		ip6->ip6_vfc = (ip6->ip6_vfc & ~IPV6_VERSION_MASK) |
336 			(IPV6_VERSION & IPV6_VERSION_MASK);
337 		ip6->ip6_nxt = IPPROTO_TCP;
338 		ip6->ip6_plen = sizeof(struct tcphdr);
339 		ip6->ip6_src = inp->in6p_laddr;
340 		ip6->ip6_dst = inp->in6p_faddr;
341 	} else
342 #endif
343 	{
344 		struct ip *ip;
345 
346 		ip = (struct ip *)ip_ptr;
347 		ip->ip_v = IPVERSION;
348 		ip->ip_hl = 5;
349 		ip->ip_tos = inp->inp_ip_tos;
350 		ip->ip_len = 0;
351 		ip->ip_id = 0;
352 		ip->ip_off = 0;
353 		ip->ip_ttl = inp->inp_ip_ttl;
354 		ip->ip_sum = 0;
355 		ip->ip_p = IPPROTO_TCP;
356 		ip->ip_src = inp->inp_laddr;
357 		ip->ip_dst = inp->inp_faddr;
358 	}
359 	th->th_sport = inp->inp_lport;
360 	th->th_dport = inp->inp_fport;
361 	th->th_seq = 0;
362 	th->th_ack = 0;
363 	th->th_x2 = 0;
364 	th->th_off = 5;
365 	th->th_flags = 0;
366 	th->th_win = 0;
367 	th->th_urp = 0;
368 	th->th_sum = 0;		/* in_pseudo() is called later for ipv4 */
369 }
370 
371 /*
372  * Create template to be used to send tcp packets on a connection.
373  * Allocates an mbuf and fills in a skeletal tcp/ip header.  The only
374  * use for this function is in keepalives, which use tcp_respond.
375  */
376 struct tcptemp *
377 tcpip_maketemplate(inp)
378 	struct inpcb *inp;
379 {
380 	struct mbuf *m;
381 	struct tcptemp *n;
382 
383 	m = m_get(M_DONTWAIT, MT_HEADER);
384 	if (m == NULL)
385 		return (0);
386 	m->m_len = sizeof(struct tcptemp);
387 	n = mtod(m, struct tcptemp *);
388 
389 	tcpip_fillheaders(inp, (void *)&n->tt_ipgen, (void *)&n->tt_t);
390 	return (n);
391 }
392 
393 /*
394  * Send a single message to the TCP at address specified by
395  * the given TCP/IP header.  If m == NULL, then we make a copy
396  * of the tcpiphdr at ti and send directly to the addressed host.
397  * This is used to force keep alive messages out using the TCP
398  * template for a connection.  If flags are given then we send
399  * a message back to the TCP which originated the * segment ti,
400  * and discard the mbuf containing it and any other attached mbufs.
401  *
402  * In any case the ack and sequence number of the transmitted
403  * segment are as specified by the parameters.
404  *
405  * NOTE: If m != NULL, then ti must point to *inside* the mbuf.
406  */
407 void
408 tcp_respond(tp, ipgen, th, m, ack, seq, flags)
409 	struct tcpcb *tp;
410 	void *ipgen;
411 	register struct tcphdr *th;
412 	register struct mbuf *m;
413 	tcp_seq ack, seq;
414 	int flags;
415 {
416 	register int tlen;
417 	int win = 0;
418 	struct ip *ip;
419 	struct tcphdr *nth;
420 #ifdef INET6
421 	struct ip6_hdr *ip6;
422 	int isipv6;
423 #endif /* INET6 */
424 	int ipflags = 0;
425 	struct inpcb *inp;
426 
427 	KASSERT(tp != NULL || m != NULL, ("tcp_respond: tp and m both NULL"));
428 
429 #ifdef INET6
430 	isipv6 = ((struct ip *)ipgen)->ip_v == 6;
431 	ip6 = ipgen;
432 #endif /* INET6 */
433 	ip = ipgen;
434 
435 	if (tp != NULL) {
436 		inp = tp->t_inpcb;
437 		KASSERT(inp != NULL, ("tcp control block w/o inpcb"));
438 		INP_INFO_WLOCK_ASSERT(&tcbinfo);
439 		INP_LOCK_ASSERT(inp);
440 	} else
441 		inp = NULL;
442 
443 	if (tp != NULL) {
444 		if (!(flags & TH_RST)) {
445 			win = sbspace(&inp->inp_socket->so_rcv);
446 			if (win > (long)TCP_MAXWIN << tp->rcv_scale)
447 				win = (long)TCP_MAXWIN << tp->rcv_scale;
448 		}
449 	}
450 	if (m == NULL) {
451 		m = m_gethdr(M_DONTWAIT, MT_HEADER);
452 		if (m == NULL)
453 			return;
454 		tlen = 0;
455 		m->m_data += max_linkhdr;
456 #ifdef INET6
457 		if (isipv6) {
458 			bcopy((caddr_t)ip6, mtod(m, caddr_t),
459 			      sizeof(struct ip6_hdr));
460 			ip6 = mtod(m, struct ip6_hdr *);
461 			nth = (struct tcphdr *)(ip6 + 1);
462 		} else
463 #endif /* INET6 */
464 	      {
465 		bcopy((caddr_t)ip, mtod(m, caddr_t), sizeof(struct ip));
466 		ip = mtod(m, struct ip *);
467 		nth = (struct tcphdr *)(ip + 1);
468 	      }
469 		bcopy((caddr_t)th, (caddr_t)nth, sizeof(struct tcphdr));
470 		flags = TH_ACK;
471 	} else {
472 		m_freem(m->m_next);
473 		m->m_next = NULL;
474 		m->m_data = (caddr_t)ipgen;
475 		/* m_len is set later */
476 		tlen = 0;
477 #define xchg(a,b,type) { type t; t=a; a=b; b=t; }
478 #ifdef INET6
479 		if (isipv6) {
480 			xchg(ip6->ip6_dst, ip6->ip6_src, struct in6_addr);
481 			nth = (struct tcphdr *)(ip6 + 1);
482 		} else
483 #endif /* INET6 */
484 	      {
485 		xchg(ip->ip_dst.s_addr, ip->ip_src.s_addr, n_long);
486 		nth = (struct tcphdr *)(ip + 1);
487 	      }
488 		if (th != nth) {
489 			/*
490 			 * this is usually a case when an extension header
491 			 * exists between the IPv6 header and the
492 			 * TCP header.
493 			 */
494 			nth->th_sport = th->th_sport;
495 			nth->th_dport = th->th_dport;
496 		}
497 		xchg(nth->th_dport, nth->th_sport, n_short);
498 #undef xchg
499 	}
500 #ifdef INET6
501 	if (isipv6) {
502 		ip6->ip6_flow = 0;
503 		ip6->ip6_vfc = IPV6_VERSION;
504 		ip6->ip6_nxt = IPPROTO_TCP;
505 		ip6->ip6_plen = htons((u_short)(sizeof (struct tcphdr) +
506 						tlen));
507 		tlen += sizeof (struct ip6_hdr) + sizeof (struct tcphdr);
508 	} else
509 #endif
510       {
511 	tlen += sizeof (struct tcpiphdr);
512 	ip->ip_len = tlen;
513 	ip->ip_ttl = ip_defttl;
514 	if (path_mtu_discovery)
515 		ip->ip_off |= IP_DF;
516       }
517 	m->m_len = tlen;
518 	m->m_pkthdr.len = tlen;
519 	m->m_pkthdr.rcvif = NULL;
520 #ifdef MAC
521 	if (inp != NULL) {
522 		/*
523 		 * Packet is associated with a socket, so allow the
524 		 * label of the response to reflect the socket label.
525 		 */
526 		INP_LOCK_ASSERT(inp);
527 		mac_create_mbuf_from_inpcb(inp, m);
528 	} else {
529 		/*
530 		 * Packet is not associated with a socket, so possibly
531 		 * update the label in place.
532 		 */
533 		mac_reflect_mbuf_tcp(m);
534 	}
535 #endif
536 	nth->th_seq = htonl(seq);
537 	nth->th_ack = htonl(ack);
538 	nth->th_x2 = 0;
539 	nth->th_off = sizeof (struct tcphdr) >> 2;
540 	nth->th_flags = flags;
541 	if (tp != NULL)
542 		nth->th_win = htons((u_short) (win >> tp->rcv_scale));
543 	else
544 		nth->th_win = htons((u_short)win);
545 	nth->th_urp = 0;
546 #ifdef INET6
547 	if (isipv6) {
548 		nth->th_sum = 0;
549 		nth->th_sum = in6_cksum(m, IPPROTO_TCP,
550 					sizeof(struct ip6_hdr),
551 					tlen - sizeof(struct ip6_hdr));
552 		ip6->ip6_hlim = in6_selecthlim(tp != NULL ? tp->t_inpcb :
553 		    NULL, NULL);
554 	} else
555 #endif /* INET6 */
556       {
557         nth->th_sum = in_pseudo(ip->ip_src.s_addr, ip->ip_dst.s_addr,
558 	    htons((u_short)(tlen - sizeof(struct ip) + ip->ip_p)));
559         m->m_pkthdr.csum_flags = CSUM_TCP;
560         m->m_pkthdr.csum_data = offsetof(struct tcphdr, th_sum);
561       }
562 #ifdef TCPDEBUG
563 	if (tp == NULL || (inp->inp_socket->so_options & SO_DEBUG))
564 		tcp_trace(TA_OUTPUT, 0, tp, mtod(m, void *), th, 0);
565 #endif
566 #ifdef INET6
567 	if (isipv6)
568 		(void) ip6_output(m, NULL, NULL, ipflags, NULL, NULL, inp);
569 	else
570 #endif /* INET6 */
571 	(void) ip_output(m, NULL, NULL, ipflags, NULL, inp);
572 }
573 
574 /*
575  * Create a new TCP control block, making an
576  * empty reassembly queue and hooking it to the argument
577  * protocol control block.  The `inp' parameter must have
578  * come from the zone allocator set up in tcp_init().
579  */
580 struct tcpcb *
581 tcp_newtcpcb(inp)
582 	struct inpcb *inp;
583 {
584 	struct tcpcb_mem *tm;
585 	struct tcpcb *tp;
586 #ifdef INET6
587 	int isipv6 = (inp->inp_vflag & INP_IPV6) != 0;
588 #endif /* INET6 */
589 	int callout_flag;
590 
591 	tm = uma_zalloc(tcpcb_zone, M_NOWAIT | M_ZERO);
592 	if (tm == NULL)
593 		return (NULL);
594 	tp = &tm->tcb;
595 	/*	LIST_INIT(&tp->t_segq); */	/* XXX covered by M_ZERO */
596 	tp->t_maxseg = tp->t_maxopd =
597 #ifdef INET6
598 		isipv6 ? tcp_v6mssdflt :
599 #endif /* INET6 */
600 		tcp_mssdflt;
601 
602 	/* Set up our timeouts. */
603 	/*
604 	 * XXXRW: Are these actually MPSAFE?  I think so, but need to
605 	 * review the timed wait code, as it has some list variables,
606 	 * etc, that are global.
607 	 */
608 	callout_flag = debug_mpsafenet ? CALLOUT_MPSAFE : 0;
609 	callout_init(tp->tt_rexmt = &tm->tcpcb_mem_rexmt, callout_flag);
610 	callout_init(tp->tt_persist = &tm->tcpcb_mem_persist, callout_flag);
611 	callout_init(tp->tt_keep = &tm->tcpcb_mem_keep, callout_flag);
612 	callout_init(tp->tt_2msl = &tm->tcpcb_mem_2msl, callout_flag);
613 	callout_init(tp->tt_delack = &tm->tcpcb_mem_delack, callout_flag);
614 
615 	if (tcp_do_rfc1323)
616 		tp->t_flags = (TF_REQ_SCALE|TF_REQ_TSTMP);
617 	if (tcp_do_rfc1644)
618 		tp->t_flags |= TF_REQ_CC;
619 	tp->sack_enable = tcp_do_sack;
620 	tp->t_inpcb = inp;	/* XXX */
621 	/*
622 	 * Init srtt to TCPTV_SRTTBASE (0), so we can tell that we have no
623 	 * rtt estimate.  Set rttvar so that srtt + 4 * rttvar gives
624 	 * reasonable initial retransmit time.
625 	 */
626 	tp->t_srtt = TCPTV_SRTTBASE;
627 	tp->t_rttvar = ((TCPTV_RTOBASE - TCPTV_SRTTBASE) << TCP_RTTVAR_SHIFT) / 4;
628 	tp->t_rttmin = tcp_rexmit_min;
629 	tp->t_rxtcur = TCPTV_RTOBASE;
630 	tp->snd_cwnd = TCP_MAXWIN << TCP_MAX_WINSHIFT;
631 	tp->snd_bwnd = TCP_MAXWIN << TCP_MAX_WINSHIFT;
632 	tp->snd_ssthresh = TCP_MAXWIN << TCP_MAX_WINSHIFT;
633 	tp->t_rcvtime = ticks;
634 	tp->t_bw_rtttime = ticks;
635         /*
636 	 * IPv4 TTL initialization is necessary for an IPv6 socket as well,
637 	 * because the socket may be bound to an IPv6 wildcard address,
638 	 * which may match an IPv4-mapped IPv6 address.
639 	 */
640 	inp->inp_ip_ttl = ip_defttl;
641 	inp->inp_ppcb = (caddr_t)tp;
642 	return (tp);		/* XXX */
643 }
644 
645 /*
646  * Drop a TCP connection, reporting
647  * the specified error.  If connection is synchronized,
648  * then send a RST to peer.
649  */
650 struct tcpcb *
651 tcp_drop(tp, errno)
652 	register struct tcpcb *tp;
653 	int errno;
654 {
655 	struct socket *so = tp->t_inpcb->inp_socket;
656 
657 	if (TCPS_HAVERCVDSYN(tp->t_state)) {
658 		tp->t_state = TCPS_CLOSED;
659 		(void) tcp_output(tp);
660 		tcpstat.tcps_drops++;
661 	} else
662 		tcpstat.tcps_conndrops++;
663 	if (errno == ETIMEDOUT && tp->t_softerror)
664 		errno = tp->t_softerror;
665 	so->so_error = errno;
666 	return (tcp_close(tp));
667 }
668 
669 static void
670 tcp_discardcb(tp)
671 	struct tcpcb *tp;
672 {
673 	struct tseg_qent *q;
674 	struct inpcb *inp = tp->t_inpcb;
675 	struct socket *so = inp->inp_socket;
676 #ifdef INET6
677 	int isipv6 = (inp->inp_vflag & INP_IPV6) != 0;
678 #endif /* INET6 */
679 
680 	/*
681 	 * Make sure that all of our timers are stopped before we
682 	 * delete the PCB.
683 	 */
684 	callout_stop(tp->tt_rexmt);
685 	callout_stop(tp->tt_persist);
686 	callout_stop(tp->tt_keep);
687 	callout_stop(tp->tt_2msl);
688 	callout_stop(tp->tt_delack);
689 
690 	/*
691 	 * If we got enough samples through the srtt filter,
692 	 * save the rtt and rttvar in the routing entry.
693 	 * 'Enough' is arbitrarily defined as 4 rtt samples.
694 	 * 4 samples is enough for the srtt filter to converge
695 	 * to within enough % of the correct value; fewer samples
696 	 * and we could save a bogus rtt. The danger is not high
697 	 * as tcp quickly recovers from everything.
698 	 * XXX: Works very well but needs some more statistics!
699 	 */
700 	if (tp->t_rttupdated >= 4) {
701 		struct hc_metrics_lite metrics;
702 		u_long ssthresh;
703 
704 		bzero(&metrics, sizeof(metrics));
705 		/*
706 		 * Update the ssthresh always when the conditions below
707 		 * are satisfied. This gives us better new start value
708 		 * for the congestion avoidance for new connections.
709 		 * ssthresh is only set if packet loss occured on a session.
710 		 */
711 		ssthresh = tp->snd_ssthresh;
712 		if (ssthresh != 0 && ssthresh < so->so_snd.sb_hiwat / 2) {
713 			/*
714 			 * convert the limit from user data bytes to
715 			 * packets then to packet data bytes.
716 			 */
717 			ssthresh = (ssthresh + tp->t_maxseg / 2) / tp->t_maxseg;
718 			if (ssthresh < 2)
719 				ssthresh = 2;
720 			ssthresh *= (u_long)(tp->t_maxseg +
721 #ifdef INET6
722 				      (isipv6 ? sizeof (struct ip6_hdr) +
723 					       sizeof (struct tcphdr) :
724 #endif
725 				       sizeof (struct tcpiphdr)
726 #ifdef INET6
727 				       )
728 #endif
729 				      );
730 		} else
731 			ssthresh = 0;
732 		metrics.rmx_ssthresh = ssthresh;
733 
734 		metrics.rmx_rtt = tp->t_srtt;
735 		metrics.rmx_rttvar = tp->t_rttvar;
736 		/* XXX: This wraps if the pipe is more than 4 Gbit per second */
737 		metrics.rmx_bandwidth = tp->snd_bandwidth;
738 		metrics.rmx_cwnd = tp->snd_cwnd;
739 		metrics.rmx_sendpipe = 0;
740 		metrics.rmx_recvpipe = 0;
741 
742 		tcp_hc_update(&inp->inp_inc, &metrics);
743 	}
744 
745 	/* free the reassembly queue, if any */
746 	while ((q = LIST_FIRST(&tp->t_segq)) != NULL) {
747 		LIST_REMOVE(q, tqe_q);
748 		m_freem(q->tqe_m);
749 		uma_zfree(tcp_reass_zone, q);
750 		tp->t_segqlen--;
751 		tcp_reass_qsize--;
752 	}
753 	tcp_free_sackholes(tp);
754 	inp->inp_ppcb = NULL;
755 	tp->t_inpcb = NULL;
756 	uma_zfree(tcpcb_zone, tp);
757 	soisdisconnected(so);
758 }
759 
760 /*
761  * Close a TCP control block:
762  *    discard all space held by the tcp
763  *    discard internet protocol block
764  *    wake up any sleepers
765  */
766 struct tcpcb *
767 tcp_close(tp)
768 	struct tcpcb *tp;
769 {
770 	struct inpcb *inp = tp->t_inpcb;
771 #ifdef INET6
772 	struct socket *so = inp->inp_socket;
773 #endif
774 
775 	tcp_discardcb(tp);
776 #ifdef INET6
777 	if (INP_CHECK_SOCKAF(so, AF_INET6))
778 		in6_pcbdetach(inp);
779 	else
780 #endif
781 		in_pcbdetach(inp);
782 	tcpstat.tcps_closed++;
783 	return (NULL);
784 }
785 
786 void
787 tcp_drain()
788 {
789 	if (do_tcpdrain)
790 	{
791 		struct inpcb *inpb;
792 		struct tcpcb *tcpb;
793 		struct tseg_qent *te;
794 
795 	/*
796 	 * Walk the tcpbs, if existing, and flush the reassembly queue,
797 	 * if there is one...
798 	 * XXX: The "Net/3" implementation doesn't imply that the TCP
799 	 *      reassembly queue should be flushed, but in a situation
800 	 * 	where we're really low on mbufs, this is potentially
801 	 *  	usefull.
802 	 */
803 		INP_INFO_RLOCK(&tcbinfo);
804 		LIST_FOREACH(inpb, tcbinfo.listhead, inp_list) {
805 			if (inpb->inp_vflag & INP_TIMEWAIT)
806 				continue;
807 			INP_LOCK(inpb);
808 			if ((tcpb = intotcpcb(inpb)) != NULL) {
809 				while ((te = LIST_FIRST(&tcpb->t_segq))
810 			            != NULL) {
811 					LIST_REMOVE(te, tqe_q);
812 					m_freem(te->tqe_m);
813 					uma_zfree(tcp_reass_zone, te);
814 					tcpb->t_segqlen--;
815 					tcp_reass_qsize--;
816 				}
817 			}
818 			INP_UNLOCK(inpb);
819 		}
820 		INP_INFO_RUNLOCK(&tcbinfo);
821 	}
822 }
823 
824 /*
825  * Notify a tcp user of an asynchronous error;
826  * store error as soft error, but wake up user
827  * (for now, won't do anything until can select for soft error).
828  *
829  * Do not wake up user since there currently is no mechanism for
830  * reporting soft errors (yet - a kqueue filter may be added).
831  */
832 static struct inpcb *
833 tcp_notify(inp, error)
834 	struct inpcb *inp;
835 	int error;
836 {
837 	struct tcpcb *tp = (struct tcpcb *)inp->inp_ppcb;
838 
839 	/*
840 	 * Ignore some errors if we are hooked up.
841 	 * If connection hasn't completed, has retransmitted several times,
842 	 * and receives a second error, give up now.  This is better
843 	 * than waiting a long time to establish a connection that
844 	 * can never complete.
845 	 */
846 	if (tp->t_state == TCPS_ESTABLISHED &&
847 	    (error == EHOSTUNREACH || error == ENETUNREACH ||
848 	     error == EHOSTDOWN)) {
849 		return inp;
850 	} else if (tp->t_state < TCPS_ESTABLISHED && tp->t_rxtshift > 3 &&
851 	    tp->t_softerror) {
852 		tcp_drop(tp, error);
853 		return (struct inpcb *)0;
854 	} else {
855 		tp->t_softerror = error;
856 		return inp;
857 	}
858 #if 0
859 	wakeup( &so->so_timeo);
860 	sorwakeup(so);
861 	sowwakeup(so);
862 #endif
863 }
864 
865 static int
866 tcp_pcblist(SYSCTL_HANDLER_ARGS)
867 {
868 	int error, i, n, s;
869 	struct inpcb *inp, **inp_list;
870 	inp_gen_t gencnt;
871 	struct xinpgen xig;
872 
873 	/*
874 	 * The process of preparing the TCB list is too time-consuming and
875 	 * resource-intensive to repeat twice on every request.
876 	 */
877 	if (req->oldptr == NULL) {
878 		n = tcbinfo.ipi_count;
879 		req->oldidx = 2 * (sizeof xig)
880 			+ (n + n/8) * sizeof(struct xtcpcb);
881 		return 0;
882 	}
883 
884 	if (req->newptr != NULL)
885 		return EPERM;
886 
887 	/*
888 	 * OK, now we're committed to doing something.
889 	 */
890 	s = splnet();
891 	INP_INFO_RLOCK(&tcbinfo);
892 	gencnt = tcbinfo.ipi_gencnt;
893 	n = tcbinfo.ipi_count;
894 	INP_INFO_RUNLOCK(&tcbinfo);
895 	splx(s);
896 
897 	error = sysctl_wire_old_buffer(req, 2 * (sizeof xig)
898 		+ n * sizeof(struct xtcpcb));
899 	if (error != 0)
900 		return (error);
901 
902 	xig.xig_len = sizeof xig;
903 	xig.xig_count = n;
904 	xig.xig_gen = gencnt;
905 	xig.xig_sogen = so_gencnt;
906 	error = SYSCTL_OUT(req, &xig, sizeof xig);
907 	if (error)
908 		return error;
909 
910 	inp_list = malloc(n * sizeof *inp_list, M_TEMP, M_WAITOK);
911 	if (inp_list == NULL)
912 		return ENOMEM;
913 
914 	s = splnet();
915 	INP_INFO_RLOCK(&tcbinfo);
916 	for (inp = LIST_FIRST(tcbinfo.listhead), i = 0; inp != NULL && i < n;
917 	     inp = LIST_NEXT(inp, inp_list)) {
918 		INP_LOCK(inp);
919 		if (inp->inp_gencnt <= gencnt) {
920 			/*
921 			 * XXX: This use of cr_cansee(), introduced with
922 			 * TCP state changes, is not quite right, but for
923 			 * now, better than nothing.
924 			 */
925 			if (inp->inp_vflag & INP_TIMEWAIT)
926 				error = cr_cansee(req->td->td_ucred,
927 				    intotw(inp)->tw_cred);
928 			else
929 				error = cr_canseesocket(req->td->td_ucred,
930 				    inp->inp_socket);
931 			if (error == 0)
932 				inp_list[i++] = inp;
933 		}
934 		INP_UNLOCK(inp);
935 	}
936 	INP_INFO_RUNLOCK(&tcbinfo);
937 	splx(s);
938 	n = i;
939 
940 	error = 0;
941 	for (i = 0; i < n; i++) {
942 		inp = inp_list[i];
943 		if (inp->inp_gencnt <= gencnt) {
944 			struct xtcpcb xt;
945 			caddr_t inp_ppcb;
946 			xt.xt_len = sizeof xt;
947 			/* XXX should avoid extra copy */
948 			bcopy(inp, &xt.xt_inp, sizeof *inp);
949 			inp_ppcb = inp->inp_ppcb;
950 			if (inp_ppcb == NULL)
951 				bzero((char *) &xt.xt_tp, sizeof xt.xt_tp);
952 			else if (inp->inp_vflag & INP_TIMEWAIT) {
953 				bzero((char *) &xt.xt_tp, sizeof xt.xt_tp);
954 				xt.xt_tp.t_state = TCPS_TIME_WAIT;
955 			} else
956 				bcopy(inp_ppcb, &xt.xt_tp, sizeof xt.xt_tp);
957 			if (inp->inp_socket != NULL)
958 				sotoxsocket(inp->inp_socket, &xt.xt_socket);
959 			else {
960 				bzero(&xt.xt_socket, sizeof xt.xt_socket);
961 				xt.xt_socket.xso_protocol = IPPROTO_TCP;
962 			}
963 			xt.xt_inp.inp_gencnt = inp->inp_gencnt;
964 			error = SYSCTL_OUT(req, &xt, sizeof xt);
965 		}
966 	}
967 	if (!error) {
968 		/*
969 		 * Give the user an updated idea of our state.
970 		 * If the generation differs from what we told
971 		 * her before, she knows that something happened
972 		 * while we were processing this request, and it
973 		 * might be necessary to retry.
974 		 */
975 		s = splnet();
976 		INP_INFO_RLOCK(&tcbinfo);
977 		xig.xig_gen = tcbinfo.ipi_gencnt;
978 		xig.xig_sogen = so_gencnt;
979 		xig.xig_count = tcbinfo.ipi_count;
980 		INP_INFO_RUNLOCK(&tcbinfo);
981 		splx(s);
982 		error = SYSCTL_OUT(req, &xig, sizeof xig);
983 	}
984 	free(inp_list, M_TEMP);
985 	return error;
986 }
987 
988 SYSCTL_PROC(_net_inet_tcp, TCPCTL_PCBLIST, pcblist, CTLFLAG_RD, 0, 0,
989 	    tcp_pcblist, "S,xtcpcb", "List of active TCP connections");
990 
991 static int
992 tcp_getcred(SYSCTL_HANDLER_ARGS)
993 {
994 	struct xucred xuc;
995 	struct sockaddr_in addrs[2];
996 	struct inpcb *inp;
997 	int error, s;
998 
999 	error = suser_cred(req->td->td_ucred, SUSER_ALLOWJAIL);
1000 	if (error)
1001 		return (error);
1002 	error = SYSCTL_IN(req, addrs, sizeof(addrs));
1003 	if (error)
1004 		return (error);
1005 	s = splnet();
1006 	INP_INFO_RLOCK(&tcbinfo);
1007 	inp = in_pcblookup_hash(&tcbinfo, addrs[1].sin_addr, addrs[1].sin_port,
1008 	    addrs[0].sin_addr, addrs[0].sin_port, 0, NULL);
1009 	if (inp == NULL) {
1010 		error = ENOENT;
1011 		goto outunlocked;
1012 	}
1013 	INP_LOCK(inp);
1014 	if (inp->inp_socket == NULL) {
1015 		error = ENOENT;
1016 		goto out;
1017 	}
1018 	error = cr_canseesocket(req->td->td_ucred, inp->inp_socket);
1019 	if (error)
1020 		goto out;
1021 	cru2x(inp->inp_socket->so_cred, &xuc);
1022 out:
1023 	INP_UNLOCK(inp);
1024 outunlocked:
1025 	INP_INFO_RUNLOCK(&tcbinfo);
1026 	splx(s);
1027 	if (error == 0)
1028 		error = SYSCTL_OUT(req, &xuc, sizeof(struct xucred));
1029 	return (error);
1030 }
1031 
1032 SYSCTL_PROC(_net_inet_tcp, OID_AUTO, getcred,
1033     CTLTYPE_OPAQUE|CTLFLAG_RW|CTLFLAG_PRISON, 0, 0,
1034     tcp_getcred, "S,xucred", "Get the xucred of a TCP connection");
1035 
1036 #ifdef INET6
1037 static int
1038 tcp6_getcred(SYSCTL_HANDLER_ARGS)
1039 {
1040 	struct xucred xuc;
1041 	struct sockaddr_in6 addrs[2];
1042 	struct inpcb *inp;
1043 	int error, s, mapped = 0;
1044 
1045 	error = suser_cred(req->td->td_ucred, SUSER_ALLOWJAIL);
1046 	if (error)
1047 		return (error);
1048 	error = SYSCTL_IN(req, addrs, sizeof(addrs));
1049 	if (error)
1050 		return (error);
1051 	if (IN6_IS_ADDR_V4MAPPED(&addrs[0].sin6_addr)) {
1052 		if (IN6_IS_ADDR_V4MAPPED(&addrs[1].sin6_addr))
1053 			mapped = 1;
1054 		else
1055 			return (EINVAL);
1056 	}
1057 	s = splnet();
1058 	INP_INFO_RLOCK(&tcbinfo);
1059 	if (mapped == 1)
1060 		inp = in_pcblookup_hash(&tcbinfo,
1061 			*(struct in_addr *)&addrs[1].sin6_addr.s6_addr[12],
1062 			addrs[1].sin6_port,
1063 			*(struct in_addr *)&addrs[0].sin6_addr.s6_addr[12],
1064 			addrs[0].sin6_port,
1065 			0, NULL);
1066 	else
1067 		inp = in6_pcblookup_hash(&tcbinfo, &addrs[1].sin6_addr,
1068 				 addrs[1].sin6_port,
1069 				 &addrs[0].sin6_addr, addrs[0].sin6_port,
1070 				 0, NULL);
1071 	if (inp == NULL) {
1072 		error = ENOENT;
1073 		goto outunlocked;
1074 	}
1075 	INP_LOCK(inp);
1076 	if (inp->inp_socket == NULL) {
1077 		error = ENOENT;
1078 		goto out;
1079 	}
1080 	error = cr_canseesocket(req->td->td_ucred, inp->inp_socket);
1081 	if (error)
1082 		goto out;
1083 	cru2x(inp->inp_socket->so_cred, &xuc);
1084 out:
1085 	INP_UNLOCK(inp);
1086 outunlocked:
1087 	INP_INFO_RUNLOCK(&tcbinfo);
1088 	splx(s);
1089 	if (error == 0)
1090 		error = SYSCTL_OUT(req, &xuc, sizeof(struct xucred));
1091 	return (error);
1092 }
1093 
1094 SYSCTL_PROC(_net_inet6_tcp6, OID_AUTO, getcred,
1095     CTLTYPE_OPAQUE|CTLFLAG_RW|CTLFLAG_PRISON, 0, 0,
1096     tcp6_getcred, "S,xucred", "Get the xucred of a TCP6 connection");
1097 #endif
1098 
1099 
1100 void
1101 tcp_ctlinput(cmd, sa, vip)
1102 	int cmd;
1103 	struct sockaddr *sa;
1104 	void *vip;
1105 {
1106 	struct ip *ip = vip;
1107 	struct tcphdr *th;
1108 	struct in_addr faddr;
1109 	struct inpcb *inp;
1110 	struct tcpcb *tp;
1111 	struct inpcb *(*notify)(struct inpcb *, int) = tcp_notify;
1112 	tcp_seq icmp_seq;
1113 	int s;
1114 
1115 	faddr = ((struct sockaddr_in *)sa)->sin_addr;
1116 	if (sa->sa_family != AF_INET || faddr.s_addr == INADDR_ANY)
1117 		return;
1118 
1119 	if (cmd == PRC_QUENCH)
1120 		notify = tcp_quench;
1121 	else if (icmp_may_rst && (cmd == PRC_UNREACH_ADMIN_PROHIB ||
1122 		cmd == PRC_UNREACH_PORT || cmd == PRC_TIMXCEED_INTRANS) && ip)
1123 		notify = tcp_drop_syn_sent;
1124 	else if (cmd == PRC_MSGSIZE)
1125 		notify = tcp_mtudisc;
1126 	/*
1127 	 * Redirects don't need to be handled up here.
1128 	 */
1129 	else if (PRC_IS_REDIRECT(cmd))
1130 		return;
1131 	/*
1132 	 * Hostdead is ugly because it goes linearly through all PCBs.
1133 	 * XXX: We never get this from ICMP, otherwise it makes an
1134 	 * excellent DoS attack on machines with many connections.
1135 	 */
1136 	else if (cmd == PRC_HOSTDEAD)
1137 		ip = NULL;
1138 	else if ((unsigned)cmd >= PRC_NCMDS || inetctlerrmap[cmd] == 0)
1139 		return;
1140 	if (ip != NULL) {
1141 		s = splnet();
1142 		th = (struct tcphdr *)((caddr_t)ip
1143 				       + (ip->ip_hl << 2));
1144 		INP_INFO_WLOCK(&tcbinfo);
1145 		inp = in_pcblookup_hash(&tcbinfo, faddr, th->th_dport,
1146 		    ip->ip_src, th->th_sport, 0, NULL);
1147 		if (inp != NULL)  {
1148 			INP_LOCK(inp);
1149 			if (inp->inp_socket != NULL) {
1150 				icmp_seq = htonl(th->th_seq);
1151 				tp = intotcpcb(inp);
1152 				if (SEQ_GEQ(icmp_seq, tp->snd_una) &&
1153 			    		SEQ_LT(icmp_seq, tp->snd_max))
1154 					inp = (*notify)(inp, inetctlerrmap[cmd]);
1155 			}
1156 			if (inp != NULL)
1157 				INP_UNLOCK(inp);
1158 		} else {
1159 			struct in_conninfo inc;
1160 
1161 			inc.inc_fport = th->th_dport;
1162 			inc.inc_lport = th->th_sport;
1163 			inc.inc_faddr = faddr;
1164 			inc.inc_laddr = ip->ip_src;
1165 #ifdef INET6
1166 			inc.inc_isipv6 = 0;
1167 #endif
1168 			syncache_unreach(&inc, th);
1169 		}
1170 		INP_INFO_WUNLOCK(&tcbinfo);
1171 		splx(s);
1172 	} else
1173 		in_pcbnotifyall(&tcbinfo, faddr, inetctlerrmap[cmd], notify);
1174 }
1175 
1176 #ifdef INET6
1177 void
1178 tcp6_ctlinput(cmd, sa, d)
1179 	int cmd;
1180 	struct sockaddr *sa;
1181 	void *d;
1182 {
1183 	struct tcphdr th;
1184 	struct inpcb *(*notify)(struct inpcb *, int) = tcp_notify;
1185 	struct ip6_hdr *ip6;
1186 	struct mbuf *m;
1187 	struct ip6ctlparam *ip6cp = NULL;
1188 	const struct sockaddr_in6 *sa6_src = NULL;
1189 	int off;
1190 	struct tcp_portonly {
1191 		u_int16_t th_sport;
1192 		u_int16_t th_dport;
1193 	} *thp;
1194 
1195 	if (sa->sa_family != AF_INET6 ||
1196 	    sa->sa_len != sizeof(struct sockaddr_in6))
1197 		return;
1198 
1199 	if (cmd == PRC_QUENCH)
1200 		notify = tcp_quench;
1201 	else if (cmd == PRC_MSGSIZE)
1202 		notify = tcp_mtudisc;
1203 	else if (!PRC_IS_REDIRECT(cmd) &&
1204 		 ((unsigned)cmd >= PRC_NCMDS || inet6ctlerrmap[cmd] == 0))
1205 		return;
1206 
1207 	/* if the parameter is from icmp6, decode it. */
1208 	if (d != NULL) {
1209 		ip6cp = (struct ip6ctlparam *)d;
1210 		m = ip6cp->ip6c_m;
1211 		ip6 = ip6cp->ip6c_ip6;
1212 		off = ip6cp->ip6c_off;
1213 		sa6_src = ip6cp->ip6c_src;
1214 	} else {
1215 		m = NULL;
1216 		ip6 = NULL;
1217 		off = 0;	/* fool gcc */
1218 		sa6_src = &sa6_any;
1219 	}
1220 
1221 	if (ip6 != NULL) {
1222 		struct in_conninfo inc;
1223 		/*
1224 		 * XXX: We assume that when IPV6 is non NULL,
1225 		 * M and OFF are valid.
1226 		 */
1227 
1228 		/* check if we can safely examine src and dst ports */
1229 		if (m->m_pkthdr.len < off + sizeof(*thp))
1230 			return;
1231 
1232 		bzero(&th, sizeof(th));
1233 		m_copydata(m, off, sizeof(*thp), (caddr_t)&th);
1234 
1235 		in6_pcbnotify(&tcb, sa, th.th_dport,
1236 		    (struct sockaddr *)ip6cp->ip6c_src,
1237 		    th.th_sport, cmd, NULL, notify);
1238 
1239 		inc.inc_fport = th.th_dport;
1240 		inc.inc_lport = th.th_sport;
1241 		inc.inc6_faddr = ((struct sockaddr_in6 *)sa)->sin6_addr;
1242 		inc.inc6_laddr = ip6cp->ip6c_src->sin6_addr;
1243 		inc.inc_isipv6 = 1;
1244 		syncache_unreach(&inc, &th);
1245 	} else
1246 		in6_pcbnotify(&tcb, sa, 0, (const struct sockaddr *)sa6_src,
1247 			      0, cmd, NULL, notify);
1248 }
1249 #endif /* INET6 */
1250 
1251 
1252 /*
1253  * Following is where TCP initial sequence number generation occurs.
1254  *
1255  * There are two places where we must use initial sequence numbers:
1256  * 1.  In SYN-ACK packets.
1257  * 2.  In SYN packets.
1258  *
1259  * All ISNs for SYN-ACK packets are generated by the syncache.  See
1260  * tcp_syncache.c for details.
1261  *
1262  * The ISNs in SYN packets must be monotonic; TIME_WAIT recycling
1263  * depends on this property.  In addition, these ISNs should be
1264  * unguessable so as to prevent connection hijacking.  To satisfy
1265  * the requirements of this situation, the algorithm outlined in
1266  * RFC 1948 is used, with only small modifications.
1267  *
1268  * Implementation details:
1269  *
1270  * Time is based off the system timer, and is corrected so that it
1271  * increases by one megabyte per second.  This allows for proper
1272  * recycling on high speed LANs while still leaving over an hour
1273  * before rollover.
1274  *
1275  * As reading the *exact* system time is too expensive to be done
1276  * whenever setting up a TCP connection, we increment the time
1277  * offset in two ways.  First, a small random positive increment
1278  * is added to isn_offset for each connection that is set up.
1279  * Second, the function tcp_isn_tick fires once per clock tick
1280  * and increments isn_offset as necessary so that sequence numbers
1281  * are incremented at approximately ISN_BYTES_PER_SECOND.  The
1282  * random positive increments serve only to ensure that the same
1283  * exact sequence number is never sent out twice (as could otherwise
1284  * happen when a port is recycled in less than the system tick
1285  * interval.)
1286  *
1287  * net.inet.tcp.isn_reseed_interval controls the number of seconds
1288  * between seeding of isn_secret.  This is normally set to zero,
1289  * as reseeding should not be necessary.
1290  *
1291  */
1292 
1293 #define ISN_BYTES_PER_SECOND 1048576
1294 #define ISN_STATIC_INCREMENT 4096
1295 #define ISN_RANDOM_INCREMENT (4096 - 1)
1296 
1297 u_char isn_secret[32];
1298 int isn_last_reseed;
1299 u_int32_t isn_offset, isn_offset_old;
1300 MD5_CTX isn_ctx;
1301 
1302 tcp_seq
1303 tcp_new_isn(tp)
1304 	struct tcpcb *tp;
1305 {
1306 	u_int32_t md5_buffer[4];
1307 	tcp_seq new_isn;
1308 
1309 	/* Seed if this is the first use, reseed if requested. */
1310 	if ((isn_last_reseed == 0) || ((tcp_isn_reseed_interval > 0) &&
1311 	     (((u_int)isn_last_reseed + (u_int)tcp_isn_reseed_interval*hz)
1312 		< (u_int)ticks))) {
1313 		read_random(&isn_secret, sizeof(isn_secret));
1314 		isn_last_reseed = ticks;
1315 	}
1316 
1317 	/* Compute the md5 hash and return the ISN. */
1318 	MD5Init(&isn_ctx);
1319 	MD5Update(&isn_ctx, (u_char *) &tp->t_inpcb->inp_fport, sizeof(u_short));
1320 	MD5Update(&isn_ctx, (u_char *) &tp->t_inpcb->inp_lport, sizeof(u_short));
1321 #ifdef INET6
1322 	if ((tp->t_inpcb->inp_vflag & INP_IPV6) != 0) {
1323 		MD5Update(&isn_ctx, (u_char *) &tp->t_inpcb->in6p_faddr,
1324 			  sizeof(struct in6_addr));
1325 		MD5Update(&isn_ctx, (u_char *) &tp->t_inpcb->in6p_laddr,
1326 			  sizeof(struct in6_addr));
1327 	} else
1328 #endif
1329 	{
1330 		MD5Update(&isn_ctx, (u_char *) &tp->t_inpcb->inp_faddr,
1331 			  sizeof(struct in_addr));
1332 		MD5Update(&isn_ctx, (u_char *) &tp->t_inpcb->inp_laddr,
1333 			  sizeof(struct in_addr));
1334 	}
1335 	MD5Update(&isn_ctx, (u_char *) &isn_secret, sizeof(isn_secret));
1336 	MD5Final((u_char *) &md5_buffer, &isn_ctx);
1337 	new_isn = (tcp_seq) md5_buffer[0];
1338 	isn_offset += ISN_STATIC_INCREMENT +
1339 		(arc4random() & ISN_RANDOM_INCREMENT);
1340 	new_isn += isn_offset;
1341 	return new_isn;
1342 }
1343 
1344 /*
1345  * Increment the offset to the next ISN_BYTES_PER_SECOND / hz boundary
1346  * to keep time flowing at a relatively constant rate.  If the random
1347  * increments have already pushed us past the projected offset, do nothing.
1348  */
1349 static void
1350 tcp_isn_tick(xtp)
1351 	void *xtp;
1352 {
1353 	u_int32_t projected_offset;
1354 
1355 	projected_offset = isn_offset_old + ISN_BYTES_PER_SECOND / hz;
1356 
1357 	if (projected_offset > isn_offset)
1358 		isn_offset = projected_offset;
1359 
1360 	isn_offset_old = isn_offset;
1361 	callout_reset(&isn_callout, 1, tcp_isn_tick, NULL);
1362 }
1363 
1364 /*
1365  * When a source quench is received, close congestion window
1366  * to one segment.  We will gradually open it again as we proceed.
1367  */
1368 struct inpcb *
1369 tcp_quench(inp, errno)
1370 	struct inpcb *inp;
1371 	int errno;
1372 {
1373 	struct tcpcb *tp = intotcpcb(inp);
1374 
1375 	if (tp != NULL)
1376 		tp->snd_cwnd = tp->t_maxseg;
1377 	return (inp);
1378 }
1379 
1380 /*
1381  * When a specific ICMP unreachable message is received and the
1382  * connection state is SYN-SENT, drop the connection.  This behavior
1383  * is controlled by the icmp_may_rst sysctl.
1384  */
1385 struct inpcb *
1386 tcp_drop_syn_sent(inp, errno)
1387 	struct inpcb *inp;
1388 	int errno;
1389 {
1390 	struct tcpcb *tp = intotcpcb(inp);
1391 
1392 	if (tp != NULL && tp->t_state == TCPS_SYN_SENT) {
1393 		tcp_drop(tp, errno);
1394 		return (struct inpcb *)0;
1395 	}
1396 	return inp;
1397 }
1398 
1399 /*
1400  * When `need fragmentation' ICMP is received, update our idea of the MSS
1401  * based on the new value in the route.  Also nudge TCP to send something,
1402  * since we know the packet we just sent was dropped.
1403  * This duplicates some code in the tcp_mss() function in tcp_input.c.
1404  */
1405 struct inpcb *
1406 tcp_mtudisc(inp, errno)
1407 	struct inpcb *inp;
1408 	int errno;
1409 {
1410 	struct tcpcb *tp = intotcpcb(inp);
1411 	struct rmxp_tao tao;
1412 	struct socket *so = inp->inp_socket;
1413 	u_int maxmtu;
1414 	u_int romtu;
1415 	int mss;
1416 #ifdef INET6
1417 	int isipv6 = (tp->t_inpcb->inp_vflag & INP_IPV6) != 0;
1418 #endif /* INET6 */
1419 	bzero(&tao, sizeof(tao));
1420 
1421 	if (tp != NULL) {
1422 		maxmtu = tcp_hc_getmtu(&inp->inp_inc); /* IPv4 and IPv6 */
1423 		romtu =
1424 #ifdef INET6
1425 		    isipv6 ? tcp_maxmtu6(&inp->inp_inc) :
1426 #endif /* INET6 */
1427 		    tcp_maxmtu(&inp->inp_inc);
1428 		if (!maxmtu)
1429 			maxmtu = romtu;
1430 		else
1431 			maxmtu = min(maxmtu, romtu);
1432 		if (!maxmtu) {
1433 			tp->t_maxopd = tp->t_maxseg =
1434 #ifdef INET6
1435 				isipv6 ? tcp_v6mssdflt :
1436 #endif /* INET6 */
1437 				tcp_mssdflt;
1438 			return inp;
1439 		}
1440 		mss = maxmtu -
1441 #ifdef INET6
1442 			(isipv6 ?
1443 			 sizeof(struct ip6_hdr) + sizeof(struct tcphdr) :
1444 #endif /* INET6 */
1445 			 sizeof(struct tcpiphdr)
1446 #ifdef INET6
1447 			 )
1448 #endif /* INET6 */
1449 			;
1450 
1451 		if (tcp_do_rfc1644) {
1452 			tcp_hc_gettao(&inp->inp_inc, &tao);
1453 			if (tao.tao_mssopt)
1454 				mss = min(mss, tao.tao_mssopt);
1455 		}
1456 		/*
1457 		 * XXX - The above conditional probably violates the TCP
1458 		 * spec.  The problem is that, since we don't know the
1459 		 * other end's MSS, we are supposed to use a conservative
1460 		 * default.  But, if we do that, then MTU discovery will
1461 		 * never actually take place, because the conservative
1462 		 * default is much less than the MTUs typically seen
1463 		 * on the Internet today.  For the moment, we'll sweep
1464 		 * this under the carpet.
1465 		 *
1466 		 * The conservative default might not actually be a problem
1467 		 * if the only case this occurs is when sending an initial
1468 		 * SYN with options and data to a host we've never talked
1469 		 * to before.  Then, they will reply with an MSS value which
1470 		 * will get recorded and the new parameters should get
1471 		 * recomputed.  For Further Study.
1472 		 */
1473 		if (tp->t_maxopd <= mss)
1474 			return inp;
1475 		tp->t_maxopd = mss;
1476 
1477 		if ((tp->t_flags & (TF_REQ_TSTMP|TF_NOOPT)) == TF_REQ_TSTMP &&
1478 		    (tp->t_flags & TF_RCVD_TSTMP) == TF_RCVD_TSTMP)
1479 			mss -= TCPOLEN_TSTAMP_APPA;
1480 		if ((tp->t_flags & (TF_REQ_CC|TF_NOOPT)) == TF_REQ_CC &&
1481 		    (tp->t_flags & TF_RCVD_CC) == TF_RCVD_CC)
1482 			mss -= TCPOLEN_CC_APPA;
1483 #if	(MCLBYTES & (MCLBYTES - 1)) == 0
1484 		if (mss > MCLBYTES)
1485 			mss &= ~(MCLBYTES-1);
1486 #else
1487 		if (mss > MCLBYTES)
1488 			mss = mss / MCLBYTES * MCLBYTES;
1489 #endif
1490 		if (so->so_snd.sb_hiwat < mss)
1491 			mss = so->so_snd.sb_hiwat;
1492 
1493 		tp->t_maxseg = mss;
1494 
1495 		tcpstat.tcps_mturesent++;
1496 		tp->t_rtttime = 0;
1497 		tp->snd_nxt = tp->snd_una;
1498 		tcp_output(tp);
1499 	}
1500 	return inp;
1501 }
1502 
1503 /*
1504  * Look-up the routing entry to the peer of this inpcb.  If no route
1505  * is found and it cannot be allocated, then return NULL.  This routine
1506  * is called by TCP routines that access the rmx structure and by tcp_mss
1507  * to get the interface MTU.
1508  */
1509 u_long
1510 tcp_maxmtu(inc)
1511 	struct in_conninfo *inc;
1512 {
1513 	struct route sro;
1514 	struct sockaddr_in *dst;
1515 	struct ifnet *ifp;
1516 	u_long maxmtu = 0;
1517 
1518 	KASSERT(inc != NULL, ("tcp_maxmtu with NULL in_conninfo pointer"));
1519 
1520 	bzero(&sro, sizeof(sro));
1521 	if (inc->inc_faddr.s_addr != INADDR_ANY) {
1522 	        dst = (struct sockaddr_in *)&sro.ro_dst;
1523 		dst->sin_family = AF_INET;
1524 		dst->sin_len = sizeof(*dst);
1525 		dst->sin_addr = inc->inc_faddr;
1526 		rtalloc_ign(&sro, RTF_CLONING);
1527 	}
1528 	if (sro.ro_rt != NULL) {
1529 		ifp = sro.ro_rt->rt_ifp;
1530 		if (sro.ro_rt->rt_rmx.rmx_mtu == 0)
1531 			maxmtu = ifp->if_mtu;
1532 		else
1533 			maxmtu = min(sro.ro_rt->rt_rmx.rmx_mtu, ifp->if_mtu);
1534 		RTFREE(sro.ro_rt);
1535 	}
1536 	return (maxmtu);
1537 }
1538 
1539 #ifdef INET6
1540 u_long
1541 tcp_maxmtu6(inc)
1542 	struct in_conninfo *inc;
1543 {
1544 	struct route_in6 sro6;
1545 	struct ifnet *ifp;
1546 	u_long maxmtu = 0;
1547 
1548 	KASSERT(inc != NULL, ("tcp_maxmtu6 with NULL in_conninfo pointer"));
1549 
1550 	bzero(&sro6, sizeof(sro6));
1551 	if (!IN6_IS_ADDR_UNSPECIFIED(&inc->inc6_faddr)) {
1552 		sro6.ro_dst.sin6_family = AF_INET6;
1553 		sro6.ro_dst.sin6_len = sizeof(struct sockaddr_in6);
1554 		sro6.ro_dst.sin6_addr = inc->inc6_faddr;
1555 		rtalloc_ign((struct route *)&sro6, RTF_CLONING);
1556 	}
1557 	if (sro6.ro_rt != NULL) {
1558 		ifp = sro6.ro_rt->rt_ifp;
1559 		if (sro6.ro_rt->rt_rmx.rmx_mtu == 0)
1560 			maxmtu = IN6_LINKMTU(sro6.ro_rt->rt_ifp);
1561 		else
1562 			maxmtu = min(sro6.ro_rt->rt_rmx.rmx_mtu,
1563 				     IN6_LINKMTU(sro6.ro_rt->rt_ifp));
1564 		RTFREE(sro6.ro_rt);
1565 	}
1566 
1567 	return (maxmtu);
1568 }
1569 #endif /* INET6 */
1570 
1571 #ifdef IPSEC
1572 /* compute ESP/AH header size for TCP, including outer IP header. */
1573 size_t
1574 ipsec_hdrsiz_tcp(tp)
1575 	struct tcpcb *tp;
1576 {
1577 	struct inpcb *inp;
1578 	struct mbuf *m;
1579 	size_t hdrsiz;
1580 	struct ip *ip;
1581 #ifdef INET6
1582 	struct ip6_hdr *ip6;
1583 #endif
1584 	struct tcphdr *th;
1585 
1586 	if ((tp == NULL) || ((inp = tp->t_inpcb) == NULL))
1587 		return 0;
1588 	MGETHDR(m, M_DONTWAIT, MT_DATA);
1589 	if (!m)
1590 		return 0;
1591 
1592 #ifdef INET6
1593 	if ((inp->inp_vflag & INP_IPV6) != 0) {
1594 		ip6 = mtod(m, struct ip6_hdr *);
1595 		th = (struct tcphdr *)(ip6 + 1);
1596 		m->m_pkthdr.len = m->m_len =
1597 			sizeof(struct ip6_hdr) + sizeof(struct tcphdr);
1598 		tcpip_fillheaders(inp, ip6, th);
1599 		hdrsiz = ipsec6_hdrsiz(m, IPSEC_DIR_OUTBOUND, inp);
1600 	} else
1601 #endif /* INET6 */
1602       {
1603 	ip = mtod(m, struct ip *);
1604 	th = (struct tcphdr *)(ip + 1);
1605 	m->m_pkthdr.len = m->m_len = sizeof(struct tcpiphdr);
1606 	tcpip_fillheaders(inp, ip, th);
1607 	hdrsiz = ipsec4_hdrsiz(m, IPSEC_DIR_OUTBOUND, inp);
1608       }
1609 
1610 	m_free(m);
1611 	return hdrsiz;
1612 }
1613 #endif /*IPSEC*/
1614 
1615 /*
1616  * Move a TCP connection into TIME_WAIT state.
1617  *    tcbinfo is unlocked.
1618  *    inp is locked, and is unlocked before returning.
1619  */
1620 void
1621 tcp_twstart(tp)
1622 	struct tcpcb *tp;
1623 {
1624 	struct tcptw *tw;
1625 	struct inpcb *inp;
1626 	int tw_time, acknow;
1627 	struct socket *so;
1628 
1629 	tw = uma_zalloc(tcptw_zone, M_NOWAIT);
1630 	if (tw == NULL) {
1631 		tw = tcp_timer_2msl_tw(1);
1632 		if (tw == NULL) {
1633 			tcp_close(tp);
1634 			return;
1635 		}
1636 	}
1637 	inp = tp->t_inpcb;
1638 	tw->tw_inpcb = inp;
1639 
1640 	/*
1641 	 * Recover last window size sent.
1642 	 */
1643 	tw->last_win = (tp->rcv_adv - tp->rcv_nxt) >> tp->rcv_scale;
1644 
1645 	/*
1646 	 * Set t_recent if timestamps are used on the connection.
1647 	 */
1648         if ((tp->t_flags & (TF_REQ_TSTMP|TF_RCVD_TSTMP|TF_NOOPT)) ==
1649             (TF_REQ_TSTMP|TF_RCVD_TSTMP))
1650 		tw->t_recent = tp->ts_recent;
1651 	else
1652 		tw->t_recent = 0;
1653 
1654 	tw->snd_nxt = tp->snd_nxt;
1655 	tw->rcv_nxt = tp->rcv_nxt;
1656 	tw->iss     = tp->iss;
1657 	tw->irs     = tp->irs;
1658 	tw->cc_recv = tp->cc_recv;
1659 	tw->cc_send = tp->cc_send;
1660 	tw->t_starttime = tp->t_starttime;
1661 	tw->tw_time = 0;
1662 
1663 /* XXX
1664  * If this code will
1665  * be used for fin-wait-2 state also, then we may need
1666  * a ts_recent from the last segment.
1667  */
1668 	/* Shorten TIME_WAIT [RFC-1644, p.28] */
1669 	if (tp->cc_recv != 0 && (ticks - tp->t_starttime) < tcp_msl) {
1670 		tw_time = tp->t_rxtcur * TCPTV_TWTRUNC;
1671 		/* For T/TCP client, force ACK now. */
1672 		acknow = 1;
1673 	} else {
1674 		tw_time = 2 * tcp_msl;
1675 		acknow = tp->t_flags & TF_ACKNOW;
1676 	}
1677 	tcp_discardcb(tp);
1678 	so = inp->inp_socket;
1679 	SOCK_LOCK(so);
1680 	so->so_pcb = NULL;
1681 	tw->tw_cred = crhold(so->so_cred);
1682 	tw->tw_so_options = so->so_options;
1683 	sotryfree(so);
1684 	inp->inp_socket = NULL;
1685 	if (acknow)
1686 		tcp_twrespond(tw, TH_ACK);
1687 	inp->inp_ppcb = (caddr_t)tw;
1688 	inp->inp_vflag |= INP_TIMEWAIT;
1689 	tcp_timer_2msl_reset(tw, tw_time);
1690 	INP_UNLOCK(inp);
1691 }
1692 
1693 /*
1694  * The appromixate rate of ISN increase of Microsoft TCP stacks;
1695  * the actual rate is slightly higher due to the addition of
1696  * random positive increments.
1697  *
1698  * Most other new OSes use semi-randomized ISN values, so we
1699  * do not need to worry about them.
1700  */
1701 #define MS_ISN_BYTES_PER_SECOND		250000
1702 
1703 /*
1704  * Determine if the ISN we will generate has advanced beyond the last
1705  * sequence number used by the previous connection.  If so, indicate
1706  * that it is safe to recycle this tw socket by returning 1.
1707  */
1708 int
1709 tcp_twrecycleable(struct tcptw *tw)
1710 {
1711 	tcp_seq new_iss = tw->iss;
1712 	tcp_seq new_irs = tw->irs;
1713 
1714 	new_iss += (ticks - tw->t_starttime) * (ISN_BYTES_PER_SECOND / hz);
1715 	new_irs += (ticks - tw->t_starttime) * (MS_ISN_BYTES_PER_SECOND / hz);
1716 
1717 	if (SEQ_GT(new_iss, tw->snd_nxt) && SEQ_GT(new_irs, tw->rcv_nxt))
1718 		return 1;
1719 	else
1720 		return 0;
1721 }
1722 
1723 struct tcptw *
1724 tcp_twclose(struct tcptw *tw, int reuse)
1725 {
1726 	struct inpcb *inp;
1727 
1728 	inp = tw->tw_inpcb;
1729 	tw->tw_inpcb = NULL;
1730 	tcp_timer_2msl_stop(tw);
1731 	inp->inp_ppcb = NULL;
1732 #ifdef INET6
1733 	if (inp->inp_vflag & INP_IPV6PROTO)
1734 		in6_pcbdetach(inp);
1735 	else
1736 #endif
1737 		in_pcbdetach(inp);
1738 	tcpstat.tcps_closed++;
1739 	crfree(tw->tw_cred);
1740 	tw->tw_cred = NULL;
1741 	if (reuse)
1742 		return (tw);
1743 	uma_zfree(tcptw_zone, tw);
1744 	return (NULL);
1745 }
1746 
1747 int
1748 tcp_twrespond(struct tcptw *tw, int flags)
1749 {
1750 	struct inpcb *inp = tw->tw_inpcb;
1751 	struct tcphdr *th;
1752 	struct mbuf *m;
1753 	struct ip *ip = NULL;
1754 	u_int8_t *optp;
1755 	u_int hdrlen, optlen;
1756 	int error;
1757 #ifdef INET6
1758 	struct ip6_hdr *ip6 = NULL;
1759 	int isipv6 = inp->inp_inc.inc_isipv6;
1760 #endif
1761 
1762 	m = m_gethdr(M_DONTWAIT, MT_HEADER);
1763 	if (m == NULL)
1764 		return (ENOBUFS);
1765 	m->m_data += max_linkhdr;
1766 
1767 #ifdef MAC
1768 	mac_create_mbuf_from_inpcb(inp, m);
1769 #endif
1770 
1771 #ifdef INET6
1772 	if (isipv6) {
1773 		hdrlen = sizeof(struct ip6_hdr) + sizeof(struct tcphdr);
1774 		ip6 = mtod(m, struct ip6_hdr *);
1775 		th = (struct tcphdr *)(ip6 + 1);
1776 		tcpip_fillheaders(inp, ip6, th);
1777 	} else
1778 #endif
1779 	{
1780 		hdrlen = sizeof(struct tcpiphdr);
1781 		ip = mtod(m, struct ip *);
1782 		th = (struct tcphdr *)(ip + 1);
1783 		tcpip_fillheaders(inp, ip, th);
1784 	}
1785 	optp = (u_int8_t *)(th + 1);
1786 
1787  	/*
1788 	 * Send a timestamp and echo-reply if both our side and our peer
1789 	 * have sent timestamps in our SYN's and this is not a RST.
1790  	 */
1791 	if (tw->t_recent && flags == TH_ACK) {
1792 		u_int32_t *lp = (u_int32_t *)optp;
1793 
1794  		/* Form timestamp option as shown in appendix A of RFC 1323. */
1795  		*lp++ = htonl(TCPOPT_TSTAMP_HDR);
1796  		*lp++ = htonl(ticks);
1797  		*lp   = htonl(tw->t_recent);
1798  		optp += TCPOLEN_TSTAMP_APPA;
1799  	}
1800 
1801  	/*
1802 	 * Send `CC-family' options if needed, and it's not a RST.
1803  	 */
1804 	if (tw->cc_recv != 0 && flags == TH_ACK) {
1805 		u_int32_t *lp = (u_int32_t *)optp;
1806 
1807 		*lp++ = htonl(TCPOPT_CC_HDR(TCPOPT_CC));
1808 		*lp   = htonl(tw->cc_send);
1809 		optp += TCPOLEN_CC_APPA;
1810  	}
1811 	optlen = optp - (u_int8_t *)(th + 1);
1812 
1813 	m->m_len = hdrlen + optlen;
1814 	m->m_pkthdr.len = m->m_len;
1815 
1816 	KASSERT(max_linkhdr + m->m_len <= MHLEN, ("tcptw: mbuf too small"));
1817 
1818 	th->th_seq = htonl(tw->snd_nxt);
1819 	th->th_ack = htonl(tw->rcv_nxt);
1820 	th->th_off = (sizeof(struct tcphdr) + optlen) >> 2;
1821 	th->th_flags = flags;
1822 	th->th_win = htons(tw->last_win);
1823 
1824 #ifdef INET6
1825 	if (isipv6) {
1826 		th->th_sum = in6_cksum(m, IPPROTO_TCP, sizeof(struct ip6_hdr),
1827 		    sizeof(struct tcphdr) + optlen);
1828 		ip6->ip6_hlim = in6_selecthlim(inp, NULL);
1829 		error = ip6_output(m, inp->in6p_outputopts, NULL,
1830 		    (tw->tw_so_options & SO_DONTROUTE), NULL, NULL, inp);
1831 	} else
1832 #endif
1833 	{
1834 		th->th_sum = in_pseudo(ip->ip_src.s_addr, ip->ip_dst.s_addr,
1835                     htons(sizeof(struct tcphdr) + optlen + IPPROTO_TCP));
1836 		m->m_pkthdr.csum_flags = CSUM_TCP;
1837 		m->m_pkthdr.csum_data = offsetof(struct tcphdr, th_sum);
1838 		ip->ip_len = m->m_pkthdr.len;
1839 		if (path_mtu_discovery)
1840 			ip->ip_off |= IP_DF;
1841 		error = ip_output(m, inp->inp_options, NULL,
1842 		    (tw->tw_so_options & SO_DONTROUTE), NULL, inp);
1843 	}
1844 	if (flags & TH_ACK)
1845 		tcpstat.tcps_sndacks++;
1846 	else
1847 		tcpstat.tcps_sndctrl++;
1848 	tcpstat.tcps_sndtotal++;
1849 	return (error);
1850 }
1851 
1852 /*
1853  * TCP BANDWIDTH DELAY PRODUCT WINDOW LIMITING
1854  *
1855  * This code attempts to calculate the bandwidth-delay product as a
1856  * means of determining the optimal window size to maximize bandwidth,
1857  * minimize RTT, and avoid the over-allocation of buffers on interfaces and
1858  * routers.  This code also does a fairly good job keeping RTTs in check
1859  * across slow links like modems.  We implement an algorithm which is very
1860  * similar (but not meant to be) TCP/Vegas.  The code operates on the
1861  * transmitter side of a TCP connection and so only effects the transmit
1862  * side of the connection.
1863  *
1864  * BACKGROUND:  TCP makes no provision for the management of buffer space
1865  * at the end points or at the intermediate routers and switches.  A TCP
1866  * stream, whether using NewReno or not, will eventually buffer as
1867  * many packets as it is able and the only reason this typically works is
1868  * due to the fairly small default buffers made available for a connection
1869  * (typicaly 16K or 32K).  As machines use larger windows and/or window
1870  * scaling it is now fairly easy for even a single TCP connection to blow-out
1871  * all available buffer space not only on the local interface, but on
1872  * intermediate routers and switches as well.  NewReno makes a misguided
1873  * attempt to 'solve' this problem by waiting for an actual failure to occur,
1874  * then backing off, then steadily increasing the window again until another
1875  * failure occurs, ad-infinitum.  This results in terrible oscillation that
1876  * is only made worse as network loads increase and the idea of intentionally
1877  * blowing out network buffers is, frankly, a terrible way to manage network
1878  * resources.
1879  *
1880  * It is far better to limit the transmit window prior to the failure
1881  * condition being achieved.  There are two general ways to do this:  First
1882  * you can 'scan' through different transmit window sizes and locate the
1883  * point where the RTT stops increasing, indicating that you have filled the
1884  * pipe, then scan backwards until you note that RTT stops decreasing, then
1885  * repeat ad-infinitum.  This method works in principle but has severe
1886  * implementation issues due to RTT variances, timer granularity, and
1887  * instability in the algorithm which can lead to many false positives and
1888  * create oscillations as well as interact badly with other TCP streams
1889  * implementing the same algorithm.
1890  *
1891  * The second method is to limit the window to the bandwidth delay product
1892  * of the link.  This is the method we implement.  RTT variances and our
1893  * own manipulation of the congestion window, bwnd, can potentially
1894  * destabilize the algorithm.  For this reason we have to stabilize the
1895  * elements used to calculate the window.  We do this by using the minimum
1896  * observed RTT, the long term average of the observed bandwidth, and
1897  * by adding two segments worth of slop.  It isn't perfect but it is able
1898  * to react to changing conditions and gives us a very stable basis on
1899  * which to extend the algorithm.
1900  */
1901 void
1902 tcp_xmit_bandwidth_limit(struct tcpcb *tp, tcp_seq ack_seq)
1903 {
1904 	u_long bw;
1905 	u_long bwnd;
1906 	int save_ticks;
1907 
1908 	/*
1909 	 * If inflight_enable is disabled in the middle of a tcp connection,
1910 	 * make sure snd_bwnd is effectively disabled.
1911 	 */
1912 	if (tcp_inflight_enable == 0) {
1913 		tp->snd_bwnd = TCP_MAXWIN << TCP_MAX_WINSHIFT;
1914 		tp->snd_bandwidth = 0;
1915 		return;
1916 	}
1917 
1918 	/*
1919 	 * Figure out the bandwidth.  Due to the tick granularity this
1920 	 * is a very rough number and it MUST be averaged over a fairly
1921 	 * long period of time.  XXX we need to take into account a link
1922 	 * that is not using all available bandwidth, but for now our
1923 	 * slop will ramp us up if this case occurs and the bandwidth later
1924 	 * increases.
1925 	 *
1926 	 * Note: if ticks rollover 'bw' may wind up negative.  We must
1927 	 * effectively reset t_bw_rtttime for this case.
1928 	 */
1929 	save_ticks = ticks;
1930 	if ((u_int)(save_ticks - tp->t_bw_rtttime) < 1)
1931 		return;
1932 
1933 	bw = (int64_t)(ack_seq - tp->t_bw_rtseq) * hz /
1934 	    (save_ticks - tp->t_bw_rtttime);
1935 	tp->t_bw_rtttime = save_ticks;
1936 	tp->t_bw_rtseq = ack_seq;
1937 	if (tp->t_bw_rtttime == 0 || (int)bw < 0)
1938 		return;
1939 	bw = ((int64_t)tp->snd_bandwidth * 15 + bw) >> 4;
1940 
1941 	tp->snd_bandwidth = bw;
1942 
1943 	/*
1944 	 * Calculate the semi-static bandwidth delay product, plus two maximal
1945 	 * segments.  The additional slop puts us squarely in the sweet
1946 	 * spot and also handles the bandwidth run-up case and stabilization.
1947 	 * Without the slop we could be locking ourselves into a lower
1948 	 * bandwidth.
1949 	 *
1950 	 * Situations Handled:
1951 	 *	(1) Prevents over-queueing of packets on LANs, especially on
1952 	 *	    high speed LANs, allowing larger TCP buffers to be
1953 	 *	    specified, and also does a good job preventing
1954 	 *	    over-queueing of packets over choke points like modems
1955 	 *	    (at least for the transmit side).
1956 	 *
1957 	 *	(2) Is able to handle changing network loads (bandwidth
1958 	 *	    drops so bwnd drops, bandwidth increases so bwnd
1959 	 *	    increases).
1960 	 *
1961 	 *	(3) Theoretically should stabilize in the face of multiple
1962 	 *	    connections implementing the same algorithm (this may need
1963 	 *	    a little work).
1964 	 *
1965 	 *	(4) Stability value (defaults to 20 = 2 maximal packets) can
1966 	 *	    be adjusted with a sysctl but typically only needs to be
1967 	 *	    on very slow connections.  A value no smaller then 5
1968 	 *	    should be used, but only reduce this default if you have
1969 	 *	    no other choice.
1970 	 */
1971 #define USERTT	((tp->t_srtt + tp->t_rttbest) / 2)
1972 	bwnd = (int64_t)bw * USERTT / (hz << TCP_RTT_SHIFT) + tcp_inflight_stab * tp->t_maxseg / 10;
1973 #undef USERTT
1974 
1975 	if (tcp_inflight_debug > 0) {
1976 		static int ltime;
1977 		if ((u_int)(ticks - ltime) >= hz / tcp_inflight_debug) {
1978 			ltime = ticks;
1979 			printf("%p bw %ld rttbest %d srtt %d bwnd %ld\n",
1980 			    tp,
1981 			    bw,
1982 			    tp->t_rttbest,
1983 			    tp->t_srtt,
1984 			    bwnd
1985 			);
1986 		}
1987 	}
1988 	if ((long)bwnd < tcp_inflight_min)
1989 		bwnd = tcp_inflight_min;
1990 	if (bwnd > tcp_inflight_max)
1991 		bwnd = tcp_inflight_max;
1992 	if ((long)bwnd < tp->t_maxseg * 2)
1993 		bwnd = tp->t_maxseg * 2;
1994 	tp->snd_bwnd = bwnd;
1995 }
1996 
1997 #ifdef TCP_SIGNATURE
1998 /*
1999  * Callback function invoked by m_apply() to digest TCP segment data
2000  * contained within an mbuf chain.
2001  */
2002 static int
2003 tcp_signature_apply(void *fstate, void *data, u_int len)
2004 {
2005 
2006 	MD5Update(fstate, (u_char *)data, len);
2007 	return (0);
2008 }
2009 
2010 /*
2011  * Compute TCP-MD5 hash of a TCPv4 segment. (RFC2385)
2012  *
2013  * Parameters:
2014  * m		pointer to head of mbuf chain
2015  * off0		offset to TCP header within the mbuf chain
2016  * len		length of TCP segment data, excluding options
2017  * optlen	length of TCP segment options
2018  * buf		pointer to storage for computed MD5 digest
2019  * direction	direction of flow (IPSEC_DIR_INBOUND or OUTBOUND)
2020  *
2021  * We do this over ip, tcphdr, segment data, and the key in the SADB.
2022  * When called from tcp_input(), we can be sure that th_sum has been
2023  * zeroed out and verified already.
2024  *
2025  * This function is for IPv4 use only. Calling this function with an
2026  * IPv6 packet in the mbuf chain will yield undefined results.
2027  *
2028  * Return 0 if successful, otherwise return -1.
2029  *
2030  * XXX The key is retrieved from the system's PF_KEY SADB, by keying a
2031  * search with the destination IP address, and a 'magic SPI' to be
2032  * determined by the application. This is hardcoded elsewhere to 1179
2033  * right now. Another branch of this code exists which uses the SPD to
2034  * specify per-application flows but it is unstable.
2035  */
2036 int
2037 tcp_signature_compute(struct mbuf *m, int off0, int len, int optlen,
2038     u_char *buf, u_int direction)
2039 {
2040 	union sockaddr_union dst;
2041 	struct ippseudo ippseudo;
2042 	MD5_CTX ctx;
2043 	int doff;
2044 	struct ip *ip;
2045 	struct ipovly *ipovly;
2046 	struct secasvar *sav;
2047 	struct tcphdr *th;
2048 	u_short savecsum;
2049 
2050 	KASSERT(m != NULL, ("NULL mbuf chain"));
2051 	KASSERT(buf != NULL, ("NULL signature pointer"));
2052 
2053 	/* Extract the destination from the IP header in the mbuf. */
2054 	ip = mtod(m, struct ip *);
2055 	bzero(&dst, sizeof(union sockaddr_union));
2056 	dst.sa.sa_len = sizeof(struct sockaddr_in);
2057 	dst.sa.sa_family = AF_INET;
2058 	dst.sin.sin_addr = (direction == IPSEC_DIR_INBOUND) ?
2059 	    ip->ip_src : ip->ip_dst;
2060 
2061 	/* Look up an SADB entry which matches the address of the peer. */
2062 	sav = KEY_ALLOCSA(&dst, IPPROTO_TCP, htonl(TCP_SIG_SPI));
2063 	if (sav == NULL) {
2064 		printf("%s: SADB lookup failed for %s\n", __func__,
2065 		    inet_ntoa(dst.sin.sin_addr));
2066 		return (EINVAL);
2067 	}
2068 
2069 	MD5Init(&ctx);
2070 	ipovly = (struct ipovly *)ip;
2071 	th = (struct tcphdr *)((u_char *)ip + off0);
2072 	doff = off0 + sizeof(struct tcphdr) + optlen;
2073 
2074 	/*
2075 	 * Step 1: Update MD5 hash with IP pseudo-header.
2076 	 *
2077 	 * XXX The ippseudo header MUST be digested in network byte order,
2078 	 * or else we'll fail the regression test. Assume all fields we've
2079 	 * been doing arithmetic on have been in host byte order.
2080 	 * XXX One cannot depend on ipovly->ih_len here. When called from
2081 	 * tcp_output(), the underlying ip_len member has not yet been set.
2082 	 */
2083 	ippseudo.ippseudo_src = ipovly->ih_src;
2084 	ippseudo.ippseudo_dst = ipovly->ih_dst;
2085 	ippseudo.ippseudo_pad = 0;
2086 	ippseudo.ippseudo_p = IPPROTO_TCP;
2087 	ippseudo.ippseudo_len = htons(len + sizeof(struct tcphdr) + optlen);
2088 	MD5Update(&ctx, (char *)&ippseudo, sizeof(struct ippseudo));
2089 
2090 	/*
2091 	 * Step 2: Update MD5 hash with TCP header, excluding options.
2092 	 * The TCP checksum must be set to zero.
2093 	 */
2094 	savecsum = th->th_sum;
2095 	th->th_sum = 0;
2096 	MD5Update(&ctx, (char *)th, sizeof(struct tcphdr));
2097 	th->th_sum = savecsum;
2098 
2099 	/*
2100 	 * Step 3: Update MD5 hash with TCP segment data.
2101 	 *         Use m_apply() to avoid an early m_pullup().
2102 	 */
2103 	if (len > 0)
2104 		m_apply(m, doff, len, tcp_signature_apply, &ctx);
2105 
2106 	/*
2107 	 * Step 4: Update MD5 hash with shared secret.
2108 	 */
2109 	MD5Update(&ctx, _KEYBUF(sav->key_auth), _KEYLEN(sav->key_auth));
2110 	MD5Final(buf, &ctx);
2111 
2112 	key_sa_recordxfer(sav, m);
2113 	KEY_FREESAV(&sav);
2114 	return (0);
2115 }
2116 #endif /* TCP_SIGNATURE */
2117