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