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