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