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