xref: /dragonfly/sys/netinet/in_pcb.c (revision e96fb831)
1 /*
2  * Copyright (c) 2004 Jeffrey M. Hsu.  All rights reserved.
3  * Copyright (c) 2004 The DragonFly Project.  All rights reserved.
4  *
5  * This code is derived from software contributed to The DragonFly Project
6  * by Jeffrey M. Hsu.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  * 3. Neither the name of The DragonFly Project nor the names of its
17  *    contributors may be used to endorse or promote products derived
18  *    from this software without specific, prior written permission.
19  *
20  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
21  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
22  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
23  * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE
24  * COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
25  * INCIDENTAL, SPECIAL, EXEMPLARY OR CONSEQUENTIAL DAMAGES (INCLUDING,
26  * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
27  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
28  * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
29  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
30  * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31  * SUCH DAMAGE.
32  */
33 
34 /*
35  * Copyright (c) 1982, 1986, 1991, 1993, 1995
36  *	The Regents of the University of California.  All rights reserved.
37  *
38  * Redistribution and use in source and binary forms, with or without
39  * modification, are permitted provided that the following conditions
40  * are met:
41  * 1. Redistributions of source code must retain the above copyright
42  *    notice, this list of conditions and the following disclaimer.
43  * 2. Redistributions in binary form must reproduce the above copyright
44  *    notice, this list of conditions and the following disclaimer in the
45  *    documentation and/or other materials provided with the distribution.
46  * 3. All advertising materials mentioning features or use of this software
47  *    must display the following acknowledgement:
48  *	This product includes software developed by the University of
49  *	California, Berkeley and its contributors.
50  * 4. Neither the name of the University nor the names of its contributors
51  *    may be used to endorse or promote products derived from this software
52  *    without specific prior written permission.
53  *
54  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
55  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
56  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
57  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
58  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
59  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
60  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
61  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
62  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
63  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
64  * SUCH DAMAGE.
65  *
66  *	@(#)in_pcb.c	8.4 (Berkeley) 5/24/95
67  * $FreeBSD: src/sys/netinet/in_pcb.c,v 1.59.2.27 2004/01/02 04:06:42 ambrisko Exp $
68  */
69 
70 #include "opt_ipsec.h"
71 #include "opt_inet6.h"
72 
73 #include <sys/param.h>
74 #include <sys/systm.h>
75 #include <sys/malloc.h>
76 #include <sys/mbuf.h>
77 #include <sys/domain.h>
78 #include <sys/protosw.h>
79 #include <sys/socket.h>
80 #include <sys/socketvar.h>
81 #include <sys/proc.h>
82 #include <sys/priv.h>
83 #include <sys/jail.h>
84 #include <sys/kernel.h>
85 #include <sys/sysctl.h>
86 
87 #include <sys/thread2.h>
88 #include <sys/socketvar2.h>
89 #include <sys/msgport2.h>
90 
91 #include <machine/limits.h>
92 
93 #include <net/if.h>
94 #include <net/if_types.h>
95 #include <net/route.h>
96 
97 #include <netinet/in.h>
98 #include <netinet/in_pcb.h>
99 #include <netinet/in_var.h>
100 #include <netinet/ip_var.h>
101 #ifdef INET6
102 #include <netinet/ip6.h>
103 #include <netinet6/ip6_var.h>
104 #endif /* INET6 */
105 
106 #ifdef IPSEC
107 #include <netinet6/ipsec.h>
108 #include <netproto/key/key.h>
109 #include <netproto/ipsec/esp_var.h>
110 #endif
111 
112 #ifdef FAST_IPSEC
113 #if defined(IPSEC) || defined(IPSEC_ESP)
114 #error "Bad idea: don't compile with both IPSEC and FAST_IPSEC!"
115 #endif
116 
117 #include <netproto/ipsec/ipsec.h>
118 #include <netproto/ipsec/key.h>
119 #define	IPSEC
120 #endif /* FAST_IPSEC */
121 
122 struct in_addr zeroin_addr;
123 
124 /*
125  * These configure the range of local port addresses assigned to
126  * "unspecified" outgoing connections/packets/whatever.
127  */
128 int ipport_lowfirstauto = IPPORT_RESERVED - 1;	/* 1023 */
129 int ipport_lowlastauto = IPPORT_RESERVEDSTART;	/* 600 */
130 
131 int ipport_firstauto = IPPORT_RESERVED;		/* 1024 */
132 int ipport_lastauto = IPPORT_USERRESERVED;	/* 5000 */
133 
134 int ipport_hifirstauto = IPPORT_HIFIRSTAUTO;	/* 49152 */
135 int ipport_hilastauto = IPPORT_HILASTAUTO;	/* 65535 */
136 
137 #define RANGECHK(var, min, max) \
138 	if ((var) < (min)) { (var) = (min); } \
139 	else if ((var) > (max)) { (var) = (max); }
140 
141 int udpencap_enable = 1;	/* enabled by default */
142 int udpencap_port = 4500;	/* triggers decapsulation */
143 
144 static int
145 sysctl_net_ipport_check(SYSCTL_HANDLER_ARGS)
146 {
147 	int error;
148 
149 	error = sysctl_handle_int(oidp, oidp->oid_arg1, oidp->oid_arg2, req);
150 	if (!error) {
151 		RANGECHK(ipport_lowfirstauto, 1, IPPORT_RESERVED - 1);
152 		RANGECHK(ipport_lowlastauto, 1, IPPORT_RESERVED - 1);
153 
154 		RANGECHK(ipport_firstauto, IPPORT_RESERVED, USHRT_MAX);
155 		RANGECHK(ipport_lastauto, IPPORT_RESERVED, USHRT_MAX);
156 
157 		RANGECHK(ipport_hifirstauto, IPPORT_RESERVED, USHRT_MAX);
158 		RANGECHK(ipport_hilastauto, IPPORT_RESERVED, USHRT_MAX);
159 	}
160 	return (error);
161 }
162 
163 #undef RANGECHK
164 
165 SYSCTL_NODE(_net_inet_ip, IPPROTO_IP, portrange, CTLFLAG_RW, 0, "IP Ports");
166 
167 SYSCTL_PROC(_net_inet_ip_portrange, OID_AUTO, lowfirst, CTLTYPE_INT|CTLFLAG_RW,
168 	   &ipport_lowfirstauto, 0, &sysctl_net_ipport_check, "I", "");
169 SYSCTL_PROC(_net_inet_ip_portrange, OID_AUTO, lowlast, CTLTYPE_INT|CTLFLAG_RW,
170 	   &ipport_lowlastauto, 0, &sysctl_net_ipport_check, "I", "");
171 SYSCTL_PROC(_net_inet_ip_portrange, OID_AUTO, first, CTLTYPE_INT|CTLFLAG_RW,
172 	   &ipport_firstauto, 0, &sysctl_net_ipport_check, "I", "");
173 SYSCTL_PROC(_net_inet_ip_portrange, OID_AUTO, last, CTLTYPE_INT|CTLFLAG_RW,
174 	   &ipport_lastauto, 0, &sysctl_net_ipport_check, "I", "");
175 SYSCTL_PROC(_net_inet_ip_portrange, OID_AUTO, hifirst, CTLTYPE_INT|CTLFLAG_RW,
176 	   &ipport_hifirstauto, 0, &sysctl_net_ipport_check, "I", "");
177 SYSCTL_PROC(_net_inet_ip_portrange, OID_AUTO, hilast, CTLTYPE_INT|CTLFLAG_RW,
178 	   &ipport_hilastauto, 0, &sysctl_net_ipport_check, "I", "");
179 
180 /*
181  * in_pcb.c: manage the Protocol Control Blocks.
182  *
183  * NOTE: It is assumed that most of these functions will be called from
184  * a critical section.  XXX - There are, unfortunately, a few exceptions
185  * to this rule that should be fixed.
186  *
187  * NOTE: The caller should initialize the cpu field to the cpu running the
188  * protocol stack associated with this inpcbinfo.
189  */
190 
191 void
192 in_pcbinfo_init(struct inpcbinfo *pcbinfo)
193 {
194 	LIST_INIT(&pcbinfo->pcblisthead);
195 	pcbinfo->cpu = -1;
196 	pcbinfo->portsave = kmalloc(sizeof(*pcbinfo->portsave), M_PCB,
197 				    M_WAITOK | M_ZERO);
198 }
199 
200 struct baddynamicports baddynamicports;
201 
202 /*
203  * Check if the specified port is invalid for dynamic allocation.
204  */
205 int
206 in_baddynamic(u_int16_t port, u_int16_t proto)
207 {
208 	switch (proto) {
209 	case IPPROTO_TCP:
210 		return (DP_ISSET(baddynamicports.tcp, port));
211 	case IPPROTO_UDP:
212 #ifdef IPSEC
213 		/* Cannot preset this as it is a sysctl */
214 		if (port == udpencap_port)
215 			return (1);
216 #endif
217 		return (DP_ISSET(baddynamicports.udp, port));
218 	default:
219 		return (0);
220 	}
221 }
222 
223 
224 /*
225  * Allocate a PCB and associate it with the socket.
226  */
227 int
228 in_pcballoc(struct socket *so, struct inpcbinfo *pcbinfo)
229 {
230 	struct inpcb *inp;
231 #ifdef IPSEC
232 	int error;
233 #endif
234 
235 	inp = kmalloc(pcbinfo->ipi_size, M_PCB, M_WAITOK|M_ZERO);
236 	inp->inp_gencnt = ++pcbinfo->ipi_gencnt;
237 	inp->inp_pcbinfo = inp->inp_cpcbinfo = pcbinfo;
238 	inp->inp_socket = so;
239 #ifdef IPSEC
240 	error = ipsec_init_policy(so, &inp->inp_sp);
241 	if (error != 0) {
242 		kfree(inp, M_PCB);
243 		return (error);
244 	}
245 #endif
246 #ifdef INET6
247 	if (INP_SOCKAF(so) == AF_INET6 && ip6_v6only)
248 		inp->inp_flags |= IN6P_IPV6_V6ONLY;
249 	if (ip6_auto_flowlabel)
250 		inp->inp_flags |= IN6P_AUTOFLOWLABEL;
251 #endif
252 	soreference(so);
253 	so->so_pcb = inp;
254 	LIST_INSERT_HEAD(&pcbinfo->pcblisthead, inp, inp_list);
255 	pcbinfo->ipi_count++;
256 	return (0);
257 }
258 
259 /*
260  * Unlink a pcb with the intention of moving it to another cpu with a
261  * different pcbinfo.  While unlinked nothing should attempt to dereference
262  * inp_pcbinfo, NULL it out so we assert if it does.
263  */
264 void
265 in_pcbunlink(struct inpcb *inp, struct inpcbinfo *pcbinfo)
266 {
267 	KKASSERT(inp->inp_pcbinfo == pcbinfo);
268 
269 	LIST_REMOVE(inp, inp_list);
270 	pcbinfo->ipi_count--;
271 	inp->inp_pcbinfo = NULL;
272 }
273 
274 /*
275  * Relink a pcb into a new pcbinfo.
276  */
277 void
278 in_pcblink(struct inpcb *inp, struct inpcbinfo *pcbinfo)
279 {
280 	KKASSERT(inp->inp_pcbinfo == NULL);
281 	inp->inp_pcbinfo = pcbinfo;
282 	LIST_INSERT_HEAD(&pcbinfo->pcblisthead, inp, inp_list);
283 	pcbinfo->ipi_count++;
284 }
285 
286 int
287 in_pcbbind(struct inpcb *inp, struct sockaddr *nam, struct thread *td)
288 {
289 	struct socket *so = inp->inp_socket;
290 	struct proc *p = td->td_proc;
291 	unsigned short *lastport;
292 	struct sockaddr_in *sin;
293 	struct sockaddr_in jsin;
294 	struct inpcbinfo *pcbinfo = inp->inp_pcbinfo;
295 	struct ucred *cred = NULL;
296 	u_short lport = 0;
297 	int wild = 0, reuseport = (so->so_options & SO_REUSEPORT);
298 	int error;
299 
300 	KKASSERT(p);
301 
302 	if (TAILQ_EMPTY(&in_ifaddrheads[mycpuid])) /* XXX broken! */
303 		return (EADDRNOTAVAIL);
304 	if (inp->inp_lport != 0 || inp->inp_laddr.s_addr != INADDR_ANY)
305 		return (EINVAL);	/* already bound */
306 
307 	if (!(so->so_options & (SO_REUSEADDR|SO_REUSEPORT)))
308 		wild = 1;    /* neither SO_REUSEADDR nor SO_REUSEPORT is set */
309 	if (p)
310 		cred = p->p_ucred;
311 
312 	/*
313 	 * This has to be atomic.  If the porthash is shared across multiple
314 	 * protocol threads (aka tcp) then the token will be non-NULL.
315 	 */
316 	if (pcbinfo->porttoken)
317 		lwkt_gettoken(pcbinfo->porttoken);
318 
319 	if (nam != NULL) {
320 		sin = (struct sockaddr_in *)nam;
321 		if (nam->sa_len != sizeof *sin) {
322 			error = EINVAL;
323 			goto done;
324 		}
325 #ifdef notdef
326 		/*
327 		 * We should check the family, but old programs
328 		 * incorrectly fail to initialize it.
329 		 */
330 		if (sin->sin_family != AF_INET) {
331 			error = EAFNOSUPPORT;
332 			goto done;
333 		}
334 #endif
335 		if (!prison_replace_wildcards(td, nam)) {
336 			error = EINVAL;
337 			goto done;
338 		}
339 		lport = sin->sin_port;
340 		if (IN_MULTICAST(ntohl(sin->sin_addr.s_addr))) {
341 			/*
342 			 * Treat SO_REUSEADDR as SO_REUSEPORT for multicast;
343 			 * allow complete duplication of binding if
344 			 * SO_REUSEPORT is set, or if SO_REUSEADDR is set
345 			 * and a multicast address is bound on both
346 			 * new and duplicated sockets.
347 			 */
348 			if (so->so_options & SO_REUSEADDR)
349 				reuseport = SO_REUSEADDR | SO_REUSEPORT;
350 		} else if (sin->sin_addr.s_addr != INADDR_ANY) {
351 			sin->sin_port = 0;		/* yech... */
352 			bzero(&sin->sin_zero, sizeof sin->sin_zero);
353 			if (ifa_ifwithaddr((struct sockaddr *)sin) == NULL) {
354 				error = EADDRNOTAVAIL;
355 				goto done;
356 			}
357 		}
358 		if (lport != 0) {
359 			struct inpcb *t;
360 
361 			/* GROSS */
362 			if (ntohs(lport) < IPPORT_RESERVED &&
363 			    cred &&
364 			    priv_check_cred(cred, PRIV_NETINET_RESERVEDPORT, 0)) {
365 				error = EACCES;
366 				goto done;
367 			}
368 			if (so->so_cred->cr_uid != 0 &&
369 			    !IN_MULTICAST(ntohl(sin->sin_addr.s_addr))) {
370 				t = in_pcblookup_local(pcbinfo,
371 						       sin->sin_addr,
372 						       lport,
373 						       INPLOOKUP_WILDCARD,
374 						       cred);
375 				if (t &&
376 				    (!in_nullhost(sin->sin_addr) ||
377 				     !in_nullhost(t->inp_laddr) ||
378 				     (t->inp_socket->so_options &
379 					 SO_REUSEPORT) == 0) &&
380 				    (so->so_cred->cr_uid !=
381 				     t->inp_socket->so_cred->cr_uid)) {
382 #ifdef INET6
383 					if (!in_nullhost(sin->sin_addr) ||
384 					    !in_nullhost(t->inp_laddr) ||
385 					    INP_SOCKAF(so) ==
386 					    INP_SOCKAF(t->inp_socket))
387 #endif
388 					{
389 						error = EADDRINUSE;
390 						goto done;
391 					}
392 				}
393 			}
394 			if (cred && !prison_replace_wildcards(td, nam)) {
395 				error = EADDRNOTAVAIL;
396 				goto done;
397 			}
398 			t = in_pcblookup_local(pcbinfo, sin->sin_addr, lport,
399 					       wild, cred);
400 			if (t && !(reuseport & t->inp_socket->so_options)) {
401 #ifdef INET6
402 				if (!in_nullhost(sin->sin_addr) ||
403 				    !in_nullhost(t->inp_laddr) ||
404 				    INP_SOCKAF(so) == INP_SOCKAF(t->inp_socket))
405 #endif
406 				{
407 					error = EADDRINUSE;
408 					goto done;
409 				}
410 			}
411 		}
412 		inp->inp_laddr = sin->sin_addr;
413 	}
414 	if (lport == 0) {
415 		ushort first, last;
416 		int count;
417 
418 		jsin.sin_family = AF_INET;
419 		jsin.sin_addr.s_addr = inp->inp_laddr.s_addr;
420 		if (!prison_replace_wildcards(td, (struct sockaddr *)&jsin)) {
421 			inp->inp_laddr.s_addr = INADDR_ANY;
422 			error = EINVAL;
423 			goto done;
424 		}
425 		inp->inp_laddr.s_addr = jsin.sin_addr.s_addr;
426 
427 		inp->inp_flags |= INP_ANONPORT;
428 
429 		if (inp->inp_flags & INP_HIGHPORT) {
430 			first = ipport_hifirstauto;	/* sysctl */
431 			last  = ipport_hilastauto;
432 			lastport = &pcbinfo->lasthi;
433 		} else if (inp->inp_flags & INP_LOWPORT) {
434 			if (cred &&
435 			    (error = priv_check_cred(cred, PRIV_NETINET_RESERVEDPORT, 0))) {
436 				inp->inp_laddr.s_addr = INADDR_ANY;
437 				goto done;
438 			}
439 			first = ipport_lowfirstauto;	/* 1023 */
440 			last  = ipport_lowlastauto;	/* 600 */
441 			lastport = &pcbinfo->lastlow;
442 		} else {
443 			first = ipport_firstauto;	/* sysctl */
444 			last  = ipport_lastauto;
445 			lastport = &pcbinfo->lastport;
446 		}
447 		/*
448 		 * Simple check to ensure all ports are not used up causing
449 		 * a deadlock here.
450 		 *
451 		 * We split the two cases (up and down) so that the direction
452 		 * is not being tested on each round of the loop.
453 		 */
454 		if (first > last) {
455 			/*
456 			 * counting down
457 			 */
458 			count = first - last;
459 
460 			do {
461 				if (count-- < 0) {	/* completely used? */
462 					inp->inp_laddr.s_addr = INADDR_ANY;
463 					error = EADDRNOTAVAIL;
464 					goto done;
465 				}
466 				--*lastport;
467 				if (*lastport > first || *lastport < last)
468 					*lastport = first;
469 				lport = htons(*lastport);
470 			} while (in_pcblookup_local(pcbinfo, inp->inp_laddr,
471 						    lport, wild, cred));
472 		} else {
473 			/*
474 			 * counting up
475 			 */
476 			count = last - first;
477 
478 			do {
479 				if (count-- < 0) {	/* completely used? */
480 					inp->inp_laddr.s_addr = INADDR_ANY;
481 					error = EADDRNOTAVAIL;
482 					goto done;
483 				}
484 				++*lastport;
485 				if (*lastport < first || *lastport > last)
486 					*lastport = first;
487 				lport = htons(*lastport);
488 			} while (in_pcblookup_local(pcbinfo, inp->inp_laddr,
489 						    lport, wild, cred));
490 		}
491 	}
492 	inp->inp_lport = lport;
493 
494 	jsin.sin_family = AF_INET;
495 	jsin.sin_addr.s_addr = inp->inp_laddr.s_addr;
496 	if (!prison_replace_wildcards(td, (struct sockaddr*)&jsin)) {
497 		inp->inp_laddr.s_addr = INADDR_ANY;
498 		inp->inp_lport = 0;
499 		error = EINVAL;
500 		goto done;
501 	}
502 	inp->inp_laddr.s_addr = jsin.sin_addr.s_addr;
503 
504 	if (in_pcbinsporthash(inp) != 0) {
505 		inp->inp_laddr.s_addr = INADDR_ANY;
506 		inp->inp_lport = 0;
507 		error = EAGAIN;
508 		goto done;
509 	}
510 	error = 0;
511 done:
512 	if (pcbinfo->porttoken)
513 		lwkt_reltoken(pcbinfo->porttoken);
514 	return error;
515 }
516 
517 static struct inpcb *
518 in_pcblookup_addrport(struct inpcbinfo *pcbinfo, struct in_addr laddr,
519     u_short lport, struct in_addr faddr, u_short fport, struct ucred *cred)
520 {
521 	struct inpcb *inp;
522 	struct inpcbporthead *porthash;
523 	struct inpcbport *phd;
524 	struct inpcb *match = NULL;
525 
526 	/*
527 	 * If the porthashbase is shared across several cpus we need
528 	 * to lock.
529 	 */
530 	if (pcbinfo->porttoken)
531 		lwkt_gettoken(pcbinfo->porttoken);
532 
533 	/*
534 	 * Best fit PCB lookup.
535 	 *
536 	 * First see if this local port is in use by looking on the
537 	 * port hash list.
538 	 */
539 	porthash = &pcbinfo->porthashbase[
540 			INP_PCBPORTHASH(lport, pcbinfo->porthashmask)];
541 	LIST_FOREACH(phd, porthash, phd_hash) {
542 		if (phd->phd_port == lport)
543 			break;
544 	}
545 	if (phd != NULL) {
546 		LIST_FOREACH(inp, &phd->phd_pcblist, inp_portlist) {
547 #ifdef INET6
548 			if ((inp->inp_vflag & INP_IPV4) == 0)
549 				continue;
550 #endif
551 			if (inp->inp_laddr.s_addr != INADDR_ANY &&
552 			    inp->inp_laddr.s_addr != laddr.s_addr)
553 				continue;
554 
555 			if (inp->inp_faddr.s_addr != INADDR_ANY &&
556 			    inp->inp_faddr.s_addr != faddr.s_addr)
557 				continue;
558 
559 			if (inp->inp_fport != 0 && inp->inp_fport != fport)
560 				continue;
561 
562 			if (cred == NULL ||
563 			    cred->cr_prison ==
564 			    inp->inp_socket->so_cred->cr_prison) {
565 				match = inp;
566 				break;
567 			}
568 		}
569 	}
570 	if (pcbinfo->porttoken)
571 		lwkt_reltoken(pcbinfo->porttoken);
572 	return (match);
573 }
574 
575 int
576 in_pcbconn_bind(struct inpcb *inp, const struct sockaddr *nam,
577     struct thread *td)
578 {
579 	struct proc *p = td->td_proc;
580 	unsigned short *lastport;
581 	const struct sockaddr_in *sin = (const struct sockaddr_in *)nam;
582 	struct sockaddr_in jsin;
583 	struct inpcbinfo *pcbinfo = inp->inp_pcbinfo;
584 	struct ucred *cred = NULL;
585 	u_short lport = 0;
586 	ushort first, last;
587 	int count, error, dup = 0;
588 
589 	if (TAILQ_EMPTY(&in_ifaddrheads[mycpuid])) /* XXX broken! */
590 		return (EADDRNOTAVAIL);
591 
592 	KKASSERT(inp->inp_laddr.s_addr != INADDR_ANY);
593 	if (inp->inp_lport != 0)
594 		return (EINVAL);	/* already bound */
595 
596 	KKASSERT(p);
597 	cred = p->p_ucred;
598 
599 	/*
600 	 * This has to be atomic.  If the porthash is shared across multiple
601 	 * protocol threads (aka tcp) then the token will be non-NULL.
602 	 */
603 	if (pcbinfo->porttoken)
604 		lwkt_gettoken(pcbinfo->porttoken);
605 
606 	jsin.sin_family = AF_INET;
607 	jsin.sin_addr.s_addr = inp->inp_laddr.s_addr;
608 	if (!prison_replace_wildcards(td, (struct sockaddr *)&jsin)) {
609 		inp->inp_laddr.s_addr = INADDR_ANY;
610 		error = EINVAL;
611 		goto done;
612 	}
613 	inp->inp_laddr.s_addr = jsin.sin_addr.s_addr;
614 
615 	inp->inp_flags |= INP_ANONPORT;
616 
617 	if (inp->inp_flags & INP_HIGHPORT) {
618 		first = ipport_hifirstauto;	/* sysctl */
619 		last  = ipport_hilastauto;
620 		lastport = &pcbinfo->lasthi;
621 	} else if (inp->inp_flags & INP_LOWPORT) {
622 		if (cred &&
623 		    (error = priv_check_cred(cred, PRIV_NETINET_RESERVEDPORT, 0))) {
624 			inp->inp_laddr.s_addr = INADDR_ANY;
625 			goto done;
626 		}
627 		first = ipport_lowfirstauto;	/* 1023 */
628 		last  = ipport_lowlastauto;	/* 600 */
629 		lastport = &pcbinfo->lastlow;
630 	} else {
631 		first = ipport_firstauto;	/* sysctl */
632 		last  = ipport_lastauto;
633 		lastport = &pcbinfo->lastport;
634 	}
635 
636 again:
637 	/*
638 	 * Simple check to ensure all ports are not used up causing
639 	 * a deadlock here.
640 	 *
641 	 * We split the two cases (up and down) so that the direction
642 	 * is not being tested on each round of the loop.
643 	 */
644 	if (first > last) {
645 		/*
646 		 * counting down
647 		 */
648 		count = first - last;
649 
650 		do {
651 			if (count-- < 0) {	/* completely used? */
652 				inp->inp_laddr.s_addr = INADDR_ANY;
653 				error = EADDRNOTAVAIL;
654 				goto done;
655 			}
656 			--*lastport;
657 			if (*lastport > first || *lastport < last)
658 				*lastport = first;
659 			lport = htons(*lastport);
660 		} while (in_pcblookup_addrport(pcbinfo, inp->inp_laddr, lport,
661 				sin->sin_addr, sin->sin_port, cred));
662 	} else {
663 		/*
664 		 * counting up
665 		 */
666 		count = last - first;
667 
668 		do {
669 			if (count-- < 0) {	/* completely used? */
670 				inp->inp_laddr.s_addr = INADDR_ANY;
671 				error = EADDRNOTAVAIL;
672 				goto done;
673 			}
674 			++*lastport;
675 			if (*lastport < first || *lastport > last)
676 				*lastport = first;
677 			lport = htons(*lastport);
678 		} while (in_pcblookup_addrport(pcbinfo, inp->inp_laddr, lport,
679 				sin->sin_addr, sin->sin_port, cred));
680 	}
681 
682 	/* This could happen on loopback interface */
683 	if (sin->sin_port == lport &&
684 	    sin->sin_addr.s_addr == inp->inp_laddr.s_addr) {
685 		if (dup) {
686 			/*
687 			 * Duplicate again; give up
688 			 */
689 			inp->inp_laddr.s_addr = INADDR_ANY;
690 			error = EADDRNOTAVAIL;
691 			goto done;
692 		}
693 		dup = 1;
694 		goto again;
695 	}
696 	inp->inp_lport = lport;
697 
698 	jsin.sin_family = AF_INET;
699 	jsin.sin_addr.s_addr = inp->inp_laddr.s_addr;
700 	if (!prison_replace_wildcards(td, (struct sockaddr*)&jsin)) {
701 		inp->inp_laddr.s_addr = INADDR_ANY;
702 		inp->inp_lport = 0;
703 		error = EINVAL;
704 		goto done;
705 	}
706 	inp->inp_laddr.s_addr = jsin.sin_addr.s_addr;
707 
708 	if (in_pcbinsporthash(inp) != 0) {
709 		inp->inp_laddr.s_addr = INADDR_ANY;
710 		inp->inp_lport = 0;
711 		error = EAGAIN;
712 		goto done;
713 	}
714 	error = 0;
715 done:
716 	if (pcbinfo->porttoken)
717 		lwkt_reltoken(pcbinfo->porttoken);
718 	return error;
719 }
720 
721 /*
722  *   Transform old in_pcbconnect() into an inner subroutine for new
723  *   in_pcbconnect(): Do some validity-checking on the remote
724  *   address (in mbuf 'nam') and then determine local host address
725  *   (i.e., which interface) to use to access that remote host.
726  *
727  *   This preserves definition of in_pcbconnect(), while supporting a
728  *   slightly different version for T/TCP.  (This is more than
729  *   a bit of a kludge, but cleaning up the internal interfaces would
730  *   have forced minor changes in every protocol).
731  */
732 int
733 in_pcbladdr(struct inpcb *inp, struct sockaddr *nam,
734 	struct sockaddr_in **plocal_sin, struct thread *td)
735 {
736 	struct in_ifaddr *ia;
737 	struct ucred *cred = NULL;
738 	struct sockaddr_in *sin = (struct sockaddr_in *)nam;
739 	struct sockaddr *jsin;
740 	int jailed = 0, alloc_route = 0;
741 
742 	if (nam->sa_len != sizeof *sin)
743 		return (EINVAL);
744 	if (sin->sin_family != AF_INET)
745 		return (EAFNOSUPPORT);
746 	if (sin->sin_port == 0)
747 		return (EADDRNOTAVAIL);
748 	if (td && td->td_proc && td->td_proc->p_ucred)
749 		cred = td->td_proc->p_ucred;
750 	if (cred && cred->cr_prison)
751 		jailed = 1;
752 	if (!TAILQ_EMPTY(&in_ifaddrheads[mycpuid])) {
753 		ia = TAILQ_FIRST(&in_ifaddrheads[mycpuid])->ia;
754 		/*
755 		 * If the destination address is INADDR_ANY,
756 		 * use the primary local address.
757 		 * If the supplied address is INADDR_BROADCAST,
758 		 * and the primary interface supports broadcast,
759 		 * choose the broadcast address for that interface.
760 		 */
761 		if (sin->sin_addr.s_addr == INADDR_ANY)
762 			sin->sin_addr = IA_SIN(ia)->sin_addr;
763 		else if (sin->sin_addr.s_addr == (u_long)INADDR_BROADCAST &&
764 		    (ia->ia_ifp->if_flags & IFF_BROADCAST))
765 			sin->sin_addr = satosin(&ia->ia_broadaddr)->sin_addr;
766 	}
767 	if (inp->inp_laddr.s_addr == INADDR_ANY) {
768 		struct route *ro;
769 
770 		ia = NULL;
771 		/*
772 		 * If route is known or can be allocated now,
773 		 * our src addr is taken from the i/f, else punt.
774 		 * Note that we should check the address family of the cached
775 		 * destination, in case of sharing the cache with IPv6.
776 		 */
777 		ro = &inp->inp_route;
778 		if (ro->ro_rt &&
779 		    (!(ro->ro_rt->rt_flags & RTF_UP) ||
780 		     ro->ro_dst.sa_family != AF_INET ||
781 		     satosin(&ro->ro_dst)->sin_addr.s_addr !=
782 				      sin->sin_addr.s_addr ||
783 		     inp->inp_socket->so_options & SO_DONTROUTE)) {
784 			RTFREE(ro->ro_rt);
785 			ro->ro_rt = NULL;
786 		}
787 		if (!(inp->inp_socket->so_options & SO_DONTROUTE) && /*XXX*/
788 		    (ro->ro_rt == NULL ||
789 		    ro->ro_rt->rt_ifp == NULL)) {
790 			/* No route yet, so try to acquire one */
791 			bzero(&ro->ro_dst, sizeof(struct sockaddr_in));
792 			ro->ro_dst.sa_family = AF_INET;
793 			ro->ro_dst.sa_len = sizeof(struct sockaddr_in);
794 			((struct sockaddr_in *) &ro->ro_dst)->sin_addr =
795 				sin->sin_addr;
796 			rtalloc(ro);
797 			alloc_route = 1;
798 		}
799 		/*
800 		 * If we found a route, use the address
801 		 * corresponding to the outgoing interface
802 		 * unless it is the loopback (in case a route
803 		 * to our address on another net goes to loopback).
804 		 */
805 		if (ro->ro_rt && !(ro->ro_rt->rt_ifp->if_flags & IFF_LOOPBACK)) {
806 			if (jailed) {
807 				if (jailed_ip(cred->cr_prison,
808 				    ro->ro_rt->rt_ifa->ifa_addr)) {
809 					ia = ifatoia(ro->ro_rt->rt_ifa);
810 				}
811 			} else {
812 				ia = ifatoia(ro->ro_rt->rt_ifa);
813 			}
814 		}
815 		if (ia == NULL) {
816 			u_short fport = sin->sin_port;
817 
818 			sin->sin_port = 0;
819 			ia = ifatoia(ifa_ifwithdstaddr(sintosa(sin)));
820 			if (ia && jailed && !jailed_ip(cred->cr_prison,
821 			    sintosa(&ia->ia_addr)))
822 				ia = NULL;
823 			if (ia == NULL)
824 				ia = ifatoia(ifa_ifwithnet(sintosa(sin)));
825 			if (ia && jailed && !jailed_ip(cred->cr_prison,
826 			    sintosa(&ia->ia_addr)))
827 				ia = NULL;
828 			sin->sin_port = fport;
829 			if (ia == NULL &&
830 			    !TAILQ_EMPTY(&in_ifaddrheads[mycpuid]))
831 				ia = TAILQ_FIRST(&in_ifaddrheads[mycpuid])->ia;
832 			if (ia && jailed && !jailed_ip(cred->cr_prison,
833 			    sintosa(&ia->ia_addr)))
834 				ia = NULL;
835 
836 			if (!jailed && ia == NULL)
837 				goto fail;
838 		}
839 		/*
840 		 * If the destination address is multicast and an outgoing
841 		 * interface has been set as a multicast option, use the
842 		 * address of that interface as our source address.
843 		 */
844 		if (!jailed && IN_MULTICAST(ntohl(sin->sin_addr.s_addr)) &&
845 		    inp->inp_moptions != NULL) {
846 			struct ip_moptions *imo;
847 			struct ifnet *ifp;
848 
849 			imo = inp->inp_moptions;
850 			if (imo->imo_multicast_ifp != NULL) {
851 				struct in_ifaddr_container *iac;
852 
853 				ifp = imo->imo_multicast_ifp;
854 				ia = NULL;
855 				TAILQ_FOREACH(iac,
856 				&in_ifaddrheads[mycpuid], ia_link) {
857 					if (iac->ia->ia_ifp == ifp) {
858 						ia = iac->ia;
859 						break;
860 					}
861 				}
862 				if (ia == NULL)
863 					goto fail;
864 			}
865 		}
866 		/*
867 		 * Don't do pcblookup call here; return interface in plocal_sin
868 		 * and exit to caller, that will do the lookup.
869 		 */
870 		if (ia == NULL && jailed) {
871 			if ((jsin = prison_get_nonlocal(cred->cr_prison, AF_INET, NULL)) != NULL ||
872 			    (jsin = prison_get_local(cred->cr_prison, AF_INET, NULL)) != NULL) {
873 				*plocal_sin = satosin(jsin);
874 			} else {
875 				/* IPv6 only Jail */
876 				goto fail;
877 			}
878 		} else {
879 			*plocal_sin = &ia->ia_addr;
880 		}
881 	}
882 	return (0);
883 fail:
884 	if (alloc_route) {
885 		struct route *ro = &inp->inp_route;
886 
887 		if (ro->ro_rt != NULL)
888 			RTFREE(ro->ro_rt);
889 		bzero(ro, sizeof(*ro));
890 	}
891 	return (EADDRNOTAVAIL);
892 }
893 
894 /*
895  * Outer subroutine:
896  * Connect from a socket to a specified address.
897  * Both address and port must be specified in argument sin.
898  * If don't have a local address for this socket yet,
899  * then pick one.
900  */
901 int
902 in_pcbconnect(struct inpcb *inp, struct sockaddr *nam, struct thread *td)
903 {
904 	struct sockaddr_in *if_sin;
905 	struct sockaddr_in *sin = (struct sockaddr_in *)nam;
906 	int error;
907 
908 	/* Call inner routine to assign local interface address. */
909 	if ((error = in_pcbladdr(inp, nam, &if_sin, td)) != 0)
910 		return (error);
911 
912 	if (in_pcblookup_hash(inp->inp_cpcbinfo, sin->sin_addr, sin->sin_port,
913 			      inp->inp_laddr.s_addr ?
914 				inp->inp_laddr : if_sin->sin_addr,
915 			      inp->inp_lport, FALSE, NULL) != NULL) {
916 		return (EADDRINUSE);
917 	}
918 	if (inp->inp_laddr.s_addr == INADDR_ANY) {
919 		if (inp->inp_lport == 0) {
920 			error = in_pcbbind(inp, NULL, td);
921 			if (error)
922 				return (error);
923 		}
924 		inp->inp_laddr = if_sin->sin_addr;
925 	}
926 	inp->inp_faddr = sin->sin_addr;
927 	inp->inp_fport = sin->sin_port;
928 	in_pcbinsconnhash(inp);
929 	return (0);
930 }
931 
932 void
933 in_pcbdisconnect(struct inpcb *inp)
934 {
935 
936 	inp->inp_faddr.s_addr = INADDR_ANY;
937 	inp->inp_fport = 0;
938 	in_pcbremconnhash(inp);
939 	if (inp->inp_socket->so_state & SS_NOFDREF)
940 		in_pcbdetach(inp);
941 }
942 
943 void
944 in_pcbdetach(struct inpcb *inp)
945 {
946 	struct socket *so = inp->inp_socket;
947 	struct inpcbinfo *ipi = inp->inp_pcbinfo;
948 
949 #ifdef IPSEC
950 	ipsec4_delete_pcbpolicy(inp);
951 #endif /*IPSEC*/
952 	inp->inp_gencnt = ++ipi->ipi_gencnt;
953 	KKASSERT((so->so_state & SS_ASSERTINPROG) == 0);
954 	in_pcbremlists(inp);
955 	so->so_pcb = NULL;
956 	sofree(so);			/* remove pcb ref */
957 	if (inp->inp_options)
958 		m_free(inp->inp_options);
959 	if (inp->inp_route.ro_rt)
960 		rtfree(inp->inp_route.ro_rt);
961 	ip_freemoptions(inp->inp_moptions);
962 	inp->inp_vflag = 0;
963 	kfree(inp, M_PCB);
964 }
965 
966 /*
967  * The calling convention of in_setsockaddr() and in_setpeeraddr() was
968  * modified to match the pru_sockaddr() and pru_peeraddr() entry points
969  * in struct pr_usrreqs, so that protocols can just reference then directly
970  * without the need for a wrapper function.  The socket must have a valid
971  * (i.e., non-nil) PCB, but it should be impossible to get an invalid one
972  * except through a kernel programming error, so it is acceptable to panic
973  * (or in this case trap) if the PCB is invalid.  (Actually, we don't trap
974  * because there actually /is/ a programming error somewhere... XXX)
975  */
976 int
977 in_setsockaddr(struct socket *so, struct sockaddr **nam)
978 {
979 	struct inpcb *inp;
980 	struct sockaddr_in *sin;
981 
982 	/*
983 	 * Do the malloc first in case it blocks.
984 	 */
985 	sin = kmalloc(sizeof *sin, M_SONAME, M_WAITOK | M_ZERO);
986 	sin->sin_family = AF_INET;
987 	sin->sin_len = sizeof *sin;
988 
989 	crit_enter();
990 	inp = so->so_pcb;
991 	if (!inp) {
992 		crit_exit();
993 		kfree(sin, M_SONAME);
994 		return (ECONNRESET);
995 	}
996 	sin->sin_port = inp->inp_lport;
997 	sin->sin_addr = inp->inp_laddr;
998 	crit_exit();
999 
1000 	*nam = (struct sockaddr *)sin;
1001 	return (0);
1002 }
1003 
1004 void
1005 in_setsockaddr_dispatch(netmsg_t msg)
1006 {
1007 	int error;
1008 
1009 	error = in_setsockaddr(msg->base.nm_so, msg->peeraddr.nm_nam);
1010 	lwkt_replymsg(&msg->lmsg, error);
1011 }
1012 
1013 int
1014 in_setpeeraddr(struct socket *so, struct sockaddr **nam)
1015 {
1016 	struct inpcb *inp;
1017 	struct sockaddr_in *sin;
1018 
1019 	/*
1020 	 * Do the malloc first in case it blocks.
1021 	 */
1022 	sin = kmalloc(sizeof *sin, M_SONAME, M_WAITOK | M_ZERO);
1023 	sin->sin_family = AF_INET;
1024 	sin->sin_len = sizeof *sin;
1025 
1026 	crit_enter();
1027 	inp = so->so_pcb;
1028 	if (!inp) {
1029 		crit_exit();
1030 		kfree(sin, M_SONAME);
1031 		return (ECONNRESET);
1032 	}
1033 	sin->sin_port = inp->inp_fport;
1034 	sin->sin_addr = inp->inp_faddr;
1035 	crit_exit();
1036 
1037 	*nam = (struct sockaddr *)sin;
1038 	return (0);
1039 }
1040 
1041 void
1042 in_setpeeraddr_dispatch(netmsg_t msg)
1043 {
1044 	int error;
1045 
1046 	error = in_setpeeraddr(msg->base.nm_so, msg->peeraddr.nm_nam);
1047 	lwkt_replymsg(&msg->lmsg, error);
1048 }
1049 
1050 void
1051 in_pcbnotifyall(struct inpcbhead *head, struct in_addr faddr, int err,
1052 		void (*notify)(struct inpcb *, int))
1053 {
1054 	struct inpcb *inp, *ninp;
1055 
1056 	/*
1057 	 * note: if INP_PLACEMARKER is set we must ignore the rest of
1058 	 * the structure and skip it.
1059 	 */
1060 	crit_enter();
1061 	LIST_FOREACH_MUTABLE(inp, head, inp_list, ninp) {
1062 		if (inp->inp_flags & INP_PLACEMARKER)
1063 			continue;
1064 #ifdef INET6
1065 		if (!(inp->inp_vflag & INP_IPV4))
1066 			continue;
1067 #endif
1068 		if (inp->inp_faddr.s_addr != faddr.s_addr ||
1069 		    inp->inp_socket == NULL)
1070 			continue;
1071 		(*notify)(inp, err);		/* can remove inp from list! */
1072 	}
1073 	crit_exit();
1074 }
1075 
1076 void
1077 in_pcbpurgeif0(struct inpcb *head, struct ifnet *ifp)
1078 {
1079 	struct inpcb *inp;
1080 	struct ip_moptions *imo;
1081 	int i, gap;
1082 
1083 	for (inp = head; inp != NULL; inp = LIST_NEXT(inp, inp_list)) {
1084 		if (inp->inp_flags & INP_PLACEMARKER)
1085 			continue;
1086 		imo = inp->inp_moptions;
1087 		if ((inp->inp_vflag & INP_IPV4) && imo != NULL) {
1088 			/*
1089 			 * Unselect the outgoing interface if it is being
1090 			 * detached.
1091 			 */
1092 			if (imo->imo_multicast_ifp == ifp)
1093 				imo->imo_multicast_ifp = NULL;
1094 
1095 			/*
1096 			 * Drop multicast group membership if we joined
1097 			 * through the interface being detached.
1098 			 */
1099 			for (i = 0, gap = 0; i < imo->imo_num_memberships;
1100 			    i++) {
1101 				if (imo->imo_membership[i]->inm_ifp == ifp) {
1102 					in_delmulti(imo->imo_membership[i]);
1103 					gap++;
1104 				} else if (gap != 0)
1105 					imo->imo_membership[i - gap] =
1106 					    imo->imo_membership[i];
1107 			}
1108 			imo->imo_num_memberships -= gap;
1109 		}
1110 	}
1111 }
1112 
1113 /*
1114  * Check for alternatives when higher level complains
1115  * about service problems.  For now, invalidate cached
1116  * routing information.  If the route was created dynamically
1117  * (by a redirect), time to try a default gateway again.
1118  */
1119 void
1120 in_losing(struct inpcb *inp)
1121 {
1122 	struct rtentry *rt;
1123 	struct rt_addrinfo rtinfo;
1124 
1125 	if ((rt = inp->inp_route.ro_rt)) {
1126 		bzero(&rtinfo, sizeof(struct rt_addrinfo));
1127 		rtinfo.rti_info[RTAX_DST] = rt_key(rt);
1128 		rtinfo.rti_info[RTAX_GATEWAY] = rt->rt_gateway;
1129 		rtinfo.rti_info[RTAX_NETMASK] = rt_mask(rt);
1130 		rtinfo.rti_flags = rt->rt_flags;
1131 		rt_missmsg(RTM_LOSING, &rtinfo, rt->rt_flags, 0);
1132 		if (rt->rt_flags & RTF_DYNAMIC)
1133 			rtrequest1_global(RTM_DELETE, &rtinfo, NULL, NULL);
1134 		inp->inp_route.ro_rt = NULL;
1135 		rtfree(rt);
1136 		/*
1137 		 * A new route can be allocated
1138 		 * the next time output is attempted.
1139 		 */
1140 	}
1141 }
1142 
1143 /*
1144  * After a routing change, flush old routing
1145  * and allocate a (hopefully) better one.
1146  */
1147 void
1148 in_rtchange(struct inpcb *inp, int err)
1149 {
1150 	if (inp->inp_route.ro_rt) {
1151 		rtfree(inp->inp_route.ro_rt);
1152 		inp->inp_route.ro_rt = NULL;
1153 		/*
1154 		 * A new route can be allocated the next time
1155 		 * output is attempted.
1156 		 */
1157 	}
1158 }
1159 
1160 /*
1161  * Lookup a PCB based on the local address and port.
1162  */
1163 struct inpcb *
1164 in_pcblookup_local(struct inpcbinfo *pcbinfo, struct in_addr laddr,
1165 		   u_int lport_arg, int wild_okay, struct ucred *cred)
1166 {
1167 	struct inpcb *inp;
1168 	int matchwild = 3, wildcard;
1169 	u_short lport = lport_arg;
1170 	struct inpcbporthead *porthash;
1171 	struct inpcbport *phd;
1172 	struct inpcb *match = NULL;
1173 
1174 	/*
1175 	 * If the porthashbase is shared across several cpus we need
1176 	 * to lock.
1177 	 */
1178 	if (pcbinfo->porttoken)
1179 		lwkt_gettoken(pcbinfo->porttoken);
1180 
1181 	/*
1182 	 * Best fit PCB lookup.
1183 	 *
1184 	 * First see if this local port is in use by looking on the
1185 	 * port hash list.
1186 	 */
1187 	porthash = &pcbinfo->porthashbase[
1188 			INP_PCBPORTHASH(lport, pcbinfo->porthashmask)];
1189 	LIST_FOREACH(phd, porthash, phd_hash) {
1190 		if (phd->phd_port == lport)
1191 			break;
1192 	}
1193 	if (phd != NULL) {
1194 		/*
1195 		 * Port is in use by one or more PCBs. Look for best
1196 		 * fit.
1197 		 */
1198 		LIST_FOREACH(inp, &phd->phd_pcblist, inp_portlist) {
1199 			wildcard = 0;
1200 #ifdef INET6
1201 			if ((inp->inp_vflag & INP_IPV4) == 0)
1202 				continue;
1203 #endif
1204 			if (inp->inp_faddr.s_addr != INADDR_ANY)
1205 				wildcard++;
1206 			if (inp->inp_laddr.s_addr != INADDR_ANY) {
1207 				if (laddr.s_addr == INADDR_ANY)
1208 					wildcard++;
1209 				else if (inp->inp_laddr.s_addr != laddr.s_addr)
1210 					continue;
1211 			} else {
1212 				if (laddr.s_addr != INADDR_ANY)
1213 					wildcard++;
1214 			}
1215 			if (wildcard && !wild_okay)
1216 				continue;
1217 			if (wildcard < matchwild &&
1218 			    (cred == NULL ||
1219 			     cred->cr_prison ==
1220 					inp->inp_socket->so_cred->cr_prison)) {
1221 				match = inp;
1222 				matchwild = wildcard;
1223 				if (matchwild == 0) {
1224 					break;
1225 				}
1226 			}
1227 		}
1228 	}
1229 	if (pcbinfo->porttoken)
1230 		lwkt_reltoken(pcbinfo->porttoken);
1231 	return (match);
1232 }
1233 
1234 /*
1235  * Lookup PCB in hash list.
1236  */
1237 struct inpcb *
1238 in_pcblookup_hash(struct inpcbinfo *pcbinfo, struct in_addr faddr,
1239 		  u_int fport_arg, struct in_addr laddr, u_int lport_arg,
1240 		  boolean_t wildcard, struct ifnet *ifp)
1241 {
1242 	struct inpcbhead *head;
1243 	struct inpcb *inp, *jinp=NULL;
1244 	u_short fport = fport_arg, lport = lport_arg;
1245 
1246 	/*
1247 	 * First look for an exact match.
1248 	 */
1249 	head = &pcbinfo->hashbase[INP_PCBCONNHASH(faddr.s_addr, fport,
1250 	    laddr.s_addr, lport, pcbinfo->hashmask)];
1251 	LIST_FOREACH(inp, head, inp_hash) {
1252 #ifdef INET6
1253 		if (!(inp->inp_vflag & INP_IPV4))
1254 			continue;
1255 #endif
1256 		if (in_hosteq(inp->inp_faddr, faddr) &&
1257 		    in_hosteq(inp->inp_laddr, laddr) &&
1258 		    inp->inp_fport == fport && inp->inp_lport == lport) {
1259 			/* found */
1260 			if (inp->inp_socket == NULL ||
1261 			    inp->inp_socket->so_cred->cr_prison == NULL) {
1262 				return (inp);
1263 			} else {
1264 				if  (jinp == NULL)
1265 					jinp = inp;
1266 			}
1267 		}
1268 	}
1269 	if (jinp != NULL)
1270 		return (jinp);
1271 	if (wildcard) {
1272 		struct inpcb *local_wild = NULL;
1273 		struct inpcb *jinp_wild = NULL;
1274 #ifdef INET6
1275 		struct inpcb *local_wild_mapped = NULL;
1276 #endif
1277 		struct inpcontainer *ic;
1278 		struct inpcontainerhead *chead;
1279 		struct sockaddr_in jsin;
1280 		struct ucred *cred;
1281 
1282 		/*
1283 		 * Order of socket selection:
1284 		 * 1. non-jailed, non-wild.
1285 		 * 2. non-jailed, wild.
1286 		 * 3. jailed, non-wild.
1287 		 * 4. jailed, wild.
1288 		 */
1289 		jsin.sin_family = AF_INET;
1290 		chead = &pcbinfo->wildcardhashbase[
1291 		    INP_PCBWILDCARDHASH(lport, pcbinfo->wildcardhashmask)];
1292 		LIST_FOREACH(ic, chead, ic_list) {
1293 			inp = ic->ic_inp;
1294 			jsin.sin_addr.s_addr = laddr.s_addr;
1295 #ifdef INET6
1296 			if (!(inp->inp_vflag & INP_IPV4))
1297 				continue;
1298 #endif
1299 			if (inp->inp_socket != NULL)
1300 				cred = inp->inp_socket->so_cred;
1301 			else
1302 				cred = NULL;
1303 			if (cred != NULL && jailed(cred)) {
1304 				if (jinp != NULL)
1305 					continue;
1306 				else
1307 					if (!jailed_ip(cred->cr_prison,
1308 					    (struct sockaddr *)&jsin))
1309 						continue;
1310 			}
1311 			if (inp->inp_lport == lport) {
1312 				if (ifp && ifp->if_type == IFT_FAITH &&
1313 				    !(inp->inp_flags & INP_FAITH))
1314 					continue;
1315 				if (inp->inp_laddr.s_addr == laddr.s_addr) {
1316 					if (cred != NULL && jailed(cred))
1317 						jinp = inp;
1318 					else
1319 						return (inp);
1320 				}
1321 				if (inp->inp_laddr.s_addr == INADDR_ANY) {
1322 #ifdef INET6
1323 					if (INP_CHECK_SOCKAF(inp->inp_socket,
1324 							     AF_INET6))
1325 						local_wild_mapped = inp;
1326 					else
1327 #endif
1328 						if (cred != NULL &&
1329 						    jailed(cred))
1330 							jinp_wild = inp;
1331 						else
1332 							local_wild = inp;
1333 				}
1334 			}
1335 		}
1336 		if (local_wild != NULL)
1337 			return (local_wild);
1338 #ifdef INET6
1339 		if (local_wild_mapped != NULL)
1340 			return (local_wild_mapped);
1341 #endif
1342 		if (jinp != NULL)
1343 			return (jinp);
1344 		return (jinp_wild);
1345 	}
1346 
1347 	/*
1348 	 * Not found.
1349 	 */
1350 	return (NULL);
1351 }
1352 
1353 /*
1354  * Insert PCB into connection hash table.
1355  */
1356 void
1357 in_pcbinsconnhash(struct inpcb *inp)
1358 {
1359 	struct inpcbinfo *pcbinfo = inp->inp_cpcbinfo;
1360 	struct inpcbhead *bucket;
1361 	u_int32_t hashkey_faddr, hashkey_laddr;
1362 
1363 #ifdef INET6
1364 	if (inp->inp_vflag & INP_IPV6) {
1365 		hashkey_faddr = inp->in6p_faddr.s6_addr32[3] /* XXX JH */;
1366 		hashkey_laddr = inp->in6p_laddr.s6_addr32[3] /* XXX JH */;
1367 	} else {
1368 #endif
1369 		hashkey_faddr = inp->inp_faddr.s_addr;
1370 		hashkey_laddr = inp->inp_laddr.s_addr;
1371 #ifdef INET6
1372 	}
1373 #endif
1374 
1375 	KASSERT(!(inp->inp_flags & INP_WILDCARD),
1376 		("already on wildcardhash\n"));
1377 	KASSERT(!(inp->inp_flags & INP_CONNECTED),
1378 		("already on connhash\n"));
1379 	inp->inp_flags |= INP_CONNECTED;
1380 
1381 	/*
1382 	 * Insert into the connection hash table.
1383 	 */
1384 	bucket = &pcbinfo->hashbase[INP_PCBCONNHASH(hashkey_faddr,
1385 	    inp->inp_fport, hashkey_laddr, inp->inp_lport, pcbinfo->hashmask)];
1386 	LIST_INSERT_HEAD(bucket, inp, inp_hash);
1387 }
1388 
1389 /*
1390  * Remove PCB from connection hash table.
1391  */
1392 void
1393 in_pcbremconnhash(struct inpcb *inp)
1394 {
1395 	KASSERT(inp->inp_flags & INP_CONNECTED, ("inp not connected"));
1396 	LIST_REMOVE(inp, inp_hash);
1397 	inp->inp_flags &= ~INP_CONNECTED;
1398 }
1399 
1400 /*
1401  * Insert PCB into port hash table.
1402  */
1403 int
1404 in_pcbinsporthash(struct inpcb *inp)
1405 {
1406 	struct inpcbinfo *pcbinfo = inp->inp_pcbinfo;
1407 	struct inpcbporthead *pcbporthash;
1408 	struct inpcbport *phd;
1409 
1410 	/*
1411 	 * If the porthashbase is shared across several cpus we need
1412 	 * to lock.
1413 	 */
1414 	if (pcbinfo->porttoken)
1415 		lwkt_gettoken(pcbinfo->porttoken);
1416 
1417 	/*
1418 	 * Insert into the port hash table.
1419 	 */
1420 	pcbporthash = &pcbinfo->porthashbase[
1421 	    INP_PCBPORTHASH(inp->inp_lport, pcbinfo->porthashmask)];
1422 
1423 	/* Go through port list and look for a head for this lport. */
1424 	LIST_FOREACH(phd, pcbporthash, phd_hash) {
1425 		if (phd->phd_port == inp->inp_lport)
1426 			break;
1427 	}
1428 
1429 	/* If none exists, malloc one and tack it on. */
1430 	if (phd == NULL) {
1431 		KKASSERT(pcbinfo->portsave != NULL);
1432 		phd = pcbinfo->portsave;
1433 		pcbinfo->portsave = NULL;
1434 		phd->phd_port = inp->inp_lport;
1435 		LIST_INIT(&phd->phd_pcblist);
1436 		LIST_INSERT_HEAD(pcbporthash, phd, phd_hash);
1437 	}
1438 
1439 	inp->inp_phd = phd;
1440 	LIST_INSERT_HEAD(&phd->phd_pcblist, inp, inp_portlist);
1441 
1442 	if (pcbinfo->porttoken)
1443 		lwkt_reltoken(pcbinfo->porttoken);
1444 	if (pcbinfo->portsave == NULL) {
1445 		pcbinfo->portsave = kmalloc(sizeof(*pcbinfo->portsave),
1446 					    M_PCB, M_INTWAIT | M_ZERO);
1447 	}
1448 	return (0);
1449 }
1450 
1451 void
1452 in_pcbinswildcardhash_oncpu(struct inpcb *inp, struct inpcbinfo *pcbinfo)
1453 {
1454 	struct inpcontainer *ic;
1455 	struct inpcontainerhead *bucket;
1456 
1457 	bucket = &pcbinfo->wildcardhashbase[
1458 	    INP_PCBWILDCARDHASH(inp->inp_lport, pcbinfo->wildcardhashmask)];
1459 
1460 	ic = kmalloc(sizeof(struct inpcontainer), M_TEMP, M_INTWAIT);
1461 	ic->ic_inp = inp;
1462 	LIST_INSERT_HEAD(bucket, ic, ic_list);
1463 }
1464 
1465 /*
1466  * Insert PCB into wildcard hash table.
1467  */
1468 void
1469 in_pcbinswildcardhash(struct inpcb *inp)
1470 {
1471 	struct inpcbinfo *pcbinfo = inp->inp_pcbinfo;
1472 
1473 	KASSERT(!(inp->inp_flags & INP_CONNECTED),
1474 		("already on connhash\n"));
1475 	KASSERT(!(inp->inp_flags & INP_WILDCARD),
1476 		("already on wildcardhash\n"));
1477 	inp->inp_flags |= INP_WILDCARD;
1478 
1479 	in_pcbinswildcardhash_oncpu(inp, pcbinfo);
1480 }
1481 
1482 void
1483 in_pcbremwildcardhash_oncpu(struct inpcb *inp, struct inpcbinfo *pcbinfo)
1484 {
1485 	struct inpcontainer *ic;
1486 	struct inpcontainerhead *head;
1487 
1488 	/* find bucket */
1489 	head = &pcbinfo->wildcardhashbase[
1490 	    INP_PCBWILDCARDHASH(inp->inp_lport, pcbinfo->wildcardhashmask)];
1491 
1492 	LIST_FOREACH(ic, head, ic_list) {
1493 		if (ic->ic_inp == inp)
1494 			goto found;
1495 	}
1496 	return;			/* not found! */
1497 
1498 found:
1499 	LIST_REMOVE(ic, ic_list);	/* remove container from bucket chain */
1500 	kfree(ic, M_TEMP);		/* deallocate container */
1501 }
1502 
1503 /*
1504  * Remove PCB from wildcard hash table.
1505  */
1506 void
1507 in_pcbremwildcardhash(struct inpcb *inp)
1508 {
1509 	struct inpcbinfo *pcbinfo = inp->inp_pcbinfo;
1510 
1511 	KASSERT(inp->inp_flags & INP_WILDCARD, ("inp not wildcard"));
1512 	in_pcbremwildcardhash_oncpu(inp, pcbinfo);
1513 	inp->inp_flags &= ~INP_WILDCARD;
1514 }
1515 
1516 /*
1517  * Remove PCB from various lists.
1518  */
1519 void
1520 in_pcbremlists(struct inpcb *inp)
1521 {
1522 	struct inpcbinfo *pcbinfo;
1523 
1524 	if (inp->inp_lport) {
1525 		struct inpcbport *phd;
1526 
1527 		pcbinfo = inp->inp_pcbinfo;
1528 		if (pcbinfo->porttoken)
1529 			lwkt_gettoken(pcbinfo->porttoken);
1530 
1531 		phd = inp->inp_phd;
1532 		LIST_REMOVE(inp, inp_portlist);
1533 		if (LIST_FIRST(&phd->phd_pcblist) == NULL) {
1534 			LIST_REMOVE(phd, phd_hash);
1535 			kfree(phd, M_PCB);
1536 		}
1537 		if (pcbinfo->porttoken)
1538 			lwkt_reltoken(pcbinfo->porttoken);
1539 	}
1540 	if (inp->inp_flags & INP_WILDCARD) {
1541 		in_pcbremwildcardhash(inp);
1542 	} else if (inp->inp_flags & INP_CONNECTED) {
1543 		in_pcbremconnhash(inp);
1544 	}
1545 	LIST_REMOVE(inp, inp_list);
1546 	inp->inp_pcbinfo->ipi_count--;
1547 }
1548 
1549 int
1550 prison_xinpcb(struct thread *td, struct inpcb *inp)
1551 {
1552 	struct ucred *cr;
1553 
1554 	if (td->td_proc == NULL)
1555 		return (0);
1556 	cr = td->td_proc->p_ucred;
1557 	if (cr->cr_prison == NULL)
1558 		return (0);
1559 	if (inp->inp_socket && inp->inp_socket->so_cred &&
1560 	    inp->inp_socket->so_cred->cr_prison &&
1561 	    cr->cr_prison == inp->inp_socket->so_cred->cr_prison)
1562 		return (0);
1563 	return (1);
1564 }
1565 
1566 int
1567 in_pcblist_global(SYSCTL_HANDLER_ARGS)
1568 {
1569 	struct inpcbinfo *pcbinfo = arg1;
1570 	struct inpcb *inp, *marker;
1571 	struct xinpcb xi;
1572 	int error, i, n;
1573 
1574 	/*
1575 	 * The process of preparing the TCB list is too time-consuming and
1576 	 * resource-intensive to repeat twice on every request.
1577 	 */
1578 	if (req->oldptr == NULL) {
1579 		n = pcbinfo->ipi_count;
1580 		req->oldidx = (n + n/8 + 10) * sizeof(struct xinpcb);
1581 		return 0;
1582 	}
1583 
1584 	if (req->newptr != NULL)
1585 		return EPERM;
1586 
1587 	/*
1588 	 * OK, now we're committed to doing something.  Re-fetch ipi_count
1589 	 * after obtaining the generation count.
1590 	 */
1591 	n = pcbinfo->ipi_count;
1592 
1593 	marker = kmalloc(sizeof(struct inpcb), M_TEMP, M_WAITOK|M_ZERO);
1594 	marker->inp_flags |= INP_PLACEMARKER;
1595 	LIST_INSERT_HEAD(&pcbinfo->pcblisthead, marker, inp_list);
1596 
1597 	i = 0;
1598 	error = 0;
1599 
1600 	while ((inp = LIST_NEXT(marker, inp_list)) != NULL && i < n) {
1601 		LIST_REMOVE(marker, inp_list);
1602 		LIST_INSERT_AFTER(inp, marker, inp_list);
1603 
1604 		if (inp->inp_flags & INP_PLACEMARKER)
1605 			continue;
1606 		if (prison_xinpcb(req->td, inp))
1607 			continue;
1608 		bzero(&xi, sizeof xi);
1609 		xi.xi_len = sizeof xi;
1610 		bcopy(inp, &xi.xi_inp, sizeof *inp);
1611 		if (inp->inp_socket)
1612 			sotoxsocket(inp->inp_socket, &xi.xi_socket);
1613 		if ((error = SYSCTL_OUT(req, &xi, sizeof xi)) != 0)
1614 			break;
1615 		++i;
1616 	}
1617 	LIST_REMOVE(marker, inp_list);
1618 	if (error == 0 && i < n) {
1619 		bzero(&xi, sizeof xi);
1620 		xi.xi_len = sizeof xi;
1621 		while (i < n) {
1622 			error = SYSCTL_OUT(req, &xi, sizeof xi);
1623 			++i;
1624 		}
1625 	}
1626 	kfree(marker, M_TEMP);
1627 	return(error);
1628 }
1629 
1630 int
1631 in_pcblist_global_nomarker(SYSCTL_HANDLER_ARGS, struct xinpcb **xi0, int *nxi0)
1632 {
1633 	struct inpcbinfo *pcbinfo = arg1;
1634 	struct inpcb *inp;
1635 	struct xinpcb *xi;
1636 	int nxi;
1637 
1638 	*nxi0 = 0;
1639 	*xi0 = NULL;
1640 
1641 	/*
1642 	 * The process of preparing the PCB list is too time-consuming and
1643 	 * resource-intensive to repeat twice on every request.
1644 	 */
1645 	if (req->oldptr == NULL) {
1646 		int n = pcbinfo->ipi_count;
1647 
1648 		req->oldidx = (n + n/8 + 10) * sizeof(struct xinpcb);
1649 		return 0;
1650 	}
1651 
1652 	if (req->newptr != NULL)
1653 		return EPERM;
1654 
1655 	if (pcbinfo->ipi_count == 0)
1656 		return 0;
1657 
1658 	nxi = 0;
1659 	xi = kmalloc(pcbinfo->ipi_count * sizeof(*xi), M_TEMP,
1660 		     M_WAITOK | M_ZERO | M_NULLOK);
1661 	if (xi == NULL)
1662 		return ENOMEM;
1663 
1664 	LIST_FOREACH(inp, &pcbinfo->pcblisthead, inp_list) {
1665 		struct xinpcb *xi_ptr = &xi[nxi];
1666 
1667 		if (prison_xinpcb(req->td, inp))
1668 			continue;
1669 
1670 		xi_ptr->xi_len = sizeof(*xi_ptr);
1671 		bcopy(inp, &xi_ptr->xi_inp, sizeof(*inp));
1672 		if (inp->inp_socket)
1673 			sotoxsocket(inp->inp_socket, &xi_ptr->xi_socket);
1674 		++nxi;
1675 	}
1676 
1677 	if (nxi == 0) {
1678 		kfree(xi, M_TEMP);
1679 		return 0;
1680 	}
1681 
1682 	*nxi0 = nxi;
1683 	*xi0 = xi;
1684 
1685 	return 0;
1686 }
1687 
1688 void
1689 in_savefaddr(struct socket *so, const struct sockaddr *faddr)
1690 {
1691 	struct sockaddr_in *sin;
1692 
1693 	KASSERT(faddr->sa_family == AF_INET,
1694 	    ("not AF_INET faddr %d\n", faddr->sa_family));
1695 
1696 	sin = kmalloc(sizeof(*sin), M_SONAME, M_WAITOK | M_ZERO);
1697 	sin->sin_family = AF_INET;
1698 	sin->sin_len = sizeof(*sin);
1699 	sin->sin_port = ((const struct sockaddr_in *)faddr)->sin_port;
1700 	sin->sin_addr = ((const struct sockaddr_in *)faddr)->sin_addr;
1701 
1702 	so->so_faddr = (struct sockaddr *)sin;
1703 }
1704