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