in_pcb.c revision 309108
1/*-
2 * Copyright (c) 1982, 1986, 1991, 1993, 1995
3 *	The Regents of the University of California.
4 * Copyright (c) 2007-2009 Robert N. M. Watson
5 * Copyright (c) 2010-2011 Juniper Networks, Inc.
6 * All rights reserved.
7 *
8 * Portions of this software were developed by Robert N. M. Watson under
9 * contract to Juniper Networks, Inc.
10 *
11 * Redistribution and use in source and binary forms, with or without
12 * modification, are permitted provided that the following conditions
13 * are met:
14 * 1. Redistributions of source code must retain the above copyright
15 *    notice, this list of conditions and the following disclaimer.
16 * 2. Redistributions in binary form must reproduce the above copyright
17 *    notice, this list of conditions and the following disclaimer in the
18 *    documentation and/or other materials provided with the distribution.
19 * 4. Neither the name of the University nor the names of its contributors
20 *    may be used to endorse or promote products derived from this software
21 *    without specific prior written permission.
22 *
23 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
24 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
25 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
26 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
27 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
28 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
29 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
30 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
31 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
32 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
33 * SUCH DAMAGE.
34 *
35 *	@(#)in_pcb.c	8.4 (Berkeley) 5/24/95
36 */
37
38#include <sys/cdefs.h>
39__FBSDID("$FreeBSD: stable/10/sys/netinet/in_pcb.c 309108 2016-11-24 14:48:46Z jch $");
40
41#include "opt_ddb.h"
42#include "opt_ipsec.h"
43#include "opt_inet.h"
44#include "opt_inet6.h"
45#include "opt_pcbgroup.h"
46
47#include <sys/param.h>
48#include <sys/systm.h>
49#include <sys/malloc.h>
50#include <sys/mbuf.h>
51#include <sys/callout.h>
52#include <sys/domain.h>
53#include <sys/protosw.h>
54#include <sys/socket.h>
55#include <sys/socketvar.h>
56#include <sys/priv.h>
57#include <sys/proc.h>
58#include <sys/refcount.h>
59#include <sys/jail.h>
60#include <sys/kernel.h>
61#include <sys/sysctl.h>
62
63#ifdef DDB
64#include <ddb/ddb.h>
65#endif
66
67#include <vm/uma.h>
68
69#include <net/if.h>
70#include <net/if_types.h>
71#include <net/route.h>
72#include <net/vnet.h>
73
74#if defined(INET) || defined(INET6)
75#include <netinet/in.h>
76#include <netinet/in_pcb.h>
77#include <netinet/ip_var.h>
78#include <netinet/tcp_var.h>
79#include <netinet/udp.h>
80#include <netinet/udp_var.h>
81#endif
82#ifdef INET
83#include <netinet/in_var.h>
84#endif
85#ifdef INET6
86#include <netinet/ip6.h>
87#include <netinet6/in6_pcb.h>
88#include <netinet6/in6_var.h>
89#include <netinet6/ip6_var.h>
90#endif /* INET6 */
91
92
93#ifdef IPSEC
94#include <netipsec/ipsec.h>
95#include <netipsec/key.h>
96#endif /* IPSEC */
97
98#include <security/mac/mac_framework.h>
99
100static struct callout	ipport_tick_callout;
101
102/*
103 * These configure the range of local port addresses assigned to
104 * "unspecified" outgoing connections/packets/whatever.
105 */
106VNET_DEFINE(int, ipport_lowfirstauto) = IPPORT_RESERVED - 1;	/* 1023 */
107VNET_DEFINE(int, ipport_lowlastauto) = IPPORT_RESERVEDSTART;	/* 600 */
108VNET_DEFINE(int, ipport_firstauto) = IPPORT_EPHEMERALFIRST;	/* 10000 */
109VNET_DEFINE(int, ipport_lastauto) = IPPORT_EPHEMERALLAST;	/* 65535 */
110VNET_DEFINE(int, ipport_hifirstauto) = IPPORT_HIFIRSTAUTO;	/* 49152 */
111VNET_DEFINE(int, ipport_hilastauto) = IPPORT_HILASTAUTO;	/* 65535 */
112
113/*
114 * Reserved ports accessible only to root. There are significant
115 * security considerations that must be accounted for when changing these,
116 * but the security benefits can be great. Please be careful.
117 */
118VNET_DEFINE(int, ipport_reservedhigh) = IPPORT_RESERVED - 1;	/* 1023 */
119VNET_DEFINE(int, ipport_reservedlow);
120
121/* Variables dealing with random ephemeral port allocation. */
122VNET_DEFINE(int, ipport_randomized) = 1;	/* user controlled via sysctl */
123VNET_DEFINE(int, ipport_randomcps) = 10;	/* user controlled via sysctl */
124VNET_DEFINE(int, ipport_randomtime) = 45;	/* user controlled via sysctl */
125VNET_DEFINE(int, ipport_stoprandom);		/* toggled by ipport_tick */
126VNET_DEFINE(int, ipport_tcpallocs);
127static VNET_DEFINE(int, ipport_tcplastcount);
128
129#define	V_ipport_tcplastcount		VNET(ipport_tcplastcount)
130
131static void	in_pcbremlists(struct inpcb *inp);
132#ifdef INET
133static struct inpcb	*in_pcblookup_hash_locked(struct inpcbinfo *pcbinfo,
134			    struct in_addr faddr, u_int fport_arg,
135			    struct in_addr laddr, u_int lport_arg,
136			    int lookupflags, struct ifnet *ifp);
137
138#define RANGECHK(var, min, max) \
139	if ((var) < (min)) { (var) = (min); } \
140	else if ((var) > (max)) { (var) = (max); }
141
142static int
143sysctl_net_ipport_check(SYSCTL_HANDLER_ARGS)
144{
145	int error;
146
147	error = sysctl_handle_int(oidp, arg1, arg2, req);
148	if (error == 0) {
149		RANGECHK(V_ipport_lowfirstauto, 1, IPPORT_RESERVED - 1);
150		RANGECHK(V_ipport_lowlastauto, 1, IPPORT_RESERVED - 1);
151		RANGECHK(V_ipport_firstauto, IPPORT_RESERVED, IPPORT_MAX);
152		RANGECHK(V_ipport_lastauto, IPPORT_RESERVED, IPPORT_MAX);
153		RANGECHK(V_ipport_hifirstauto, IPPORT_RESERVED, IPPORT_MAX);
154		RANGECHK(V_ipport_hilastauto, IPPORT_RESERVED, IPPORT_MAX);
155	}
156	return (error);
157}
158
159#undef RANGECHK
160
161static SYSCTL_NODE(_net_inet_ip, IPPROTO_IP, portrange, CTLFLAG_RW, 0,
162    "IP Ports");
163
164SYSCTL_VNET_PROC(_net_inet_ip_portrange, OID_AUTO, lowfirst,
165	CTLTYPE_INT|CTLFLAG_RW, &VNET_NAME(ipport_lowfirstauto), 0,
166	&sysctl_net_ipport_check, "I", "");
167SYSCTL_VNET_PROC(_net_inet_ip_portrange, OID_AUTO, lowlast,
168	CTLTYPE_INT|CTLFLAG_RW, &VNET_NAME(ipport_lowlastauto), 0,
169	&sysctl_net_ipport_check, "I", "");
170SYSCTL_VNET_PROC(_net_inet_ip_portrange, OID_AUTO, first,
171	CTLTYPE_INT|CTLFLAG_RW, &VNET_NAME(ipport_firstauto), 0,
172	&sysctl_net_ipport_check, "I", "");
173SYSCTL_VNET_PROC(_net_inet_ip_portrange, OID_AUTO, last,
174	CTLTYPE_INT|CTLFLAG_RW, &VNET_NAME(ipport_lastauto), 0,
175	&sysctl_net_ipport_check, "I", "");
176SYSCTL_VNET_PROC(_net_inet_ip_portrange, OID_AUTO, hifirst,
177	CTLTYPE_INT|CTLFLAG_RW, &VNET_NAME(ipport_hifirstauto), 0,
178	&sysctl_net_ipport_check, "I", "");
179SYSCTL_VNET_PROC(_net_inet_ip_portrange, OID_AUTO, hilast,
180	CTLTYPE_INT|CTLFLAG_RW, &VNET_NAME(ipport_hilastauto), 0,
181	&sysctl_net_ipport_check, "I", "");
182SYSCTL_VNET_INT(_net_inet_ip_portrange, OID_AUTO, reservedhigh,
183	CTLFLAG_RW|CTLFLAG_SECURE, &VNET_NAME(ipport_reservedhigh), 0, "");
184SYSCTL_VNET_INT(_net_inet_ip_portrange, OID_AUTO, reservedlow,
185	CTLFLAG_RW|CTLFLAG_SECURE, &VNET_NAME(ipport_reservedlow), 0, "");
186SYSCTL_VNET_INT(_net_inet_ip_portrange, OID_AUTO, randomized, CTLFLAG_RW,
187	&VNET_NAME(ipport_randomized), 0, "Enable random port allocation");
188SYSCTL_VNET_INT(_net_inet_ip_portrange, OID_AUTO, randomcps, CTLFLAG_RW,
189	&VNET_NAME(ipport_randomcps), 0, "Maximum number of random port "
190	"allocations before switching to a sequental one");
191SYSCTL_VNET_INT(_net_inet_ip_portrange, OID_AUTO, randomtime, CTLFLAG_RW,
192	&VNET_NAME(ipport_randomtime), 0,
193	"Minimum time to keep sequental port "
194	"allocation before switching to a random one");
195#endif /* INET */
196
197/*
198 * in_pcb.c: manage the Protocol Control Blocks.
199 *
200 * NOTE: It is assumed that most of these functions will be called with
201 * the pcbinfo lock held, and often, the inpcb lock held, as these utility
202 * functions often modify hash chains or addresses in pcbs.
203 */
204
205/*
206 * Initialize an inpcbinfo -- we should be able to reduce the number of
207 * arguments in time.
208 */
209void
210in_pcbinfo_init(struct inpcbinfo *pcbinfo, const char *name,
211    struct inpcbhead *listhead, int hash_nelements, int porthash_nelements,
212    char *inpcbzone_name, uma_init inpcbzone_init, uma_fini inpcbzone_fini,
213    uint32_t inpcbzone_flags, u_int hashfields)
214{
215
216	INP_INFO_LOCK_INIT(pcbinfo, name);
217	INP_HASH_LOCK_INIT(pcbinfo, "pcbinfohash");	/* XXXRW: argument? */
218	INP_LIST_LOCK_INIT(pcbinfo, "pcbinfolist");
219#ifdef VIMAGE
220	pcbinfo->ipi_vnet = curvnet;
221#endif
222	pcbinfo->ipi_listhead = listhead;
223	LIST_INIT(pcbinfo->ipi_listhead);
224	pcbinfo->ipi_count = 0;
225	pcbinfo->ipi_hashbase = hashinit(hash_nelements, M_PCB,
226	    &pcbinfo->ipi_hashmask);
227	pcbinfo->ipi_porthashbase = hashinit(porthash_nelements, M_PCB,
228	    &pcbinfo->ipi_porthashmask);
229#ifdef PCBGROUP
230	in_pcbgroup_init(pcbinfo, hashfields, hash_nelements);
231#endif
232	pcbinfo->ipi_zone = uma_zcreate(inpcbzone_name, sizeof(struct inpcb),
233	    NULL, NULL, inpcbzone_init, inpcbzone_fini, UMA_ALIGN_PTR,
234	    inpcbzone_flags);
235	uma_zone_set_max(pcbinfo->ipi_zone, maxsockets);
236	uma_zone_set_warning(pcbinfo->ipi_zone,
237	    "kern.ipc.maxsockets limit reached");
238}
239
240/*
241 * Destroy an inpcbinfo.
242 */
243void
244in_pcbinfo_destroy(struct inpcbinfo *pcbinfo)
245{
246
247	KASSERT(pcbinfo->ipi_count == 0,
248	    ("%s: ipi_count = %u", __func__, pcbinfo->ipi_count));
249
250	hashdestroy(pcbinfo->ipi_hashbase, M_PCB, pcbinfo->ipi_hashmask);
251	hashdestroy(pcbinfo->ipi_porthashbase, M_PCB,
252	    pcbinfo->ipi_porthashmask);
253#ifdef PCBGROUP
254	in_pcbgroup_destroy(pcbinfo);
255#endif
256	uma_zdestroy(pcbinfo->ipi_zone);
257	INP_LIST_LOCK_DESTROY(pcbinfo);
258	INP_HASH_LOCK_DESTROY(pcbinfo);
259	INP_INFO_LOCK_DESTROY(pcbinfo);
260}
261
262/*
263 * Allocate a PCB and associate it with the socket.
264 * On success return with the PCB locked.
265 */
266int
267in_pcballoc(struct socket *so, struct inpcbinfo *pcbinfo)
268{
269	struct inpcb *inp;
270	int error;
271
272#ifdef INVARIANTS
273	if (pcbinfo == &V_tcbinfo) {
274		INP_INFO_RLOCK_ASSERT(pcbinfo);
275	} else {
276		INP_INFO_WLOCK_ASSERT(pcbinfo);
277	}
278#endif
279
280	error = 0;
281	inp = uma_zalloc(pcbinfo->ipi_zone, M_NOWAIT);
282	if (inp == NULL)
283		return (ENOBUFS);
284	bzero(inp, inp_zero_size);
285	inp->inp_pcbinfo = pcbinfo;
286	inp->inp_socket = so;
287	inp->inp_cred = crhold(so->so_cred);
288	inp->inp_inc.inc_fibnum = so->so_fibnum;
289#ifdef MAC
290	error = mac_inpcb_init(inp, M_NOWAIT);
291	if (error != 0)
292		goto out;
293	mac_inpcb_create(so, inp);
294#endif
295#ifdef IPSEC
296	error = ipsec_init_policy(so, &inp->inp_sp);
297	if (error != 0) {
298#ifdef MAC
299		mac_inpcb_destroy(inp);
300#endif
301		goto out;
302	}
303#endif /*IPSEC*/
304#ifdef INET6
305	if (INP_SOCKAF(so) == AF_INET6) {
306		inp->inp_vflag |= INP_IPV6PROTO;
307		if (V_ip6_v6only)
308			inp->inp_flags |= IN6P_IPV6_V6ONLY;
309	}
310#endif
311	INP_WLOCK(inp);
312	INP_LIST_WLOCK(pcbinfo);
313	LIST_INSERT_HEAD(pcbinfo->ipi_listhead, inp, inp_list);
314	pcbinfo->ipi_count++;
315	so->so_pcb = (caddr_t)inp;
316#ifdef INET6
317	if (V_ip6_auto_flowlabel)
318		inp->inp_flags |= IN6P_AUTOFLOWLABEL;
319#endif
320	inp->inp_gencnt = ++pcbinfo->ipi_gencnt;
321	refcount_init(&inp->inp_refcount, 1);	/* Reference from inpcbinfo */
322	INP_LIST_WUNLOCK(pcbinfo);
323#if defined(IPSEC) || defined(MAC)
324out:
325	if (error != 0) {
326		crfree(inp->inp_cred);
327		uma_zfree(pcbinfo->ipi_zone, inp);
328	}
329#endif
330	return (error);
331}
332
333#ifdef INET
334int
335in_pcbbind(struct inpcb *inp, struct sockaddr *nam, struct ucred *cred)
336{
337	int anonport, error;
338
339	INP_WLOCK_ASSERT(inp);
340	INP_HASH_WLOCK_ASSERT(inp->inp_pcbinfo);
341
342	if (inp->inp_lport != 0 || inp->inp_laddr.s_addr != INADDR_ANY)
343		return (EINVAL);
344	anonport = nam == NULL || ((struct sockaddr_in *)nam)->sin_port == 0;
345	error = in_pcbbind_setup(inp, nam, &inp->inp_laddr.s_addr,
346	    &inp->inp_lport, cred);
347	if (error)
348		return (error);
349	if (in_pcbinshash(inp) != 0) {
350		inp->inp_laddr.s_addr = INADDR_ANY;
351		inp->inp_lport = 0;
352		return (EAGAIN);
353	}
354	if (anonport)
355		inp->inp_flags |= INP_ANONPORT;
356	return (0);
357}
358#endif
359
360#if defined(INET) || defined(INET6)
361int
362in_pcb_lport(struct inpcb *inp, struct in_addr *laddrp, u_short *lportp,
363    struct ucred *cred, int lookupflags)
364{
365	struct inpcbinfo *pcbinfo;
366	struct inpcb *tmpinp;
367	unsigned short *lastport;
368	int count, dorandom, error;
369	u_short aux, first, last, lport;
370#ifdef INET
371	struct in_addr laddr;
372#endif
373
374	pcbinfo = inp->inp_pcbinfo;
375
376	/*
377	 * Because no actual state changes occur here, a global write lock on
378	 * the pcbinfo isn't required.
379	 */
380	INP_LOCK_ASSERT(inp);
381	INP_HASH_LOCK_ASSERT(pcbinfo);
382
383	if (inp->inp_flags & INP_HIGHPORT) {
384		first = V_ipport_hifirstauto;	/* sysctl */
385		last  = V_ipport_hilastauto;
386		lastport = &pcbinfo->ipi_lasthi;
387	} else if (inp->inp_flags & INP_LOWPORT) {
388		error = priv_check_cred(cred, PRIV_NETINET_RESERVEDPORT, 0);
389		if (error)
390			return (error);
391		first = V_ipport_lowfirstauto;	/* 1023 */
392		last  = V_ipport_lowlastauto;	/* 600 */
393		lastport = &pcbinfo->ipi_lastlow;
394	} else {
395		first = V_ipport_firstauto;	/* sysctl */
396		last  = V_ipport_lastauto;
397		lastport = &pcbinfo->ipi_lastport;
398	}
399	/*
400	 * For UDP(-Lite), use random port allocation as long as the user
401	 * allows it.  For TCP (and as of yet unknown) connections,
402	 * use random port allocation only if the user allows it AND
403	 * ipport_tick() allows it.
404	 */
405	if (V_ipport_randomized &&
406		(!V_ipport_stoprandom || pcbinfo == &V_udbinfo ||
407		pcbinfo == &V_ulitecbinfo))
408		dorandom = 1;
409	else
410		dorandom = 0;
411	/*
412	 * It makes no sense to do random port allocation if
413	 * we have the only port available.
414	 */
415	if (first == last)
416		dorandom = 0;
417	/* Make sure to not include UDP(-Lite) packets in the count. */
418	if (pcbinfo != &V_udbinfo || pcbinfo != &V_ulitecbinfo)
419		V_ipport_tcpallocs++;
420	/*
421	 * Instead of having two loops further down counting up or down
422	 * make sure that first is always <= last and go with only one
423	 * code path implementing all logic.
424	 */
425	if (first > last) {
426		aux = first;
427		first = last;
428		last = aux;
429	}
430
431#ifdef INET
432	/* Make the compiler happy. */
433	laddr.s_addr = 0;
434	if ((inp->inp_vflag & (INP_IPV4|INP_IPV6)) == INP_IPV4) {
435		KASSERT(laddrp != NULL, ("%s: laddrp NULL for v4 inp %p",
436		    __func__, inp));
437		laddr = *laddrp;
438	}
439#endif
440	tmpinp = NULL;	/* Make compiler happy. */
441	lport = *lportp;
442
443	if (dorandom)
444		*lastport = first + (arc4random() % (last - first));
445
446	count = last - first;
447
448	do {
449		if (count-- < 0)	/* completely used? */
450			return (EADDRNOTAVAIL);
451		++*lastport;
452		if (*lastport < first || *lastport > last)
453			*lastport = first;
454		lport = htons(*lastport);
455
456#ifdef INET6
457		if ((inp->inp_vflag & INP_IPV6) != 0)
458			tmpinp = in6_pcblookup_local(pcbinfo,
459			    &inp->in6p_laddr, lport, lookupflags, cred);
460#endif
461#if defined(INET) && defined(INET6)
462		else
463#endif
464#ifdef INET
465			tmpinp = in_pcblookup_local(pcbinfo, laddr,
466			    lport, lookupflags, cred);
467#endif
468	} while (tmpinp != NULL);
469
470#ifdef INET
471	if ((inp->inp_vflag & (INP_IPV4|INP_IPV6)) == INP_IPV4)
472		laddrp->s_addr = laddr.s_addr;
473#endif
474	*lportp = lport;
475
476	return (0);
477}
478
479/*
480 * Return cached socket options.
481 */
482short
483inp_so_options(const struct inpcb *inp)
484{
485   short so_options;
486
487   so_options = 0;
488
489   if ((inp->inp_flags2 & INP_REUSEPORT) != 0)
490	   so_options |= SO_REUSEPORT;
491   if ((inp->inp_flags2 & INP_REUSEADDR) != 0)
492	   so_options |= SO_REUSEADDR;
493   return (so_options);
494}
495#endif /* INET || INET6 */
496
497#ifdef INET
498/*
499 * Set up a bind operation on a PCB, performing port allocation
500 * as required, but do not actually modify the PCB. Callers can
501 * either complete the bind by setting inp_laddr/inp_lport and
502 * calling in_pcbinshash(), or they can just use the resulting
503 * port and address to authorise the sending of a once-off packet.
504 *
505 * On error, the values of *laddrp and *lportp are not changed.
506 */
507int
508in_pcbbind_setup(struct inpcb *inp, struct sockaddr *nam, in_addr_t *laddrp,
509    u_short *lportp, struct ucred *cred)
510{
511	struct socket *so = inp->inp_socket;
512	struct sockaddr_in *sin;
513	struct inpcbinfo *pcbinfo = inp->inp_pcbinfo;
514	struct in_addr laddr;
515	u_short lport = 0;
516	int lookupflags = 0, reuseport = (so->so_options & SO_REUSEPORT);
517	int error;
518
519	/*
520	 * No state changes, so read locks are sufficient here.
521	 */
522	INP_LOCK_ASSERT(inp);
523	INP_HASH_LOCK_ASSERT(pcbinfo);
524
525	if (TAILQ_EMPTY(&V_in_ifaddrhead)) /* XXX broken! */
526		return (EADDRNOTAVAIL);
527	laddr.s_addr = *laddrp;
528	if (nam != NULL && laddr.s_addr != INADDR_ANY)
529		return (EINVAL);
530	if ((so->so_options & (SO_REUSEADDR|SO_REUSEPORT)) == 0)
531		lookupflags = INPLOOKUP_WILDCARD;
532	if (nam == NULL) {
533		if ((error = prison_local_ip4(cred, &laddr)) != 0)
534			return (error);
535	} else {
536		sin = (struct sockaddr_in *)nam;
537		if (nam->sa_len != sizeof (*sin))
538			return (EINVAL);
539#ifdef notdef
540		/*
541		 * We should check the family, but old programs
542		 * incorrectly fail to initialize it.
543		 */
544		if (sin->sin_family != AF_INET)
545			return (EAFNOSUPPORT);
546#endif
547		error = prison_local_ip4(cred, &sin->sin_addr);
548		if (error)
549			return (error);
550		if (sin->sin_port != *lportp) {
551			/* Don't allow the port to change. */
552			if (*lportp != 0)
553				return (EINVAL);
554			lport = sin->sin_port;
555		}
556		/* NB: lport is left as 0 if the port isn't being changed. */
557		if (IN_MULTICAST(ntohl(sin->sin_addr.s_addr))) {
558			/*
559			 * Treat SO_REUSEADDR as SO_REUSEPORT for multicast;
560			 * allow complete duplication of binding if
561			 * SO_REUSEPORT is set, or if SO_REUSEADDR is set
562			 * and a multicast address is bound on both
563			 * new and duplicated sockets.
564			 */
565			if ((so->so_options & (SO_REUSEADDR|SO_REUSEPORT)) != 0)
566				reuseport = SO_REUSEADDR|SO_REUSEPORT;
567		} else if (sin->sin_addr.s_addr != INADDR_ANY) {
568			sin->sin_port = 0;		/* yech... */
569			bzero(&sin->sin_zero, sizeof(sin->sin_zero));
570			/*
571			 * Is the address a local IP address?
572			 * If INP_BINDANY is set, then the socket may be bound
573			 * to any endpoint address, local or not.
574			 */
575			if ((inp->inp_flags & INP_BINDANY) == 0 &&
576			    ifa_ifwithaddr_check((struct sockaddr *)sin) == 0)
577				return (EADDRNOTAVAIL);
578		}
579		laddr = sin->sin_addr;
580		if (lport) {
581			struct inpcb *t;
582			struct tcptw *tw;
583
584			/* GROSS */
585			if (ntohs(lport) <= V_ipport_reservedhigh &&
586			    ntohs(lport) >= V_ipport_reservedlow &&
587			    priv_check_cred(cred, PRIV_NETINET_RESERVEDPORT,
588			    0))
589				return (EACCES);
590			if (!IN_MULTICAST(ntohl(sin->sin_addr.s_addr)) &&
591			    priv_check_cred(inp->inp_cred,
592			    PRIV_NETINET_REUSEPORT, 0) != 0) {
593				t = in_pcblookup_local(pcbinfo, sin->sin_addr,
594				    lport, INPLOOKUP_WILDCARD, cred);
595	/*
596	 * XXX
597	 * This entire block sorely needs a rewrite.
598	 */
599				if (t &&
600				    ((t->inp_flags & INP_TIMEWAIT) == 0) &&
601				    (so->so_type != SOCK_STREAM ||
602				     ntohl(t->inp_faddr.s_addr) == INADDR_ANY) &&
603				    (ntohl(sin->sin_addr.s_addr) != INADDR_ANY ||
604				     ntohl(t->inp_laddr.s_addr) != INADDR_ANY ||
605				     (t->inp_flags2 & INP_REUSEPORT) == 0) &&
606				    (inp->inp_cred->cr_uid !=
607				     t->inp_cred->cr_uid))
608					return (EADDRINUSE);
609			}
610			t = in_pcblookup_local(pcbinfo, sin->sin_addr,
611			    lport, lookupflags, cred);
612			if (t && (t->inp_flags & INP_TIMEWAIT)) {
613				/*
614				 * XXXRW: If an incpb has had its timewait
615				 * state recycled, we treat the address as
616				 * being in use (for now).  This is better
617				 * than a panic, but not desirable.
618				 */
619				tw = intotw(t);
620				if (tw == NULL ||
621				    (reuseport & tw->tw_so_options) == 0)
622					return (EADDRINUSE);
623			} else if (t && (reuseport & inp_so_options(t)) == 0) {
624#ifdef INET6
625				if (ntohl(sin->sin_addr.s_addr) !=
626				    INADDR_ANY ||
627				    ntohl(t->inp_laddr.s_addr) !=
628				    INADDR_ANY ||
629				    (inp->inp_vflag & INP_IPV6PROTO) == 0 ||
630				    (t->inp_vflag & INP_IPV6PROTO) == 0)
631#endif
632				return (EADDRINUSE);
633			}
634		}
635	}
636	if (*lportp != 0)
637		lport = *lportp;
638	if (lport == 0) {
639		error = in_pcb_lport(inp, &laddr, &lport, cred, lookupflags);
640		if (error != 0)
641			return (error);
642
643	}
644	*laddrp = laddr.s_addr;
645	*lportp = lport;
646	return (0);
647}
648
649/*
650 * Connect from a socket to a specified address.
651 * Both address and port must be specified in argument sin.
652 * If don't have a local address for this socket yet,
653 * then pick one.
654 */
655int
656in_pcbconnect_mbuf(struct inpcb *inp, struct sockaddr *nam,
657    struct ucred *cred, struct mbuf *m)
658{
659	u_short lport, fport;
660	in_addr_t laddr, faddr;
661	int anonport, error;
662
663	INP_WLOCK_ASSERT(inp);
664	INP_HASH_WLOCK_ASSERT(inp->inp_pcbinfo);
665
666	lport = inp->inp_lport;
667	laddr = inp->inp_laddr.s_addr;
668	anonport = (lport == 0);
669	error = in_pcbconnect_setup(inp, nam, &laddr, &lport, &faddr, &fport,
670	    NULL, cred);
671	if (error)
672		return (error);
673
674	/* Do the initial binding of the local address if required. */
675	if (inp->inp_laddr.s_addr == INADDR_ANY && inp->inp_lport == 0) {
676		inp->inp_lport = lport;
677		inp->inp_laddr.s_addr = laddr;
678		if (in_pcbinshash(inp) != 0) {
679			inp->inp_laddr.s_addr = INADDR_ANY;
680			inp->inp_lport = 0;
681			return (EAGAIN);
682		}
683	}
684
685	/* Commit the remaining changes. */
686	inp->inp_lport = lport;
687	inp->inp_laddr.s_addr = laddr;
688	inp->inp_faddr.s_addr = faddr;
689	inp->inp_fport = fport;
690	in_pcbrehash_mbuf(inp, m);
691
692	if (anonport)
693		inp->inp_flags |= INP_ANONPORT;
694	return (0);
695}
696
697int
698in_pcbconnect(struct inpcb *inp, struct sockaddr *nam, struct ucred *cred)
699{
700
701	return (in_pcbconnect_mbuf(inp, nam, cred, NULL));
702}
703
704/*
705 * Do proper source address selection on an unbound socket in case
706 * of connect. Take jails into account as well.
707 */
708int
709in_pcbladdr(struct inpcb *inp, struct in_addr *faddr, struct in_addr *laddr,
710    struct ucred *cred)
711{
712	struct ifaddr *ifa;
713	struct sockaddr *sa;
714	struct sockaddr_in *sin;
715	struct route sro;
716	int error;
717
718	KASSERT(laddr != NULL, ("%s: laddr NULL", __func__));
719
720	/*
721	 * Bypass source address selection and use the primary jail IP
722	 * if requested.
723	 */
724	if (cred != NULL && !prison_saddrsel_ip4(cred, laddr))
725		return (0);
726
727	error = 0;
728	bzero(&sro, sizeof(sro));
729
730	sin = (struct sockaddr_in *)&sro.ro_dst;
731	sin->sin_family = AF_INET;
732	sin->sin_len = sizeof(struct sockaddr_in);
733	sin->sin_addr.s_addr = faddr->s_addr;
734
735	/*
736	 * If route is known our src addr is taken from the i/f,
737	 * else punt.
738	 *
739	 * Find out route to destination.
740	 */
741	if ((inp->inp_socket->so_options & SO_DONTROUTE) == 0)
742		in_rtalloc_ign(&sro, 0, inp->inp_inc.inc_fibnum);
743
744	/*
745	 * If we found a route, use the address corresponding to
746	 * the outgoing interface.
747	 *
748	 * Otherwise assume faddr is reachable on a directly connected
749	 * network and try to find a corresponding interface to take
750	 * the source address from.
751	 */
752	if (sro.ro_rt == NULL || sro.ro_rt->rt_ifp == NULL) {
753		struct in_ifaddr *ia;
754		struct ifnet *ifp;
755
756		ia = ifatoia(ifa_ifwithdstaddr((struct sockaddr *)sin));
757		if (ia == NULL)
758			ia = ifatoia(ifa_ifwithnet((struct sockaddr *)sin, 0));
759		if (ia == NULL) {
760			error = ENETUNREACH;
761			goto done;
762		}
763
764		if (cred == NULL || !prison_flag(cred, PR_IP4)) {
765			laddr->s_addr = ia->ia_addr.sin_addr.s_addr;
766			ifa_free(&ia->ia_ifa);
767			goto done;
768		}
769
770		ifp = ia->ia_ifp;
771		ifa_free(&ia->ia_ifa);
772		ia = NULL;
773		IF_ADDR_RLOCK(ifp);
774		TAILQ_FOREACH(ifa, &ifp->if_addrhead, ifa_link) {
775
776			sa = ifa->ifa_addr;
777			if (sa->sa_family != AF_INET)
778				continue;
779			sin = (struct sockaddr_in *)sa;
780			if (prison_check_ip4(cred, &sin->sin_addr) == 0) {
781				ia = (struct in_ifaddr *)ifa;
782				break;
783			}
784		}
785		if (ia != NULL) {
786			laddr->s_addr = ia->ia_addr.sin_addr.s_addr;
787			IF_ADDR_RUNLOCK(ifp);
788			goto done;
789		}
790		IF_ADDR_RUNLOCK(ifp);
791
792		/* 3. As a last resort return the 'default' jail address. */
793		error = prison_get_ip4(cred, laddr);
794		goto done;
795	}
796
797	/*
798	 * If the outgoing interface on the route found is not
799	 * a loopback interface, use the address from that interface.
800	 * In case of jails do those three steps:
801	 * 1. check if the interface address belongs to the jail. If so use it.
802	 * 2. check if we have any address on the outgoing interface
803	 *    belonging to this jail. If so use it.
804	 * 3. as a last resort return the 'default' jail address.
805	 */
806	if ((sro.ro_rt->rt_ifp->if_flags & IFF_LOOPBACK) == 0) {
807		struct in_ifaddr *ia;
808		struct ifnet *ifp;
809
810		/* If not jailed, use the default returned. */
811		if (cred == NULL || !prison_flag(cred, PR_IP4)) {
812			ia = (struct in_ifaddr *)sro.ro_rt->rt_ifa;
813			laddr->s_addr = ia->ia_addr.sin_addr.s_addr;
814			goto done;
815		}
816
817		/* Jailed. */
818		/* 1. Check if the iface address belongs to the jail. */
819		sin = (struct sockaddr_in *)sro.ro_rt->rt_ifa->ifa_addr;
820		if (prison_check_ip4(cred, &sin->sin_addr) == 0) {
821			ia = (struct in_ifaddr *)sro.ro_rt->rt_ifa;
822			laddr->s_addr = ia->ia_addr.sin_addr.s_addr;
823			goto done;
824		}
825
826		/*
827		 * 2. Check if we have any address on the outgoing interface
828		 *    belonging to this jail.
829		 */
830		ia = NULL;
831		ifp = sro.ro_rt->rt_ifp;
832		IF_ADDR_RLOCK(ifp);
833		TAILQ_FOREACH(ifa, &ifp->if_addrhead, ifa_link) {
834			sa = ifa->ifa_addr;
835			if (sa->sa_family != AF_INET)
836				continue;
837			sin = (struct sockaddr_in *)sa;
838			if (prison_check_ip4(cred, &sin->sin_addr) == 0) {
839				ia = (struct in_ifaddr *)ifa;
840				break;
841			}
842		}
843		if (ia != NULL) {
844			laddr->s_addr = ia->ia_addr.sin_addr.s_addr;
845			IF_ADDR_RUNLOCK(ifp);
846			goto done;
847		}
848		IF_ADDR_RUNLOCK(ifp);
849
850		/* 3. As a last resort return the 'default' jail address. */
851		error = prison_get_ip4(cred, laddr);
852		goto done;
853	}
854
855	/*
856	 * The outgoing interface is marked with 'loopback net', so a route
857	 * to ourselves is here.
858	 * Try to find the interface of the destination address and then
859	 * take the address from there. That interface is not necessarily
860	 * a loopback interface.
861	 * In case of jails, check that it is an address of the jail
862	 * and if we cannot find, fall back to the 'default' jail address.
863	 */
864	if ((sro.ro_rt->rt_ifp->if_flags & IFF_LOOPBACK) != 0) {
865		struct sockaddr_in sain;
866		struct in_ifaddr *ia;
867
868		bzero(&sain, sizeof(struct sockaddr_in));
869		sain.sin_family = AF_INET;
870		sain.sin_len = sizeof(struct sockaddr_in);
871		sain.sin_addr.s_addr = faddr->s_addr;
872
873		ia = ifatoia(ifa_ifwithdstaddr(sintosa(&sain)));
874		if (ia == NULL)
875			ia = ifatoia(ifa_ifwithnet(sintosa(&sain), 0));
876		if (ia == NULL)
877			ia = ifatoia(ifa_ifwithaddr(sintosa(&sain)));
878
879		if (cred == NULL || !prison_flag(cred, PR_IP4)) {
880			if (ia == NULL) {
881				error = ENETUNREACH;
882				goto done;
883			}
884			laddr->s_addr = ia->ia_addr.sin_addr.s_addr;
885			ifa_free(&ia->ia_ifa);
886			goto done;
887		}
888
889		/* Jailed. */
890		if (ia != NULL) {
891			struct ifnet *ifp;
892
893			ifp = ia->ia_ifp;
894			ifa_free(&ia->ia_ifa);
895			ia = NULL;
896			IF_ADDR_RLOCK(ifp);
897			TAILQ_FOREACH(ifa, &ifp->if_addrhead, ifa_link) {
898
899				sa = ifa->ifa_addr;
900				if (sa->sa_family != AF_INET)
901					continue;
902				sin = (struct sockaddr_in *)sa;
903				if (prison_check_ip4(cred,
904				    &sin->sin_addr) == 0) {
905					ia = (struct in_ifaddr *)ifa;
906					break;
907				}
908			}
909			if (ia != NULL) {
910				laddr->s_addr = ia->ia_addr.sin_addr.s_addr;
911				IF_ADDR_RUNLOCK(ifp);
912				goto done;
913			}
914			IF_ADDR_RUNLOCK(ifp);
915		}
916
917		/* 3. As a last resort return the 'default' jail address. */
918		error = prison_get_ip4(cred, laddr);
919		goto done;
920	}
921
922done:
923	if (sro.ro_rt != NULL)
924		RTFREE(sro.ro_rt);
925	return (error);
926}
927
928/*
929 * Set up for a connect from a socket to the specified address.
930 * On entry, *laddrp and *lportp should contain the current local
931 * address and port for the PCB; these are updated to the values
932 * that should be placed in inp_laddr and inp_lport to complete
933 * the connect.
934 *
935 * On success, *faddrp and *fportp will be set to the remote address
936 * and port. These are not updated in the error case.
937 *
938 * If the operation fails because the connection already exists,
939 * *oinpp will be set to the PCB of that connection so that the
940 * caller can decide to override it. In all other cases, *oinpp
941 * is set to NULL.
942 */
943int
944in_pcbconnect_setup(struct inpcb *inp, struct sockaddr *nam,
945    in_addr_t *laddrp, u_short *lportp, in_addr_t *faddrp, u_short *fportp,
946    struct inpcb **oinpp, struct ucred *cred)
947{
948	struct sockaddr_in *sin = (struct sockaddr_in *)nam;
949	struct in_ifaddr *ia;
950	struct inpcb *oinp;
951	struct in_addr laddr, faddr;
952	u_short lport, fport;
953	int error;
954
955	/*
956	 * Because a global state change doesn't actually occur here, a read
957	 * lock is sufficient.
958	 */
959	INP_LOCK_ASSERT(inp);
960	INP_HASH_LOCK_ASSERT(inp->inp_pcbinfo);
961
962	if (oinpp != NULL)
963		*oinpp = NULL;
964	if (nam->sa_len != sizeof (*sin))
965		return (EINVAL);
966	if (sin->sin_family != AF_INET)
967		return (EAFNOSUPPORT);
968	if (sin->sin_port == 0)
969		return (EADDRNOTAVAIL);
970	laddr.s_addr = *laddrp;
971	lport = *lportp;
972	faddr = sin->sin_addr;
973	fport = sin->sin_port;
974
975	if (!TAILQ_EMPTY(&V_in_ifaddrhead)) {
976		/*
977		 * If the destination address is INADDR_ANY,
978		 * use the primary local address.
979		 * If the supplied address is INADDR_BROADCAST,
980		 * and the primary interface supports broadcast,
981		 * choose the broadcast address for that interface.
982		 */
983		if (faddr.s_addr == INADDR_ANY) {
984			IN_IFADDR_RLOCK();
985			faddr =
986			    IA_SIN(TAILQ_FIRST(&V_in_ifaddrhead))->sin_addr;
987			IN_IFADDR_RUNLOCK();
988			if (cred != NULL &&
989			    (error = prison_get_ip4(cred, &faddr)) != 0)
990				return (error);
991		} else if (faddr.s_addr == (u_long)INADDR_BROADCAST) {
992			IN_IFADDR_RLOCK();
993			if (TAILQ_FIRST(&V_in_ifaddrhead)->ia_ifp->if_flags &
994			    IFF_BROADCAST)
995				faddr = satosin(&TAILQ_FIRST(
996				    &V_in_ifaddrhead)->ia_broadaddr)->sin_addr;
997			IN_IFADDR_RUNLOCK();
998		}
999	}
1000	if (laddr.s_addr == INADDR_ANY) {
1001		error = in_pcbladdr(inp, &faddr, &laddr, cred);
1002		/*
1003		 * If the destination address is multicast and an outgoing
1004		 * interface has been set as a multicast option, prefer the
1005		 * address of that interface as our source address.
1006		 */
1007		if (IN_MULTICAST(ntohl(faddr.s_addr)) &&
1008		    inp->inp_moptions != NULL) {
1009			struct ip_moptions *imo;
1010			struct ifnet *ifp;
1011
1012			imo = inp->inp_moptions;
1013			if (imo->imo_multicast_ifp != NULL) {
1014				ifp = imo->imo_multicast_ifp;
1015				IN_IFADDR_RLOCK();
1016				TAILQ_FOREACH(ia, &V_in_ifaddrhead, ia_link) {
1017					if ((ia->ia_ifp == ifp) &&
1018					    (cred == NULL ||
1019					    prison_check_ip4(cred,
1020					    &ia->ia_addr.sin_addr) == 0))
1021						break;
1022				}
1023				if (ia == NULL)
1024					error = EADDRNOTAVAIL;
1025				else {
1026					laddr = ia->ia_addr.sin_addr;
1027					error = 0;
1028				}
1029				IN_IFADDR_RUNLOCK();
1030			}
1031		}
1032		if (error)
1033			return (error);
1034	}
1035	oinp = in_pcblookup_hash_locked(inp->inp_pcbinfo, faddr, fport,
1036	    laddr, lport, 0, NULL);
1037	if (oinp != NULL) {
1038		if (oinpp != NULL)
1039			*oinpp = oinp;
1040		return (EADDRINUSE);
1041	}
1042	if (lport == 0) {
1043		error = in_pcbbind_setup(inp, NULL, &laddr.s_addr, &lport,
1044		    cred);
1045		if (error)
1046			return (error);
1047	}
1048	*laddrp = laddr.s_addr;
1049	*lportp = lport;
1050	*faddrp = faddr.s_addr;
1051	*fportp = fport;
1052	return (0);
1053}
1054
1055void
1056in_pcbdisconnect(struct inpcb *inp)
1057{
1058
1059	INP_WLOCK_ASSERT(inp);
1060	INP_HASH_WLOCK_ASSERT(inp->inp_pcbinfo);
1061
1062	inp->inp_faddr.s_addr = INADDR_ANY;
1063	inp->inp_fport = 0;
1064	in_pcbrehash(inp);
1065}
1066#endif /* INET */
1067
1068/*
1069 * in_pcbdetach() is responsibe for disassociating a socket from an inpcb.
1070 * For most protocols, this will be invoked immediately prior to calling
1071 * in_pcbfree().  However, with TCP the inpcb may significantly outlive the
1072 * socket, in which case in_pcbfree() is deferred.
1073 */
1074void
1075in_pcbdetach(struct inpcb *inp)
1076{
1077
1078	KASSERT(inp->inp_socket != NULL, ("%s: inp_socket == NULL", __func__));
1079
1080	inp->inp_socket->so_pcb = NULL;
1081	inp->inp_socket = NULL;
1082}
1083
1084/*
1085 * in_pcbref() bumps the reference count on an inpcb in order to maintain
1086 * stability of an inpcb pointer despite the inpcb lock being released.  This
1087 * is used in TCP when the inpcbinfo lock needs to be acquired or upgraded,
1088 * but where the inpcb lock may already held, or when acquiring a reference
1089 * via a pcbgroup.
1090 *
1091 * in_pcbref() should be used only to provide brief memory stability, and
1092 * must always be followed by a call to INP_WLOCK() and in_pcbrele() to
1093 * garbage collect the inpcb if it has been in_pcbfree()'d from another
1094 * context.  Until in_pcbrele() has returned that the inpcb is still valid,
1095 * lock and rele are the *only* safe operations that may be performed on the
1096 * inpcb.
1097 *
1098 * While the inpcb will not be freed, releasing the inpcb lock means that the
1099 * connection's state may change, so the caller should be careful to
1100 * revalidate any cached state on reacquiring the lock.  Drop the reference
1101 * using in_pcbrele().
1102 */
1103void
1104in_pcbref(struct inpcb *inp)
1105{
1106
1107	KASSERT(inp->inp_refcount > 0, ("%s: refcount 0", __func__));
1108
1109	refcount_acquire(&inp->inp_refcount);
1110}
1111
1112/*
1113 * Drop a refcount on an inpcb elevated using in_pcbref(); because a call to
1114 * in_pcbfree() may have been made between in_pcbref() and in_pcbrele(), we
1115 * return a flag indicating whether or not the inpcb remains valid.  If it is
1116 * valid, we return with the inpcb lock held.
1117 *
1118 * Notice that, unlike in_pcbref(), the inpcb lock must be held to drop a
1119 * reference on an inpcb.  Historically more work was done here (actually, in
1120 * in_pcbfree_internal()) but has been moved to in_pcbfree() to avoid the
1121 * need for the pcbinfo lock in in_pcbrele().  Deferring the free is entirely
1122 * about memory stability (and continued use of the write lock).
1123 */
1124int
1125in_pcbrele_rlocked(struct inpcb *inp)
1126{
1127	struct inpcbinfo *pcbinfo;
1128
1129	KASSERT(inp->inp_refcount > 0, ("%s: refcount 0", __func__));
1130
1131	INP_RLOCK_ASSERT(inp);
1132
1133	if (refcount_release(&inp->inp_refcount) == 0) {
1134		/*
1135		 * If the inpcb has been freed, let the caller know, even if
1136		 * this isn't the last reference.
1137		 */
1138		if (inp->inp_flags2 & INP_FREED) {
1139			INP_RUNLOCK(inp);
1140			return (1);
1141		}
1142		return (0);
1143	}
1144
1145	KASSERT(inp->inp_socket == NULL, ("%s: inp_socket != NULL", __func__));
1146
1147	INP_RUNLOCK(inp);
1148	pcbinfo = inp->inp_pcbinfo;
1149	uma_zfree(pcbinfo->ipi_zone, inp);
1150	return (1);
1151}
1152
1153int
1154in_pcbrele_wlocked(struct inpcb *inp)
1155{
1156	struct inpcbinfo *pcbinfo;
1157
1158	KASSERT(inp->inp_refcount > 0, ("%s: refcount 0", __func__));
1159
1160	INP_WLOCK_ASSERT(inp);
1161
1162	if (refcount_release(&inp->inp_refcount) == 0) {
1163		/*
1164		 * If the inpcb has been freed, let the caller know, even if
1165		 * this isn't the last reference.
1166		 */
1167		if (inp->inp_flags2 & INP_FREED) {
1168			INP_WUNLOCK(inp);
1169			return (1);
1170		}
1171		return (0);
1172	}
1173
1174	KASSERT(inp->inp_socket == NULL, ("%s: inp_socket != NULL", __func__));
1175
1176	INP_WUNLOCK(inp);
1177	pcbinfo = inp->inp_pcbinfo;
1178	uma_zfree(pcbinfo->ipi_zone, inp);
1179	return (1);
1180}
1181
1182/*
1183 * Temporary wrapper.
1184 */
1185int
1186in_pcbrele(struct inpcb *inp)
1187{
1188
1189	return (in_pcbrele_wlocked(inp));
1190}
1191
1192/*
1193 * Unconditionally schedule an inpcb to be freed by decrementing its
1194 * reference count, which should occur only after the inpcb has been detached
1195 * from its socket.  If another thread holds a temporary reference (acquired
1196 * using in_pcbref()) then the free is deferred until that reference is
1197 * released using in_pcbrele(), but the inpcb is still unlocked.  Almost all
1198 * work, including removal from global lists, is done in this context, where
1199 * the pcbinfo lock is held.
1200 */
1201void
1202in_pcbfree(struct inpcb *inp)
1203{
1204	struct inpcbinfo *pcbinfo = inp->inp_pcbinfo;
1205
1206	KASSERT(inp->inp_socket == NULL, ("%s: inp_socket != NULL", __func__));
1207
1208#ifdef INVARIANTS
1209	if (pcbinfo == &V_tcbinfo) {
1210		INP_INFO_LOCK_ASSERT(pcbinfo);
1211	} else {
1212		INP_INFO_WLOCK_ASSERT(pcbinfo);
1213	}
1214#endif
1215	INP_WLOCK_ASSERT(inp);
1216
1217	/* XXXRW: Do as much as possible here. */
1218#ifdef IPSEC
1219	if (inp->inp_sp != NULL)
1220		ipsec_delete_pcbpolicy(inp);
1221#endif
1222	INP_LIST_WLOCK(pcbinfo);
1223	inp->inp_gencnt = ++pcbinfo->ipi_gencnt;
1224	in_pcbremlists(inp);
1225	INP_LIST_WUNLOCK(pcbinfo);
1226#ifdef INET6
1227	if (inp->inp_vflag & INP_IPV6PROTO) {
1228		ip6_freepcbopts(inp->in6p_outputopts);
1229		if (inp->in6p_moptions != NULL)
1230			ip6_freemoptions(inp->in6p_moptions);
1231	}
1232#endif
1233	if (inp->inp_options)
1234		(void)m_free(inp->inp_options);
1235#ifdef INET
1236	if (inp->inp_moptions != NULL)
1237		inp_freemoptions(inp->inp_moptions);
1238#endif
1239	inp->inp_vflag = 0;
1240	inp->inp_flags2 |= INP_FREED;
1241	crfree(inp->inp_cred);
1242#ifdef MAC
1243	mac_inpcb_destroy(inp);
1244#endif
1245	if (!in_pcbrele_wlocked(inp))
1246		INP_WUNLOCK(inp);
1247}
1248
1249/*
1250 * in_pcbdrop() removes an inpcb from hashed lists, releasing its address and
1251 * port reservation, and preventing it from being returned by inpcb lookups.
1252 *
1253 * It is used by TCP to mark an inpcb as unused and avoid future packet
1254 * delivery or event notification when a socket remains open but TCP has
1255 * closed.  This might occur as a result of a shutdown()-initiated TCP close
1256 * or a RST on the wire, and allows the port binding to be reused while still
1257 * maintaining the invariant that so_pcb always points to a valid inpcb until
1258 * in_pcbdetach().
1259 *
1260 * XXXRW: Possibly in_pcbdrop() should also prevent future notifications by
1261 * in_pcbnotifyall() and in_pcbpurgeif0()?
1262 */
1263void
1264in_pcbdrop(struct inpcb *inp)
1265{
1266
1267	INP_WLOCK_ASSERT(inp);
1268
1269	/*
1270	 * XXXRW: Possibly we should protect the setting of INP_DROPPED with
1271	 * the hash lock...?
1272	 */
1273	inp->inp_flags |= INP_DROPPED;
1274	if (inp->inp_flags & INP_INHASHLIST) {
1275		struct inpcbport *phd = inp->inp_phd;
1276
1277		INP_HASH_WLOCK(inp->inp_pcbinfo);
1278		LIST_REMOVE(inp, inp_hash);
1279		LIST_REMOVE(inp, inp_portlist);
1280		if (LIST_FIRST(&phd->phd_pcblist) == NULL) {
1281			LIST_REMOVE(phd, phd_hash);
1282			free(phd, M_PCB);
1283		}
1284		INP_HASH_WUNLOCK(inp->inp_pcbinfo);
1285		inp->inp_flags &= ~INP_INHASHLIST;
1286#ifdef PCBGROUP
1287		in_pcbgroup_remove(inp);
1288#endif
1289	}
1290}
1291
1292#ifdef INET
1293/*
1294 * Common routines to return the socket addresses associated with inpcbs.
1295 */
1296struct sockaddr *
1297in_sockaddr(in_port_t port, struct in_addr *addr_p)
1298{
1299	struct sockaddr_in *sin;
1300
1301	sin = malloc(sizeof *sin, M_SONAME,
1302		M_WAITOK | M_ZERO);
1303	sin->sin_family = AF_INET;
1304	sin->sin_len = sizeof(*sin);
1305	sin->sin_addr = *addr_p;
1306	sin->sin_port = port;
1307
1308	return (struct sockaddr *)sin;
1309}
1310
1311int
1312in_getsockaddr(struct socket *so, struct sockaddr **nam)
1313{
1314	struct inpcb *inp;
1315	struct in_addr addr;
1316	in_port_t port;
1317
1318	inp = sotoinpcb(so);
1319	KASSERT(inp != NULL, ("in_getsockaddr: inp == NULL"));
1320
1321	INP_RLOCK(inp);
1322	port = inp->inp_lport;
1323	addr = inp->inp_laddr;
1324	INP_RUNLOCK(inp);
1325
1326	*nam = in_sockaddr(port, &addr);
1327	return 0;
1328}
1329
1330int
1331in_getpeeraddr(struct socket *so, struct sockaddr **nam)
1332{
1333	struct inpcb *inp;
1334	struct in_addr addr;
1335	in_port_t port;
1336
1337	inp = sotoinpcb(so);
1338	KASSERT(inp != NULL, ("in_getpeeraddr: inp == NULL"));
1339
1340	INP_RLOCK(inp);
1341	port = inp->inp_fport;
1342	addr = inp->inp_faddr;
1343	INP_RUNLOCK(inp);
1344
1345	*nam = in_sockaddr(port, &addr);
1346	return 0;
1347}
1348
1349void
1350in_pcbnotifyall(struct inpcbinfo *pcbinfo, struct in_addr faddr, int errno,
1351    struct inpcb *(*notify)(struct inpcb *, int))
1352{
1353	struct inpcb *inp, *inp_temp;
1354
1355	INP_INFO_WLOCK(pcbinfo);
1356	LIST_FOREACH_SAFE(inp, pcbinfo->ipi_listhead, inp_list, inp_temp) {
1357		INP_WLOCK(inp);
1358#ifdef INET6
1359		if ((inp->inp_vflag & INP_IPV4) == 0) {
1360			INP_WUNLOCK(inp);
1361			continue;
1362		}
1363#endif
1364		if (inp->inp_faddr.s_addr != faddr.s_addr ||
1365		    inp->inp_socket == NULL) {
1366			INP_WUNLOCK(inp);
1367			continue;
1368		}
1369		if ((*notify)(inp, errno))
1370			INP_WUNLOCK(inp);
1371	}
1372	INP_INFO_WUNLOCK(pcbinfo);
1373}
1374
1375void
1376in_pcbpurgeif0(struct inpcbinfo *pcbinfo, struct ifnet *ifp)
1377{
1378	struct inpcb *inp;
1379	struct ip_moptions *imo;
1380	int i, gap;
1381
1382	INP_INFO_WLOCK(pcbinfo);
1383	LIST_FOREACH(inp, pcbinfo->ipi_listhead, inp_list) {
1384		INP_WLOCK(inp);
1385		imo = inp->inp_moptions;
1386		if ((inp->inp_vflag & INP_IPV4) &&
1387		    imo != NULL) {
1388			/*
1389			 * Unselect the outgoing interface if it is being
1390			 * detached.
1391			 */
1392			if (imo->imo_multicast_ifp == ifp)
1393				imo->imo_multicast_ifp = NULL;
1394
1395			/*
1396			 * Drop multicast group membership if we joined
1397			 * through the interface being detached.
1398			 */
1399			for (i = 0, gap = 0; i < imo->imo_num_memberships;
1400			    i++) {
1401				if (imo->imo_membership[i]->inm_ifp == ifp) {
1402					in_delmulti(imo->imo_membership[i]);
1403					gap++;
1404				} else if (gap != 0)
1405					imo->imo_membership[i - gap] =
1406					    imo->imo_membership[i];
1407			}
1408			imo->imo_num_memberships -= gap;
1409		}
1410		INP_WUNLOCK(inp);
1411	}
1412	INP_INFO_WUNLOCK(pcbinfo);
1413}
1414
1415/*
1416 * Lookup a PCB based on the local address and port.  Caller must hold the
1417 * hash lock.  No inpcb locks or references are acquired.
1418 */
1419#define INP_LOOKUP_MAPPED_PCB_COST	3
1420struct inpcb *
1421in_pcblookup_local(struct inpcbinfo *pcbinfo, struct in_addr laddr,
1422    u_short lport, int lookupflags, struct ucred *cred)
1423{
1424	struct inpcb *inp;
1425#ifdef INET6
1426	int matchwild = 3 + INP_LOOKUP_MAPPED_PCB_COST;
1427#else
1428	int matchwild = 3;
1429#endif
1430	int wildcard;
1431
1432	KASSERT((lookupflags & ~(INPLOOKUP_WILDCARD)) == 0,
1433	    ("%s: invalid lookup flags %d", __func__, lookupflags));
1434
1435	INP_HASH_LOCK_ASSERT(pcbinfo);
1436
1437	if ((lookupflags & INPLOOKUP_WILDCARD) == 0) {
1438		struct inpcbhead *head;
1439		/*
1440		 * Look for an unconnected (wildcard foreign addr) PCB that
1441		 * matches the local address and port we're looking for.
1442		 */
1443		head = &pcbinfo->ipi_hashbase[INP_PCBHASH(INADDR_ANY, lport,
1444		    0, pcbinfo->ipi_hashmask)];
1445		LIST_FOREACH(inp, head, inp_hash) {
1446#ifdef INET6
1447			/* XXX inp locking */
1448			if ((inp->inp_vflag & INP_IPV4) == 0)
1449				continue;
1450#endif
1451			if (inp->inp_faddr.s_addr == INADDR_ANY &&
1452			    inp->inp_laddr.s_addr == laddr.s_addr &&
1453			    inp->inp_lport == lport) {
1454				/*
1455				 * Found?
1456				 */
1457				if (cred == NULL ||
1458				    prison_equal_ip4(cred->cr_prison,
1459					inp->inp_cred->cr_prison))
1460					return (inp);
1461			}
1462		}
1463		/*
1464		 * Not found.
1465		 */
1466		return (NULL);
1467	} else {
1468		struct inpcbporthead *porthash;
1469		struct inpcbport *phd;
1470		struct inpcb *match = NULL;
1471		/*
1472		 * Best fit PCB lookup.
1473		 *
1474		 * First see if this local port is in use by looking on the
1475		 * port hash list.
1476		 */
1477		porthash = &pcbinfo->ipi_porthashbase[INP_PCBPORTHASH(lport,
1478		    pcbinfo->ipi_porthashmask)];
1479		LIST_FOREACH(phd, porthash, phd_hash) {
1480			if (phd->phd_port == lport)
1481				break;
1482		}
1483		if (phd != NULL) {
1484			/*
1485			 * Port is in use by one or more PCBs. Look for best
1486			 * fit.
1487			 */
1488			LIST_FOREACH(inp, &phd->phd_pcblist, inp_portlist) {
1489				wildcard = 0;
1490				if (cred != NULL &&
1491				    !prison_equal_ip4(inp->inp_cred->cr_prison,
1492					cred->cr_prison))
1493					continue;
1494#ifdef INET6
1495				/* XXX inp locking */
1496				if ((inp->inp_vflag & INP_IPV4) == 0)
1497					continue;
1498				/*
1499				 * We never select the PCB that has
1500				 * INP_IPV6 flag and is bound to :: if
1501				 * we have another PCB which is bound
1502				 * to 0.0.0.0.  If a PCB has the
1503				 * INP_IPV6 flag, then we set its cost
1504				 * higher than IPv4 only PCBs.
1505				 *
1506				 * Note that the case only happens
1507				 * when a socket is bound to ::, under
1508				 * the condition that the use of the
1509				 * mapped address is allowed.
1510				 */
1511				if ((inp->inp_vflag & INP_IPV6) != 0)
1512					wildcard += INP_LOOKUP_MAPPED_PCB_COST;
1513#endif
1514				if (inp->inp_faddr.s_addr != INADDR_ANY)
1515					wildcard++;
1516				if (inp->inp_laddr.s_addr != INADDR_ANY) {
1517					if (laddr.s_addr == INADDR_ANY)
1518						wildcard++;
1519					else if (inp->inp_laddr.s_addr != laddr.s_addr)
1520						continue;
1521				} else {
1522					if (laddr.s_addr != INADDR_ANY)
1523						wildcard++;
1524				}
1525				if (wildcard < matchwild) {
1526					match = inp;
1527					matchwild = wildcard;
1528					if (matchwild == 0)
1529						break;
1530				}
1531			}
1532		}
1533		return (match);
1534	}
1535}
1536#undef INP_LOOKUP_MAPPED_PCB_COST
1537
1538#ifdef PCBGROUP
1539/*
1540 * Lookup PCB in hash list, using pcbgroup tables.
1541 */
1542static struct inpcb *
1543in_pcblookup_group(struct inpcbinfo *pcbinfo, struct inpcbgroup *pcbgroup,
1544    struct in_addr faddr, u_int fport_arg, struct in_addr laddr,
1545    u_int lport_arg, int lookupflags, struct ifnet *ifp)
1546{
1547	struct inpcbhead *head;
1548	struct inpcb *inp, *tmpinp;
1549	u_short fport = fport_arg, lport = lport_arg;
1550
1551	/*
1552	 * First look for an exact match.
1553	 */
1554	tmpinp = NULL;
1555	INP_GROUP_LOCK(pcbgroup);
1556	head = &pcbgroup->ipg_hashbase[INP_PCBHASH(faddr.s_addr, lport, fport,
1557	    pcbgroup->ipg_hashmask)];
1558	LIST_FOREACH(inp, head, inp_pcbgrouphash) {
1559#ifdef INET6
1560		/* XXX inp locking */
1561		if ((inp->inp_vflag & INP_IPV4) == 0)
1562			continue;
1563#endif
1564		if (inp->inp_faddr.s_addr == faddr.s_addr &&
1565		    inp->inp_laddr.s_addr == laddr.s_addr &&
1566		    inp->inp_fport == fport &&
1567		    inp->inp_lport == lport) {
1568			/*
1569			 * XXX We should be able to directly return
1570			 * the inp here, without any checks.
1571			 * Well unless both bound with SO_REUSEPORT?
1572			 */
1573			if (prison_flag(inp->inp_cred, PR_IP4))
1574				goto found;
1575			if (tmpinp == NULL)
1576				tmpinp = inp;
1577		}
1578	}
1579	if (tmpinp != NULL) {
1580		inp = tmpinp;
1581		goto found;
1582	}
1583
1584	/*
1585	 * Then look for a wildcard match, if requested.
1586	 */
1587	if ((lookupflags & INPLOOKUP_WILDCARD) != 0) {
1588		struct inpcb *local_wild = NULL, *local_exact = NULL;
1589#ifdef INET6
1590		struct inpcb *local_wild_mapped = NULL;
1591#endif
1592		struct inpcb *jail_wild = NULL;
1593		struct inpcbhead *head;
1594		int injail;
1595
1596		/*
1597		 * Order of socket selection - we always prefer jails.
1598		 *      1. jailed, non-wild.
1599		 *      2. jailed, wild.
1600		 *      3. non-jailed, non-wild.
1601		 *      4. non-jailed, wild.
1602		 */
1603		head = &pcbinfo->ipi_wildbase[INP_PCBHASH(INADDR_ANY, lport,
1604		    0, pcbinfo->ipi_wildmask)];
1605		LIST_FOREACH(inp, head, inp_pcbgroup_wild) {
1606#ifdef INET6
1607			/* XXX inp locking */
1608			if ((inp->inp_vflag & INP_IPV4) == 0)
1609				continue;
1610#endif
1611			if (inp->inp_faddr.s_addr != INADDR_ANY ||
1612			    inp->inp_lport != lport)
1613				continue;
1614
1615			/* XXX inp locking */
1616			if (ifp && ifp->if_type == IFT_FAITH &&
1617			    (inp->inp_flags & INP_FAITH) == 0)
1618				continue;
1619
1620			injail = prison_flag(inp->inp_cred, PR_IP4);
1621			if (injail) {
1622				if (prison_check_ip4(inp->inp_cred,
1623				    &laddr) != 0)
1624					continue;
1625			} else {
1626				if (local_exact != NULL)
1627					continue;
1628			}
1629
1630			if (inp->inp_laddr.s_addr == laddr.s_addr) {
1631				if (injail)
1632					goto found;
1633				else
1634					local_exact = inp;
1635			} else if (inp->inp_laddr.s_addr == INADDR_ANY) {
1636#ifdef INET6
1637				/* XXX inp locking, NULL check */
1638				if (inp->inp_vflag & INP_IPV6PROTO)
1639					local_wild_mapped = inp;
1640				else
1641#endif
1642					if (injail)
1643						jail_wild = inp;
1644					else
1645						local_wild = inp;
1646			}
1647		} /* LIST_FOREACH */
1648		inp = jail_wild;
1649		if (inp == NULL)
1650			inp = local_exact;
1651		if (inp == NULL)
1652			inp = local_wild;
1653#ifdef INET6
1654		if (inp == NULL)
1655			inp = local_wild_mapped;
1656#endif
1657		if (inp != NULL)
1658			goto found;
1659	} /* if (lookupflags & INPLOOKUP_WILDCARD) */
1660	INP_GROUP_UNLOCK(pcbgroup);
1661	return (NULL);
1662
1663found:
1664	in_pcbref(inp);
1665	INP_GROUP_UNLOCK(pcbgroup);
1666	if (lookupflags & INPLOOKUP_WLOCKPCB) {
1667		INP_WLOCK(inp);
1668		if (in_pcbrele_wlocked(inp))
1669			return (NULL);
1670	} else if (lookupflags & INPLOOKUP_RLOCKPCB) {
1671		INP_RLOCK(inp);
1672		if (in_pcbrele_rlocked(inp))
1673			return (NULL);
1674	} else
1675		panic("%s: locking bug", __func__);
1676	return (inp);
1677}
1678#endif /* PCBGROUP */
1679
1680/*
1681 * Lookup PCB in hash list, using pcbinfo tables.  This variation assumes
1682 * that the caller has locked the hash list, and will not perform any further
1683 * locking or reference operations on either the hash list or the connection.
1684 */
1685static struct inpcb *
1686in_pcblookup_hash_locked(struct inpcbinfo *pcbinfo, struct in_addr faddr,
1687    u_int fport_arg, struct in_addr laddr, u_int lport_arg, int lookupflags,
1688    struct ifnet *ifp)
1689{
1690	struct inpcbhead *head;
1691	struct inpcb *inp, *tmpinp;
1692	u_short fport = fport_arg, lport = lport_arg;
1693
1694	KASSERT((lookupflags & ~(INPLOOKUP_WILDCARD)) == 0,
1695	    ("%s: invalid lookup flags %d", __func__, lookupflags));
1696
1697	INP_HASH_LOCK_ASSERT(pcbinfo);
1698
1699	/*
1700	 * First look for an exact match.
1701	 */
1702	tmpinp = NULL;
1703	head = &pcbinfo->ipi_hashbase[INP_PCBHASH(faddr.s_addr, lport, fport,
1704	    pcbinfo->ipi_hashmask)];
1705	LIST_FOREACH(inp, head, inp_hash) {
1706#ifdef INET6
1707		/* XXX inp locking */
1708		if ((inp->inp_vflag & INP_IPV4) == 0)
1709			continue;
1710#endif
1711		if (inp->inp_faddr.s_addr == faddr.s_addr &&
1712		    inp->inp_laddr.s_addr == laddr.s_addr &&
1713		    inp->inp_fport == fport &&
1714		    inp->inp_lport == lport) {
1715			/*
1716			 * XXX We should be able to directly return
1717			 * the inp here, without any checks.
1718			 * Well unless both bound with SO_REUSEPORT?
1719			 */
1720			if (prison_flag(inp->inp_cred, PR_IP4))
1721				return (inp);
1722			if (tmpinp == NULL)
1723				tmpinp = inp;
1724		}
1725	}
1726	if (tmpinp != NULL)
1727		return (tmpinp);
1728
1729	/*
1730	 * Then look for a wildcard match, if requested.
1731	 */
1732	if ((lookupflags & INPLOOKUP_WILDCARD) != 0) {
1733		struct inpcb *local_wild = NULL, *local_exact = NULL;
1734#ifdef INET6
1735		struct inpcb *local_wild_mapped = NULL;
1736#endif
1737		struct inpcb *jail_wild = NULL;
1738		int injail;
1739
1740		/*
1741		 * Order of socket selection - we always prefer jails.
1742		 *      1. jailed, non-wild.
1743		 *      2. jailed, wild.
1744		 *      3. non-jailed, non-wild.
1745		 *      4. non-jailed, wild.
1746		 */
1747
1748		head = &pcbinfo->ipi_hashbase[INP_PCBHASH(INADDR_ANY, lport,
1749		    0, pcbinfo->ipi_hashmask)];
1750		LIST_FOREACH(inp, head, inp_hash) {
1751#ifdef INET6
1752			/* XXX inp locking */
1753			if ((inp->inp_vflag & INP_IPV4) == 0)
1754				continue;
1755#endif
1756			if (inp->inp_faddr.s_addr != INADDR_ANY ||
1757			    inp->inp_lport != lport)
1758				continue;
1759
1760			/* XXX inp locking */
1761			if (ifp && ifp->if_type == IFT_FAITH &&
1762			    (inp->inp_flags & INP_FAITH) == 0)
1763				continue;
1764
1765			injail = prison_flag(inp->inp_cred, PR_IP4);
1766			if (injail) {
1767				if (prison_check_ip4(inp->inp_cred,
1768				    &laddr) != 0)
1769					continue;
1770			} else {
1771				if (local_exact != NULL)
1772					continue;
1773			}
1774
1775			if (inp->inp_laddr.s_addr == laddr.s_addr) {
1776				if (injail)
1777					return (inp);
1778				else
1779					local_exact = inp;
1780			} else if (inp->inp_laddr.s_addr == INADDR_ANY) {
1781#ifdef INET6
1782				/* XXX inp locking, NULL check */
1783				if (inp->inp_vflag & INP_IPV6PROTO)
1784					local_wild_mapped = inp;
1785				else
1786#endif
1787					if (injail)
1788						jail_wild = inp;
1789					else
1790						local_wild = inp;
1791			}
1792		} /* LIST_FOREACH */
1793		if (jail_wild != NULL)
1794			return (jail_wild);
1795		if (local_exact != NULL)
1796			return (local_exact);
1797		if (local_wild != NULL)
1798			return (local_wild);
1799#ifdef INET6
1800		if (local_wild_mapped != NULL)
1801			return (local_wild_mapped);
1802#endif
1803	} /* if ((lookupflags & INPLOOKUP_WILDCARD) != 0) */
1804
1805	return (NULL);
1806}
1807
1808/*
1809 * Lookup PCB in hash list, using pcbinfo tables.  This variation locks the
1810 * hash list lock, and will return the inpcb locked (i.e., requires
1811 * INPLOOKUP_LOCKPCB).
1812 */
1813static struct inpcb *
1814in_pcblookup_hash(struct inpcbinfo *pcbinfo, struct in_addr faddr,
1815    u_int fport, struct in_addr laddr, u_int lport, int lookupflags,
1816    struct ifnet *ifp)
1817{
1818	struct inpcb *inp;
1819
1820	INP_HASH_RLOCK(pcbinfo);
1821	inp = in_pcblookup_hash_locked(pcbinfo, faddr, fport, laddr, lport,
1822	    (lookupflags & ~(INPLOOKUP_RLOCKPCB | INPLOOKUP_WLOCKPCB)), ifp);
1823	if (inp != NULL) {
1824		in_pcbref(inp);
1825		INP_HASH_RUNLOCK(pcbinfo);
1826		if (lookupflags & INPLOOKUP_WLOCKPCB) {
1827			INP_WLOCK(inp);
1828			if (in_pcbrele_wlocked(inp))
1829				return (NULL);
1830		} else if (lookupflags & INPLOOKUP_RLOCKPCB) {
1831			INP_RLOCK(inp);
1832			if (in_pcbrele_rlocked(inp))
1833				return (NULL);
1834		} else
1835			panic("%s: locking bug", __func__);
1836	} else
1837		INP_HASH_RUNLOCK(pcbinfo);
1838	return (inp);
1839}
1840
1841/*
1842 * Public inpcb lookup routines, accepting a 4-tuple, and optionally, an mbuf
1843 * from which a pre-calculated hash value may be extracted.
1844 *
1845 * Possibly more of this logic should be in in_pcbgroup.c.
1846 */
1847struct inpcb *
1848in_pcblookup(struct inpcbinfo *pcbinfo, struct in_addr faddr, u_int fport,
1849    struct in_addr laddr, u_int lport, int lookupflags, struct ifnet *ifp)
1850{
1851#if defined(PCBGROUP)
1852	struct inpcbgroup *pcbgroup;
1853#endif
1854
1855	KASSERT((lookupflags & ~INPLOOKUP_MASK) == 0,
1856	    ("%s: invalid lookup flags %d", __func__, lookupflags));
1857	KASSERT((lookupflags & (INPLOOKUP_RLOCKPCB | INPLOOKUP_WLOCKPCB)) != 0,
1858	    ("%s: LOCKPCB not set", __func__));
1859
1860#if defined(PCBGROUP)
1861	if (in_pcbgroup_enabled(pcbinfo)) {
1862		pcbgroup = in_pcbgroup_bytuple(pcbinfo, laddr, lport, faddr,
1863		    fport);
1864		return (in_pcblookup_group(pcbinfo, pcbgroup, faddr, fport,
1865		    laddr, lport, lookupflags, ifp));
1866	}
1867#endif
1868	return (in_pcblookup_hash(pcbinfo, faddr, fport, laddr, lport,
1869	    lookupflags, ifp));
1870}
1871
1872struct inpcb *
1873in_pcblookup_mbuf(struct inpcbinfo *pcbinfo, struct in_addr faddr,
1874    u_int fport, struct in_addr laddr, u_int lport, int lookupflags,
1875    struct ifnet *ifp, struct mbuf *m)
1876{
1877#ifdef PCBGROUP
1878	struct inpcbgroup *pcbgroup;
1879#endif
1880
1881	KASSERT((lookupflags & ~INPLOOKUP_MASK) == 0,
1882	    ("%s: invalid lookup flags %d", __func__, lookupflags));
1883	KASSERT((lookupflags & (INPLOOKUP_RLOCKPCB | INPLOOKUP_WLOCKPCB)) != 0,
1884	    ("%s: LOCKPCB not set", __func__));
1885
1886#ifdef PCBGROUP
1887	if (in_pcbgroup_enabled(pcbinfo)) {
1888		pcbgroup = in_pcbgroup_byhash(pcbinfo, M_HASHTYPE_GET(m),
1889		    m->m_pkthdr.flowid);
1890		if (pcbgroup != NULL)
1891			return (in_pcblookup_group(pcbinfo, pcbgroup, faddr,
1892			    fport, laddr, lport, lookupflags, ifp));
1893		pcbgroup = in_pcbgroup_bytuple(pcbinfo, laddr, lport, faddr,
1894		    fport);
1895		return (in_pcblookup_group(pcbinfo, pcbgroup, faddr, fport,
1896		    laddr, lport, lookupflags, ifp));
1897	}
1898#endif
1899	return (in_pcblookup_hash(pcbinfo, faddr, fport, laddr, lport,
1900	    lookupflags, ifp));
1901}
1902#endif /* INET */
1903
1904/*
1905 * Insert PCB onto various hash lists.
1906 */
1907static int
1908in_pcbinshash_internal(struct inpcb *inp, int do_pcbgroup_update)
1909{
1910	struct inpcbhead *pcbhash;
1911	struct inpcbporthead *pcbporthash;
1912	struct inpcbinfo *pcbinfo = inp->inp_pcbinfo;
1913	struct inpcbport *phd;
1914	u_int32_t hashkey_faddr;
1915
1916	INP_WLOCK_ASSERT(inp);
1917	INP_HASH_WLOCK_ASSERT(pcbinfo);
1918
1919	KASSERT((inp->inp_flags & INP_INHASHLIST) == 0,
1920	    ("in_pcbinshash: INP_INHASHLIST"));
1921
1922#ifdef INET6
1923	if (inp->inp_vflag & INP_IPV6)
1924		hashkey_faddr = inp->in6p_faddr.s6_addr32[3] /* XXX */;
1925	else
1926#endif
1927	hashkey_faddr = inp->inp_faddr.s_addr;
1928
1929	pcbhash = &pcbinfo->ipi_hashbase[INP_PCBHASH(hashkey_faddr,
1930		 inp->inp_lport, inp->inp_fport, pcbinfo->ipi_hashmask)];
1931
1932	pcbporthash = &pcbinfo->ipi_porthashbase[
1933	    INP_PCBPORTHASH(inp->inp_lport, pcbinfo->ipi_porthashmask)];
1934
1935	/*
1936	 * Go through port list and look for a head for this lport.
1937	 */
1938	LIST_FOREACH(phd, pcbporthash, phd_hash) {
1939		if (phd->phd_port == inp->inp_lport)
1940			break;
1941	}
1942	/*
1943	 * If none exists, malloc one and tack it on.
1944	 */
1945	if (phd == NULL) {
1946		phd = malloc(sizeof(struct inpcbport), M_PCB, M_NOWAIT);
1947		if (phd == NULL) {
1948			return (ENOBUFS); /* XXX */
1949		}
1950		phd->phd_port = inp->inp_lport;
1951		LIST_INIT(&phd->phd_pcblist);
1952		LIST_INSERT_HEAD(pcbporthash, phd, phd_hash);
1953	}
1954	inp->inp_phd = phd;
1955	LIST_INSERT_HEAD(&phd->phd_pcblist, inp, inp_portlist);
1956	LIST_INSERT_HEAD(pcbhash, inp, inp_hash);
1957	inp->inp_flags |= INP_INHASHLIST;
1958#ifdef PCBGROUP
1959	if (do_pcbgroup_update)
1960		in_pcbgroup_update(inp);
1961#endif
1962	return (0);
1963}
1964
1965/*
1966 * For now, there are two public interfaces to insert an inpcb into the hash
1967 * lists -- one that does update pcbgroups, and one that doesn't.  The latter
1968 * is used only in the TCP syncache, where in_pcbinshash is called before the
1969 * full 4-tuple is set for the inpcb, and we don't want to install in the
1970 * pcbgroup until later.
1971 *
1972 * XXXRW: This seems like a misfeature.  in_pcbinshash should always update
1973 * connection groups, and partially initialised inpcbs should not be exposed
1974 * to either reservation hash tables or pcbgroups.
1975 */
1976int
1977in_pcbinshash(struct inpcb *inp)
1978{
1979
1980	return (in_pcbinshash_internal(inp, 1));
1981}
1982
1983int
1984in_pcbinshash_nopcbgroup(struct inpcb *inp)
1985{
1986
1987	return (in_pcbinshash_internal(inp, 0));
1988}
1989
1990/*
1991 * Move PCB to the proper hash bucket when { faddr, fport } have  been
1992 * changed. NOTE: This does not handle the case of the lport changing (the
1993 * hashed port list would have to be updated as well), so the lport must
1994 * not change after in_pcbinshash() has been called.
1995 */
1996void
1997in_pcbrehash_mbuf(struct inpcb *inp, struct mbuf *m)
1998{
1999	struct inpcbinfo *pcbinfo = inp->inp_pcbinfo;
2000	struct inpcbhead *head;
2001	u_int32_t hashkey_faddr;
2002
2003	INP_WLOCK_ASSERT(inp);
2004	INP_HASH_WLOCK_ASSERT(pcbinfo);
2005
2006	KASSERT(inp->inp_flags & INP_INHASHLIST,
2007	    ("in_pcbrehash: !INP_INHASHLIST"));
2008
2009#ifdef INET6
2010	if (inp->inp_vflag & INP_IPV6)
2011		hashkey_faddr = inp->in6p_faddr.s6_addr32[3] /* XXX */;
2012	else
2013#endif
2014	hashkey_faddr = inp->inp_faddr.s_addr;
2015
2016	head = &pcbinfo->ipi_hashbase[INP_PCBHASH(hashkey_faddr,
2017		inp->inp_lport, inp->inp_fport, pcbinfo->ipi_hashmask)];
2018
2019	LIST_REMOVE(inp, inp_hash);
2020	LIST_INSERT_HEAD(head, inp, inp_hash);
2021
2022#ifdef PCBGROUP
2023	if (m != NULL)
2024		in_pcbgroup_update_mbuf(inp, m);
2025	else
2026		in_pcbgroup_update(inp);
2027#endif
2028}
2029
2030void
2031in_pcbrehash(struct inpcb *inp)
2032{
2033
2034	in_pcbrehash_mbuf(inp, NULL);
2035}
2036
2037/*
2038 * Remove PCB from various lists.
2039 */
2040static void
2041in_pcbremlists(struct inpcb *inp)
2042{
2043	struct inpcbinfo *pcbinfo = inp->inp_pcbinfo;
2044
2045#ifdef INVARIANTS
2046	if (pcbinfo == &V_tcbinfo) {
2047		INP_INFO_RLOCK_ASSERT(pcbinfo);
2048	} else {
2049		INP_INFO_WLOCK_ASSERT(pcbinfo);
2050	}
2051#endif
2052
2053	INP_WLOCK_ASSERT(inp);
2054	INP_LIST_WLOCK_ASSERT(pcbinfo);
2055
2056	inp->inp_gencnt = ++pcbinfo->ipi_gencnt;
2057	if (inp->inp_flags & INP_INHASHLIST) {
2058		struct inpcbport *phd = inp->inp_phd;
2059
2060		INP_HASH_WLOCK(pcbinfo);
2061		LIST_REMOVE(inp, inp_hash);
2062		LIST_REMOVE(inp, inp_portlist);
2063		if (LIST_FIRST(&phd->phd_pcblist) == NULL) {
2064			LIST_REMOVE(phd, phd_hash);
2065			free(phd, M_PCB);
2066		}
2067		INP_HASH_WUNLOCK(pcbinfo);
2068		inp->inp_flags &= ~INP_INHASHLIST;
2069	}
2070	LIST_REMOVE(inp, inp_list);
2071	pcbinfo->ipi_count--;
2072#ifdef PCBGROUP
2073	in_pcbgroup_remove(inp);
2074#endif
2075}
2076
2077/*
2078 * A set label operation has occurred at the socket layer, propagate the
2079 * label change into the in_pcb for the socket.
2080 */
2081void
2082in_pcbsosetlabel(struct socket *so)
2083{
2084#ifdef MAC
2085	struct inpcb *inp;
2086
2087	inp = sotoinpcb(so);
2088	KASSERT(inp != NULL, ("in_pcbsosetlabel: so->so_pcb == NULL"));
2089
2090	INP_WLOCK(inp);
2091	SOCK_LOCK(so);
2092	mac_inpcb_sosetlabel(so, inp);
2093	SOCK_UNLOCK(so);
2094	INP_WUNLOCK(inp);
2095#endif
2096}
2097
2098/*
2099 * ipport_tick runs once per second, determining if random port allocation
2100 * should be continued.  If more than ipport_randomcps ports have been
2101 * allocated in the last second, then we return to sequential port
2102 * allocation. We return to random allocation only once we drop below
2103 * ipport_randomcps for at least ipport_randomtime seconds.
2104 */
2105static void
2106ipport_tick(void *xtp)
2107{
2108	VNET_ITERATOR_DECL(vnet_iter);
2109
2110	VNET_LIST_RLOCK_NOSLEEP();
2111	VNET_FOREACH(vnet_iter) {
2112		CURVNET_SET(vnet_iter);	/* XXX appease INVARIANTS here */
2113		if (V_ipport_tcpallocs <=
2114		    V_ipport_tcplastcount + V_ipport_randomcps) {
2115			if (V_ipport_stoprandom > 0)
2116				V_ipport_stoprandom--;
2117		} else
2118			V_ipport_stoprandom = V_ipport_randomtime;
2119		V_ipport_tcplastcount = V_ipport_tcpallocs;
2120		CURVNET_RESTORE();
2121	}
2122	VNET_LIST_RUNLOCK_NOSLEEP();
2123	callout_reset(&ipport_tick_callout, hz, ipport_tick, NULL);
2124}
2125
2126static void
2127ip_fini(void *xtp)
2128{
2129
2130	callout_stop(&ipport_tick_callout);
2131}
2132
2133/*
2134 * The ipport_callout should start running at about the time we attach the
2135 * inet or inet6 domains.
2136 */
2137static void
2138ipport_tick_init(const void *unused __unused)
2139{
2140
2141	/* Start ipport_tick. */
2142	callout_init(&ipport_tick_callout, CALLOUT_MPSAFE);
2143	callout_reset(&ipport_tick_callout, 1, ipport_tick, NULL);
2144	EVENTHANDLER_REGISTER(shutdown_pre_sync, ip_fini, NULL,
2145		SHUTDOWN_PRI_DEFAULT);
2146}
2147SYSINIT(ipport_tick_init, SI_SUB_PROTO_DOMAIN, SI_ORDER_MIDDLE,
2148    ipport_tick_init, NULL);
2149
2150void
2151inp_wlock(struct inpcb *inp)
2152{
2153
2154	INP_WLOCK(inp);
2155}
2156
2157void
2158inp_wunlock(struct inpcb *inp)
2159{
2160
2161	INP_WUNLOCK(inp);
2162}
2163
2164void
2165inp_rlock(struct inpcb *inp)
2166{
2167
2168	INP_RLOCK(inp);
2169}
2170
2171void
2172inp_runlock(struct inpcb *inp)
2173{
2174
2175	INP_RUNLOCK(inp);
2176}
2177
2178#ifdef INVARIANTS
2179void
2180inp_lock_assert(struct inpcb *inp)
2181{
2182
2183	INP_WLOCK_ASSERT(inp);
2184}
2185
2186void
2187inp_unlock_assert(struct inpcb *inp)
2188{
2189
2190	INP_UNLOCK_ASSERT(inp);
2191}
2192#endif
2193
2194void
2195inp_apply_all(void (*func)(struct inpcb *, void *), void *arg)
2196{
2197	struct inpcb *inp;
2198
2199	INP_INFO_WLOCK(&V_tcbinfo);
2200	LIST_FOREACH(inp, V_tcbinfo.ipi_listhead, inp_list) {
2201		INP_WLOCK(inp);
2202		func(inp, arg);
2203		INP_WUNLOCK(inp);
2204	}
2205	INP_INFO_WUNLOCK(&V_tcbinfo);
2206}
2207
2208struct socket *
2209inp_inpcbtosocket(struct inpcb *inp)
2210{
2211
2212	INP_WLOCK_ASSERT(inp);
2213	return (inp->inp_socket);
2214}
2215
2216struct tcpcb *
2217inp_inpcbtotcpcb(struct inpcb *inp)
2218{
2219
2220	INP_WLOCK_ASSERT(inp);
2221	return ((struct tcpcb *)inp->inp_ppcb);
2222}
2223
2224int
2225inp_ip_tos_get(const struct inpcb *inp)
2226{
2227
2228	return (inp->inp_ip_tos);
2229}
2230
2231void
2232inp_ip_tos_set(struct inpcb *inp, int val)
2233{
2234
2235	inp->inp_ip_tos = val;
2236}
2237
2238void
2239inp_4tuple_get(struct inpcb *inp, uint32_t *laddr, uint16_t *lp,
2240    uint32_t *faddr, uint16_t *fp)
2241{
2242
2243	INP_LOCK_ASSERT(inp);
2244	*laddr = inp->inp_laddr.s_addr;
2245	*faddr = inp->inp_faddr.s_addr;
2246	*lp = inp->inp_lport;
2247	*fp = inp->inp_fport;
2248}
2249
2250struct inpcb *
2251so_sotoinpcb(struct socket *so)
2252{
2253
2254	return (sotoinpcb(so));
2255}
2256
2257struct tcpcb *
2258so_sototcpcb(struct socket *so)
2259{
2260
2261	return (sototcpcb(so));
2262}
2263
2264#ifdef DDB
2265static void
2266db_print_indent(int indent)
2267{
2268	int i;
2269
2270	for (i = 0; i < indent; i++)
2271		db_printf(" ");
2272}
2273
2274static void
2275db_print_inconninfo(struct in_conninfo *inc, const char *name, int indent)
2276{
2277	char faddr_str[48], laddr_str[48];
2278
2279	db_print_indent(indent);
2280	db_printf("%s at %p\n", name, inc);
2281
2282	indent += 2;
2283
2284#ifdef INET6
2285	if (inc->inc_flags & INC_ISIPV6) {
2286		/* IPv6. */
2287		ip6_sprintf(laddr_str, &inc->inc6_laddr);
2288		ip6_sprintf(faddr_str, &inc->inc6_faddr);
2289	} else
2290#endif
2291	{
2292		/* IPv4. */
2293		inet_ntoa_r(inc->inc_laddr, laddr_str);
2294		inet_ntoa_r(inc->inc_faddr, faddr_str);
2295	}
2296	db_print_indent(indent);
2297	db_printf("inc_laddr %s   inc_lport %u\n", laddr_str,
2298	    ntohs(inc->inc_lport));
2299	db_print_indent(indent);
2300	db_printf("inc_faddr %s   inc_fport %u\n", faddr_str,
2301	    ntohs(inc->inc_fport));
2302}
2303
2304static void
2305db_print_inpflags(int inp_flags)
2306{
2307	int comma;
2308
2309	comma = 0;
2310	if (inp_flags & INP_RECVOPTS) {
2311		db_printf("%sINP_RECVOPTS", comma ? ", " : "");
2312		comma = 1;
2313	}
2314	if (inp_flags & INP_RECVRETOPTS) {
2315		db_printf("%sINP_RECVRETOPTS", comma ? ", " : "");
2316		comma = 1;
2317	}
2318	if (inp_flags & INP_RECVDSTADDR) {
2319		db_printf("%sINP_RECVDSTADDR", comma ? ", " : "");
2320		comma = 1;
2321	}
2322	if (inp_flags & INP_HDRINCL) {
2323		db_printf("%sINP_HDRINCL", comma ? ", " : "");
2324		comma = 1;
2325	}
2326	if (inp_flags & INP_HIGHPORT) {
2327		db_printf("%sINP_HIGHPORT", comma ? ", " : "");
2328		comma = 1;
2329	}
2330	if (inp_flags & INP_LOWPORT) {
2331		db_printf("%sINP_LOWPORT", comma ? ", " : "");
2332		comma = 1;
2333	}
2334	if (inp_flags & INP_ANONPORT) {
2335		db_printf("%sINP_ANONPORT", comma ? ", " : "");
2336		comma = 1;
2337	}
2338	if (inp_flags & INP_RECVIF) {
2339		db_printf("%sINP_RECVIF", comma ? ", " : "");
2340		comma = 1;
2341	}
2342	if (inp_flags & INP_MTUDISC) {
2343		db_printf("%sINP_MTUDISC", comma ? ", " : "");
2344		comma = 1;
2345	}
2346	if (inp_flags & INP_FAITH) {
2347		db_printf("%sINP_FAITH", comma ? ", " : "");
2348		comma = 1;
2349	}
2350	if (inp_flags & INP_RECVTTL) {
2351		db_printf("%sINP_RECVTTL", comma ? ", " : "");
2352		comma = 1;
2353	}
2354	if (inp_flags & INP_DONTFRAG) {
2355		db_printf("%sINP_DONTFRAG", comma ? ", " : "");
2356		comma = 1;
2357	}
2358	if (inp_flags & INP_RECVTOS) {
2359		db_printf("%sINP_RECVTOS", comma ? ", " : "");
2360		comma = 1;
2361	}
2362	if (inp_flags & IN6P_IPV6_V6ONLY) {
2363		db_printf("%sIN6P_IPV6_V6ONLY", comma ? ", " : "");
2364		comma = 1;
2365	}
2366	if (inp_flags & IN6P_PKTINFO) {
2367		db_printf("%sIN6P_PKTINFO", comma ? ", " : "");
2368		comma = 1;
2369	}
2370	if (inp_flags & IN6P_HOPLIMIT) {
2371		db_printf("%sIN6P_HOPLIMIT", comma ? ", " : "");
2372		comma = 1;
2373	}
2374	if (inp_flags & IN6P_HOPOPTS) {
2375		db_printf("%sIN6P_HOPOPTS", comma ? ", " : "");
2376		comma = 1;
2377	}
2378	if (inp_flags & IN6P_DSTOPTS) {
2379		db_printf("%sIN6P_DSTOPTS", comma ? ", " : "");
2380		comma = 1;
2381	}
2382	if (inp_flags & IN6P_RTHDR) {
2383		db_printf("%sIN6P_RTHDR", comma ? ", " : "");
2384		comma = 1;
2385	}
2386	if (inp_flags & IN6P_RTHDRDSTOPTS) {
2387		db_printf("%sIN6P_RTHDRDSTOPTS", comma ? ", " : "");
2388		comma = 1;
2389	}
2390	if (inp_flags & IN6P_TCLASS) {
2391		db_printf("%sIN6P_TCLASS", comma ? ", " : "");
2392		comma = 1;
2393	}
2394	if (inp_flags & IN6P_AUTOFLOWLABEL) {
2395		db_printf("%sIN6P_AUTOFLOWLABEL", comma ? ", " : "");
2396		comma = 1;
2397	}
2398	if (inp_flags & INP_TIMEWAIT) {
2399		db_printf("%sINP_TIMEWAIT", comma ? ", " : "");
2400		comma  = 1;
2401	}
2402	if (inp_flags & INP_ONESBCAST) {
2403		db_printf("%sINP_ONESBCAST", comma ? ", " : "");
2404		comma  = 1;
2405	}
2406	if (inp_flags & INP_DROPPED) {
2407		db_printf("%sINP_DROPPED", comma ? ", " : "");
2408		comma  = 1;
2409	}
2410	if (inp_flags & INP_SOCKREF) {
2411		db_printf("%sINP_SOCKREF", comma ? ", " : "");
2412		comma  = 1;
2413	}
2414	if (inp_flags & IN6P_RFC2292) {
2415		db_printf("%sIN6P_RFC2292", comma ? ", " : "");
2416		comma = 1;
2417	}
2418	if (inp_flags & IN6P_MTU) {
2419		db_printf("IN6P_MTU%s", comma ? ", " : "");
2420		comma = 1;
2421	}
2422}
2423
2424static void
2425db_print_inpvflag(u_char inp_vflag)
2426{
2427	int comma;
2428
2429	comma = 0;
2430	if (inp_vflag & INP_IPV4) {
2431		db_printf("%sINP_IPV4", comma ? ", " : "");
2432		comma  = 1;
2433	}
2434	if (inp_vflag & INP_IPV6) {
2435		db_printf("%sINP_IPV6", comma ? ", " : "");
2436		comma  = 1;
2437	}
2438	if (inp_vflag & INP_IPV6PROTO) {
2439		db_printf("%sINP_IPV6PROTO", comma ? ", " : "");
2440		comma  = 1;
2441	}
2442}
2443
2444static void
2445db_print_inpcb(struct inpcb *inp, const char *name, int indent)
2446{
2447
2448	db_print_indent(indent);
2449	db_printf("%s at %p\n", name, inp);
2450
2451	indent += 2;
2452
2453	db_print_indent(indent);
2454	db_printf("inp_flow: 0x%x\n", inp->inp_flow);
2455
2456	db_print_inconninfo(&inp->inp_inc, "inp_conninfo", indent);
2457
2458	db_print_indent(indent);
2459	db_printf("inp_ppcb: %p   inp_pcbinfo: %p   inp_socket: %p\n",
2460	    inp->inp_ppcb, inp->inp_pcbinfo, inp->inp_socket);
2461
2462	db_print_indent(indent);
2463	db_printf("inp_label: %p   inp_flags: 0x%x (",
2464	   inp->inp_label, inp->inp_flags);
2465	db_print_inpflags(inp->inp_flags);
2466	db_printf(")\n");
2467
2468	db_print_indent(indent);
2469	db_printf("inp_sp: %p   inp_vflag: 0x%x (", inp->inp_sp,
2470	    inp->inp_vflag);
2471	db_print_inpvflag(inp->inp_vflag);
2472	db_printf(")\n");
2473
2474	db_print_indent(indent);
2475	db_printf("inp_ip_ttl: %d   inp_ip_p: %d   inp_ip_minttl: %d\n",
2476	    inp->inp_ip_ttl, inp->inp_ip_p, inp->inp_ip_minttl);
2477
2478	db_print_indent(indent);
2479#ifdef INET6
2480	if (inp->inp_vflag & INP_IPV6) {
2481		db_printf("in6p_options: %p   in6p_outputopts: %p   "
2482		    "in6p_moptions: %p\n", inp->in6p_options,
2483		    inp->in6p_outputopts, inp->in6p_moptions);
2484		db_printf("in6p_icmp6filt: %p   in6p_cksum %d   "
2485		    "in6p_hops %u\n", inp->in6p_icmp6filt, inp->in6p_cksum,
2486		    inp->in6p_hops);
2487	} else
2488#endif
2489	{
2490		db_printf("inp_ip_tos: %d   inp_ip_options: %p   "
2491		    "inp_ip_moptions: %p\n", inp->inp_ip_tos,
2492		    inp->inp_options, inp->inp_moptions);
2493	}
2494
2495	db_print_indent(indent);
2496	db_printf("inp_phd: %p   inp_gencnt: %ju\n", inp->inp_phd,
2497	    (uintmax_t)inp->inp_gencnt);
2498}
2499
2500DB_SHOW_COMMAND(inpcb, db_show_inpcb)
2501{
2502	struct inpcb *inp;
2503
2504	if (!have_addr) {
2505		db_printf("usage: show inpcb <addr>\n");
2506		return;
2507	}
2508	inp = (struct inpcb *)addr;
2509
2510	db_print_inpcb(inp, "inpcb", 0);
2511}
2512#endif /* DDB */
2513