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