xref: /openbsd/sys/netinet/in_pcb.c (revision 9c7bd2b0)
1 /*	$OpenBSD: in_pcb.c,v 1.310 2025/01/09 16:47:24 bluhm Exp $	*/
2 /*	$NetBSD: in_pcb.c,v 1.25 1996/02/13 23:41:53 christos Exp $	*/
3 
4 /*
5  * Copyright (c) 1982, 1986, 1991, 1993
6  *	The Regents of the University of California.  All rights reserved.
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 University nor the names of its contributors
17  *    may be used to endorse or promote products derived from this software
18  *    without specific prior written permission.
19  *
20  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
21  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
24  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
26  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
29  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
30  * SUCH DAMAGE.
31  *
32  *	@(#)COPYRIGHT	1.1 (NRL) 17 January 1995
33  *
34  * NRL grants permission for redistribution and use in source and binary
35  * forms, with or without modification, of the software and documentation
36  * created at NRL provided that the following conditions are met:
37  *
38  * 1. Redistributions of source code must retain the above copyright
39  *    notice, this list of conditions and the following disclaimer.
40  * 2. Redistributions in binary form must reproduce the above copyright
41  *    notice, this list of conditions and the following disclaimer in the
42  *    documentation and/or other materials provided with the distribution.
43  * 3. All advertising materials mentioning features or use of this software
44  *    must display the following acknowledgements:
45  *	This product includes software developed by the University of
46  *	California, Berkeley and its contributors.
47  *	This product includes software developed at the Information
48  *	Technology Division, US Naval Research Laboratory.
49  * 4. Neither the name of the NRL nor the names of its contributors
50  *    may be used to endorse or promote products derived from this software
51  *    without specific prior written permission.
52  *
53  * THE SOFTWARE PROVIDED BY NRL IS PROVIDED BY NRL AND CONTRIBUTORS ``AS
54  * IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
55  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
56  * PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL NRL OR
57  * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
58  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
59  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
60  * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
61  * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
62  * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
63  * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
64  *
65  * The views and conclusions contained in the software and documentation
66  * are those of the authors and should not be interpreted as representing
67  * official policies, either expressed or implied, of the US Naval
68  * Research Laboratory (NRL).
69  */
70 
71 #include "pf.h"
72 
73 #include <sys/param.h>
74 #include <sys/systm.h>
75 #include <sys/mbuf.h>
76 #include <sys/protosw.h>
77 #include <sys/socket.h>
78 #include <sys/socketvar.h>
79 #include <sys/domain.h>
80 #include <sys/mount.h>
81 #include <sys/pool.h>
82 #include <sys/proc.h>
83 
84 #include <net/if.h>
85 #include <net/if_var.h>
86 #include <net/pfvar.h>
87 #include <net/route.h>
88 
89 #include <netinet/in.h>
90 #include <netinet/in_var.h>
91 #include <netinet/ip.h>
92 #include <netinet/ip_var.h>
93 #include <netinet6/ip6_var.h>
94 #include <netinet/in_pcb.h>
95 #ifdef IPSEC
96 #include <netinet/ip_esp.h>
97 #endif /* IPSEC */
98 
99 #include "stoeplitz.h"
100 #if NSTOEPLITZ > 0
101 #include <net/toeplitz.h>
102 #endif
103 
104 const struct in_addr zeroin_addr;
105 const union inpaddru zeroin46_addr;
106 
107 /*
108  * These configure the range of local port addresses assigned to
109  * "unspecified" outgoing connections/packets/whatever.
110  */
111 int ipport_firstauto = IPPORT_RESERVED;
112 int ipport_lastauto = IPPORT_USERRESERVED;
113 int ipport_hifirstauto = IPPORT_HIFIRSTAUTO;
114 int ipport_hilastauto = IPPORT_HILASTAUTO;
115 
116 struct baddynamicports baddynamicports;
117 struct baddynamicports rootonlyports;
118 struct pool inpcb_pool;
119 
120 void	in_pcbhash_insert(struct inpcb *);
121 struct inpcb *in_pcbhash_lookup(struct inpcbtable *, uint64_t, u_int,
122     const struct in_addr *, u_short, const struct in_addr *, u_short);
123 int	in_pcbresize(struct inpcbtable *, int);
124 
125 #define	INPCBHASH_LOADFACTOR(_x)	(((_x) * 3) / 4)
126 
127 uint64_t in_pcbhash(struct inpcbtable *, u_int,
128     const struct in_addr *, u_short, const struct in_addr *, u_short);
129 uint64_t in_pcblhash(struct inpcbtable *, u_int, u_short);
130 
131 struct inpcb *in_pcblookup_lock(struct inpcbtable *, struct in_addr, u_int,
132     struct in_addr, u_int, u_int, int);
133 int	in_pcbaddrisavail_lock(const struct inpcb *, struct sockaddr_in *, int,
134     struct proc *, int);
135 int	in_pcbpickport(u_int16_t *, const void *, int, const struct inpcb *,
136     struct proc *);
137 
138 /*
139  * in_pcb is used for inet and inet6.  in6_pcb only contains special
140  * IPv6 cases.  So the internet initializer is used for both domains.
141  */
142 void
143 in_init(void)
144 {
145 	pool_init(&inpcb_pool, sizeof(struct inpcb), 0,
146 	    IPL_SOFTNET, 0, "inpcb", NULL);
147 }
148 
149 uint64_t
150 in_pcbhash(struct inpcbtable *table, u_int rdomain,
151     const struct in_addr *faddr, u_short fport,
152     const struct in_addr *laddr, u_short lport)
153 {
154 	SIPHASH_CTX ctx;
155 	u_int32_t nrdom = htonl(rdomain);
156 
157 	SipHash24_Init(&ctx, &table->inpt_key);
158 	SipHash24_Update(&ctx, &nrdom, sizeof(nrdom));
159 	SipHash24_Update(&ctx, faddr, sizeof(*faddr));
160 	SipHash24_Update(&ctx, &fport, sizeof(fport));
161 	SipHash24_Update(&ctx, laddr, sizeof(*laddr));
162 	SipHash24_Update(&ctx, &lport, sizeof(lport));
163 	return SipHash24_End(&ctx);
164 }
165 
166 uint64_t
167 in_pcblhash(struct inpcbtable *table, u_int rdomain, u_short lport)
168 {
169 	SIPHASH_CTX ctx;
170 	u_int32_t nrdom = htonl(rdomain);
171 
172 	SipHash24_Init(&ctx, &table->inpt_lkey);
173 	SipHash24_Update(&ctx, &nrdom, sizeof(nrdom));
174 	SipHash24_Update(&ctx, &lport, sizeof(lport));
175 	return SipHash24_End(&ctx);
176 }
177 
178 void
179 in_pcbinit(struct inpcbtable *table, int hashsize)
180 {
181 	mtx_init(&table->inpt_mtx, IPL_SOFTNET);
182 	TAILQ_INIT(&table->inpt_queue);
183 	table->inpt_hashtbl = hashinit(hashsize, M_PCB, M_WAITOK,
184 	    &table->inpt_mask);
185 	table->inpt_lhashtbl = hashinit(hashsize, M_PCB, M_WAITOK,
186 	    &table->inpt_lmask);
187 	table->inpt_count = 0;
188 	table->inpt_size = hashsize;
189 	arc4random_buf(&table->inpt_key, sizeof(table->inpt_key));
190 	arc4random_buf(&table->inpt_lkey, sizeof(table->inpt_lkey));
191 }
192 
193 /*
194  * Check if the specified port is invalid for dynamic allocation.
195  */
196 int
197 in_baddynamic(u_int16_t port, u_int16_t proto)
198 {
199 	switch (proto) {
200 	case IPPROTO_TCP:
201 		return (DP_ISSET(baddynamicports.tcp, port));
202 	case IPPROTO_UDP:
203 #ifdef IPSEC
204 		/* Cannot preset this as it is a sysctl */
205 		if (port == udpencap_port)
206 			return (1);
207 #endif
208 		return (DP_ISSET(baddynamicports.udp, port));
209 	default:
210 		return (0);
211 	}
212 }
213 
214 int
215 in_rootonly(u_int16_t port, u_int16_t proto)
216 {
217 	switch (proto) {
218 	case IPPROTO_TCP:
219 		return (port < IPPORT_RESERVED ||
220 		    DP_ISSET(rootonlyports.tcp, port));
221 	case IPPROTO_UDP:
222 		return (port < IPPORT_RESERVED ||
223 		    DP_ISSET(rootonlyports.udp, port));
224 	default:
225 		return (0);
226 	}
227 }
228 
229 int
230 in_pcballoc(struct socket *so, struct inpcbtable *table, int wait)
231 {
232 	struct inpcb *inp;
233 
234 	inp = pool_get(&inpcb_pool, (wait == M_WAIT ? PR_WAITOK : PR_NOWAIT) |
235 	    PR_ZERO);
236 	if (inp == NULL)
237 		return (ENOBUFS);
238 	inp->inp_table = table;
239 	inp->inp_socket = so;
240 	mtx_init(&inp->inp_sofree_mtx, IPL_SOFTNET);
241 	refcnt_init_trace(&inp->inp_refcnt, DT_REFCNT_IDX_INPCB);
242 	inp->inp_seclevel.sl_auth = IPSEC_AUTH_LEVEL_DEFAULT;
243 	inp->inp_seclevel.sl_esp_trans = IPSEC_ESP_TRANS_LEVEL_DEFAULT;
244 	inp->inp_seclevel.sl_esp_network = IPSEC_ESP_NETWORK_LEVEL_DEFAULT;
245 	inp->inp_seclevel.sl_ipcomp = IPSEC_IPCOMP_LEVEL_DEFAULT;
246 	inp->inp_rtableid = curproc->p_p->ps_rtableid;
247 	inp->inp_hops = -1;
248 #ifdef INET6
249 	switch (so->so_proto->pr_domain->dom_family) {
250 	case PF_INET6:
251 		inp->inp_flags = INP_IPV6;
252 		break;
253 	case PF_INET:
254 		/* inp->inp_flags is initialized to 0 */
255 		break;
256 	default:
257 		unhandled_af(so->so_proto->pr_domain->dom_family);
258 	}
259 	inp->inp_cksum6 = -1;
260 #endif /* INET6 */
261 
262 	mtx_enter(&table->inpt_mtx);
263 	if (table->inpt_count++ > INPCBHASH_LOADFACTOR(table->inpt_size))
264 		(void)in_pcbresize(table, table->inpt_size * 2);
265 	TAILQ_INSERT_HEAD(&table->inpt_queue, inp, inp_queue);
266 	in_pcbhash_insert(inp);
267 	mtx_leave(&table->inpt_mtx);
268 
269 	so->so_pcb = inp;
270 
271 	return (0);
272 }
273 
274 int
275 in_pcbbind_locked(struct inpcb *inp, struct mbuf *nam, const void *laddr,
276     struct proc *p)
277 {
278 	struct socket *so = inp->inp_socket;
279 	u_int16_t lport = 0;
280 	int wild = 0;
281 	int error;
282 
283 	if (inp->inp_lport)
284 		return (EINVAL);
285 
286 	if ((so->so_options & (SO_REUSEADDR|SO_REUSEPORT)) == 0 &&
287 	    ((so->so_proto->pr_flags & PR_CONNREQUIRED) == 0 ||
288 	     (so->so_options & SO_ACCEPTCONN) == 0))
289 		wild = INPLOOKUP_WILDCARD;
290 
291 #ifdef INET6
292 	if (ISSET(inp->inp_flags, INP_IPV6)) {
293 		if (!IN6_IS_ADDR_UNSPECIFIED(&inp->inp_laddr6))
294 			return (EINVAL);
295 		wild |= INPLOOKUP_IPV6;
296 
297 		if (nam) {
298 			struct sockaddr_in6 *sin6;
299 
300 			if ((error = in6_nam2sin6(nam, &sin6)))
301 				return (error);
302 			if ((error = in6_pcbaddrisavail_lock(inp, sin6, wild,
303 			    p, IN_PCBLOCK_HOLD)))
304 				return (error);
305 			laddr = &sin6->sin6_addr;
306 			lport = sin6->sin6_port;
307 		}
308 	} else
309 #endif
310 	{
311 		if (inp->inp_laddr.s_addr != INADDR_ANY)
312 			return (EINVAL);
313 
314 		if (nam) {
315 			struct sockaddr_in *sin;
316 
317 			if ((error = in_nam2sin(nam, &sin)))
318 				return (error);
319 			if ((error = in_pcbaddrisavail_lock(inp, sin, wild,
320 			    p, IN_PCBLOCK_HOLD)))
321 				return (error);
322 			laddr = &sin->sin_addr;
323 			lport = sin->sin_port;
324 		}
325 	}
326 
327 	if (lport == 0) {
328 		if ((error = in_pcbpickport(&lport, laddr, wild, inp, p)))
329 			return (error);
330 	} else {
331 		if (in_rootonly(ntohs(lport), so->so_proto->pr_protocol) &&
332 		    suser(p) != 0)
333 			return (EACCES);
334 	}
335 	if (nam) {
336 #ifdef INET6
337 		if (ISSET(inp->inp_flags, INP_IPV6))
338 			inp->inp_laddr6 = *(struct in6_addr *)laddr;
339 		else
340 #endif
341 			inp->inp_laddr = *(struct in_addr *)laddr;
342 	}
343 	inp->inp_lport = lport;
344 	in_pcbrehash(inp);
345 
346 	return (0);
347 }
348 
349 int
350 in_pcbbind(struct inpcb *inp, struct mbuf *nam, struct proc *p)
351 {
352 	struct inpcbtable *table = inp->inp_table;
353 	int error;
354 
355 	/* keep lookup, modification, and rehash in sync */
356 	mtx_enter(&table->inpt_mtx);
357 	error = in_pcbbind_locked(inp, nam, &zeroin46_addr, p);
358 	mtx_leave(&table->inpt_mtx);
359 
360 	return error;
361 }
362 
363 int
364 in_pcbaddrisavail_lock(const struct inpcb *inp, struct sockaddr_in *sin,
365     int wild, struct proc *p, int lock)
366 {
367 	struct socket *so = inp->inp_socket;
368 	struct inpcbtable *table = inp->inp_table;
369 	u_int16_t lport = sin->sin_port;
370 	int reuseport = (so->so_options & SO_REUSEPORT);
371 
372 	if (IN_MULTICAST(sin->sin_addr.s_addr)) {
373 		/*
374 		 * Treat SO_REUSEADDR as SO_REUSEPORT for multicast;
375 		 * allow complete duplication of binding if
376 		 * SO_REUSEPORT is set, or if SO_REUSEADDR is set
377 		 * and a multicast address is bound on both
378 		 * new and duplicated sockets.
379 		 */
380 		if (so->so_options & (SO_REUSEADDR|SO_REUSEPORT))
381 			reuseport = SO_REUSEADDR|SO_REUSEPORT;
382 	} else if (sin->sin_addr.s_addr != INADDR_ANY) {
383 		/*
384 		 * we must check that we are binding to an address we
385 		 * own except when:
386 		 * - SO_BINDANY is set or
387 		 * - we are binding a UDP socket to 255.255.255.255 or
388 		 * - we are binding a UDP socket to one of our broadcast
389 		 *   addresses
390 		 */
391 		if (!ISSET(so->so_options, SO_BINDANY) &&
392 		    !(so->so_type == SOCK_DGRAM &&
393 		    sin->sin_addr.s_addr == INADDR_BROADCAST) &&
394 		    !(so->so_type == SOCK_DGRAM &&
395 		    in_broadcast(sin->sin_addr, inp->inp_rtableid))) {
396 			struct ifaddr *ia;
397 
398 			sin->sin_port = 0;
399 			memset(sin->sin_zero, 0, sizeof(sin->sin_zero));
400 			ia = ifa_ifwithaddr(sintosa(sin), inp->inp_rtableid);
401 			sin->sin_port = lport;
402 
403 			if (ia == NULL)
404 				return (EADDRNOTAVAIL);
405 		}
406 	}
407 	if (lport) {
408 		struct inpcb *t;
409 		int error = 0;
410 
411 		if (so->so_euid && !IN_MULTICAST(sin->sin_addr.s_addr)) {
412 			t = in_pcblookup_local_lock(table, &sin->sin_addr,
413 			    lport, INPLOOKUP_WILDCARD, inp->inp_rtableid, lock);
414 			if (t && (so->so_euid != t->inp_socket->so_euid))
415 				error = EADDRINUSE;
416 			if (lock == IN_PCBLOCK_GRAB)
417 				in_pcbunref(t);
418 			if (error)
419 				return (error);
420 		}
421 		t = in_pcblookup_local_lock(table, &sin->sin_addr, lport,
422 		    wild, inp->inp_rtableid, lock);
423 		if (t && (reuseport & t->inp_socket->so_options) == 0)
424 			error = EADDRINUSE;
425 		if (lock == IN_PCBLOCK_GRAB)
426 			in_pcbunref(t);
427 		if (error)
428 			return (error);
429 	}
430 
431 	return (0);
432 }
433 
434 int
435 in_pcbaddrisavail(const struct inpcb *inp, struct sockaddr_in *sin,
436     int wild, struct proc *p)
437 {
438 	return in_pcbaddrisavail_lock(inp, sin, wild, p, IN_PCBLOCK_GRAB);
439 }
440 
441 int
442 in_pcbpickport(u_int16_t *lport, const void *laddr, int wild,
443     const struct inpcb *inp, struct proc *p)
444 {
445 	struct socket *so = inp->inp_socket;
446 	struct inpcbtable *table = inp->inp_table;
447 	struct inpcb *t;
448 	u_int16_t first, last, lower, higher, candidate, localport;
449 	int count;
450 
451 	MUTEX_ASSERT_LOCKED(&table->inpt_mtx);
452 
453 	if (inp->inp_flags & INP_HIGHPORT) {
454 		first = ipport_hifirstauto;	/* sysctl */
455 		last = ipport_hilastauto;
456 	} else if (inp->inp_flags & INP_LOWPORT) {
457 		if (suser(p))
458 			return (EACCES);
459 		first = IPPORT_RESERVED-1; /* 1023 */
460 		last = 600;		   /* not IPPORT_RESERVED/2 */
461 	} else {
462 		first = ipport_firstauto;	/* sysctl */
463 		last = ipport_lastauto;
464 	}
465 	if (first < last) {
466 		lower = first;
467 		higher = last;
468 	} else {
469 		lower = last;
470 		higher = first;
471 	}
472 
473 	/*
474 	 * Simple check to ensure all ports are not used up causing
475 	 * a deadlock here.
476 	 */
477 
478 	count = higher - lower;
479 	candidate = lower + arc4random_uniform(count);
480 
481 	do {
482 		do {
483 			if (count-- < 0)	/* completely used? */
484 				return (EADDRNOTAVAIL);
485 			++candidate;
486 			if (candidate < lower || candidate > higher)
487 				candidate = lower;
488 			localport = htons(candidate);
489 		} while (in_baddynamic(candidate, so->so_proto->pr_protocol));
490 		t = in_pcblookup_local_lock(table, laddr, localport, wild,
491 		    inp->inp_rtableid, IN_PCBLOCK_HOLD);
492 	} while (t != NULL);
493 	*lport = localport;
494 
495 	return (0);
496 }
497 
498 /*
499  * Connect from a socket to a specified address.
500  * Both address and port must be specified in argument sin.
501  * If don't have a local address for this socket yet,
502  * then pick one.
503  */
504 int
505 in_pcbconnect(struct inpcb *inp, struct mbuf *nam)
506 {
507 	struct inpcbtable *table = inp->inp_table;
508 	struct in_addr ina;
509 	struct sockaddr_in *sin;
510 	struct inpcb *t;
511 	int error;
512 
513 #ifdef INET6
514 	if (ISSET(inp->inp_flags, INP_IPV6))
515 		return (in6_pcbconnect(inp, nam));
516 #endif
517 
518 	if ((error = in_nam2sin(nam, &sin)))
519 		return (error);
520 	if (sin->sin_port == 0)
521 		return (EADDRNOTAVAIL);
522 	error = in_pcbselsrc(&ina, sin, inp);
523 	if (error)
524 		return (error);
525 
526 	/* keep lookup, modification, and rehash in sync */
527 	mtx_enter(&table->inpt_mtx);
528 
529 	t = in_pcblookup_lock(inp->inp_table, sin->sin_addr, sin->sin_port,
530 	    ina, inp->inp_lport, inp->inp_rtableid, IN_PCBLOCK_HOLD);
531 	if (t != NULL) {
532 		mtx_leave(&table->inpt_mtx);
533 		return (EADDRINUSE);
534 	}
535 
536 	KASSERT(inp->inp_laddr.s_addr == INADDR_ANY || inp->inp_lport);
537 
538 	if (inp->inp_laddr.s_addr == INADDR_ANY) {
539 		if (inp->inp_lport == 0) {
540 			error = in_pcbbind_locked(inp, NULL, &ina, curproc);
541 			if (error) {
542 				mtx_leave(&table->inpt_mtx);
543 				return (error);
544 			}
545 			t = in_pcblookup_lock(inp->inp_table, sin->sin_addr,
546 			    sin->sin_port, ina, inp->inp_lport,
547 			    inp->inp_rtableid, IN_PCBLOCK_HOLD);
548 			if (t != NULL) {
549 				inp->inp_lport = 0;
550 				mtx_leave(&table->inpt_mtx);
551 				return (EADDRINUSE);
552 			}
553 		}
554 		inp->inp_laddr = ina;
555 	}
556 	inp->inp_faddr = sin->sin_addr;
557 	inp->inp_fport = sin->sin_port;
558 	in_pcbrehash(inp);
559 
560 	mtx_leave(&table->inpt_mtx);
561 
562 #if NSTOEPLITZ > 0
563 	inp->inp_flowid = stoeplitz_ip4port(inp->inp_faddr.s_addr,
564 	    inp->inp_laddr.s_addr, inp->inp_fport, inp->inp_lport);
565 #endif
566 	return (0);
567 }
568 
569 void
570 in_pcbdisconnect(struct inpcb *inp)
571 {
572 #if NPF > 0
573 	pf_remove_divert_state(inp);
574 	pf_inp_unlink(inp);
575 #endif
576 	inp->inp_flowid = 0;
577 	if (inp->inp_socket->so_state & SS_NOFDREF)
578 		in_pcbdetach(inp);
579 }
580 
581 void
582 in_pcbdetach(struct inpcb *inp)
583 {
584 	struct socket *so = inp->inp_socket;
585 	struct inpcbtable *table = inp->inp_table;
586 
587 	so->so_pcb = NULL;
588 	mtx_enter(&inp->inp_sofree_mtx);
589 	inp->inp_socket = NULL;
590 	mtx_leave(&inp->inp_sofree_mtx);
591 	/*
592 	 * As long as the NET_LOCK() is the default lock for Internet
593 	 * sockets, do not release it to not introduce new sleeping
594 	 * points.
595 	 */
596 	sofree(so, 1);
597 	if (inp->inp_route.ro_rt) {
598 		rtfree(inp->inp_route.ro_rt);
599 		inp->inp_route.ro_rt = NULL;
600 	}
601 #ifdef INET6
602 	if (ISSET(inp->inp_flags, INP_IPV6)) {
603 		ip6_freepcbopts(inp->inp_outputopts6);
604 		ip6_freemoptions(inp->inp_moptions6);
605 	} else
606 #endif
607 	{
608 		m_freem(inp->inp_options);
609 		ip_freemoptions(inp->inp_moptions);
610 	}
611 #if NPF > 0
612 	pf_remove_divert_state(inp);
613 	pf_inp_unlink(inp);
614 #endif
615 	mtx_enter(&table->inpt_mtx);
616 	LIST_REMOVE(inp, inp_lhash);
617 	LIST_REMOVE(inp, inp_hash);
618 	TAILQ_REMOVE(&table->inpt_queue, inp, inp_queue);
619 	table->inpt_count--;
620 	mtx_leave(&table->inpt_mtx);
621 
622 	in_pcbunref(inp);
623 }
624 
625 struct socket *
626 in_pcbsolock_ref(struct inpcb *inp)
627 {
628 	struct socket *so;
629 
630 	NET_ASSERT_LOCKED();
631 
632 	mtx_enter(&inp->inp_sofree_mtx);
633 	so = soref(inp->inp_socket);
634 	mtx_leave(&inp->inp_sofree_mtx);
635 	if (so == NULL)
636 		return NULL;
637 	rw_enter_write(&so->so_lock);
638 	return so;
639 }
640 
641 void
642 in_pcbsounlock_rele(struct inpcb *inp, struct socket *so)
643 {
644 	if (so == NULL)
645 		return;
646 	KASSERT(inp->inp_socket == NULL || inp->inp_socket == so);
647 	rw_exit_write(&so->so_lock);
648 	sorele(so);
649 }
650 
651 struct inpcb *
652 in_pcbref(struct inpcb *inp)
653 {
654 	if (inp == NULL)
655 		return NULL;
656 	refcnt_take(&inp->inp_refcnt);
657 	return inp;
658 }
659 
660 void
661 in_pcbunref(struct inpcb *inp)
662 {
663 	if (inp == NULL)
664 		return;
665 	if (refcnt_rele(&inp->inp_refcnt) == 0)
666 		return;
667 	KASSERT((LIST_NEXT(inp, inp_hash) == NULL) ||
668 	    (LIST_NEXT(inp, inp_hash) == _Q_INVALID));
669 	KASSERT((LIST_NEXT(inp, inp_lhash) == NULL) ||
670 	    (LIST_NEXT(inp, inp_lhash) == _Q_INVALID));
671 	KASSERT((TAILQ_NEXT(inp, inp_queue) == NULL) ||
672 	    (TAILQ_NEXT(inp, inp_queue) == _Q_INVALID));
673 	pool_put(&inpcb_pool, inp);
674 }
675 
676 struct inpcb *
677 in_pcb_iterator(struct inpcbtable *table, struct inpcb *inp,
678     struct inpcb_iterator *iter)
679 {
680 	struct inpcb *tmp;
681 
682 	MUTEX_ASSERT_LOCKED(&table->inpt_mtx);
683 
684 	if (inp)
685 		tmp = TAILQ_NEXT((struct inpcb *)iter, inp_queue);
686 	else
687 		tmp = TAILQ_FIRST(&table->inpt_queue);
688 
689 	while (tmp && tmp->inp_table == NULL)
690 		tmp = TAILQ_NEXT(tmp, inp_queue);
691 
692 	if (inp) {
693 		TAILQ_REMOVE(&table->inpt_queue, (struct inpcb *)iter,
694 		    inp_queue);
695 		in_pcbunref(inp);
696 	}
697 	if (tmp) {
698 		TAILQ_INSERT_AFTER(&table->inpt_queue, tmp,
699 		    (struct inpcb *)iter, inp_queue);
700 		in_pcbref(tmp);
701 	}
702 
703 	return tmp;
704 }
705 
706 void
707 in_pcb_iterator_abort(struct inpcbtable *table, struct inpcb *inp,
708     struct inpcb_iterator *iter)
709 {
710 	MUTEX_ASSERT_LOCKED(&table->inpt_mtx);
711 
712 	if (inp) {
713 		TAILQ_REMOVE(&table->inpt_queue, (struct inpcb *)iter,
714 		    inp_queue);
715 		in_pcbunref(inp);
716 	}
717 }
718 
719 void
720 in_setsockaddr(struct inpcb *inp, struct mbuf *nam)
721 {
722 	struct sockaddr_in *sin;
723 
724 #ifdef INET6
725 	if (ISSET(inp->inp_flags, INP_IPV6)) {
726 		in6_setsockaddr(inp, nam);
727 		return;
728 	}
729 #endif
730 
731 	nam->m_len = sizeof(*sin);
732 	sin = mtod(nam, struct sockaddr_in *);
733 	memset(sin, 0, sizeof(*sin));
734 	sin->sin_family = AF_INET;
735 	sin->sin_len = sizeof(*sin);
736 	sin->sin_port = inp->inp_lport;
737 	sin->sin_addr = inp->inp_laddr;
738 }
739 
740 void
741 in_setpeeraddr(struct inpcb *inp, struct mbuf *nam)
742 {
743 	struct sockaddr_in *sin;
744 
745 #ifdef INET6
746 	if (ISSET(inp->inp_flags, INP_IPV6)) {
747 		in6_setpeeraddr(inp, nam);
748 		return;
749 	}
750 #endif
751 
752 	nam->m_len = sizeof(*sin);
753 	sin = mtod(nam, struct sockaddr_in *);
754 	memset(sin, 0, sizeof(*sin));
755 	sin->sin_family = AF_INET;
756 	sin->sin_len = sizeof(*sin);
757 	sin->sin_port = inp->inp_fport;
758 	sin->sin_addr = inp->inp_faddr;
759 }
760 
761 int
762 in_sockaddr(struct socket *so, struct mbuf *nam)
763 {
764 	struct inpcb *inp;
765 
766 	inp = sotoinpcb(so);
767 	in_setsockaddr(inp, nam);
768 
769 	return (0);
770 }
771 
772 int
773 in_peeraddr(struct socket *so, struct mbuf *nam)
774 {
775 	struct inpcb *inp;
776 
777 	inp = sotoinpcb(so);
778 	in_setpeeraddr(inp, nam);
779 
780 	return (0);
781 }
782 
783 /*
784  * Pass some notification to all connections of a protocol
785  * associated with address dst.  The "usual action" will be
786  * taken, depending on the ctlinput cmd.  The caller must filter any
787  * cmds that are uninteresting (e.g., no error in the map).
788  * Call the protocol specific routine (if any) to report
789  * any errors for each matching socket.
790  */
791 void
792 in_pcbnotifyall(struct inpcbtable *table, const struct sockaddr_in *dst,
793     u_int rtable, int errno, void (*notify)(struct inpcb *, int))
794 {
795 	struct inpcb_iterator iter = { .inp_table = NULL };
796 	struct inpcb *inp = NULL;
797 	u_int rdomain;
798 
799 	if (dst->sin_addr.s_addr == INADDR_ANY)
800 		return;
801 	if (notify == NULL)
802 		return;
803 
804 	rdomain = rtable_l2(rtable);
805 	mtx_enter(&table->inpt_mtx);
806 	while ((inp = in_pcb_iterator(table, inp, &iter)) != NULL) {
807 		KASSERT(!ISSET(inp->inp_flags, INP_IPV6));
808 
809 		if (inp->inp_faddr.s_addr != dst->sin_addr.s_addr ||
810 		    rtable_l2(inp->inp_rtableid) != rdomain) {
811 			continue;
812 		}
813 		mtx_leave(&table->inpt_mtx);
814 		(*notify)(inp, errno);
815 		mtx_enter(&table->inpt_mtx);
816 	}
817 	mtx_leave(&table->inpt_mtx);
818 }
819 
820 /*
821  * Check for alternatives when higher level complains
822  * about service problems.  For now, invalidate cached
823  * routing information.  If the route was created dynamically
824  * (by a redirect), time to try a default gateway again.
825  */
826 void
827 in_losing(struct inpcb *inp)
828 {
829 	struct rtentry *rt = inp->inp_route.ro_rt;
830 
831 	if (rt) {
832 		inp->inp_route.ro_rt = NULL;
833 
834 		if (rt->rt_flags & RTF_DYNAMIC) {
835 			struct ifnet *ifp;
836 
837 			ifp = if_get(rt->rt_ifidx);
838 			/*
839 			 * If the interface is gone, all its attached
840 			 * route entries have been removed from the table,
841 			 * so we're dealing with a stale cache and have
842 			 * nothing to do.
843 			 */
844 			if (ifp != NULL)
845 				rtdeletemsg(rt, ifp, inp->inp_rtableid);
846 			if_put(ifp);
847 		}
848 		/*
849 		 * A new route can be allocated
850 		 * the next time output is attempted.
851 		 * rtfree() needs to be called in anycase because the inp
852 		 * is still holding a reference to rt.
853 		 */
854 		rtfree(rt);
855 	}
856 }
857 
858 /*
859  * After a routing change, flush old routing
860  * and allocate a (hopefully) better one.
861  */
862 void
863 in_rtchange(struct inpcb *inp, int errno)
864 {
865 	if (inp->inp_route.ro_rt) {
866 		rtfree(inp->inp_route.ro_rt);
867 		inp->inp_route.ro_rt = NULL;
868 		/*
869 		 * A new route can be allocated the next time
870 		 * output is attempted.
871 		 */
872 	}
873 }
874 
875 struct inpcb *
876 in_pcblookup_local_lock(struct inpcbtable *table, const void *laddrp,
877     u_int lport_arg, int flags, u_int rtable, int lock)
878 {
879 	struct inpcb *inp, *match = NULL;
880 	int matchwild = 3, wildcard;
881 	u_int16_t lport = lport_arg;
882 	const struct in_addr laddr = *(const struct in_addr *)laddrp;
883 #ifdef INET6
884 	const struct in6_addr *laddr6 = (const struct in6_addr *)laddrp;
885 #endif
886 	struct inpcbhead *head;
887 	uint64_t lhash;
888 	u_int rdomain;
889 
890 	rdomain = rtable_l2(rtable);
891 	lhash = in_pcblhash(table, rdomain, lport);
892 
893 	if (lock == IN_PCBLOCK_GRAB) {
894 		mtx_enter(&table->inpt_mtx);
895 	} else {
896 		KASSERT(lock == IN_PCBLOCK_HOLD);
897 		MUTEX_ASSERT_LOCKED(&table->inpt_mtx);
898 	}
899 	head = &table->inpt_lhashtbl[lhash & table->inpt_lmask];
900 	LIST_FOREACH(inp, head, inp_lhash) {
901 		if (rtable_l2(inp->inp_rtableid) != rdomain)
902 			continue;
903 		if (inp->inp_lport != lport)
904 			continue;
905 		wildcard = 0;
906 #ifdef INET6
907 		if (ISSET(flags, INPLOOKUP_IPV6)) {
908 			KASSERT(ISSET(inp->inp_flags, INP_IPV6));
909 
910 			if (!IN6_IS_ADDR_UNSPECIFIED(&inp->inp_faddr6))
911 				wildcard++;
912 
913 			if (!IN6_ARE_ADDR_EQUAL(&inp->inp_laddr6, laddr6)) {
914 				if (IN6_IS_ADDR_UNSPECIFIED(&inp->inp_laddr6) ||
915 				    IN6_IS_ADDR_UNSPECIFIED(laddr6))
916 					wildcard++;
917 				else
918 					continue;
919 			}
920 
921 		} else
922 #endif /* INET6 */
923 		{
924 			KASSERT(!ISSET(inp->inp_flags, INP_IPV6));
925 
926 			if (inp->inp_faddr.s_addr != INADDR_ANY)
927 				wildcard++;
928 
929 			if (inp->inp_laddr.s_addr != laddr.s_addr) {
930 				if (inp->inp_laddr.s_addr == INADDR_ANY ||
931 				    laddr.s_addr == INADDR_ANY)
932 					wildcard++;
933 				else
934 					continue;
935 			}
936 
937 		}
938 		if ((!wildcard || (flags & INPLOOKUP_WILDCARD)) &&
939 		    wildcard < matchwild) {
940 			match = inp;
941 			if ((matchwild = wildcard) == 0)
942 				break;
943 		}
944 	}
945 	if (lock == IN_PCBLOCK_GRAB) {
946 		in_pcbref(match);
947 		mtx_leave(&table->inpt_mtx);
948 	}
949 
950 	return (match);
951 }
952 
953 struct rtentry *
954 in_pcbrtentry(struct inpcb *inp)
955 {
956 	soassertlocked(inp->inp_socket);
957 
958 #ifdef INET6
959 	if (ISSET(inp->inp_flags, INP_IPV6))
960 		return in6_pcbrtentry(inp);
961 #endif
962 
963 	if (inp->inp_faddr.s_addr == INADDR_ANY)
964 		return (NULL);
965 	return (route_mpath(&inp->inp_route, &inp->inp_faddr, &inp->inp_laddr,
966 	    inp->inp_rtableid));
967 }
968 
969 /*
970  * Return an IPv4 address, which is the most appropriate for a given
971  * destination.
972  * If necessary, this function lookups the routing table and returns
973  * an entry to the caller for later use.
974  */
975 int
976 in_pcbselsrc(struct in_addr *insrc, struct sockaddr_in *sin,
977     struct inpcb *inp)
978 {
979 	struct ip_moptions *mopts = inp->inp_moptions;
980 	struct rtentry *rt;
981 	const struct in_addr *laddr = &inp->inp_laddr;
982 	u_int rtableid = inp->inp_rtableid;
983 	struct sockaddr	*ip4_source = NULL;
984 	struct in_ifaddr *ia = NULL;
985 
986 	/*
987 	 * If the socket(if any) is already bound, use that bound address
988 	 * unless it is INADDR_ANY or INADDR_BROADCAST.
989 	 */
990 	if (laddr->s_addr != INADDR_ANY &&
991 	    laddr->s_addr != INADDR_BROADCAST) {
992 		*insrc = *laddr;
993 		return (0);
994 	}
995 
996 	/*
997 	 * If the destination address is multicast or limited
998 	 * broadcast (255.255.255.255) and an outgoing interface has
999 	 * been set as a multicast option, use the address of that
1000 	 * interface as our source address.
1001 	 */
1002 	if ((IN_MULTICAST(sin->sin_addr.s_addr) ||
1003 	    sin->sin_addr.s_addr == INADDR_BROADCAST) && mopts != NULL) {
1004 		struct ifnet *ifp;
1005 
1006 		ifp = if_get(mopts->imo_ifidx);
1007 		if (ifp != NULL) {
1008 			if (ifp->if_rdomain == rtable_l2(rtableid))
1009 				IFP_TO_IA(ifp, ia);
1010 			if (ia == NULL) {
1011 				if_put(ifp);
1012 				return (EADDRNOTAVAIL);
1013 			}
1014 
1015 			*insrc = ia->ia_addr.sin_addr;
1016 			if_put(ifp);
1017 			return (0);
1018 		}
1019 	}
1020 
1021 	/*
1022 	 * If route is known or can be allocated now,
1023 	 * our src addr is taken from the i/f, else punt.
1024 	 */
1025 	rt = route_mpath(&inp->inp_route, &sin->sin_addr, NULL, rtableid);
1026 
1027 	/*
1028 	 * If we found a route, use the address
1029 	 * corresponding to the outgoing interface.
1030 	 */
1031 	if (rt != NULL)
1032 		ia = ifatoia(rt->rt_ifa);
1033 
1034 	/*
1035 	 * Use preferred source address if :
1036 	 * - destination is not onlink
1037 	 * - preferred source address is set
1038 	 * - output interface is UP
1039 	 */
1040 	if (rt != NULL && !(rt->rt_flags & RTF_LLINFO) &&
1041 	    !(rt->rt_flags & RTF_HOST)) {
1042 		ip4_source = rtable_getsource(rtableid, AF_INET);
1043 		if (ip4_source != NULL) {
1044 			struct ifaddr *ifa;
1045 			if ((ifa = ifa_ifwithaddr(ip4_source, rtableid)) !=
1046 			    NULL && ISSET(ifa->ifa_ifp->if_flags, IFF_UP)) {
1047 				*insrc = satosin(ip4_source)->sin_addr;
1048 				return (0);
1049 			}
1050 		}
1051 	}
1052 
1053 	if (ia == NULL)
1054 		return (EADDRNOTAVAIL);
1055 
1056 	*insrc = ia->ia_addr.sin_addr;
1057 	return (0);
1058 }
1059 
1060 void
1061 in_pcbrehash(struct inpcb *inp)
1062 {
1063 	LIST_REMOVE(inp, inp_lhash);
1064 	LIST_REMOVE(inp, inp_hash);
1065 	in_pcbhash_insert(inp);
1066 }
1067 
1068 void
1069 in_pcbhash_insert(struct inpcb *inp)
1070 {
1071 	struct inpcbtable *table = inp->inp_table;
1072 	struct inpcbhead *head;
1073 	uint64_t hash, lhash;
1074 
1075 	MUTEX_ASSERT_LOCKED(&table->inpt_mtx);
1076 
1077 	lhash = in_pcblhash(table, inp->inp_rtableid, inp->inp_lport);
1078 	head = &table->inpt_lhashtbl[lhash & table->inpt_lmask];
1079 	LIST_INSERT_HEAD(head, inp, inp_lhash);
1080 #ifdef INET6
1081 	if (ISSET(inp->inp_flags, INP_IPV6))
1082 		hash = in6_pcbhash(table, rtable_l2(inp->inp_rtableid),
1083 		    &inp->inp_faddr6, inp->inp_fport,
1084 		    &inp->inp_laddr6, inp->inp_lport);
1085 	else
1086 #endif
1087 		hash = in_pcbhash(table, rtable_l2(inp->inp_rtableid),
1088 		    &inp->inp_faddr, inp->inp_fport,
1089 		    &inp->inp_laddr, inp->inp_lport);
1090 	head = &table->inpt_hashtbl[hash & table->inpt_mask];
1091 	LIST_INSERT_HEAD(head, inp, inp_hash);
1092 }
1093 
1094 struct inpcb *
1095 in_pcbhash_lookup(struct inpcbtable *table, uint64_t hash, u_int rdomain,
1096     const struct in_addr *faddr, u_short fport,
1097     const struct in_addr *laddr, u_short lport)
1098 {
1099 	struct inpcbhead *head;
1100 	struct inpcb *inp;
1101 
1102 	MUTEX_ASSERT_LOCKED(&table->inpt_mtx);
1103 
1104 	head = &table->inpt_hashtbl[hash & table->inpt_mask];
1105 	LIST_FOREACH(inp, head, inp_hash) {
1106 		KASSERT(!ISSET(inp->inp_flags, INP_IPV6));
1107 
1108 		if (inp->inp_fport == fport && inp->inp_lport == lport &&
1109 		    inp->inp_faddr.s_addr == faddr->s_addr &&
1110 		    inp->inp_laddr.s_addr == laddr->s_addr &&
1111 		    rtable_l2(inp->inp_rtableid) == rdomain) {
1112 			break;
1113 		}
1114 	}
1115 	if (inp != NULL) {
1116 		/*
1117 		 * Move this PCB to the head of hash chain so that
1118 		 * repeated accesses are quicker.  This is analogous to
1119 		 * the historic single-entry PCB cache.
1120 		 */
1121 		if (inp != LIST_FIRST(head)) {
1122 			LIST_REMOVE(inp, inp_hash);
1123 			LIST_INSERT_HEAD(head, inp, inp_hash);
1124 		}
1125 	}
1126 	return (inp);
1127 }
1128 
1129 int
1130 in_pcbresize(struct inpcbtable *table, int hashsize)
1131 {
1132 	u_long nmask, nlmask;
1133 	int osize;
1134 	void *nhashtbl, *nlhashtbl, *ohashtbl, *olhashtbl;
1135 	struct inpcb *inp;
1136 
1137 	MUTEX_ASSERT_LOCKED(&table->inpt_mtx);
1138 
1139 	ohashtbl = table->inpt_hashtbl;
1140 	olhashtbl = table->inpt_lhashtbl;
1141 	osize = table->inpt_size;
1142 
1143 	nhashtbl = hashinit(hashsize, M_PCB, M_NOWAIT, &nmask);
1144 	if (nhashtbl == NULL)
1145 		return ENOBUFS;
1146 	nlhashtbl = hashinit(hashsize, M_PCB, M_NOWAIT, &nlmask);
1147 	if (nlhashtbl == NULL) {
1148 		hashfree(nhashtbl, hashsize, M_PCB);
1149 		return ENOBUFS;
1150 	}
1151 	table->inpt_hashtbl = nhashtbl;
1152 	table->inpt_lhashtbl = nlhashtbl;
1153 	table->inpt_mask = nmask;
1154 	table->inpt_lmask = nlmask;
1155 	table->inpt_size = hashsize;
1156 
1157 	TAILQ_FOREACH(inp, &table->inpt_queue, inp_queue) {
1158 		if (in_pcb_is_iterator(inp))
1159 			continue;
1160 		LIST_REMOVE(inp, inp_lhash);
1161 		LIST_REMOVE(inp, inp_hash);
1162 		in_pcbhash_insert(inp);
1163 	}
1164 	hashfree(ohashtbl, osize, M_PCB);
1165 	hashfree(olhashtbl, osize, M_PCB);
1166 
1167 	return (0);
1168 }
1169 
1170 #ifdef DIAGNOSTIC
1171 int	in_pcbnotifymiss = 0;
1172 #endif
1173 
1174 /*
1175  * The in(6)_pcblookup functions are used to locate connected sockets
1176  * quickly:
1177  *     faddr.fport <-> laddr.lport
1178  * No wildcard matching is done so that listening sockets are not found.
1179  * If the functions return NULL in(6)_pcblookup_listen can be used to
1180  * find a listening/bound socket that may accept the connection.
1181  * After those two lookups no other are necessary.
1182  */
1183 struct inpcb *
1184 in_pcblookup_lock(struct inpcbtable *table, struct in_addr faddr,
1185     u_int fport, struct in_addr laddr, u_int lport, u_int rtable, int lock)
1186 {
1187 	struct inpcb *inp;
1188 	uint64_t hash;
1189 	u_int rdomain;
1190 
1191 	rdomain = rtable_l2(rtable);
1192 	hash = in_pcbhash(table, rdomain, &faddr, fport, &laddr, lport);
1193 
1194 	if (lock == IN_PCBLOCK_GRAB) {
1195 		mtx_enter(&table->inpt_mtx);
1196 	} else {
1197 		KASSERT(lock == IN_PCBLOCK_HOLD);
1198 		MUTEX_ASSERT_LOCKED(&table->inpt_mtx);
1199 	}
1200 	inp = in_pcbhash_lookup(table, hash, rdomain,
1201 	    &faddr, fport, &laddr, lport);
1202 	if (lock == IN_PCBLOCK_GRAB) {
1203 		in_pcbref(inp);
1204 		mtx_leave(&table->inpt_mtx);
1205 	}
1206 
1207 #ifdef DIAGNOSTIC
1208 	if (inp == NULL && in_pcbnotifymiss) {
1209 		printf("%s: faddr=%08x fport=%d laddr=%08x lport=%d rdom=%u\n",
1210 		    __func__, ntohl(faddr.s_addr), ntohs(fport),
1211 		    ntohl(laddr.s_addr), ntohs(lport), rdomain);
1212 	}
1213 #endif
1214 	return (inp);
1215 }
1216 
1217 struct inpcb *
1218 in_pcblookup(struct inpcbtable *table, struct in_addr faddr,
1219     u_int fport, struct in_addr laddr, u_int lport, u_int rtable)
1220 {
1221 	return in_pcblookup_lock(table, faddr, fport, laddr, lport, rtable,
1222 	    IN_PCBLOCK_GRAB);
1223 }
1224 
1225 /*
1226  * The in(6)_pcblookup_listen functions are used to locate listening
1227  * sockets quickly.  This are sockets with unspecified foreign address
1228  * and port:
1229  *		*.*     <-> laddr.lport
1230  *		*.*     <->     *.lport
1231  */
1232 struct inpcb *
1233 in_pcblookup_listen(struct inpcbtable *table, struct in_addr laddr,
1234     u_int lport_arg, struct mbuf *m, u_int rtable)
1235 {
1236 	const struct in_addr *key1, *key2;
1237 	struct inpcb *inp;
1238 	uint64_t hash;
1239 	u_int16_t lport = lport_arg;
1240 	u_int rdomain;
1241 
1242 	key1 = &laddr;
1243 	key2 = &zeroin_addr;
1244 #if NPF > 0
1245 	if (m && m->m_pkthdr.pf.flags & PF_TAG_DIVERTED) {
1246 		struct pf_divert *divert;
1247 
1248 		divert = pf_find_divert(m);
1249 		KASSERT(divert != NULL);
1250 		switch (divert->type) {
1251 		case PF_DIVERT_TO:
1252 			key1 = key2 = &divert->addr.v4;
1253 			lport = divert->port;
1254 			break;
1255 		case PF_DIVERT_REPLY:
1256 			return (NULL);
1257 		default:
1258 			panic("%s: unknown divert type %d, mbuf %p, divert %p",
1259 			    __func__, divert->type, m, divert);
1260 		}
1261 	} else if (m && m->m_pkthdr.pf.flags & PF_TAG_TRANSLATE_LOCALHOST) {
1262 		/*
1263 		 * Redirected connections should not be treated the same
1264 		 * as connections directed to 127.0.0.0/8 since localhost
1265 		 * can only be accessed from the host itself.
1266 		 * For example portmap(8) grants more permissions for
1267 		 * connections to the socket bound to 127.0.0.1 than
1268 		 * to the * socket.
1269 		 */
1270 		key1 = &zeroin_addr;
1271 		key2 = &laddr;
1272 	}
1273 #endif
1274 
1275 	rdomain = rtable_l2(rtable);
1276 	hash = in_pcbhash(table, rdomain, &zeroin_addr, 0, key1, lport);
1277 
1278 	mtx_enter(&table->inpt_mtx);
1279 	inp = in_pcbhash_lookup(table, hash, rdomain,
1280 	    &zeroin_addr, 0, key1, lport);
1281 	if (inp == NULL && key1->s_addr != key2->s_addr) {
1282 		hash = in_pcbhash(table, rdomain,
1283 		    &zeroin_addr, 0, key2, lport);
1284 		inp = in_pcbhash_lookup(table, hash, rdomain,
1285 		    &zeroin_addr, 0, key2, lport);
1286 	}
1287 	in_pcbref(inp);
1288 	mtx_leave(&table->inpt_mtx);
1289 
1290 #ifdef DIAGNOSTIC
1291 	if (inp == NULL && in_pcbnotifymiss) {
1292 		printf("%s: laddr=%08x lport=%d rdom=%u\n",
1293 		    __func__, ntohl(laddr.s_addr), ntohs(lport), rdomain);
1294 	}
1295 #endif
1296 	return (inp);
1297 }
1298 
1299 int
1300 in_pcbset_rtableid(struct inpcb *inp, u_int rtableid)
1301 {
1302 	struct inpcbtable *table = inp->inp_table;
1303 
1304 	/* table must exist */
1305 	if (!rtable_exists(rtableid))
1306 		return (EINVAL);
1307 
1308 	mtx_enter(&table->inpt_mtx);
1309 	if (inp->inp_lport) {
1310 		mtx_leave(&table->inpt_mtx);
1311 		return (EBUSY);
1312 	}
1313 	inp->inp_rtableid = rtableid;
1314 	in_pcbrehash(inp);
1315 	mtx_leave(&table->inpt_mtx);
1316 
1317 	return (0);
1318 }
1319 
1320 void
1321 in_pcbset_laddr(struct inpcb *inp, const struct sockaddr *sa, u_int rtableid)
1322 {
1323 	struct inpcbtable *table = inp->inp_table;
1324 
1325 	mtx_enter(&table->inpt_mtx);
1326 	inp->inp_rtableid = rtableid;
1327 #ifdef INET6
1328 	if (ISSET(inp->inp_flags, INP_IPV6)) {
1329 		const struct sockaddr_in6 *sin6;
1330 
1331 		KASSERT(sa->sa_family == AF_INET6);
1332 		sin6 = satosin6_const(sa);
1333 		inp->inp_lport = sin6->sin6_port;
1334 		inp->inp_laddr6 = sin6->sin6_addr;
1335 	} else
1336 #endif
1337 	{
1338 		const struct sockaddr_in *sin;
1339 
1340 		KASSERT(sa->sa_family == AF_INET);
1341 		sin = satosin_const(sa);
1342 		inp->inp_lport = sin->sin_port;
1343 		inp->inp_laddr = sin->sin_addr;
1344 	}
1345 	in_pcbrehash(inp);
1346 	mtx_leave(&table->inpt_mtx);
1347 }
1348 
1349 void
1350 in_pcbunset_faddr(struct inpcb *inp)
1351 {
1352 	struct inpcbtable *table = inp->inp_table;
1353 
1354 	mtx_enter(&table->inpt_mtx);
1355 #ifdef INET6
1356 	if (ISSET(inp->inp_flags, INP_IPV6))
1357 		inp->inp_faddr6 = in6addr_any;
1358 	else
1359 #endif
1360 		inp->inp_faddr.s_addr = INADDR_ANY;
1361 	inp->inp_fport = 0;
1362 	in_pcbrehash(inp);
1363 	mtx_leave(&table->inpt_mtx);
1364 }
1365 
1366 void
1367 in_pcbunset_laddr(struct inpcb *inp)
1368 {
1369 	struct inpcbtable *table = inp->inp_table;
1370 
1371 	mtx_enter(&table->inpt_mtx);
1372 #ifdef INET6
1373 	if (ISSET(inp->inp_flags, INP_IPV6)) {
1374 		inp->inp_faddr6 = in6addr_any;
1375 		inp->inp_laddr6 = in6addr_any;
1376 	} else
1377 #endif
1378 	{
1379 		inp->inp_faddr.s_addr = INADDR_ANY;
1380 		inp->inp_laddr.s_addr = INADDR_ANY;
1381 	}
1382 	inp->inp_fport = 0;
1383 	in_pcbrehash(inp);
1384 	mtx_leave(&table->inpt_mtx);
1385 }
1386