1 /*	$OpenBSD: in_pcb.c,v 1.311 2025/02/05 10:15:10 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
in_init(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
in_pcbhash(struct inpcbtable * table,u_int rdomain,const struct in_addr * faddr,u_short fport,const struct in_addr * laddr,u_short lport)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
in_pcblhash(struct inpcbtable * table,u_int rdomain,u_short lport)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
in_pcbinit(struct inpcbtable * table,int hashsize)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
in_baddynamic(u_int16_t port,u_int16_t proto)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
in_rootonly(u_int16_t port,u_int16_t proto)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
in_pcballoc(struct socket * so,struct inpcbtable * table,int wait)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
in_pcbbind_locked(struct inpcb * inp,struct mbuf * nam,const void * laddr,struct proc * p)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
in_pcbbind(struct inpcb * inp,struct mbuf * nam,struct proc * p)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
in_pcbaddrisavail_lock(const struct inpcb * inp,struct sockaddr_in * sin,int wild,struct proc * p,int lock)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
in_pcbaddrisavail(const struct inpcb * inp,struct sockaddr_in * sin,int wild,struct proc * p)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
in_pcbpickport(u_int16_t * lport,const void * laddr,int wild,const struct inpcb * inp,struct proc * p)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
in_pcbconnect(struct inpcb * inp,struct mbuf * nam)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
in_pcbdisconnect(struct inpcb * inp)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
in_pcbdetach(struct inpcb * inp)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 *
in_pcbsolock_ref(struct inpcb * inp)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 	/* between mutex and rwlock inpcb could be detached */
639 	if (so->so_pcb == NULL) {
640 		rw_exit_write(&so->so_lock);
641 		sorele(so);
642 		return NULL;
643 	}
644 	KASSERT(inp->inp_socket == so && sotoinpcb(so) == inp);
645 	return so;
646 }
647 
648 void
in_pcbsounlock_rele(struct inpcb * inp,struct socket * so)649 in_pcbsounlock_rele(struct inpcb *inp, struct socket *so)
650 {
651 	if (so == NULL)
652 		return;
653 	rw_exit_write(&so->so_lock);
654 	sorele(so);
655 }
656 
657 struct inpcb *
in_pcbref(struct inpcb * inp)658 in_pcbref(struct inpcb *inp)
659 {
660 	if (inp == NULL)
661 		return NULL;
662 	refcnt_take(&inp->inp_refcnt);
663 	return inp;
664 }
665 
666 void
in_pcbunref(struct inpcb * inp)667 in_pcbunref(struct inpcb *inp)
668 {
669 	if (inp == NULL)
670 		return;
671 	if (refcnt_rele(&inp->inp_refcnt) == 0)
672 		return;
673 	KASSERT((LIST_NEXT(inp, inp_hash) == NULL) ||
674 	    (LIST_NEXT(inp, inp_hash) == _Q_INVALID));
675 	KASSERT((LIST_NEXT(inp, inp_lhash) == NULL) ||
676 	    (LIST_NEXT(inp, inp_lhash) == _Q_INVALID));
677 	KASSERT((TAILQ_NEXT(inp, inp_queue) == NULL) ||
678 	    (TAILQ_NEXT(inp, inp_queue) == _Q_INVALID));
679 	pool_put(&inpcb_pool, inp);
680 }
681 
682 struct inpcb *
in_pcb_iterator(struct inpcbtable * table,struct inpcb * inp,struct inpcb_iterator * iter)683 in_pcb_iterator(struct inpcbtable *table, struct inpcb *inp,
684     struct inpcb_iterator *iter)
685 {
686 	struct inpcb *tmp;
687 
688 	MUTEX_ASSERT_LOCKED(&table->inpt_mtx);
689 
690 	if (inp)
691 		tmp = TAILQ_NEXT((struct inpcb *)iter, inp_queue);
692 	else
693 		tmp = TAILQ_FIRST(&table->inpt_queue);
694 
695 	while (tmp && tmp->inp_table == NULL)
696 		tmp = TAILQ_NEXT(tmp, inp_queue);
697 
698 	if (inp) {
699 		TAILQ_REMOVE(&table->inpt_queue, (struct inpcb *)iter,
700 		    inp_queue);
701 		in_pcbunref(inp);
702 	}
703 	if (tmp) {
704 		TAILQ_INSERT_AFTER(&table->inpt_queue, tmp,
705 		    (struct inpcb *)iter, inp_queue);
706 		in_pcbref(tmp);
707 	}
708 
709 	return tmp;
710 }
711 
712 void
in_pcb_iterator_abort(struct inpcbtable * table,struct inpcb * inp,struct inpcb_iterator * iter)713 in_pcb_iterator_abort(struct inpcbtable *table, struct inpcb *inp,
714     struct inpcb_iterator *iter)
715 {
716 	MUTEX_ASSERT_LOCKED(&table->inpt_mtx);
717 
718 	if (inp) {
719 		TAILQ_REMOVE(&table->inpt_queue, (struct inpcb *)iter,
720 		    inp_queue);
721 		in_pcbunref(inp);
722 	}
723 }
724 
725 void
in_setsockaddr(struct inpcb * inp,struct mbuf * nam)726 in_setsockaddr(struct inpcb *inp, struct mbuf *nam)
727 {
728 	struct sockaddr_in *sin;
729 
730 #ifdef INET6
731 	if (ISSET(inp->inp_flags, INP_IPV6)) {
732 		in6_setsockaddr(inp, nam);
733 		return;
734 	}
735 #endif
736 
737 	nam->m_len = sizeof(*sin);
738 	sin = mtod(nam, struct sockaddr_in *);
739 	memset(sin, 0, sizeof(*sin));
740 	sin->sin_family = AF_INET;
741 	sin->sin_len = sizeof(*sin);
742 	sin->sin_port = inp->inp_lport;
743 	sin->sin_addr = inp->inp_laddr;
744 }
745 
746 void
in_setpeeraddr(struct inpcb * inp,struct mbuf * nam)747 in_setpeeraddr(struct inpcb *inp, struct mbuf *nam)
748 {
749 	struct sockaddr_in *sin;
750 
751 #ifdef INET6
752 	if (ISSET(inp->inp_flags, INP_IPV6)) {
753 		in6_setpeeraddr(inp, nam);
754 		return;
755 	}
756 #endif
757 
758 	nam->m_len = sizeof(*sin);
759 	sin = mtod(nam, struct sockaddr_in *);
760 	memset(sin, 0, sizeof(*sin));
761 	sin->sin_family = AF_INET;
762 	sin->sin_len = sizeof(*sin);
763 	sin->sin_port = inp->inp_fport;
764 	sin->sin_addr = inp->inp_faddr;
765 }
766 
767 int
in_sockaddr(struct socket * so,struct mbuf * nam)768 in_sockaddr(struct socket *so, struct mbuf *nam)
769 {
770 	struct inpcb *inp;
771 
772 	inp = sotoinpcb(so);
773 	in_setsockaddr(inp, nam);
774 
775 	return (0);
776 }
777 
778 int
in_peeraddr(struct socket * so,struct mbuf * nam)779 in_peeraddr(struct socket *so, struct mbuf *nam)
780 {
781 	struct inpcb *inp;
782 
783 	inp = sotoinpcb(so);
784 	in_setpeeraddr(inp, nam);
785 
786 	return (0);
787 }
788 
789 /*
790  * Pass some notification to all connections of a protocol
791  * associated with address dst.  The "usual action" will be
792  * taken, depending on the ctlinput cmd.  The caller must filter any
793  * cmds that are uninteresting (e.g., no error in the map).
794  * Call the protocol specific routine (if any) to report
795  * any errors for each matching socket.
796  */
797 void
in_pcbnotifyall(struct inpcbtable * table,const struct sockaddr_in * dst,u_int rtable,int errno,void (* notify)(struct inpcb *,int))798 in_pcbnotifyall(struct inpcbtable *table, const struct sockaddr_in *dst,
799     u_int rtable, int errno, void (*notify)(struct inpcb *, int))
800 {
801 	struct inpcb_iterator iter = { .inp_table = NULL };
802 	struct inpcb *inp = NULL;
803 	u_int rdomain;
804 
805 	if (dst->sin_addr.s_addr == INADDR_ANY)
806 		return;
807 	if (notify == NULL)
808 		return;
809 
810 	rdomain = rtable_l2(rtable);
811 	mtx_enter(&table->inpt_mtx);
812 	while ((inp = in_pcb_iterator(table, inp, &iter)) != NULL) {
813 		KASSERT(!ISSET(inp->inp_flags, INP_IPV6));
814 
815 		if (inp->inp_faddr.s_addr != dst->sin_addr.s_addr ||
816 		    rtable_l2(inp->inp_rtableid) != rdomain) {
817 			continue;
818 		}
819 		mtx_leave(&table->inpt_mtx);
820 		(*notify)(inp, errno);
821 		mtx_enter(&table->inpt_mtx);
822 	}
823 	mtx_leave(&table->inpt_mtx);
824 }
825 
826 /*
827  * Check for alternatives when higher level complains
828  * about service problems.  For now, invalidate cached
829  * routing information.  If the route was created dynamically
830  * (by a redirect), time to try a default gateway again.
831  */
832 void
in_losing(struct inpcb * inp)833 in_losing(struct inpcb *inp)
834 {
835 	struct rtentry *rt = inp->inp_route.ro_rt;
836 
837 	if (rt) {
838 		inp->inp_route.ro_rt = NULL;
839 
840 		if (rt->rt_flags & RTF_DYNAMIC) {
841 			struct ifnet *ifp;
842 
843 			ifp = if_get(rt->rt_ifidx);
844 			/*
845 			 * If the interface is gone, all its attached
846 			 * route entries have been removed from the table,
847 			 * so we're dealing with a stale cache and have
848 			 * nothing to do.
849 			 */
850 			if (ifp != NULL)
851 				rtdeletemsg(rt, ifp, inp->inp_rtableid);
852 			if_put(ifp);
853 		}
854 		/*
855 		 * A new route can be allocated
856 		 * the next time output is attempted.
857 		 * rtfree() needs to be called in anycase because the inp
858 		 * is still holding a reference to rt.
859 		 */
860 		rtfree(rt);
861 	}
862 }
863 
864 /*
865  * After a routing change, flush old routing
866  * and allocate a (hopefully) better one.
867  */
868 void
in_rtchange(struct inpcb * inp,int errno)869 in_rtchange(struct inpcb *inp, int errno)
870 {
871 	if (inp->inp_route.ro_rt) {
872 		rtfree(inp->inp_route.ro_rt);
873 		inp->inp_route.ro_rt = NULL;
874 		/*
875 		 * A new route can be allocated the next time
876 		 * output is attempted.
877 		 */
878 	}
879 }
880 
881 struct inpcb *
in_pcblookup_local_lock(struct inpcbtable * table,const void * laddrp,u_int lport_arg,int flags,u_int rtable,int lock)882 in_pcblookup_local_lock(struct inpcbtable *table, const void *laddrp,
883     u_int lport_arg, int flags, u_int rtable, int lock)
884 {
885 	struct inpcb *inp, *match = NULL;
886 	int matchwild = 3, wildcard;
887 	u_int16_t lport = lport_arg;
888 	const struct in_addr laddr = *(const struct in_addr *)laddrp;
889 #ifdef INET6
890 	const struct in6_addr *laddr6 = (const struct in6_addr *)laddrp;
891 #endif
892 	struct inpcbhead *head;
893 	uint64_t lhash;
894 	u_int rdomain;
895 
896 	rdomain = rtable_l2(rtable);
897 	lhash = in_pcblhash(table, rdomain, lport);
898 
899 	if (lock == IN_PCBLOCK_GRAB) {
900 		mtx_enter(&table->inpt_mtx);
901 	} else {
902 		KASSERT(lock == IN_PCBLOCK_HOLD);
903 		MUTEX_ASSERT_LOCKED(&table->inpt_mtx);
904 	}
905 	head = &table->inpt_lhashtbl[lhash & table->inpt_lmask];
906 	LIST_FOREACH(inp, head, inp_lhash) {
907 		if (rtable_l2(inp->inp_rtableid) != rdomain)
908 			continue;
909 		if (inp->inp_lport != lport)
910 			continue;
911 		wildcard = 0;
912 #ifdef INET6
913 		if (ISSET(flags, INPLOOKUP_IPV6)) {
914 			KASSERT(ISSET(inp->inp_flags, INP_IPV6));
915 
916 			if (!IN6_IS_ADDR_UNSPECIFIED(&inp->inp_faddr6))
917 				wildcard++;
918 
919 			if (!IN6_ARE_ADDR_EQUAL(&inp->inp_laddr6, laddr6)) {
920 				if (IN6_IS_ADDR_UNSPECIFIED(&inp->inp_laddr6) ||
921 				    IN6_IS_ADDR_UNSPECIFIED(laddr6))
922 					wildcard++;
923 				else
924 					continue;
925 			}
926 
927 		} else
928 #endif /* INET6 */
929 		{
930 			KASSERT(!ISSET(inp->inp_flags, INP_IPV6));
931 
932 			if (inp->inp_faddr.s_addr != INADDR_ANY)
933 				wildcard++;
934 
935 			if (inp->inp_laddr.s_addr != laddr.s_addr) {
936 				if (inp->inp_laddr.s_addr == INADDR_ANY ||
937 				    laddr.s_addr == INADDR_ANY)
938 					wildcard++;
939 				else
940 					continue;
941 			}
942 
943 		}
944 		if ((!wildcard || (flags & INPLOOKUP_WILDCARD)) &&
945 		    wildcard < matchwild) {
946 			match = inp;
947 			if ((matchwild = wildcard) == 0)
948 				break;
949 		}
950 	}
951 	if (lock == IN_PCBLOCK_GRAB) {
952 		in_pcbref(match);
953 		mtx_leave(&table->inpt_mtx);
954 	}
955 
956 	return (match);
957 }
958 
959 struct rtentry *
in_pcbrtentry(struct inpcb * inp)960 in_pcbrtentry(struct inpcb *inp)
961 {
962 	soassertlocked(inp->inp_socket);
963 
964 #ifdef INET6
965 	if (ISSET(inp->inp_flags, INP_IPV6))
966 		return in6_pcbrtentry(inp);
967 #endif
968 
969 	if (inp->inp_faddr.s_addr == INADDR_ANY)
970 		return (NULL);
971 	return (route_mpath(&inp->inp_route, &inp->inp_faddr, &inp->inp_laddr,
972 	    inp->inp_rtableid));
973 }
974 
975 /*
976  * Return an IPv4 address, which is the most appropriate for a given
977  * destination.
978  * If necessary, this function lookups the routing table and returns
979  * an entry to the caller for later use.
980  */
981 int
in_pcbselsrc(struct in_addr * insrc,struct sockaddr_in * sin,struct inpcb * inp)982 in_pcbselsrc(struct in_addr *insrc, struct sockaddr_in *sin,
983     struct inpcb *inp)
984 {
985 	struct ip_moptions *mopts = inp->inp_moptions;
986 	struct rtentry *rt;
987 	const struct in_addr *laddr = &inp->inp_laddr;
988 	u_int rtableid = inp->inp_rtableid;
989 	struct sockaddr	*ip4_source = NULL;
990 	struct in_ifaddr *ia = NULL;
991 
992 	/*
993 	 * If the socket(if any) is already bound, use that bound address
994 	 * unless it is INADDR_ANY or INADDR_BROADCAST.
995 	 */
996 	if (laddr->s_addr != INADDR_ANY &&
997 	    laddr->s_addr != INADDR_BROADCAST) {
998 		*insrc = *laddr;
999 		return (0);
1000 	}
1001 
1002 	/*
1003 	 * If the destination address is multicast or limited
1004 	 * broadcast (255.255.255.255) and an outgoing interface has
1005 	 * been set as a multicast option, use the address of that
1006 	 * interface as our source address.
1007 	 */
1008 	if ((IN_MULTICAST(sin->sin_addr.s_addr) ||
1009 	    sin->sin_addr.s_addr == INADDR_BROADCAST) && mopts != NULL) {
1010 		struct ifnet *ifp;
1011 
1012 		ifp = if_get(mopts->imo_ifidx);
1013 		if (ifp != NULL) {
1014 			if (ifp->if_rdomain == rtable_l2(rtableid))
1015 				IFP_TO_IA(ifp, ia);
1016 			if (ia == NULL) {
1017 				if_put(ifp);
1018 				return (EADDRNOTAVAIL);
1019 			}
1020 
1021 			*insrc = ia->ia_addr.sin_addr;
1022 			if_put(ifp);
1023 			return (0);
1024 		}
1025 	}
1026 
1027 	/*
1028 	 * If route is known or can be allocated now,
1029 	 * our src addr is taken from the i/f, else punt.
1030 	 */
1031 	rt = route_mpath(&inp->inp_route, &sin->sin_addr, NULL, rtableid);
1032 
1033 	/*
1034 	 * If we found a route, use the address
1035 	 * corresponding to the outgoing interface.
1036 	 */
1037 	if (rt != NULL)
1038 		ia = ifatoia(rt->rt_ifa);
1039 
1040 	/*
1041 	 * Use preferred source address if :
1042 	 * - destination is not onlink
1043 	 * - preferred source address is set
1044 	 * - output interface is UP
1045 	 */
1046 	if (rt != NULL && !(rt->rt_flags & RTF_LLINFO) &&
1047 	    !(rt->rt_flags & RTF_HOST)) {
1048 		ip4_source = rtable_getsource(rtableid, AF_INET);
1049 		if (ip4_source != NULL) {
1050 			struct ifaddr *ifa;
1051 			if ((ifa = ifa_ifwithaddr(ip4_source, rtableid)) !=
1052 			    NULL && ISSET(ifa->ifa_ifp->if_flags, IFF_UP)) {
1053 				*insrc = satosin(ip4_source)->sin_addr;
1054 				return (0);
1055 			}
1056 		}
1057 	}
1058 
1059 	if (ia == NULL)
1060 		return (EADDRNOTAVAIL);
1061 
1062 	*insrc = ia->ia_addr.sin_addr;
1063 	return (0);
1064 }
1065 
1066 void
in_pcbrehash(struct inpcb * inp)1067 in_pcbrehash(struct inpcb *inp)
1068 {
1069 	LIST_REMOVE(inp, inp_lhash);
1070 	LIST_REMOVE(inp, inp_hash);
1071 	in_pcbhash_insert(inp);
1072 }
1073 
1074 void
in_pcbhash_insert(struct inpcb * inp)1075 in_pcbhash_insert(struct inpcb *inp)
1076 {
1077 	struct inpcbtable *table = inp->inp_table;
1078 	struct inpcbhead *head;
1079 	uint64_t hash, lhash;
1080 
1081 	MUTEX_ASSERT_LOCKED(&table->inpt_mtx);
1082 
1083 	lhash = in_pcblhash(table, inp->inp_rtableid, inp->inp_lport);
1084 	head = &table->inpt_lhashtbl[lhash & table->inpt_lmask];
1085 	LIST_INSERT_HEAD(head, inp, inp_lhash);
1086 #ifdef INET6
1087 	if (ISSET(inp->inp_flags, INP_IPV6))
1088 		hash = in6_pcbhash(table, rtable_l2(inp->inp_rtableid),
1089 		    &inp->inp_faddr6, inp->inp_fport,
1090 		    &inp->inp_laddr6, inp->inp_lport);
1091 	else
1092 #endif
1093 		hash = in_pcbhash(table, rtable_l2(inp->inp_rtableid),
1094 		    &inp->inp_faddr, inp->inp_fport,
1095 		    &inp->inp_laddr, inp->inp_lport);
1096 	head = &table->inpt_hashtbl[hash & table->inpt_mask];
1097 	LIST_INSERT_HEAD(head, inp, inp_hash);
1098 }
1099 
1100 struct inpcb *
in_pcbhash_lookup(struct inpcbtable * table,uint64_t hash,u_int rdomain,const struct in_addr * faddr,u_short fport,const struct in_addr * laddr,u_short lport)1101 in_pcbhash_lookup(struct inpcbtable *table, uint64_t hash, u_int rdomain,
1102     const struct in_addr *faddr, u_short fport,
1103     const struct in_addr *laddr, u_short lport)
1104 {
1105 	struct inpcbhead *head;
1106 	struct inpcb *inp;
1107 
1108 	MUTEX_ASSERT_LOCKED(&table->inpt_mtx);
1109 
1110 	head = &table->inpt_hashtbl[hash & table->inpt_mask];
1111 	LIST_FOREACH(inp, head, inp_hash) {
1112 		KASSERT(!ISSET(inp->inp_flags, INP_IPV6));
1113 
1114 		if (inp->inp_fport == fport && inp->inp_lport == lport &&
1115 		    inp->inp_faddr.s_addr == faddr->s_addr &&
1116 		    inp->inp_laddr.s_addr == laddr->s_addr &&
1117 		    rtable_l2(inp->inp_rtableid) == rdomain) {
1118 			break;
1119 		}
1120 	}
1121 	if (inp != NULL) {
1122 		/*
1123 		 * Move this PCB to the head of hash chain so that
1124 		 * repeated accesses are quicker.  This is analogous to
1125 		 * the historic single-entry PCB cache.
1126 		 */
1127 		if (inp != LIST_FIRST(head)) {
1128 			LIST_REMOVE(inp, inp_hash);
1129 			LIST_INSERT_HEAD(head, inp, inp_hash);
1130 		}
1131 	}
1132 	return (inp);
1133 }
1134 
1135 int
in_pcbresize(struct inpcbtable * table,int hashsize)1136 in_pcbresize(struct inpcbtable *table, int hashsize)
1137 {
1138 	u_long nmask, nlmask;
1139 	int osize;
1140 	void *nhashtbl, *nlhashtbl, *ohashtbl, *olhashtbl;
1141 	struct inpcb *inp;
1142 
1143 	MUTEX_ASSERT_LOCKED(&table->inpt_mtx);
1144 
1145 	ohashtbl = table->inpt_hashtbl;
1146 	olhashtbl = table->inpt_lhashtbl;
1147 	osize = table->inpt_size;
1148 
1149 	nhashtbl = hashinit(hashsize, M_PCB, M_NOWAIT, &nmask);
1150 	if (nhashtbl == NULL)
1151 		return ENOBUFS;
1152 	nlhashtbl = hashinit(hashsize, M_PCB, M_NOWAIT, &nlmask);
1153 	if (nlhashtbl == NULL) {
1154 		hashfree(nhashtbl, hashsize, M_PCB);
1155 		return ENOBUFS;
1156 	}
1157 	table->inpt_hashtbl = nhashtbl;
1158 	table->inpt_lhashtbl = nlhashtbl;
1159 	table->inpt_mask = nmask;
1160 	table->inpt_lmask = nlmask;
1161 	table->inpt_size = hashsize;
1162 
1163 	TAILQ_FOREACH(inp, &table->inpt_queue, inp_queue) {
1164 		if (in_pcb_is_iterator(inp))
1165 			continue;
1166 		LIST_REMOVE(inp, inp_lhash);
1167 		LIST_REMOVE(inp, inp_hash);
1168 		in_pcbhash_insert(inp);
1169 	}
1170 	hashfree(ohashtbl, osize, M_PCB);
1171 	hashfree(olhashtbl, osize, M_PCB);
1172 
1173 	return (0);
1174 }
1175 
1176 #ifdef DIAGNOSTIC
1177 int	in_pcbnotifymiss = 0;
1178 #endif
1179 
1180 /*
1181  * The in(6)_pcblookup functions are used to locate connected sockets
1182  * quickly:
1183  *     faddr.fport <-> laddr.lport
1184  * No wildcard matching is done so that listening sockets are not found.
1185  * If the functions return NULL in(6)_pcblookup_listen can be used to
1186  * find a listening/bound socket that may accept the connection.
1187  * After those two lookups no other are necessary.
1188  */
1189 struct inpcb *
in_pcblookup_lock(struct inpcbtable * table,struct in_addr faddr,u_int fport,struct in_addr laddr,u_int lport,u_int rtable,int lock)1190 in_pcblookup_lock(struct inpcbtable *table, struct in_addr faddr,
1191     u_int fport, struct in_addr laddr, u_int lport, u_int rtable, int lock)
1192 {
1193 	struct inpcb *inp;
1194 	uint64_t hash;
1195 	u_int rdomain;
1196 
1197 	rdomain = rtable_l2(rtable);
1198 	hash = in_pcbhash(table, rdomain, &faddr, fport, &laddr, lport);
1199 
1200 	if (lock == IN_PCBLOCK_GRAB) {
1201 		mtx_enter(&table->inpt_mtx);
1202 	} else {
1203 		KASSERT(lock == IN_PCBLOCK_HOLD);
1204 		MUTEX_ASSERT_LOCKED(&table->inpt_mtx);
1205 	}
1206 	inp = in_pcbhash_lookup(table, hash, rdomain,
1207 	    &faddr, fport, &laddr, lport);
1208 	if (lock == IN_PCBLOCK_GRAB) {
1209 		in_pcbref(inp);
1210 		mtx_leave(&table->inpt_mtx);
1211 	}
1212 
1213 #ifdef DIAGNOSTIC
1214 	if (inp == NULL && in_pcbnotifymiss) {
1215 		printf("%s: faddr=%08x fport=%d laddr=%08x lport=%d rdom=%u\n",
1216 		    __func__, ntohl(faddr.s_addr), ntohs(fport),
1217 		    ntohl(laddr.s_addr), ntohs(lport), rdomain);
1218 	}
1219 #endif
1220 	return (inp);
1221 }
1222 
1223 struct inpcb *
in_pcblookup(struct inpcbtable * table,struct in_addr faddr,u_int fport,struct in_addr laddr,u_int lport,u_int rtable)1224 in_pcblookup(struct inpcbtable *table, struct in_addr faddr,
1225     u_int fport, struct in_addr laddr, u_int lport, u_int rtable)
1226 {
1227 	return in_pcblookup_lock(table, faddr, fport, laddr, lport, rtable,
1228 	    IN_PCBLOCK_GRAB);
1229 }
1230 
1231 /*
1232  * The in(6)_pcblookup_listen functions are used to locate listening
1233  * sockets quickly.  This are sockets with unspecified foreign address
1234  * and port:
1235  *		*.*     <-> laddr.lport
1236  *		*.*     <->     *.lport
1237  */
1238 struct inpcb *
in_pcblookup_listen(struct inpcbtable * table,struct in_addr laddr,u_int lport_arg,struct mbuf * m,u_int rtable)1239 in_pcblookup_listen(struct inpcbtable *table, struct in_addr laddr,
1240     u_int lport_arg, struct mbuf *m, u_int rtable)
1241 {
1242 	const struct in_addr *key1, *key2;
1243 	struct inpcb *inp;
1244 	uint64_t hash;
1245 	u_int16_t lport = lport_arg;
1246 	u_int rdomain;
1247 
1248 	key1 = &laddr;
1249 	key2 = &zeroin_addr;
1250 #if NPF > 0
1251 	if (m && m->m_pkthdr.pf.flags & PF_TAG_DIVERTED) {
1252 		struct pf_divert *divert;
1253 
1254 		divert = pf_find_divert(m);
1255 		KASSERT(divert != NULL);
1256 		switch (divert->type) {
1257 		case PF_DIVERT_TO:
1258 			key1 = key2 = &divert->addr.v4;
1259 			lport = divert->port;
1260 			break;
1261 		case PF_DIVERT_REPLY:
1262 			return (NULL);
1263 		default:
1264 			panic("%s: unknown divert type %d, mbuf %p, divert %p",
1265 			    __func__, divert->type, m, divert);
1266 		}
1267 	} else if (m && m->m_pkthdr.pf.flags & PF_TAG_TRANSLATE_LOCALHOST) {
1268 		/*
1269 		 * Redirected connections should not be treated the same
1270 		 * as connections directed to 127.0.0.0/8 since localhost
1271 		 * can only be accessed from the host itself.
1272 		 * For example portmap(8) grants more permissions for
1273 		 * connections to the socket bound to 127.0.0.1 than
1274 		 * to the * socket.
1275 		 */
1276 		key1 = &zeroin_addr;
1277 		key2 = &laddr;
1278 	}
1279 #endif
1280 
1281 	rdomain = rtable_l2(rtable);
1282 	hash = in_pcbhash(table, rdomain, &zeroin_addr, 0, key1, lport);
1283 
1284 	mtx_enter(&table->inpt_mtx);
1285 	inp = in_pcbhash_lookup(table, hash, rdomain,
1286 	    &zeroin_addr, 0, key1, lport);
1287 	if (inp == NULL && key1->s_addr != key2->s_addr) {
1288 		hash = in_pcbhash(table, rdomain,
1289 		    &zeroin_addr, 0, key2, lport);
1290 		inp = in_pcbhash_lookup(table, hash, rdomain,
1291 		    &zeroin_addr, 0, key2, lport);
1292 	}
1293 	in_pcbref(inp);
1294 	mtx_leave(&table->inpt_mtx);
1295 
1296 #ifdef DIAGNOSTIC
1297 	if (inp == NULL && in_pcbnotifymiss) {
1298 		printf("%s: laddr=%08x lport=%d rdom=%u\n",
1299 		    __func__, ntohl(laddr.s_addr), ntohs(lport), rdomain);
1300 	}
1301 #endif
1302 	return (inp);
1303 }
1304 
1305 int
in_pcbset_rtableid(struct inpcb * inp,u_int rtableid)1306 in_pcbset_rtableid(struct inpcb *inp, u_int rtableid)
1307 {
1308 	struct inpcbtable *table = inp->inp_table;
1309 
1310 	/* table must exist */
1311 	if (!rtable_exists(rtableid))
1312 		return (EINVAL);
1313 
1314 	mtx_enter(&table->inpt_mtx);
1315 	if (inp->inp_lport) {
1316 		mtx_leave(&table->inpt_mtx);
1317 		return (EBUSY);
1318 	}
1319 	inp->inp_rtableid = rtableid;
1320 	in_pcbrehash(inp);
1321 	mtx_leave(&table->inpt_mtx);
1322 
1323 	return (0);
1324 }
1325 
1326 void
in_pcbset_laddr(struct inpcb * inp,const struct sockaddr * sa,u_int rtableid)1327 in_pcbset_laddr(struct inpcb *inp, const struct sockaddr *sa, u_int rtableid)
1328 {
1329 	struct inpcbtable *table = inp->inp_table;
1330 
1331 	mtx_enter(&table->inpt_mtx);
1332 	inp->inp_rtableid = rtableid;
1333 #ifdef INET6
1334 	if (ISSET(inp->inp_flags, INP_IPV6)) {
1335 		const struct sockaddr_in6 *sin6;
1336 
1337 		KASSERT(sa->sa_family == AF_INET6);
1338 		sin6 = satosin6_const(sa);
1339 		inp->inp_lport = sin6->sin6_port;
1340 		inp->inp_laddr6 = sin6->sin6_addr;
1341 	} else
1342 #endif
1343 	{
1344 		const struct sockaddr_in *sin;
1345 
1346 		KASSERT(sa->sa_family == AF_INET);
1347 		sin = satosin_const(sa);
1348 		inp->inp_lport = sin->sin_port;
1349 		inp->inp_laddr = sin->sin_addr;
1350 	}
1351 	in_pcbrehash(inp);
1352 	mtx_leave(&table->inpt_mtx);
1353 }
1354 
1355 void
in_pcbunset_faddr(struct inpcb * inp)1356 in_pcbunset_faddr(struct inpcb *inp)
1357 {
1358 	struct inpcbtable *table = inp->inp_table;
1359 
1360 	mtx_enter(&table->inpt_mtx);
1361 #ifdef INET6
1362 	if (ISSET(inp->inp_flags, INP_IPV6))
1363 		inp->inp_faddr6 = in6addr_any;
1364 	else
1365 #endif
1366 		inp->inp_faddr.s_addr = INADDR_ANY;
1367 	inp->inp_fport = 0;
1368 	in_pcbrehash(inp);
1369 	mtx_leave(&table->inpt_mtx);
1370 }
1371 
1372 void
in_pcbunset_laddr(struct inpcb * inp)1373 in_pcbunset_laddr(struct inpcb *inp)
1374 {
1375 	struct inpcbtable *table = inp->inp_table;
1376 
1377 	mtx_enter(&table->inpt_mtx);
1378 #ifdef INET6
1379 	if (ISSET(inp->inp_flags, INP_IPV6)) {
1380 		inp->inp_faddr6 = in6addr_any;
1381 		inp->inp_laddr6 = in6addr_any;
1382 	} else
1383 #endif
1384 	{
1385 		inp->inp_faddr.s_addr = INADDR_ANY;
1386 		inp->inp_laddr.s_addr = INADDR_ANY;
1387 	}
1388 	inp->inp_fport = 0;
1389 	in_pcbrehash(inp);
1390 	mtx_leave(&table->inpt_mtx);
1391 }
1392