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