xref: /freebsd/sys/netinet6/in6_pcb.c (revision 577b62c2bacc7dfa228591ca3da361e1bc398301)
1 /*-
2  * SPDX-License-Identifier: BSD-3-Clause
3  *
4  * Copyright (C) 1995, 1996, 1997, and 1998 WIDE Project.
5  * Copyright (c) 2010-2011 Juniper Networks, Inc.
6  * All rights reserved.
7  *
8  * Portions of this software were developed by Robert N. M. Watson under
9  * contract to Juniper Networks, Inc.
10  *
11  * Redistribution and use in source and binary forms, with or without
12  * modification, are permitted provided that the following conditions
13  * are met:
14  * 1. Redistributions of source code must retain the above copyright
15  *    notice, this list of conditions and the following disclaimer.
16  * 2. Redistributions in binary form must reproduce the above copyright
17  *    notice, this list of conditions and the following disclaimer in the
18  *    documentation and/or other materials provided with the distribution.
19  * 3. Neither the name of the project nor the names of its contributors
20  *    may be used to endorse or promote products derived from this software
21  *    without specific prior written permission.
22  *
23  * THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND
24  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
25  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
26  * ARE DISCLAIMED.  IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE
27  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
28  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
29  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
30  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
31  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
32  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
33  * SUCH DAMAGE.
34  *
35  *	$KAME: in6_pcb.c,v 1.31 2001/05/21 05:45:10 jinmei Exp $
36  */
37 
38 /*-
39  * Copyright (c) 1982, 1986, 1991, 1993
40  *	The Regents of the University of California.  All rights reserved.
41  *
42  * Redistribution and use in source and binary forms, with or without
43  * modification, are permitted provided that the following conditions
44  * are met:
45  * 1. Redistributions of source code must retain the above copyright
46  *    notice, this list of conditions and the following disclaimer.
47  * 2. Redistributions in binary form must reproduce the above copyright
48  *    notice, this list of conditions and the following disclaimer in the
49  *    documentation and/or other materials provided with the distribution.
50  * 3. Neither the name of the University nor the names of its contributors
51  *    may be used to endorse or promote products derived from this software
52  *    without specific prior written permission.
53  *
54  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
55  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
56  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
57  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
58  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
59  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
60  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
61  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
62  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
63  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
64  * SUCH DAMAGE.
65  *
66  *	@(#)in_pcb.c	8.2 (Berkeley) 1/4/94
67  */
68 
69 #include <sys/cdefs.h>
70 __FBSDID("$FreeBSD$");
71 
72 #include "opt_inet.h"
73 #include "opt_inet6.h"
74 #include "opt_ipsec.h"
75 #include "opt_route.h"
76 #include "opt_rss.h"
77 
78 #include <sys/hash.h>
79 #include <sys/param.h>
80 #include <sys/systm.h>
81 #include <sys/malloc.h>
82 #include <sys/mbuf.h>
83 #include <sys/domain.h>
84 #include <sys/protosw.h>
85 #include <sys/socket.h>
86 #include <sys/socketvar.h>
87 #include <sys/sockio.h>
88 #include <sys/errno.h>
89 #include <sys/time.h>
90 #include <sys/priv.h>
91 #include <sys/proc.h>
92 #include <sys/jail.h>
93 
94 #include <vm/uma.h>
95 
96 #include <net/if.h>
97 #include <net/if_var.h>
98 #include <net/if_llatbl.h>
99 #include <net/if_types.h>
100 #include <net/route.h>
101 #include <net/route/nhop.h>
102 
103 #include <netinet/in.h>
104 #include <netinet/in_var.h>
105 #include <netinet/in_systm.h>
106 #include <netinet/ip6.h>
107 #include <netinet/ip_var.h>
108 
109 #include <netinet6/ip6_var.h>
110 #include <netinet6/nd6.h>
111 #include <netinet/in_pcb.h>
112 #include <netinet/in_pcb_var.h>
113 #include <netinet6/in6_pcb.h>
114 #include <netinet6/in6_fib.h>
115 #include <netinet6/scope6_var.h>
116 
117 int
118 in6_pcbsetport(struct in6_addr *laddr, struct inpcb *inp, struct ucred *cred)
119 {
120 	struct socket *so = inp->inp_socket;
121 	u_int16_t lport = 0;
122 	int error, lookupflags = 0;
123 #ifdef INVARIANTS
124 	struct inpcbinfo *pcbinfo = inp->inp_pcbinfo;
125 #endif
126 
127 	INP_WLOCK_ASSERT(inp);
128 	INP_HASH_WLOCK_ASSERT(pcbinfo);
129 
130 	error = prison_local_ip6(cred, laddr,
131 	    ((inp->inp_flags & IN6P_IPV6_V6ONLY) != 0));
132 	if (error)
133 		return(error);
134 
135 	/* XXX: this is redundant when called from in6_pcbbind */
136 	if ((so->so_options & (SO_REUSEADDR|SO_REUSEPORT|SO_REUSEPORT_LB)) == 0)
137 		lookupflags = INPLOOKUP_WILDCARD;
138 
139 	inp->inp_flags |= INP_ANONPORT;
140 
141 	error = in_pcb_lport(inp, NULL, &lport, cred, lookupflags);
142 	if (error != 0)
143 		return (error);
144 
145 	inp->inp_lport = lport;
146 	if (in_pcbinshash(inp) != 0) {
147 		inp->in6p_laddr = in6addr_any;
148 		inp->inp_lport = 0;
149 		return (EAGAIN);
150 	}
151 
152 	return (0);
153 }
154 
155 int
156 in6_pcbbind(struct inpcb *inp, struct sockaddr_in6 *sin6, struct ucred *cred)
157 {
158 	struct socket *so = inp->inp_socket;
159 	struct inpcbinfo *pcbinfo = inp->inp_pcbinfo;
160 	u_short	lport = 0;
161 	int error, lookupflags = 0;
162 	int reuseport = (so->so_options & SO_REUSEPORT);
163 
164 	/*
165 	 * XXX: Maybe we could let SO_REUSEPORT_LB set SO_REUSEPORT bit here
166 	 * so that we don't have to add to the (already messy) code below.
167 	 */
168 	int reuseport_lb = (so->so_options & SO_REUSEPORT_LB);
169 
170 	INP_WLOCK_ASSERT(inp);
171 	INP_HASH_WLOCK_ASSERT(pcbinfo);
172 
173 	if (inp->inp_lport || !IN6_IS_ADDR_UNSPECIFIED(&inp->in6p_laddr))
174 		return (EINVAL);
175 	if ((so->so_options & (SO_REUSEADDR|SO_REUSEPORT|SO_REUSEPORT_LB)) == 0)
176 		lookupflags = INPLOOKUP_WILDCARD;
177 	if (sin6 == NULL) {
178 		if ((error = prison_local_ip6(cred, &inp->in6p_laddr,
179 		    ((inp->inp_flags & IN6P_IPV6_V6ONLY) != 0))) != 0)
180 			return (error);
181 	} else {
182 		KASSERT(sin6->sin6_family == AF_INET6,
183 		    ("%s: invalid address family for %p", __func__, sin6));
184 		KASSERT(sin6->sin6_len == sizeof(*sin6),
185 		    ("%s: invalid address length for %p", __func__, sin6));
186 
187 		if ((error = sa6_embedscope(sin6, V_ip6_use_defzone)) != 0)
188 			return(error);
189 
190 		if ((error = prison_local_ip6(cred, &sin6->sin6_addr,
191 		    ((inp->inp_flags & IN6P_IPV6_V6ONLY) != 0))) != 0)
192 			return (error);
193 
194 		lport = sin6->sin6_port;
195 		if (IN6_IS_ADDR_MULTICAST(&sin6->sin6_addr)) {
196 			/*
197 			 * Treat SO_REUSEADDR as SO_REUSEPORT for multicast;
198 			 * allow compepte duplication of binding if
199 			 * SO_REUSEPORT is set, or if SO_REUSEADDR is set
200 			 * and a multicast address is bound on both
201 			 * new and duplicated sockets.
202 			 */
203 			if ((so->so_options & (SO_REUSEADDR|SO_REUSEPORT)) != 0)
204 				reuseport = SO_REUSEADDR|SO_REUSEPORT;
205 			/*
206 			 * XXX: How to deal with SO_REUSEPORT_LB here?
207 			 * Treat same as SO_REUSEPORT for now.
208 			 */
209 			if ((so->so_options &
210 			    (SO_REUSEADDR|SO_REUSEPORT_LB)) != 0)
211 				reuseport_lb = SO_REUSEADDR|SO_REUSEPORT_LB;
212 		} else if (!IN6_IS_ADDR_UNSPECIFIED(&sin6->sin6_addr)) {
213 			struct epoch_tracker et;
214 			struct ifaddr *ifa;
215 
216 			sin6->sin6_port = 0;		/* yech... */
217 			NET_EPOCH_ENTER(et);
218 			if ((ifa = ifa_ifwithaddr((struct sockaddr *)sin6)) ==
219 			    NULL &&
220 			    (inp->inp_flags & INP_BINDANY) == 0) {
221 				NET_EPOCH_EXIT(et);
222 				return (EADDRNOTAVAIL);
223 			}
224 
225 			/*
226 			 * XXX: bind to an anycast address might accidentally
227 			 * cause sending a packet with anycast source address.
228 			 * We should allow to bind to a deprecated address, since
229 			 * the application dares to use it.
230 			 */
231 			if (ifa != NULL &&
232 			    ((struct in6_ifaddr *)ifa)->ia6_flags &
233 			    (IN6_IFF_ANYCAST|IN6_IFF_NOTREADY|IN6_IFF_DETACHED)) {
234 				NET_EPOCH_EXIT(et);
235 				return (EADDRNOTAVAIL);
236 			}
237 			NET_EPOCH_EXIT(et);
238 		}
239 		if (lport) {
240 			struct inpcb *t;
241 
242 			/* GROSS */
243 			if (ntohs(lport) <= V_ipport_reservedhigh &&
244 			    ntohs(lport) >= V_ipport_reservedlow &&
245 			    priv_check_cred(cred, PRIV_NETINET_RESERVEDPORT))
246 				return (EACCES);
247 			if (!IN6_IS_ADDR_MULTICAST(&sin6->sin6_addr) &&
248 			    priv_check_cred(inp->inp_cred, PRIV_NETINET_REUSEPORT) != 0) {
249 				t = in6_pcblookup_local(pcbinfo,
250 				    &sin6->sin6_addr, lport,
251 				    INPLOOKUP_WILDCARD, cred);
252 				if (t != NULL &&
253 				    (so->so_type != SOCK_STREAM ||
254 				     IN6_IS_ADDR_UNSPECIFIED(&t->in6p_faddr)) &&
255 				    (!IN6_IS_ADDR_UNSPECIFIED(&sin6->sin6_addr) ||
256 				     !IN6_IS_ADDR_UNSPECIFIED(&t->in6p_laddr) ||
257 				     (t->inp_flags2 & INP_REUSEPORT) ||
258 				     (t->inp_flags2 & INP_REUSEPORT_LB) == 0) &&
259 				    (inp->inp_cred->cr_uid !=
260 				     t->inp_cred->cr_uid))
261 					return (EADDRINUSE);
262 
263 #ifdef INET
264 				if ((inp->inp_flags & IN6P_IPV6_V6ONLY) == 0 &&
265 				    IN6_IS_ADDR_UNSPECIFIED(&sin6->sin6_addr)) {
266 					struct sockaddr_in sin;
267 
268 					in6_sin6_2_sin(&sin, sin6);
269 					t = in_pcblookup_local(pcbinfo,
270 					    sin.sin_addr, lport,
271 					    INPLOOKUP_WILDCARD, cred);
272 					if (t != NULL &&
273 					    (so->so_type != SOCK_STREAM ||
274 					     ntohl(t->inp_faddr.s_addr) ==
275 					      INADDR_ANY) &&
276 					    (inp->inp_cred->cr_uid !=
277 					     t->inp_cred->cr_uid))
278 						return (EADDRINUSE);
279 				}
280 #endif
281 			}
282 			t = in6_pcblookup_local(pcbinfo, &sin6->sin6_addr,
283 			    lport, lookupflags, cred);
284 			if (t && (reuseport & inp_so_options(t)) == 0 &&
285 			    (reuseport_lb & inp_so_options(t)) == 0) {
286 				return (EADDRINUSE);
287 			}
288 #ifdef INET
289 			if ((inp->inp_flags & IN6P_IPV6_V6ONLY) == 0 &&
290 			    IN6_IS_ADDR_UNSPECIFIED(&sin6->sin6_addr)) {
291 				struct sockaddr_in sin;
292 
293 				in6_sin6_2_sin(&sin, sin6);
294 				t = in_pcblookup_local(pcbinfo, sin.sin_addr,
295 				   lport, lookupflags, cred);
296 				if (t &&
297 				    (reuseport & inp_so_options(t)) == 0 &&
298 				    (reuseport_lb & inp_so_options(t)) == 0 &&
299 				    (ntohl(t->inp_laddr.s_addr) != INADDR_ANY ||
300 				        (t->inp_vflag & INP_IPV6PROTO) != 0)) {
301 					return (EADDRINUSE);
302 				}
303 			}
304 #endif
305 		}
306 		inp->in6p_laddr = sin6->sin6_addr;
307 	}
308 	if (lport == 0) {
309 		if ((error = in6_pcbsetport(&inp->in6p_laddr, inp, cred)) != 0) {
310 			/* Undo an address bind that may have occurred. */
311 			inp->in6p_laddr = in6addr_any;
312 			return (error);
313 		}
314 	} else {
315 		inp->inp_lport = lport;
316 		if (in_pcbinshash(inp) != 0) {
317 			inp->in6p_laddr = in6addr_any;
318 			inp->inp_lport = 0;
319 			return (EAGAIN);
320 		}
321 	}
322 	return (0);
323 }
324 
325 /*
326  *   Transform old in6_pcbconnect() into an inner subroutine for new
327  *   in6_pcbconnect(): Do some validity-checking on the remote
328  *   address (in mbuf 'nam') and then determine local host address
329  *   (i.e., which interface) to use to access that remote host.
330  *
331  *   This preserves definition of in6_pcbconnect(), while supporting a
332  *   slightly different version for T/TCP.  (This is more than
333  *   a bit of a kludge, but cleaning up the internal interfaces would
334  *   have forced minor changes in every protocol).
335  */
336 static int
337 in6_pcbladdr(struct inpcb *inp, struct sockaddr_in6 *sin6,
338     struct in6_addr *plocal_addr6)
339 {
340 	int error = 0;
341 	int scope_ambiguous = 0;
342 	struct in6_addr in6a;
343 
344 	NET_EPOCH_ASSERT();
345 	INP_WLOCK_ASSERT(inp);
346 	INP_HASH_WLOCK_ASSERT(inp->inp_pcbinfo);	/* XXXRW: why? */
347 
348 	if (sin6->sin6_port == 0)
349 		return (EADDRNOTAVAIL);
350 
351 	if (sin6->sin6_scope_id == 0 && !V_ip6_use_defzone)
352 		scope_ambiguous = 1;
353 	if ((error = sa6_embedscope(sin6, V_ip6_use_defzone)) != 0)
354 		return(error);
355 
356 	if (!CK_STAILQ_EMPTY(&V_in6_ifaddrhead)) {
357 		/*
358 		 * If the destination address is UNSPECIFIED addr,
359 		 * use the loopback addr, e.g ::1.
360 		 */
361 		if (IN6_IS_ADDR_UNSPECIFIED(&sin6->sin6_addr))
362 			sin6->sin6_addr = in6addr_loopback;
363 	}
364 	if ((error = prison_remote_ip6(inp->inp_cred, &sin6->sin6_addr)) != 0)
365 		return (error);
366 
367 	error = in6_selectsrc_socket(sin6, inp->in6p_outputopts,
368 	    inp, inp->inp_cred, scope_ambiguous, &in6a, NULL);
369 	if (error)
370 		return (error);
371 
372 	/*
373 	 * Do not update this earlier, in case we return with an error.
374 	 *
375 	 * XXX: this in6_selectsrc_socket result might replace the bound local
376 	 * address with the address specified by setsockopt(IPV6_PKTINFO).
377 	 * Is it the intended behavior?
378 	 */
379 	*plocal_addr6 = in6a;
380 
381 	/*
382 	 * Don't do pcblookup call here; return interface in
383 	 * plocal_addr6
384 	 * and exit to caller, that will do the lookup.
385 	 */
386 
387 	return (0);
388 }
389 
390 /*
391  * Outer subroutine:
392  * Connect from a socket to a specified address.
393  * Both address and port must be specified in argument sin.
394  * If don't have a local address for this socket yet,
395  * then pick one.
396  */
397 int
398 in6_pcbconnect(struct inpcb *inp, struct sockaddr_in6 *sin6, struct ucred *cred,
399     bool rehash)
400 {
401 	struct inpcbinfo *pcbinfo = inp->inp_pcbinfo;
402 	struct sockaddr_in6 laddr6;
403 	int error;
404 
405 	NET_EPOCH_ASSERT();
406 	INP_WLOCK_ASSERT(inp);
407 	INP_HASH_WLOCK_ASSERT(pcbinfo);
408 	KASSERT(sin6->sin6_family == AF_INET6,
409 	    ("%s: invalid address family for %p", __func__, sin6));
410 	KASSERT(sin6->sin6_len == sizeof(*sin6),
411 	    ("%s: invalid address length for %p", __func__, sin6));
412 
413 	bzero(&laddr6, sizeof(laddr6));
414 	laddr6.sin6_family = AF_INET6;
415 
416 #ifdef ROUTE_MPATH
417 	if (CALC_FLOWID_OUTBOUND) {
418 		uint32_t hash_type, hash_val;
419 
420 		hash_val = fib6_calc_software_hash(&inp->in6p_laddr,
421 		    &sin6->sin6_addr, 0, sin6->sin6_port,
422 		    inp->inp_socket->so_proto->pr_protocol, &hash_type);
423 		inp->inp_flowid = hash_val;
424 		inp->inp_flowtype = hash_type;
425 	}
426 #endif
427 	/*
428 	 * Call inner routine, to assign local interface address.
429 	 * in6_pcbladdr() may automatically fill in sin6_scope_id.
430 	 */
431 	if ((error = in6_pcbladdr(inp, sin6, &laddr6.sin6_addr)) != 0)
432 		return (error);
433 
434 	if (in6_pcblookup_hash_locked(pcbinfo, &sin6->sin6_addr,
435 	    sin6->sin6_port, IN6_IS_ADDR_UNSPECIFIED(&inp->in6p_laddr) ?
436 	    &laddr6.sin6_addr : &inp->in6p_laddr, inp->inp_lport, 0,
437 	    M_NODOM) != NULL)
438 		return (EADDRINUSE);
439 	if (IN6_IS_ADDR_UNSPECIFIED(&inp->in6p_laddr)) {
440 		if (inp->inp_lport == 0) {
441 			/*
442 			 * rehash was required to be true in the past for
443 			 * this case; retain that convention.  However,
444 			 * we now call in_pcb_lport_dest rather than
445 			 * in6_pcbbind; the former does not insert into
446 			 * the hash table, the latter does.  Change rehash
447 			 * to false to do the in_pcbinshash below.
448 			 */
449 			KASSERT(rehash == true,
450 			    ("Rehashing required for unbound inps"));
451 			rehash = false;
452 			error = in_pcb_lport_dest(inp,
453 			    (struct sockaddr *) &laddr6, &inp->inp_lport,
454 			    (struct sockaddr *) sin6, sin6->sin6_port, cred,
455 			    INPLOOKUP_WILDCARD);
456 			if (error)
457 				return (error);
458 		}
459 		inp->in6p_laddr = laddr6.sin6_addr;
460 	}
461 	inp->in6p_faddr = sin6->sin6_addr;
462 	inp->inp_fport = sin6->sin6_port;
463 	/* update flowinfo - draft-itojun-ipv6-flowlabel-api-00 */
464 	inp->inp_flow &= ~IPV6_FLOWLABEL_MASK;
465 	if (inp->inp_flags & IN6P_AUTOFLOWLABEL)
466 		inp->inp_flow |=
467 		    (htonl(ip6_randomflowlabel()) & IPV6_FLOWLABEL_MASK);
468 
469 	if (rehash) {
470 		in_pcbrehash(inp);
471 	} else {
472 		in_pcbinshash(inp);
473 	}
474 
475 	return (0);
476 }
477 
478 void
479 in6_pcbdisconnect(struct inpcb *inp)
480 {
481 
482 	INP_WLOCK_ASSERT(inp);
483 	INP_HASH_WLOCK_ASSERT(inp->inp_pcbinfo);
484 
485 	memset(&inp->in6p_laddr, 0, sizeof(inp->in6p_laddr));
486 	memset(&inp->in6p_faddr, 0, sizeof(inp->in6p_faddr));
487 	inp->inp_fport = 0;
488 	/* clear flowinfo - draft-itojun-ipv6-flowlabel-api-00 */
489 	inp->inp_flow &= ~IPV6_FLOWLABEL_MASK;
490 	in_pcbrehash(inp);
491 }
492 
493 struct sockaddr *
494 in6_sockaddr(in_port_t port, struct in6_addr *addr_p)
495 {
496 	struct sockaddr_in6 *sin6;
497 
498 	sin6 = malloc(sizeof *sin6, M_SONAME, M_WAITOK);
499 	bzero(sin6, sizeof *sin6);
500 	sin6->sin6_family = AF_INET6;
501 	sin6->sin6_len = sizeof(*sin6);
502 	sin6->sin6_port = port;
503 	sin6->sin6_addr = *addr_p;
504 	(void)sa6_recoverscope(sin6); /* XXX: should catch errors */
505 
506 	return (struct sockaddr *)sin6;
507 }
508 
509 struct sockaddr *
510 in6_v4mapsin6_sockaddr(in_port_t port, struct in_addr *addr_p)
511 {
512 	struct sockaddr_in sin;
513 	struct sockaddr_in6 *sin6_p;
514 
515 	bzero(&sin, sizeof sin);
516 	sin.sin_family = AF_INET;
517 	sin.sin_len = sizeof(sin);
518 	sin.sin_port = port;
519 	sin.sin_addr = *addr_p;
520 
521 	sin6_p = malloc(sizeof *sin6_p, M_SONAME,
522 		M_WAITOK);
523 	in6_sin_2_v4mapsin6(&sin, sin6_p);
524 
525 	return (struct sockaddr *)sin6_p;
526 }
527 
528 int
529 in6_getsockaddr(struct socket *so, struct sockaddr **nam)
530 {
531 	struct inpcb *inp;
532 	struct in6_addr addr;
533 	in_port_t port;
534 
535 	inp = sotoinpcb(so);
536 	KASSERT(inp != NULL, ("in6_getsockaddr: inp == NULL"));
537 
538 	INP_RLOCK(inp);
539 	port = inp->inp_lport;
540 	addr = inp->in6p_laddr;
541 	INP_RUNLOCK(inp);
542 
543 	*nam = in6_sockaddr(port, &addr);
544 	return 0;
545 }
546 
547 int
548 in6_getpeeraddr(struct socket *so, struct sockaddr **nam)
549 {
550 	struct inpcb *inp;
551 	struct in6_addr addr;
552 	in_port_t port;
553 
554 	inp = sotoinpcb(so);
555 	KASSERT(inp != NULL, ("in6_getpeeraddr: inp == NULL"));
556 
557 	INP_RLOCK(inp);
558 	port = inp->inp_fport;
559 	addr = inp->in6p_faddr;
560 	INP_RUNLOCK(inp);
561 
562 	*nam = in6_sockaddr(port, &addr);
563 	return 0;
564 }
565 
566 int
567 in6_mapped_sockaddr(struct socket *so, struct sockaddr **nam)
568 {
569 	struct	inpcb *inp;
570 	int	error;
571 
572 	inp = sotoinpcb(so);
573 	KASSERT(inp != NULL, ("in6_mapped_sockaddr: inp == NULL"));
574 
575 #ifdef INET
576 	if ((inp->inp_vflag & (INP_IPV4 | INP_IPV6)) == INP_IPV4) {
577 		error = in_getsockaddr(so, nam);
578 		if (error == 0)
579 			in6_sin_2_v4mapsin6_in_sock(nam);
580 	} else
581 #endif
582 	{
583 		/* scope issues will be handled in in6_getsockaddr(). */
584 		error = in6_getsockaddr(so, nam);
585 	}
586 
587 	return error;
588 }
589 
590 int
591 in6_mapped_peeraddr(struct socket *so, struct sockaddr **nam)
592 {
593 	struct	inpcb *inp;
594 	int	error;
595 
596 	inp = sotoinpcb(so);
597 	KASSERT(inp != NULL, ("in6_mapped_peeraddr: inp == NULL"));
598 
599 #ifdef INET
600 	if ((inp->inp_vflag & (INP_IPV4 | INP_IPV6)) == INP_IPV4) {
601 		error = in_getpeeraddr(so, nam);
602 		if (error == 0)
603 			in6_sin_2_v4mapsin6_in_sock(nam);
604 	} else
605 #endif
606 	/* scope issues will be handled in in6_getpeeraddr(). */
607 	error = in6_getpeeraddr(so, nam);
608 
609 	return error;
610 }
611 
612 /*
613  * Pass some notification to all connections of a protocol
614  * associated with address dst.  The local address and/or port numbers
615  * may be specified to limit the search.  The "usual action" will be
616  * taken, depending on the ctlinput cmd.  The caller must filter any
617  * cmds that are uninteresting (e.g., no error in the map).
618  * Call the protocol specific routine (if any) to report
619  * any errors for each matching socket.
620  */
621 static bool
622 inp_match6(const struct inpcb *inp, void *v __unused)
623 {
624 
625 	return ((inp->inp_vflag & INP_IPV6) != 0);
626 }
627 
628 void
629 in6_pcbnotify(struct inpcbinfo *pcbinfo, struct sockaddr_in6 *sa6_dst,
630     u_int fport_arg, const struct sockaddr_in6 *src, u_int lport_arg,
631     int errno, void *cmdarg,
632     struct inpcb *(*notify)(struct inpcb *, int))
633 {
634 	struct inpcb_iterator inpi = INP_ITERATOR(pcbinfo, INPLOOKUP_WLOCKPCB,
635 	    inp_match6, NULL);
636 	struct inpcb *inp;
637 	struct sockaddr_in6 sa6_src;
638 	u_short	fport = fport_arg, lport = lport_arg;
639 	u_int32_t flowinfo;
640 
641 	if (IN6_IS_ADDR_UNSPECIFIED(&sa6_dst->sin6_addr))
642 		return;
643 
644 	/*
645 	 * note that src can be NULL when we get notify by local fragmentation.
646 	 */
647 	sa6_src = (src == NULL) ? sa6_any : *src;
648 	flowinfo = sa6_src.sin6_flowinfo;
649 
650 	while ((inp = inp_next(&inpi)) != NULL) {
651 		INP_WLOCK_ASSERT(inp);
652 		/*
653 		 * If the error designates a new path MTU for a destination
654 		 * and the application (associated with this socket) wanted to
655 		 * know the value, notify.
656 		 * XXX: should we avoid to notify the value to TCP sockets?
657 		 */
658 		if (errno == EMSGSIZE && cmdarg != NULL)
659 			ip6_notify_pmtu(inp, sa6_dst, *(uint32_t *)cmdarg);
660 
661 		/*
662 		 * Detect if we should notify the error. If no source and
663 		 * destination ports are specified, but non-zero flowinfo and
664 		 * local address match, notify the error. This is the case
665 		 * when the error is delivered with an encrypted buffer
666 		 * by ESP. Otherwise, just compare addresses and ports
667 		 * as usual.
668 		 */
669 		if (lport == 0 && fport == 0 && flowinfo &&
670 		    inp->inp_socket != NULL &&
671 		    flowinfo == (inp->inp_flow & IPV6_FLOWLABEL_MASK) &&
672 		    IN6_ARE_ADDR_EQUAL(&inp->in6p_laddr, &sa6_src.sin6_addr))
673 			goto do_notify;
674 		else if (!IN6_ARE_ADDR_EQUAL(&inp->in6p_faddr,
675 					     &sa6_dst->sin6_addr) ||
676 			 inp->inp_socket == 0 ||
677 			 (lport && inp->inp_lport != lport) ||
678 			 (!IN6_IS_ADDR_UNSPECIFIED(&sa6_src.sin6_addr) &&
679 			  !IN6_ARE_ADDR_EQUAL(&inp->in6p_laddr,
680 					      &sa6_src.sin6_addr)) ||
681 			 (fport && inp->inp_fport != fport)) {
682 			continue;
683 		}
684 
685 	  do_notify:
686 		if (notify)
687 			(*notify)(inp, errno);
688 	}
689 }
690 
691 /*
692  * Lookup a PCB based on the local address and port.  Caller must hold the
693  * hash lock.  No inpcb locks or references are acquired.
694  */
695 struct inpcb *
696 in6_pcblookup_local(struct inpcbinfo *pcbinfo, struct in6_addr *laddr,
697     u_short lport, int lookupflags, struct ucred *cred)
698 {
699 	struct inpcb *inp;
700 	int matchwild = 3, wildcard;
701 
702 	KASSERT((lookupflags & ~(INPLOOKUP_WILDCARD)) == 0,
703 	    ("%s: invalid lookup flags %d", __func__, lookupflags));
704 
705 	INP_HASH_LOCK_ASSERT(pcbinfo);
706 
707 	if ((lookupflags & INPLOOKUP_WILDCARD) == 0) {
708 		struct inpcbhead *head;
709 		/*
710 		 * Look for an unconnected (wildcard foreign addr) PCB that
711 		 * matches the local address and port we're looking for.
712 		 */
713 		head = &pcbinfo->ipi_hashbase[INP_PCBHASH_WILD(lport,
714 		    pcbinfo->ipi_hashmask)];
715 		CK_LIST_FOREACH(inp, head, inp_hash) {
716 			/* XXX inp locking */
717 			if ((inp->inp_vflag & INP_IPV6) == 0)
718 				continue;
719 			if (IN6_IS_ADDR_UNSPECIFIED(&inp->in6p_faddr) &&
720 			    IN6_ARE_ADDR_EQUAL(&inp->in6p_laddr, laddr) &&
721 			    inp->inp_lport == lport) {
722 				/* Found. */
723 				if (prison_equal_ip6(cred->cr_prison,
724 				    inp->inp_cred->cr_prison))
725 					return (inp);
726 			}
727 		}
728 		/*
729 		 * Not found.
730 		 */
731 		return (NULL);
732 	} else {
733 		struct inpcbporthead *porthash;
734 		struct inpcbport *phd;
735 		struct inpcb *match = NULL;
736 		/*
737 		 * Best fit PCB lookup.
738 		 *
739 		 * First see if this local port is in use by looking on the
740 		 * port hash list.
741 		 */
742 		porthash = &pcbinfo->ipi_porthashbase[INP_PCBPORTHASH(lport,
743 		    pcbinfo->ipi_porthashmask)];
744 		CK_LIST_FOREACH(phd, porthash, phd_hash) {
745 			if (phd->phd_port == lport)
746 				break;
747 		}
748 		if (phd != NULL) {
749 			/*
750 			 * Port is in use by one or more PCBs. Look for best
751 			 * fit.
752 			 */
753 			CK_LIST_FOREACH(inp, &phd->phd_pcblist, inp_portlist) {
754 				wildcard = 0;
755 				if (!prison_equal_ip6(cred->cr_prison,
756 				    inp->inp_cred->cr_prison))
757 					continue;
758 				/* XXX inp locking */
759 				if ((inp->inp_vflag & INP_IPV6) == 0)
760 					continue;
761 				if (!IN6_IS_ADDR_UNSPECIFIED(&inp->in6p_faddr))
762 					wildcard++;
763 				if (!IN6_IS_ADDR_UNSPECIFIED(
764 					&inp->in6p_laddr)) {
765 					if (IN6_IS_ADDR_UNSPECIFIED(laddr))
766 						wildcard++;
767 					else if (!IN6_ARE_ADDR_EQUAL(
768 					    &inp->in6p_laddr, laddr))
769 						continue;
770 				} else {
771 					if (!IN6_IS_ADDR_UNSPECIFIED(laddr))
772 						wildcard++;
773 				}
774 				if (wildcard < matchwild) {
775 					match = inp;
776 					matchwild = wildcard;
777 					if (matchwild == 0)
778 						break;
779 				}
780 			}
781 		}
782 		return (match);
783 	}
784 }
785 
786 static bool
787 in6_multi_match(const struct inpcb *inp, void *v __unused)
788 {
789 
790 	if ((inp->inp_vflag & INP_IPV6) && inp->in6p_moptions != NULL)
791 		return (true);
792 	else
793 		return (false);
794 }
795 
796 void
797 in6_pcbpurgeif0(struct inpcbinfo *pcbinfo, struct ifnet *ifp)
798 {
799 	struct inpcb_iterator inpi = INP_ITERATOR(pcbinfo, INPLOOKUP_RLOCKPCB,
800 	    in6_multi_match, NULL);
801 	struct inpcb *inp;
802 	struct in6_multi *inm;
803 	struct in6_mfilter *imf;
804 	struct ip6_moptions *im6o;
805 
806 	IN6_MULTI_LOCK_ASSERT();
807 
808 	while ((inp = inp_next(&inpi)) != NULL) {
809 		INP_RLOCK_ASSERT(inp);
810 
811 		im6o = inp->in6p_moptions;
812 		/*
813 		 * Unselect the outgoing ifp for multicast if it
814 		 * is being detached.
815 		 */
816 		if (im6o->im6o_multicast_ifp == ifp)
817 			im6o->im6o_multicast_ifp = NULL;
818 		/*
819 		 * Drop multicast group membership if we joined
820 		 * through the interface being detached.
821 		 */
822 restart:
823 		IP6_MFILTER_FOREACH(imf, &im6o->im6o_head) {
824 			if ((inm = imf->im6f_in6m) == NULL)
825 				continue;
826 			if (inm->in6m_ifp != ifp)
827 				continue;
828 			ip6_mfilter_remove(&im6o->im6o_head, imf);
829 			in6_leavegroup_locked(inm, NULL);
830 			ip6_mfilter_free(imf);
831 			goto restart;
832 		}
833 	}
834 }
835 
836 /*
837  * Check for alternatives when higher level complains
838  * about service problems.  For now, invalidate cached
839  * routing information.  If the route was created dynamically
840  * (by a redirect), time to try a default gateway again.
841  */
842 void
843 in6_losing(struct inpcb *inp)
844 {
845 
846 	RO_INVALIDATE_CACHE(&inp->inp_route6);
847 }
848 
849 /*
850  * After a routing change, flush old routing
851  * and allocate a (hopefully) better one.
852  */
853 struct inpcb *
854 in6_rtchange(struct inpcb *inp, int errno __unused)
855 {
856 
857 	RO_INVALIDATE_CACHE(&inp->inp_route6);
858 	return inp;
859 }
860 
861 static bool
862 in6_pcblookup_lb_numa_match(const struct inpcblbgroup *grp, int domain)
863 {
864 	return (domain == M_NODOM || domain == grp->il_numa_domain);
865 }
866 
867 static struct inpcb *
868 in6_pcblookup_lbgroup(const struct inpcbinfo *pcbinfo,
869     const struct in6_addr *faddr, uint16_t fport, const struct in6_addr *laddr,
870     uint16_t lport, uint8_t domain)
871 {
872 	const struct inpcblbgrouphead *hdr;
873 	struct inpcblbgroup *grp;
874 	struct inpcblbgroup *jail_exact, *jail_wild, *local_exact, *local_wild;
875 
876 	INP_HASH_LOCK_ASSERT(pcbinfo);
877 
878 	hdr = &pcbinfo->ipi_lbgrouphashbase[
879 	    INP_PCBPORTHASH(lport, pcbinfo->ipi_lbgrouphashmask)];
880 
881 	/*
882 	 * Search for an LB group match based on the following criteria:
883 	 * - prefer jailed groups to non-jailed groups
884 	 * - prefer exact source address matches to wildcard matches
885 	 * - prefer groups bound to the specified NUMA domain
886 	 */
887 	jail_exact = jail_wild = local_exact = local_wild = NULL;
888 	CK_LIST_FOREACH(grp, hdr, il_list) {
889 		bool injail;
890 
891 #ifdef INET
892 		if (!(grp->il_vflag & INP_IPV6))
893 			continue;
894 #endif
895 		if (grp->il_lport != lport)
896 			continue;
897 
898 		injail = prison_flag(grp->il_cred, PR_IP6) != 0;
899 		if (injail && prison_check_ip6_locked(grp->il_cred->cr_prison,
900 		    laddr) != 0)
901 			continue;
902 
903 		if (IN6_ARE_ADDR_EQUAL(&grp->il6_laddr, laddr)) {
904 			if (injail) {
905 				jail_exact = grp;
906 				if (in6_pcblookup_lb_numa_match(grp, domain))
907 					/* This is a perfect match. */
908 					goto out;
909 			} else if (local_exact == NULL ||
910 			    in6_pcblookup_lb_numa_match(grp, domain)) {
911 				local_exact = grp;
912 			}
913 		} else if (IN6_IS_ADDR_UNSPECIFIED(&grp->il6_laddr)) {
914 			if (injail) {
915 				if (jail_wild == NULL ||
916 				    in6_pcblookup_lb_numa_match(grp, domain))
917 					jail_wild = grp;
918 			} else if (local_wild == NULL ||
919 			    in6_pcblookup_lb_numa_match(grp, domain)) {
920 				local_wild = grp;
921 			}
922 		}
923 	}
924 
925 	if (jail_exact != NULL)
926 		grp = jail_exact;
927 	else if (jail_wild != NULL)
928 		grp = jail_wild;
929 	else if (local_exact != NULL)
930 		grp = local_exact;
931 	else
932 		grp = local_wild;
933 	if (grp == NULL)
934 		return (NULL);
935 out:
936 	return (grp->il_inp[INP6_PCBLBGROUP_PKTHASH(faddr, lport, fport) %
937 	    grp->il_inpcnt]);
938 }
939 
940 static struct inpcb *
941 in6_pcblookup_hash_exact(struct inpcbinfo *pcbinfo, struct in6_addr *faddr,
942     u_short fport, struct in6_addr *laddr, u_short lport)
943 {
944 	struct inpcbhead *head;
945 	struct inpcb *inp, *match;
946 
947 	INP_HASH_LOCK_ASSERT(pcbinfo);
948 
949 	/*
950 	 * First look for an exact match.
951 	 */
952 	match = NULL;
953 	head = &pcbinfo->ipi_hashbase[INP6_PCBHASH(faddr, lport, fport,
954 	    pcbinfo->ipi_hashmask)];
955 	CK_LIST_FOREACH(inp, head, inp_hash) {
956 		/* XXX inp locking */
957 		if ((inp->inp_vflag & INP_IPV6) == 0)
958 			continue;
959 		if (IN6_ARE_ADDR_EQUAL(&inp->in6p_faddr, faddr) &&
960 		    IN6_ARE_ADDR_EQUAL(&inp->in6p_laddr, laddr) &&
961 		    inp->inp_fport == fport &&
962 		    inp->inp_lport == lport)
963 			return (inp);
964 	}
965 	return (match);
966 }
967 
968 static struct inpcb *
969 in6_pcblookup_hash_wild_locked(struct inpcbinfo *pcbinfo,
970     struct in6_addr *faddr, u_short fport, struct in6_addr *laddr,
971     u_short lport)
972 {
973 	struct inpcbhead *head;
974 	struct inpcb *inp, *jail_wild, *local_exact, *local_wild;
975 
976 	/*
977 	 * Order of socket selection - we always prefer jails.
978 	 *      1. jailed, non-wild.
979 	 *      2. jailed, wild.
980 	 *      3. non-jailed, non-wild.
981 	 *      4. non-jailed, wild.
982 	 */
983 	head = &pcbinfo->ipi_hashbase[INP_PCBHASH_WILD(lport,
984 	    pcbinfo->ipi_hashmask)];
985 	local_wild = local_exact = jail_wild = NULL;
986 	CK_LIST_FOREACH(inp, head, inp_hash) {
987 		bool injail;
988 
989 		/* XXX inp locking */
990 		if ((inp->inp_vflag & INP_IPV6) == 0)
991 			continue;
992 
993 		if (!IN6_IS_ADDR_UNSPECIFIED(&inp->in6p_faddr) ||
994 		    inp->inp_lport != lport) {
995 			continue;
996 		}
997 
998 		injail = prison_flag(inp->inp_cred, PR_IP6) != 0;
999 		if (injail) {
1000 			if (prison_check_ip6_locked(
1001 			    inp->inp_cred->cr_prison, laddr) != 0)
1002 				continue;
1003 		} else {
1004 			if (local_exact != NULL)
1005 				continue;
1006 		}
1007 
1008 		if (IN6_ARE_ADDR_EQUAL(&inp->in6p_laddr, laddr)) {
1009 			if (injail)
1010 				return (inp);
1011 			else
1012 				local_exact = inp;
1013 		} else if (IN6_IS_ADDR_UNSPECIFIED(&inp->in6p_laddr)) {
1014 			if (injail)
1015 				jail_wild = inp;
1016 			else
1017 				local_wild = inp;
1018 		}
1019 	}
1020 
1021 	if (jail_wild != NULL)
1022 		return (jail_wild);
1023 	if (local_exact != NULL)
1024 		return (local_exact);
1025 	if (local_wild != NULL)
1026 		return (local_wild);
1027 	return (NULL);
1028 }
1029 
1030 struct inpcb *
1031 in6_pcblookup_hash_locked(struct inpcbinfo *pcbinfo, struct in6_addr *faddr,
1032     u_int fport_arg, struct in6_addr *laddr, u_int lport_arg,
1033     int lookupflags, uint8_t numa_domain)
1034 {
1035 	struct inpcb *inp;
1036 	u_short fport = fport_arg, lport = lport_arg;
1037 
1038 	KASSERT((lookupflags & ~INPLOOKUP_WILDCARD) == 0,
1039 	    ("%s: invalid lookup flags %d", __func__, lookupflags));
1040 	KASSERT(!IN6_IS_ADDR_UNSPECIFIED(faddr),
1041 	    ("%s: invalid foreign address", __func__));
1042 	KASSERT(!IN6_IS_ADDR_UNSPECIFIED(laddr),
1043 	    ("%s: invalid local address", __func__));
1044 
1045 	INP_HASH_LOCK_ASSERT(pcbinfo);
1046 
1047 	inp = in6_pcblookup_hash_exact(pcbinfo, faddr, fport, laddr, lport);
1048 	if (inp != NULL)
1049 		return (inp);
1050 
1051 	if ((lookupflags & INPLOOKUP_WILDCARD) != 0) {
1052 		inp = in6_pcblookup_lbgroup(pcbinfo, faddr, fport, laddr,
1053 		    lport, numa_domain);
1054 		if (inp == NULL) {
1055 			inp = in6_pcblookup_hash_wild_locked(pcbinfo, faddr,
1056 			    fport, laddr, lport);
1057 		}
1058 	}
1059 	return (inp);
1060 }
1061 
1062 static struct inpcb *
1063 in6_pcblookup_hash_smr(struct inpcbinfo *pcbinfo, struct in6_addr *faddr,
1064     u_int fport, struct in6_addr *laddr, u_int lport, int lookupflags,
1065     uint8_t numa_domain)
1066 {
1067 	struct inpcb *inp;
1068 
1069 	KASSERT((lookupflags & ~INPLOOKUP_MASK) == 0,
1070 	    ("%s: invalid lookup flags %d", __func__, lookupflags));
1071 	KASSERT((lookupflags & (INPLOOKUP_RLOCKPCB | INPLOOKUP_WLOCKPCB)) != 0,
1072 	    ("%s: LOCKPCB not set", __func__));
1073 
1074 	smr_enter(pcbinfo->ipi_smr);
1075 	inp = in6_pcblookup_hash_locked(pcbinfo, faddr, fport, laddr, lport,
1076 	    lookupflags & INPLOOKUP_WILDCARD, numa_domain);
1077 	if (inp != NULL) {
1078 		if (__predict_false(inp_smr_lock(inp,
1079 		    (lookupflags & INPLOOKUP_LOCKMASK)) == false))
1080 			inp = NULL;
1081 	} else
1082 		smr_exit(pcbinfo->ipi_smr);
1083 
1084 	return (inp);
1085 }
1086 
1087 /*
1088  * Public inpcb lookup routines, accepting a 4-tuple, and optionally, an mbuf
1089  * from which a pre-calculated hash value may be extracted.
1090  */
1091 struct inpcb *
1092 in6_pcblookup(struct inpcbinfo *pcbinfo, struct in6_addr *faddr, u_int fport,
1093     struct in6_addr *laddr, u_int lport, int lookupflags,
1094     struct ifnet *ifp __unused)
1095 {
1096 	return (in6_pcblookup_hash_smr(pcbinfo, faddr, fport, laddr, lport,
1097 	    lookupflags, M_NODOM));
1098 }
1099 
1100 struct inpcb *
1101 in6_pcblookup_mbuf(struct inpcbinfo *pcbinfo, struct in6_addr *faddr,
1102     u_int fport, struct in6_addr *laddr, u_int lport, int lookupflags,
1103     struct ifnet *ifp __unused, struct mbuf *m)
1104 {
1105 	return (in6_pcblookup_hash_smr(pcbinfo, faddr, fport, laddr, lport,
1106 	    lookupflags, m->m_pkthdr.numa_domain));
1107 }
1108 
1109 void
1110 init_sin6(struct sockaddr_in6 *sin6, struct mbuf *m, int srcordst)
1111 {
1112 	struct ip6_hdr *ip;
1113 
1114 	ip = mtod(m, struct ip6_hdr *);
1115 	bzero(sin6, sizeof(*sin6));
1116 	sin6->sin6_len = sizeof(*sin6);
1117 	sin6->sin6_family = AF_INET6;
1118 	sin6->sin6_addr = srcordst ? ip->ip6_dst : ip->ip6_src;
1119 
1120 	(void)sa6_recoverscope(sin6); /* XXX: should catch errors... */
1121 
1122 	return;
1123 }
1124