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