xref: /xnu-8792.81.2/bsd/netinet6/in6_pcb.c (revision 19c3b8c28c31cb8130e034cfb5df6bf9ba342d90)
1 /*
2  * Copyright (c) 2003-2021 Apple Inc. All rights reserved.
3  *
4  * @APPLE_OSREFERENCE_LICENSE_HEADER_START@
5  *
6  * This file contains Original Code and/or Modifications of Original Code
7  * as defined in and that are subject to the Apple Public Source License
8  * Version 2.0 (the 'License'). You may not use this file except in
9  * compliance with the License. The rights granted to you under the License
10  * may not be used to create, or enable the creation or redistribution of,
11  * unlawful or unlicensed copies of an Apple operating system, or to
12  * circumvent, violate, or enable the circumvention or violation of, any
13  * terms of an Apple operating system software license agreement.
14  *
15  * Please obtain a copy of the License at
16  * http://www.opensource.apple.com/apsl/ and read it before using this file.
17  *
18  * The Original Code and all software distributed under the License are
19  * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
20  * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
21  * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
22  * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
23  * Please see the License for the specific language governing rights and
24  * limitations under the License.
25  *
26  * @APPLE_OSREFERENCE_LICENSE_HEADER_END@
27  */
28 /*
29  * Copyright (C) 1995, 1996, 1997, and 1998 WIDE Project.
30  * All rights reserved.
31  *
32  * Redistribution and use in source and binary forms, with or without
33  * modification, are permitted provided that the following conditions
34  * are met:
35  * 1. Redistributions of source code must retain the above copyright
36  *    notice, this list of conditions and the following disclaimer.
37  * 2. Redistributions in binary form must reproduce the above copyright
38  *    notice, this list of conditions and the following disclaimer in the
39  *    documentation and/or other materials provided with the distribution.
40  * 3. Neither the name of the project nor the names of its contributors
41  *    may be used to endorse or promote products derived from this software
42  *    without specific prior written permission.
43  *
44  * THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND
45  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
46  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
47  * ARE DISCLAIMED.  IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE
48  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
49  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
50  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
51  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
52  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
53  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
54  * SUCH DAMAGE.
55  *
56  */
57 
58 /*
59  * Copyright (c) 1982, 1986, 1991, 1993
60  *	The Regents of the University of California.  All rights reserved.
61  *
62  * Redistribution and use in source and binary forms, with or without
63  * modification, are permitted provided that the following conditions
64  * are met:
65  * 1. Redistributions of source code must retain the above copyright
66  *    notice, this list of conditions and the following disclaimer.
67  * 2. Redistributions in binary form must reproduce the above copyright
68  *    notice, this list of conditions and the following disclaimer in the
69  *    documentation and/or other materials provided with the distribution.
70  * 3. All advertising materials mentioning features or use of this software
71  *    must display the following acknowledgement:
72  *	This product includes software developed by the University of
73  *	California, Berkeley and its contributors.
74  * 4. Neither the name of the University nor the names of its contributors
75  *    may be used to endorse or promote products derived from this software
76  *    without specific prior written permission.
77  *
78  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
79  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
80  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
81  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
82  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
83  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
84  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
85  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
86  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
87  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
88  * SUCH DAMAGE.
89  *
90  *	@(#)in_pcb.c	8.2 (Berkeley) 1/4/94
91  */
92 
93 #include <sys/param.h>
94 #include <sys/systm.h>
95 #include <sys/malloc.h>
96 #include <sys/mbuf.h>
97 #include <sys/domain.h>
98 #include <sys/protosw.h>
99 #include <sys/socket.h>
100 #include <sys/socketvar.h>
101 #include <sys/sockio.h>
102 #include <sys/errno.h>
103 #include <sys/time.h>
104 #include <sys/proc.h>
105 #include <sys/kauth.h>
106 #include <sys/priv.h>
107 
108 #include <net/if.h>
109 #include <net/if_types.h>
110 #include <net/route.h>
111 #include <net/ntstat.h>
112 #include <net/restricted_in_port.h>
113 
114 #include <netinet/in.h>
115 #include <netinet/in_var.h>
116 #include <netinet/in_systm.h>
117 #include <netinet/ip6.h>
118 #include <netinet/ip_var.h>
119 
120 #include <netinet6/ip6_var.h>
121 #include <netinet6/nd6.h>
122 #include <netinet/in_pcb.h>
123 #include <netinet6/in6_pcb.h>
124 
125 #include <net/if_types.h>
126 #include <net/if_var.h>
127 
128 #include <kern/kern_types.h>
129 #include <kern/zalloc.h>
130 
131 #if IPSEC
132 #include <netinet6/ipsec.h>
133 #include <netinet6/ipsec6.h>
134 #include <netinet6/ah.h>
135 #include <netinet6/ah6.h>
136 #include <netkey/key.h>
137 #endif /* IPSEC */
138 
139 #if NECP
140 #include <net/necp.h>
141 #endif /* NECP */
142 
143 /*
144  * in6_pcblookup_local_and_cleanup does everything
145  * in6_pcblookup_local does but it checks for a socket
146  * that's going away. Since we know that the lock is
147  * held read+write when this function is called, we
148  * can safely dispose of this socket like the slow
149  * timer would usually do and return NULL. This is
150  * great for bind.
151  */
152 static struct inpcb *
in6_pcblookup_local_and_cleanup(struct inpcbinfo * pcbinfo,struct in6_addr * laddr,u_int lport_arg,uint32_t ifscope,int wild_okay)153 in6_pcblookup_local_and_cleanup(struct inpcbinfo *pcbinfo,
154     struct in6_addr *laddr, u_int lport_arg, uint32_t ifscope, int wild_okay)
155 {
156 	struct inpcb *inp;
157 
158 	/* Perform normal lookup */
159 	inp = in6_pcblookup_local(pcbinfo, laddr, lport_arg, ifscope, wild_okay);
160 
161 	/* Check if we found a match but it's waiting to be disposed */
162 	if (inp != NULL && inp->inp_wantcnt == WNT_STOPUSING) {
163 		struct socket *so = inp->inp_socket;
164 
165 		socket_lock(so, 0);
166 
167 		if (so->so_usecount == 0) {
168 			if (inp->inp_state != INPCB_STATE_DEAD) {
169 				in6_pcbdetach(inp);
170 			}
171 			in_pcbdispose(inp);     /* will unlock & destroy */
172 			inp = NULL;
173 		} else {
174 			socket_unlock(so, 0);
175 		}
176 	}
177 
178 	return inp;
179 }
180 
181 /*
182  * Bind an INPCB to an address and/or port.  This routine should not alter
183  * the caller-supplied local address "nam".
184  */
185 int
in6_pcbbind(struct inpcb * inp,struct sockaddr * nam,struct proc * p)186 in6_pcbbind(struct inpcb *inp, struct sockaddr *nam, struct proc *p)
187 {
188 	struct socket *so = inp->inp_socket;
189 	struct inpcbinfo *pcbinfo = inp->inp_pcbinfo;
190 	u_short lport = 0;
191 	int wild = 0, reuseport = (so->so_options & SO_REUSEPORT);
192 	struct ifnet *outif = NULL;
193 	struct sockaddr_in6 sin6;
194 	uint32_t lifscope = IFSCOPE_NONE;
195 #if XNU_TARGET_OS_OSX
196 	int error;
197 	kauth_cred_t cred;
198 #endif /* XNU_TARGET_OS_OSX */
199 
200 	if (TAILQ_EMPTY(&in6_ifaddrhead)) { /* XXX broken! */
201 		return EADDRNOTAVAIL;
202 	}
203 	if (!(so->so_options & (SO_REUSEADDR | SO_REUSEPORT))) {
204 		wild = 1;
205 	}
206 
207 	socket_unlock(so, 0); /* keep reference */
208 	lck_rw_lock_exclusive(&pcbinfo->ipi_lock);
209 	if (inp->inp_lport || !IN6_IS_ADDR_UNSPECIFIED(&inp->in6p_laddr)) {
210 		/* another thread completed the bind */
211 		lck_rw_done(&pcbinfo->ipi_lock);
212 		socket_lock(so, 0);
213 		return EINVAL;
214 	}
215 
216 	bzero(&sin6, sizeof(sin6));
217 	if (nam != NULL) {
218 		if (nam->sa_len != sizeof(struct sockaddr_in6)) {
219 			lck_rw_done(&pcbinfo->ipi_lock);
220 			socket_lock(so, 0);
221 			return EINVAL;
222 		}
223 		/*
224 		 * family check.
225 		 */
226 		if (nam->sa_family != AF_INET6) {
227 			lck_rw_done(&pcbinfo->ipi_lock);
228 			socket_lock(so, 0);
229 			return EAFNOSUPPORT;
230 		}
231 		lport = SIN6(nam)->sin6_port;
232 
233 		*(&sin6) = *SIN6(nam);
234 
235 		/* KAME hack: embed scopeid */
236 		if (in6_embedscope(&sin6.sin6_addr, &sin6, inp, NULL,
237 		    NULL, &lifscope) != 0) {
238 			lck_rw_done(&pcbinfo->ipi_lock);
239 			socket_lock(so, 0);
240 			return EINVAL;
241 		}
242 
243 		/* Sanitize local copy for address searches */
244 		sin6.sin6_flowinfo = 0;
245 		sin6.sin6_port = 0;
246 		if (in6_embedded_scope) {
247 			sin6.sin6_scope_id = 0;
248 		}
249 
250 		if (IN6_IS_ADDR_MULTICAST(&sin6.sin6_addr)) {
251 			/*
252 			 * Treat SO_REUSEADDR as SO_REUSEPORT for multicast;
253 			 * allow compepte duplication of binding if
254 			 * SO_REUSEPORT is set, or if SO_REUSEADDR is set
255 			 * and a multicast address is bound on both
256 			 * new and duplicated sockets.
257 			 */
258 			if (so->so_options & SO_REUSEADDR) {
259 				reuseport = SO_REUSEADDR | SO_REUSEPORT;
260 			}
261 		} else if (!IN6_IS_ADDR_UNSPECIFIED(&sin6.sin6_addr)) {
262 			struct ifaddr *ifa;
263 
264 			ifa = ifa_ifwithaddr(SA(&sin6));
265 			if (ifa == NULL) {
266 				lck_rw_done(&pcbinfo->ipi_lock);
267 				socket_lock(so, 0);
268 				return EADDRNOTAVAIL;
269 			} else {
270 				/*
271 				 * XXX: bind to an anycast address might
272 				 * accidentally cause sending a packet with
273 				 * anycast source address.  We should allow
274 				 * to bind to a deprecated address, since
275 				 * the application dare to use it.
276 				 */
277 				IFA_LOCK_SPIN(ifa);
278 				if (((struct in6_ifaddr *)ifa)->ia6_flags &
279 				    (IN6_IFF_ANYCAST | IN6_IFF_NOTREADY |
280 				    IN6_IFF_DETACHED | IN6_IFF_CLAT46)) {
281 					IFA_UNLOCK(ifa);
282 					IFA_REMREF(ifa);
283 					lck_rw_done(&pcbinfo->ipi_lock);
284 					socket_lock(so, 0);
285 					return EADDRNOTAVAIL;
286 				}
287 				/*
288 				 * Opportunistically determine the outbound
289 				 * interface that may be used; this may not
290 				 * hold true if we end up using a route
291 				 * going over a different interface, e.g.
292 				 * when sending to a local address.  This
293 				 * will get updated again after sending.
294 				 */
295 				outif = ifa->ifa_ifp;
296 				IFA_UNLOCK(ifa);
297 				IFA_REMREF(ifa);
298 			}
299 		}
300 
301 #if SKYWALK
302 		if (inp->inp_flags2 & INP2_EXTERNAL_PORT) {
303 			// Extract the external flow info
304 			struct ns_flow_info nfi = {};
305 			int netns_error = necp_client_get_netns_flow_info(inp->necp_client_uuid,
306 			    &nfi);
307 			if (netns_error != 0) {
308 				lck_rw_done(&pcbinfo->ipi_lock);
309 				socket_lock(so, 0);
310 				return netns_error;
311 			}
312 
313 			// Extract the reserved port
314 			u_int16_t reserved_lport = 0;
315 			if (nfi.nfi_laddr.sa.sa_family == AF_INET) {
316 				reserved_lport = nfi.nfi_laddr.sin.sin_port;
317 			} else if (nfi.nfi_laddr.sa.sa_family == AF_INET6) {
318 				reserved_lport = nfi.nfi_laddr.sin6.sin6_port;
319 			} else {
320 				lck_rw_done(&pcbinfo->ipi_lock);
321 				socket_lock(so, 0);
322 				return EINVAL;
323 			}
324 
325 			// Validate or use the reserved port
326 			if (lport == 0) {
327 				lport = reserved_lport;
328 			} else if (lport != reserved_lport) {
329 				lck_rw_done(&pcbinfo->ipi_lock);
330 				socket_lock(so, 0);
331 				return EINVAL;
332 			}
333 		}
334 
335 		/* Do not allow reserving a UDP port if remaining UDP port count is below 4096 */
336 		if (SOCK_PROTO(so) == IPPROTO_UDP && !allow_udp_port_exhaustion) {
337 			uint32_t current_reservations = 0;
338 			current_reservations = netns_lookup_reservations_count_in6(inp->in6p_laddr, IPPROTO_UDP);
339 			if (USHRT_MAX - UDP_RANDOM_PORT_RESERVE < current_reservations) {
340 				log(LOG_ERR, "UDP port not available, less than 4096 UDP ports left");
341 				lck_rw_done(&pcbinfo->ipi_lock);
342 				socket_lock(so, 0);
343 				return EADDRNOTAVAIL;
344 			}
345 		}
346 
347 #endif /* SKYWALK */
348 
349 		if (lport != 0) {
350 			struct inpcb *t;
351 			uid_t u;
352 
353 #if XNU_TARGET_OS_OSX
354 			if (ntohs(lport) < IPV6PORT_RESERVED &&
355 			    !IN6_IS_ADDR_UNSPECIFIED(&sin6.sin6_addr) &&
356 			    !(inp->inp_flags2 & INP2_EXTERNAL_PORT)) {
357 				cred = kauth_cred_proc_ref(p);
358 				error = priv_check_cred(cred,
359 				    PRIV_NETINET_RESERVEDPORT, 0);
360 				kauth_cred_unref(&cred);
361 				if (error != 0) {
362 					lck_rw_done(&pcbinfo->ipi_lock);
363 					socket_lock(so, 0);
364 					return EACCES;
365 				}
366 			}
367 #endif /* XNU_TARGET_OS_OSX */
368 			/*
369 			 * Check wether the process is allowed to bind to a restricted port
370 			 */
371 			if (!current_task_can_use_restricted_in_port(lport,
372 			    (uint8_t)SOCK_PROTO(so), PORT_FLAGS_BSD)) {
373 				lck_rw_done(&pcbinfo->ipi_lock);
374 				socket_lock(so, 0);
375 				return EADDRINUSE;
376 			}
377 
378 			if (!IN6_IS_ADDR_MULTICAST(&sin6.sin6_addr) &&
379 			    (u = kauth_cred_getuid(so->so_cred)) != 0) {
380 				t = in6_pcblookup_local_and_cleanup(pcbinfo,
381 				    &sin6.sin6_addr, lport, sin6.sin6_scope_id,
382 				    INPLOOKUP_WILDCARD);
383 				if (t != NULL &&
384 				    (!IN6_IS_ADDR_UNSPECIFIED(&sin6.sin6_addr) ||
385 				    !IN6_IS_ADDR_UNSPECIFIED(&t->in6p_laddr) ||
386 				    !(t->inp_socket->so_options & SO_REUSEPORT)) &&
387 				    (u != kauth_cred_getuid(t->inp_socket->so_cred)) &&
388 				    !(t->inp_socket->so_flags & SOF_REUSESHAREUID) &&
389 				    (!(t->inp_flags2 & INP2_EXTERNAL_PORT) ||
390 				    !(inp->inp_flags2 & INP2_EXTERNAL_PORT) ||
391 				    uuid_compare(t->necp_client_uuid, inp->necp_client_uuid) != 0)) {
392 					lck_rw_done(&pcbinfo->ipi_lock);
393 					socket_lock(so, 0);
394 					return EADDRINUSE;
395 				}
396 				if (!(inp->inp_flags & IN6P_IPV6_V6ONLY) &&
397 				    IN6_IS_ADDR_UNSPECIFIED(&sin6.sin6_addr)) {
398 					struct sockaddr_in sin;
399 
400 					in6_sin6_2_sin(&sin, &sin6);
401 					t = in_pcblookup_local_and_cleanup(
402 						pcbinfo, sin.sin_addr, lport,
403 						INPLOOKUP_WILDCARD);
404 					if (t != NULL &&
405 					    !(t->inp_socket->so_options & SO_REUSEPORT) &&
406 					    (kauth_cred_getuid(so->so_cred) !=
407 					    kauth_cred_getuid(t->inp_socket->so_cred)) &&
408 					    (t->inp_laddr.s_addr != INADDR_ANY ||
409 					    SOCK_DOM(so) == SOCK_DOM(t->inp_socket)) &&
410 					    (!(t->inp_flags2 & INP2_EXTERNAL_PORT) ||
411 					    !(inp->inp_flags2 & INP2_EXTERNAL_PORT) ||
412 					    uuid_compare(t->necp_client_uuid, inp->necp_client_uuid) != 0)) {
413 						lck_rw_done(&pcbinfo->ipi_lock);
414 						socket_lock(so, 0);
415 						return EADDRINUSE;
416 					}
417 
418 #if SKYWALK
419 					VERIFY(!NETNS_TOKEN_VALID(
420 						    &inp->inp_wildcard_netns_token));
421 					if ((SOCK_PROTO(so) == IPPROTO_TCP ||
422 					    SOCK_PROTO(so) == IPPROTO_UDP) &&
423 					    !(inp->inp_flags2 & INP2_EXTERNAL_PORT)) {
424 						if (netns_reserve_in(&inp->
425 						    inp_wildcard_netns_token,
426 						    sin.sin_addr,
427 						    (uint8_t)SOCK_PROTO(so), lport,
428 						    NETNS_BSD, NULL) != 0) {
429 							lck_rw_done(&pcbinfo->ipi_lock);
430 							socket_lock(so, 0);
431 							return EADDRINUSE;
432 						}
433 					}
434 #endif /* SKYWALK */
435 				}
436 			}
437 			t = in6_pcblookup_local_and_cleanup(pcbinfo,
438 			    &sin6.sin6_addr, lport, sin6.sin6_scope_id, wild);
439 			if (t != NULL &&
440 			    (reuseport & t->inp_socket->so_options) == 0 &&
441 			    (!(t->inp_flags2 & INP2_EXTERNAL_PORT) ||
442 			    !(inp->inp_flags2 & INP2_EXTERNAL_PORT) ||
443 			    uuid_compare(t->necp_client_uuid, inp->necp_client_uuid) != 0)) {
444 #if SKYWALK
445 				netns_release(&inp->inp_wildcard_netns_token);
446 #endif /* SKYWALK */
447 				lck_rw_done(&pcbinfo->ipi_lock);
448 				socket_lock(so, 0);
449 				return EADDRINUSE;
450 			}
451 			if (!(inp->inp_flags & IN6P_IPV6_V6ONLY) &&
452 			    IN6_IS_ADDR_UNSPECIFIED(&sin6.sin6_addr)) {
453 				struct sockaddr_in sin;
454 
455 				in6_sin6_2_sin(&sin, &sin6);
456 				t = in_pcblookup_local_and_cleanup(pcbinfo,
457 				    sin.sin_addr, lport, wild);
458 				if (t != NULL && (reuseport &
459 				    t->inp_socket->so_options) == 0 &&
460 				    (t->inp_laddr.s_addr != INADDR_ANY ||
461 				    SOCK_DOM(so) == SOCK_DOM(t->inp_socket)) &&
462 				    (!(t->inp_flags2 & INP2_EXTERNAL_PORT) ||
463 				    !(inp->inp_flags2 & INP2_EXTERNAL_PORT) ||
464 				    uuid_compare(t->necp_client_uuid, inp->necp_client_uuid) != 0)) {
465 #if SKYWALK
466 					netns_release(&inp->inp_wildcard_netns_token);
467 #endif /* SKYWALK */
468 					lck_rw_done(&pcbinfo->ipi_lock);
469 					socket_lock(so, 0);
470 					return EADDRINUSE;
471 				}
472 #if SKYWALK
473 				if ((SOCK_PROTO(so) == IPPROTO_TCP ||
474 				    SOCK_PROTO(so) == IPPROTO_UDP) &&
475 				    !(inp->inp_flags2 & INP2_EXTERNAL_PORT) &&
476 				    (!NETNS_TOKEN_VALID(
477 					    &inp->inp_wildcard_netns_token))) {
478 					if (netns_reserve_in(&inp->
479 					    inp_wildcard_netns_token,
480 					    sin.sin_addr,
481 					    (uint8_t)SOCK_PROTO(so), lport,
482 					    NETNS_BSD, NULL) != 0) {
483 						lck_rw_done(&pcbinfo->ipi_lock);
484 						socket_lock(so, 0);
485 						return EADDRINUSE;
486 					}
487 				}
488 #endif /* SKYWALK */
489 			}
490 #if SKYWALK
491 			if ((SOCK_PROTO(so) == IPPROTO_TCP ||
492 			    SOCK_PROTO(so) == IPPROTO_UDP) &&
493 			    !(inp->inp_flags2 & INP2_EXTERNAL_PORT)) {
494 				if (netns_reserve_in6(&inp->inp_netns_token,
495 				    sin6.sin6_addr, (uint8_t)SOCK_PROTO(so), lport,
496 				    NETNS_BSD, NULL) != 0) {
497 					netns_release(&inp->inp_wildcard_netns_token);
498 					lck_rw_done(&pcbinfo->ipi_lock);
499 					socket_lock(so, 0);
500 					return EADDRINUSE;
501 				}
502 			}
503 #endif /* SKYWALK */
504 		}
505 	}
506 
507 	socket_lock(so, 0);
508 	/*
509 	 * We unlocked socket's protocol lock for a long time.
510 	 * The socket might have been dropped/defuncted.
511 	 * Checking if world has changed since.
512 	 */
513 	if (inp->inp_state == INPCB_STATE_DEAD) {
514 #if SKYWALK
515 		netns_release(&inp->inp_netns_token);
516 		netns_release(&inp->inp_wildcard_netns_token);
517 #endif /* SKYWALK */
518 		lck_rw_done(&pcbinfo->ipi_lock);
519 		return ECONNABORTED;
520 	}
521 
522 	/* check if the socket got bound when the lock was released */
523 	if (inp->inp_lport || !IN6_IS_ADDR_UNSPECIFIED(&inp->in6p_laddr)) {
524 #if SKYWALK
525 		netns_release(&inp->inp_netns_token);
526 		netns_release(&inp->inp_wildcard_netns_token);
527 #endif /* SKYWALK */
528 		lck_rw_done(&pcbinfo->ipi_lock);
529 		return EINVAL;
530 	}
531 
532 	if (!IN6_IS_ADDR_UNSPECIFIED(&sin6.sin6_addr)) {
533 		inp->in6p_laddr = sin6.sin6_addr;
534 		inp->in6p_last_outifp = outif;
535 		inp->inp_lifscope = lifscope;
536 		in6_verify_ifscope(&inp->in6p_laddr, lifscope);
537 #if SKYWALK
538 		if (NETNS_TOKEN_VALID(&inp->inp_netns_token)) {
539 			netns_set_ifnet(&inp->inp_netns_token,
540 			    inp->in6p_last_outifp);
541 		}
542 #endif /* SKYWALK */
543 	}
544 
545 	if (lport == 0) {
546 		int e;
547 		if ((e = in6_pcbsetport(&inp->in6p_laddr, inp, p, 1)) != 0) {
548 			/* Undo any address bind from above. */
549 #if SKYWALK
550 			netns_release(&inp->inp_netns_token);
551 			netns_release(&inp->inp_wildcard_netns_token);
552 #endif /* SKYWALK */
553 			inp->in6p_laddr = in6addr_any;
554 			inp->in6p_last_outifp = NULL;
555 			inp->inp_lifscope = IFSCOPE_NONE;
556 			lck_rw_done(&pcbinfo->ipi_lock);
557 			return e;
558 		}
559 	} else {
560 		inp->inp_lport = lport;
561 		if (in_pcbinshash(inp, 1) != 0) {
562 #if SKYWALK
563 			netns_release(&inp->inp_netns_token);
564 			netns_release(&inp->inp_wildcard_netns_token);
565 #endif /* SKYWALK */
566 			inp->in6p_laddr = in6addr_any;
567 			inp->inp_lifscope = IFSCOPE_NONE;
568 			inp->inp_lport = 0;
569 			inp->in6p_last_outifp = NULL;
570 			lck_rw_done(&pcbinfo->ipi_lock);
571 			return EAGAIN;
572 		}
573 	}
574 	lck_rw_done(&pcbinfo->ipi_lock);
575 	sflt_notify(so, sock_evt_bound, NULL);
576 	return 0;
577 }
578 
579 /*
580  * Transform old in6_pcbconnect() into an inner subroutine for new
581  * in6_pcbconnect(); do some validity-checking on the remote address
582  * (in "nam") and then determine local host address (i.e., which
583  * interface) to use to access that remote host.
584  *
585  * This routine may alter the caller-supplied remote address "nam".
586  *
587  * This routine might return an ifp with a reference held if the caller
588  * provides a non-NULL outif, even in the error case.  The caller is
589  * responsible for releasing its reference.
590  */
591 int
in6_pcbladdr(struct inpcb * inp,struct sockaddr * nam,struct in6_addr * plocal_addr6,struct ifnet ** outif)592 in6_pcbladdr(struct inpcb *inp, struct sockaddr *nam,
593     struct in6_addr *plocal_addr6, struct ifnet **outif)
594 {
595 	struct in6_addr *addr6 = NULL;
596 	struct in6_addr src_storage;
597 	int error = 0;
598 	unsigned int ifscope;
599 
600 	if (outif != NULL) {
601 		*outif = NULL;
602 	}
603 	if (nam->sa_len != sizeof(struct sockaddr_in6)) {
604 		return EINVAL;
605 	}
606 	if (SIN6(nam)->sin6_family != AF_INET6) {
607 		return EAFNOSUPPORT;
608 	}
609 	if (SIN6(nam)->sin6_port == 0) {
610 		return EADDRNOTAVAIL;
611 	}
612 
613 	/* KAME hack: embed scopeid */
614 	if (in6_embedscope(&SIN6(nam)->sin6_addr, SIN6(nam), inp, NULL, NULL, IN6_NULL_IF_EMBEDDED_SCOPE(&SIN6(nam)->sin6_scope_id)) != 0) {
615 		return EINVAL;
616 	}
617 
618 	if (!TAILQ_EMPTY(&in6_ifaddrhead)) {
619 		/*
620 		 * If the destination address is UNSPECIFIED addr,
621 		 * use the loopback addr, e.g ::1.
622 		 */
623 		if (IN6_IS_ADDR_UNSPECIFIED(&SIN6(nam)->sin6_addr)) {
624 			SIN6(nam)->sin6_addr = in6addr_loopback;
625 		}
626 	}
627 
628 	ifscope = (inp->inp_flags & INP_BOUND_IF) ?
629 	    inp->inp_boundifp->if_index : IFSCOPE_NONE;
630 
631 	/*
632 	 * XXX: in6_selectsrc might replace the bound local address
633 	 * with the address specified by setsockopt(IPV6_PKTINFO).
634 	 * Is it the intended behavior?
635 	 *
636 	 * in6_selectsrc() might return outif with its reference held
637 	 * even in the error case; caller always needs to release it
638 	 * if non-NULL.
639 	 */
640 	addr6 = in6_selectsrc(SIN6(nam), inp->in6p_outputopts, inp,
641 	    &inp->in6p_route, outif, &src_storage, ifscope, &error);
642 
643 	if (outif != NULL) {
644 		struct rtentry *rt = inp->in6p_route.ro_rt;
645 		/*
646 		 * If in6_selectsrc() returns a route, it should be one
647 		 * which points to the same ifp as outif.  Just in case
648 		 * it isn't, use the one from the route for consistency.
649 		 * Otherwise if there is no route, leave outif alone as
650 		 * it could still be useful to the caller.
651 		 */
652 		if (rt != NULL && rt->rt_ifp != *outif) {
653 			ifnet_reference(rt->rt_ifp);    /* for caller */
654 			if (*outif != NULL) {
655 				ifnet_release(*outif);
656 			}
657 			*outif = rt->rt_ifp;
658 		}
659 	}
660 
661 	if (addr6 == NULL) {
662 		if (outif != NULL && (*outif) != NULL &&
663 		    inp_restricted_send(inp, *outif)) {
664 			soevent(inp->inp_socket,
665 			    (SO_FILT_HINT_LOCKED | SO_FILT_HINT_IFDENIED));
666 			error = EHOSTUNREACH;
667 		}
668 		if (error == 0) {
669 			error = EADDRNOTAVAIL;
670 		}
671 		return error;
672 	}
673 
674 	*plocal_addr6 = *addr6;
675 	/*
676 	 * Don't do pcblookup call here; return interface in
677 	 * plocal_addr6 and exit to caller, that will do the lookup.
678 	 */
679 	return 0;
680 }
681 
682 /*
683  * Outer subroutine:
684  * Connect from a socket to a specified address.
685  * Both address and port must be specified in argument sin.
686  * If don't have a local address for this socket yet,
687  * then pick one.
688  */
689 int
in6_pcbconnect(struct inpcb * inp,struct sockaddr * nam,struct proc * p)690 in6_pcbconnect(struct inpcb *inp, struct sockaddr *nam, struct proc *p)
691 {
692 	struct in6_addr addr6;
693 	struct sockaddr_in6 *sin6 = (struct sockaddr_in6 *)(void *)nam;
694 	struct inpcb *pcb;
695 	int error = 0;
696 	struct ifnet *outif = NULL;
697 	struct socket *so = inp->inp_socket;
698 
699 #if CONTENT_FILTER
700 	so->so_state_change_cnt++;
701 #endif
702 
703 	if (so->so_proto->pr_protocol == IPPROTO_UDP &&
704 	    sin6->sin6_port == htons(53) && !(so->so_flags1 & SOF1_DNS_COUNTED)) {
705 		so->so_flags1 |= SOF1_DNS_COUNTED;
706 		INC_ATOMIC_INT64_LIM(net_api_stats.nas_socket_inet_dgram_dns);
707 	}
708 
709 	/*
710 	 * Call inner routine, to assign local interface address.
711 	 * in6_pcbladdr() may automatically fill in sin6_scope_id.
712 	 *
713 	 * in6_pcbladdr() might return an ifp with its reference held
714 	 * even in the error case, so make sure that it's released
715 	 * whenever it's non-NULL.
716 	 */
717 	if ((error = in6_pcbladdr(inp, nam, &addr6, &outif)) != 0) {
718 		if (outif != NULL && inp_restricted_send(inp, outif)) {
719 			soevent(so,
720 			    (SO_FILT_HINT_LOCKED | SO_FILT_HINT_IFDENIED));
721 		}
722 		goto done;
723 	}
724 	socket_unlock(so, 0);
725 
726 	uint32_t lifscope;
727 	if (!IN6_IS_ADDR_UNSPECIFIED(&inp->in6p_laddr)) {
728 		lifscope = inp->inp_lifscope;
729 	} else if (outif != NULL) {
730 		lifscope = in6_addr2scopeid(outif, &addr6);
731 	} else {
732 		lifscope = sin6->sin6_scope_id;
733 	}
734 
735 	pcb = in6_pcblookup_hash(inp->inp_pcbinfo, &sin6->sin6_addr,
736 	    sin6->sin6_port, sin6->sin6_scope_id, IN6_IS_ADDR_UNSPECIFIED(&inp->in6p_laddr) ?
737 	    &addr6 : &inp->in6p_laddr, inp->inp_lport, lifscope, 0, NULL);
738 	socket_lock(so, 0);
739 	if (pcb != NULL) {
740 		in_pcb_checkstate(pcb, WNT_RELEASE, pcb == inp ? 1 : 0);
741 		error = EADDRINUSE;
742 		goto done;
743 	}
744 	if (IN6_IS_ADDR_UNSPECIFIED(&inp->in6p_laddr)) {
745 		if (inp->inp_lport == 0) {
746 			error = in6_pcbbind(inp, NULL, p);
747 			if (error) {
748 				goto done;
749 			}
750 		}
751 		inp->in6p_laddr = addr6;
752 		inp->in6p_last_outifp = outif;  /* no reference needed */
753 		if (IN6_IS_SCOPE_EMBED(&inp->in6p_laddr) &&
754 		    IN6_ARE_ADDR_EQUAL(&inp->in6p_laddr, &sin6->sin6_addr)) {
755 			inp->inp_lifscope = sin6->sin6_scope_id;
756 		} else {
757 			inp->inp_lifscope = lifscope;
758 		}
759 		in6_verify_ifscope(&inp->in6p_laddr, inp->inp_lifscope);
760 #if SKYWALK
761 		if (NETNS_TOKEN_VALID(&inp->inp_netns_token)) {
762 			netns_set_ifnet(&inp->inp_netns_token,
763 			    inp->in6p_last_outifp);
764 		}
765 #endif /* SKYWALK */
766 		inp->in6p_flags |= INP_IN6ADDR_ANY;
767 	}
768 	if (!lck_rw_try_lock_exclusive(&inp->inp_pcbinfo->ipi_lock)) {
769 		/* lock inversion issue, mostly with udp multicast packets */
770 		socket_unlock(so, 0);
771 		lck_rw_lock_exclusive(&inp->inp_pcbinfo->ipi_lock);
772 		socket_lock(so, 0);
773 	}
774 	inp->in6p_faddr = sin6->sin6_addr;
775 	inp->inp_fport = sin6->sin6_port;
776 	inp->inp_fifscope = sin6->sin6_scope_id;
777 	in6_verify_ifscope(&inp->in6p_faddr, inp->inp_fifscope);
778 	if (nstat_collect && SOCK_PROTO(so) == IPPROTO_UDP) {
779 		nstat_pcb_invalidate_cache(inp);
780 	}
781 	in_pcbrehash(inp);
782 	lck_rw_done(&inp->inp_pcbinfo->ipi_lock);
783 
784 done:
785 	if (outif != NULL) {
786 		ifnet_release(outif);
787 	}
788 
789 	return error;
790 }
791 
792 void
in6_pcbdisconnect(struct inpcb * inp)793 in6_pcbdisconnect(struct inpcb *inp)
794 {
795 	struct socket *so = inp->inp_socket;
796 
797 #if CONTENT_FILTER
798 	if (so) {
799 		so->so_state_change_cnt++;
800 	}
801 #endif
802 
803 	if (!lck_rw_try_lock_exclusive(&inp->inp_pcbinfo->ipi_lock)) {
804 		/* lock inversion issue, mostly with udp multicast packets */
805 		socket_unlock(so, 0);
806 		lck_rw_lock_exclusive(&inp->inp_pcbinfo->ipi_lock);
807 		socket_lock(so, 0);
808 	}
809 	if (nstat_collect && SOCK_PROTO(so) == IPPROTO_UDP) {
810 		nstat_pcb_cache(inp);
811 	}
812 	bzero((caddr_t)&inp->in6p_faddr, sizeof(inp->in6p_faddr));
813 	inp->inp_fport = 0;
814 	/* clear flowinfo - RFC 6437 */
815 	inp->inp_flow &= ~IPV6_FLOWLABEL_MASK;
816 	in_pcbrehash(inp);
817 	lck_rw_done(&inp->inp_pcbinfo->ipi_lock);
818 	/*
819 	 * A multipath subflow socket would have its SS_NOFDREF set by default,
820 	 * so check for SOF_MP_SUBFLOW socket flag before detaching the PCB;
821 	 * when the socket is closed for real, SOF_MP_SUBFLOW would be cleared.
822 	 */
823 	if (!(so->so_flags & SOF_MP_SUBFLOW) && (so->so_state & SS_NOFDREF)) {
824 		in6_pcbdetach(inp);
825 	}
826 }
827 
828 void
in6_pcbdetach(struct inpcb * inp)829 in6_pcbdetach(struct inpcb *inp)
830 {
831 	struct socket *so = inp->inp_socket;
832 
833 	if (so->so_pcb == NULL) {
834 		/* PCB has been disposed */
835 		panic("%s: inp=%p so=%p proto=%d so_pcb is null!", __func__,
836 		    inp, so, SOCK_PROTO(so));
837 		/* NOTREACHED */
838 	}
839 
840 #if IPSEC
841 	if (inp->in6p_sp != NULL) {
842 		(void) ipsec6_delete_pcbpolicy(inp);
843 	}
844 #endif /* IPSEC */
845 
846 	if (inp->inp_stat != NULL && SOCK_PROTO(so) == IPPROTO_UDP) {
847 		if (inp->inp_stat->rxpackets == 0 && inp->inp_stat->txpackets == 0) {
848 			INC_ATOMIC_INT64_LIM(net_api_stats.nas_socket_inet6_dgram_no_data);
849 		}
850 	}
851 
852 	/*
853 	 * Let NetworkStatistics know this PCB is going away
854 	 * before we detach it.
855 	 */
856 	if (nstat_collect &&
857 	    (SOCK_PROTO(so) == IPPROTO_TCP || SOCK_PROTO(so) == IPPROTO_UDP)) {
858 		nstat_pcb_detach(inp);
859 	}
860 	/* mark socket state as dead */
861 	if (in_pcb_checkstate(inp, WNT_STOPUSING, 1) != WNT_STOPUSING) {
862 		panic("%s: so=%p proto=%d couldn't set to STOPUSING",
863 		    __func__, so, SOCK_PROTO(so));
864 		/* NOTREACHED */
865 	}
866 
867 	if (!(so->so_flags & SOF_PCBCLEARING)) {
868 		struct ip_moptions *imo;
869 		struct ip6_moptions *im6o;
870 
871 		inp->inp_vflag = 0;
872 		if (inp->in6p_options != NULL) {
873 			m_freem(inp->in6p_options);
874 			inp->in6p_options = NULL;
875 		}
876 		ip6_freepcbopts(inp->in6p_outputopts);
877 		inp->in6p_outputopts = NULL;
878 		ROUTE_RELEASE(&inp->in6p_route);
879 		/* free IPv4 related resources in case of mapped addr */
880 		if (inp->inp_options != NULL) {
881 			(void) m_free(inp->inp_options);
882 			inp->inp_options = NULL;
883 		}
884 		im6o = inp->in6p_moptions;
885 		inp->in6p_moptions = NULL;
886 		if (im6o != NULL) {
887 			IM6O_REMREF(im6o);
888 		}
889 		imo = inp->inp_moptions;
890 		inp->inp_moptions = NULL;
891 		if (imo != NULL) {
892 			IMO_REMREF(imo);
893 		}
894 
895 		sofreelastref(so, 0);
896 		inp->inp_state = INPCB_STATE_DEAD;
897 		/* makes sure we're not called twice from so_close */
898 		so->so_flags |= SOF_PCBCLEARING;
899 
900 		inpcb_gc_sched(inp->inp_pcbinfo, INPCB_TIMER_FAST);
901 	}
902 }
903 
904 struct sockaddr *
in6_sockaddr(in_port_t port,struct in6_addr * addr_p,uint32_t ifscope)905 in6_sockaddr(in_port_t port, struct in6_addr *addr_p, uint32_t ifscope)
906 {
907 	struct sockaddr_in6 *sin6;
908 
909 	sin6 = (struct sockaddr_in6 *)alloc_sockaddr(sizeof(*sin6),
910 	    Z_WAITOK | Z_NOFAIL);
911 
912 	sin6->sin6_family = AF_INET6;
913 	sin6->sin6_port = port;
914 	sin6->sin6_addr = *addr_p;
915 
916 	/* would be good to use sa6_recoverscope(), except for locking  */
917 	if (IN6_IS_SCOPE_EMBED(&sin6->sin6_addr)) {
918 		sin6->sin6_scope_id = ifscope;
919 		if (in6_embedded_scope) {
920 			in6_verify_ifscope(&sin6->sin6_addr, ifscope);
921 			sin6->sin6_scope_id = ntohs(sin6->sin6_addr.s6_addr16[1]);
922 		}
923 	} else {
924 		sin6->sin6_scope_id = 0;        /* XXX */
925 	}
926 	if (in6_embedded_scope && IN6_IS_SCOPE_LINKLOCAL(&sin6->sin6_addr)) {
927 		sin6->sin6_addr.s6_addr16[1] = 0;
928 	}
929 
930 	return (struct sockaddr *)sin6;
931 }
932 
933 void
in6_sockaddr_s(in_port_t port,struct in6_addr * addr_p,struct sockaddr_in6 * sin6,uint32_t ifscope)934 in6_sockaddr_s(in_port_t port, struct in6_addr *addr_p,
935     struct sockaddr_in6 *sin6, uint32_t ifscope)
936 {
937 	bzero(sin6, sizeof(*sin6));
938 	sin6->sin6_family = AF_INET6;
939 	sin6->sin6_len = sizeof(*sin6);
940 	sin6->sin6_port = port;
941 	sin6->sin6_addr = *addr_p;
942 
943 	/* would be good to use sa6_recoverscope(), except for locking  */
944 	if (IN6_IS_SCOPE_LINKLOCAL(&sin6->sin6_addr)) {
945 		sin6->sin6_scope_id = ifscope;
946 		if (in6_embedded_scope) {
947 			in6_verify_ifscope(&sin6->sin6_addr, ifscope);
948 			sin6->sin6_scope_id = ntohs(sin6->sin6_addr.s6_addr16[1]);
949 		}
950 	} else {
951 		sin6->sin6_scope_id = 0;        /* XXX */
952 	}
953 	if (in6_embedded_scope && IN6_IS_SCOPE_LINKLOCAL(&sin6->sin6_addr)) {
954 		sin6->sin6_addr.s6_addr16[1] = 0;
955 	}
956 }
957 
958 /*
959  * The calling convention of in6_getsockaddr() and in6_getpeeraddr() was
960  * modified to match the pru_sockaddr() and pru_peeraddr() entry points
961  * in struct pr_usrreqs, so that protocols can just reference then directly
962  * without the need for a wrapper function.
963  */
964 int
in6_getsockaddr(struct socket * so,struct sockaddr ** nam)965 in6_getsockaddr(struct socket *so, struct sockaddr **nam)
966 {
967 	struct inpcb *inp;
968 	struct in6_addr addr;
969 	in_port_t port;
970 
971 	if ((inp = sotoinpcb(so)) == NULL) {
972 		return EINVAL;
973 	}
974 
975 	port = inp->inp_lport;
976 	addr = inp->in6p_laddr;
977 
978 	*nam = in6_sockaddr(port, &addr, inp->inp_lifscope);
979 	if (*nam == NULL) {
980 		return ENOBUFS;
981 	}
982 	return 0;
983 }
984 
985 int
in6_getsockaddr_s(struct socket * so,struct sockaddr_in6 * ss)986 in6_getsockaddr_s(struct socket *so, struct sockaddr_in6 *ss)
987 {
988 	struct inpcb *inp;
989 	struct in6_addr addr;
990 	in_port_t port;
991 
992 	VERIFY(ss != NULL);
993 	bzero(ss, sizeof(*ss));
994 
995 	if ((inp = sotoinpcb(so)) == NULL) {
996 		return EINVAL;
997 	}
998 
999 	port = inp->inp_lport;
1000 	addr = inp->in6p_laddr;
1001 
1002 	in6_sockaddr_s(port, &addr, ss, inp->inp_lifscope);
1003 	return 0;
1004 }
1005 
1006 int
in6_getpeeraddr(struct socket * so,struct sockaddr ** nam)1007 in6_getpeeraddr(struct socket *so, struct sockaddr **nam)
1008 {
1009 	struct inpcb *inp;
1010 	struct in6_addr addr;
1011 	in_port_t port;
1012 
1013 	if ((inp = sotoinpcb(so)) == NULL) {
1014 		return EINVAL;
1015 	}
1016 
1017 	port = inp->inp_fport;
1018 	addr = inp->in6p_faddr;
1019 
1020 	*nam = in6_sockaddr(port, &addr, inp->inp_fifscope);
1021 	if (*nam == NULL) {
1022 		return ENOBUFS;
1023 	}
1024 	return 0;
1025 }
1026 
1027 int
in6_mapped_sockaddr(struct socket * so,struct sockaddr ** nam)1028 in6_mapped_sockaddr(struct socket *so, struct sockaddr **nam)
1029 {
1030 	struct  inpcb *inp = sotoinpcb(so);
1031 	int     error;
1032 
1033 	if (inp == NULL) {
1034 		return EINVAL;
1035 	}
1036 	if (inp->inp_vflag & INP_IPV4) {
1037 		error = in_getsockaddr(so, nam);
1038 		if (error == 0) {
1039 			error = in6_sin_2_v4mapsin6_in_sock(nam);
1040 		}
1041 	} else {
1042 		/* scope issues will be handled in in6_getsockaddr(). */
1043 		error = in6_getsockaddr(so, nam);
1044 	}
1045 	return error;
1046 }
1047 
1048 int
in6_mapped_peeraddr(struct socket * so,struct sockaddr ** nam)1049 in6_mapped_peeraddr(struct socket *so, struct sockaddr **nam)
1050 {
1051 	struct  inpcb *inp = sotoinpcb(so);
1052 	int     error;
1053 
1054 	if (inp == NULL) {
1055 		return EINVAL;
1056 	}
1057 	if (inp->inp_vflag & INP_IPV4) {
1058 		error = in_getpeeraddr(so, nam);
1059 		if (error == 0) {
1060 			error = in6_sin_2_v4mapsin6_in_sock(nam);
1061 		}
1062 	} else {
1063 		/* scope issues will be handled in in6_getpeeraddr(). */
1064 		error = in6_getpeeraddr(so, nam);
1065 	}
1066 	return error;
1067 }
1068 
1069 /*
1070  * Pass some notification to all connections of a protocol
1071  * associated with address dst.  The local address and/or port numbers
1072  * may be specified to limit the search.  The "usual action" will be
1073  * taken, depending on the ctlinput cmd.  The caller must filter any
1074  * cmds that are uninteresting (e.g., no error in the map).
1075  * Call the protocol specific routine (if any) to report
1076  * any errors for each matching socket.
1077  */
1078 void
in6_pcbnotify(struct inpcbinfo * pcbinfo,struct sockaddr * dst,u_int fport_arg,const struct sockaddr * src,u_int lport_arg,int cmd,void * cmdarg,void (* notify)(struct inpcb *,int))1079 in6_pcbnotify(struct inpcbinfo *pcbinfo, struct sockaddr *dst, u_int fport_arg,
1080     const struct sockaddr *src, u_int lport_arg, int cmd, void *cmdarg,
1081     void (*notify)(struct inpcb *, int))
1082 {
1083 	struct inpcbhead *head = pcbinfo->ipi_listhead;
1084 	struct inpcb *inp, *ninp;
1085 	struct sockaddr_in6 sa6_src, *sa6_dst;
1086 	uint16_t fport = (uint16_t)fport_arg, lport = (uint16_t)lport_arg;
1087 	u_int32_t flowinfo;
1088 	int errno;
1089 
1090 	if ((unsigned)cmd >= PRC_NCMDS || dst->sa_family != AF_INET6) {
1091 		return;
1092 	}
1093 
1094 	sa6_dst = (struct sockaddr_in6 *)(void *)dst;
1095 	if (IN6_IS_ADDR_UNSPECIFIED(&sa6_dst->sin6_addr)) {
1096 		return;
1097 	}
1098 
1099 	/*
1100 	 * note that src can be NULL when we get notify by local fragmentation.
1101 	 */
1102 	sa6_src = (src == NULL) ?
1103 	    sa6_any : *(struct sockaddr_in6 *)(uintptr_t)(size_t)src;
1104 	flowinfo = sa6_src.sin6_flowinfo;
1105 
1106 	/*
1107 	 * Redirects go to all references to the destination,
1108 	 * and use in6_rtchange to invalidate the route cache.
1109 	 * Dead host indications: also use in6_rtchange to invalidate
1110 	 * the cache, and deliver the error to all the sockets.
1111 	 * Otherwise, if we have knowledge of the local port and address,
1112 	 * deliver only to that socket.
1113 	 */
1114 	if (PRC_IS_REDIRECT(cmd) || cmd == PRC_HOSTDEAD) {
1115 		fport = 0;
1116 		lport = 0;
1117 		bzero((caddr_t)&sa6_src.sin6_addr, sizeof(sa6_src.sin6_addr));
1118 
1119 		if (cmd != PRC_HOSTDEAD) {
1120 			notify = in6_rtchange;
1121 		}
1122 	}
1123 	errno = inet6ctlerrmap[cmd];
1124 	lck_rw_lock_shared(&pcbinfo->ipi_lock);
1125 	for (inp = LIST_FIRST(head); inp != NULL; inp = ninp) {
1126 		ninp = LIST_NEXT(inp, inp_list);
1127 
1128 		if (!(inp->inp_vflag & INP_IPV6)) {
1129 			continue;
1130 		}
1131 
1132 		/*
1133 		 * If the error designates a new path MTU for a destination
1134 		 * and the application (associated with this socket) wanted to
1135 		 * know the value, notify. Note that we notify for all
1136 		 * disconnected sockets if the corresponding application
1137 		 * wanted. This is because some UDP applications keep sending
1138 		 * sockets disconnected.
1139 		 * XXX: should we avoid to notify the value to TCP sockets?
1140 		 */
1141 		if (cmd == PRC_MSGSIZE && cmdarg != NULL) {
1142 			socket_lock(inp->inp_socket, 1);
1143 			ip6_notify_pmtu(inp, (struct sockaddr_in6 *)(void *)dst,
1144 			    (u_int32_t *)cmdarg);
1145 			socket_unlock(inp->inp_socket, 1);
1146 		}
1147 
1148 		/*
1149 		 * Detect if we should notify the error. If no source and
1150 		 * destination ports are specifed, but non-zero flowinfo and
1151 		 * local address match, notify the error. This is the case
1152 		 * when the error is delivered with an encrypted buffer
1153 		 * by ESP. Otherwise, just compare addresses and ports
1154 		 * as usual.
1155 		 */
1156 		if (lport == 0 && fport == 0 && flowinfo &&
1157 		    inp->inp_socket != NULL &&
1158 		    flowinfo == (inp->inp_flow & IPV6_FLOWLABEL_MASK) &&
1159 		    in6_are_addr_equal_scoped(&inp->in6p_laddr, &sa6_src.sin6_addr, inp->inp_lifscope, sa6_src.sin6_scope_id)) {
1160 			goto do_notify;
1161 		} else if (!in6_are_addr_equal_scoped(&inp->in6p_faddr, &sa6_dst->sin6_addr,
1162 		    inp->inp_fifscope, sa6_dst->sin6_scope_id) || inp->inp_socket == NULL ||
1163 		    (lport && inp->inp_lport != lport) ||
1164 		    (!IN6_IS_ADDR_UNSPECIFIED(&sa6_src.sin6_addr) &&
1165 		    !in6_are_addr_equal_scoped(&inp->in6p_laddr, &sa6_src.sin6_addr, inp->inp_lifscope, sa6_src.sin6_scope_id)) || (fport && inp->inp_fport != fport)) {
1166 			continue;
1167 		}
1168 
1169 do_notify:
1170 		if (notify) {
1171 			if (in_pcb_checkstate(inp, WNT_ACQUIRE, 0) ==
1172 			    WNT_STOPUSING) {
1173 				continue;
1174 			}
1175 			socket_lock(inp->inp_socket, 1);
1176 			(*notify)(inp, errno);
1177 			(void) in_pcb_checkstate(inp, WNT_RELEASE, 1);
1178 			socket_unlock(inp->inp_socket, 1);
1179 		}
1180 	}
1181 	lck_rw_done(&pcbinfo->ipi_lock);
1182 }
1183 
1184 /*
1185  * Lookup a PCB based on the local address and port.
1186  */
1187 struct inpcb *
in6_pcblookup_local(struct inpcbinfo * pcbinfo,struct in6_addr * laddr,u_int lport_arg,uint32_t ifscope,int wild_okay)1188 in6_pcblookup_local(struct inpcbinfo *pcbinfo, struct in6_addr *laddr,
1189     u_int lport_arg, uint32_t ifscope, int wild_okay)
1190 {
1191 	struct inpcb *inp;
1192 	int matchwild = 3, wildcard;
1193 	uint16_t lport = (uint16_t)lport_arg;
1194 	struct inpcbporthead *porthash;
1195 	struct inpcb *match = NULL;
1196 	struct inpcbport *phd;
1197 
1198 	if (!wild_okay) {
1199 		struct inpcbhead *head;
1200 		/*
1201 		 * Look for an unconnected (wildcard foreign addr) PCB that
1202 		 * matches the local address and port we're looking for.
1203 		 */
1204 		head = &pcbinfo->ipi_hashbase[INP_PCBHASH(INADDR_ANY, lport, 0,
1205 		    pcbinfo->ipi_hashmask)];
1206 		LIST_FOREACH(inp, head, inp_hash) {
1207 			if (!(inp->inp_vflag & INP_IPV6)) {
1208 				continue;
1209 			}
1210 			if (IN6_IS_ADDR_UNSPECIFIED(&inp->in6p_faddr) &&
1211 			    in6_are_addr_equal_scoped(&inp->in6p_laddr, laddr, inp->inp_lifscope, ifscope) &&
1212 			    inp->inp_lport == lport) {
1213 				/*
1214 				 * Found.
1215 				 */
1216 				return inp;
1217 			}
1218 		}
1219 		/*
1220 		 * Not found.
1221 		 */
1222 		return NULL;
1223 	}
1224 	/*
1225 	 * Best fit PCB lookup.
1226 	 *
1227 	 * First see if this local port is in use by looking on the
1228 	 * port hash list.
1229 	 */
1230 	porthash = &pcbinfo->ipi_porthashbase[INP_PCBPORTHASH(lport,
1231 	    pcbinfo->ipi_porthashmask)];
1232 	LIST_FOREACH(phd, porthash, phd_hash) {
1233 		if (phd->phd_port == lport) {
1234 			break;
1235 		}
1236 	}
1237 	if (phd != NULL) {
1238 		/*
1239 		 * Port is in use by one or more PCBs. Look for best
1240 		 * fit.
1241 		 */
1242 		LIST_FOREACH(inp, &phd->phd_pcblist, inp_portlist) {
1243 			wildcard = 0;
1244 			if (!(inp->inp_vflag & INP_IPV6)) {
1245 				continue;
1246 			}
1247 			if (!IN6_IS_ADDR_UNSPECIFIED(&inp->in6p_faddr)) {
1248 				wildcard++;
1249 			}
1250 			if (!IN6_IS_ADDR_UNSPECIFIED(&inp->in6p_laddr)) {
1251 				if (IN6_IS_ADDR_UNSPECIFIED(laddr)) {
1252 					wildcard++;
1253 				} else if (!in6_are_addr_equal_scoped(
1254 					    &inp->in6p_laddr, laddr, inp->inp_lifscope, ifscope)) {
1255 					continue;
1256 				}
1257 			} else {
1258 				if (!IN6_IS_ADDR_UNSPECIFIED(laddr)) {
1259 					wildcard++;
1260 				}
1261 			}
1262 			if (wildcard < matchwild) {
1263 				match = inp;
1264 				matchwild = wildcard;
1265 				if (matchwild == 0) {
1266 					break;
1267 				}
1268 			}
1269 		}
1270 	}
1271 	return match;
1272 }
1273 
1274 /*
1275  * Check for alternatives when higher level complains
1276  * about service problems.  For now, invalidate cached
1277  * routing information.  If the route was created dynamically
1278  * (by a redirect), time to try a default gateway again.
1279  */
1280 void
in6_losing(struct inpcb * in6p)1281 in6_losing(struct inpcb *in6p)
1282 {
1283 	struct rtentry *rt;
1284 
1285 	if ((rt = in6p->in6p_route.ro_rt) != NULL) {
1286 		RT_LOCK(rt);
1287 		if (rt->rt_flags & RTF_DYNAMIC) {
1288 			/*
1289 			 * Prevent another thread from modifying rt_key,
1290 			 * rt_gateway via rt_setgate() after the rt_lock
1291 			 * is dropped by marking the route as defunct.
1292 			 */
1293 			rt->rt_flags |= RTF_CONDEMNED;
1294 			RT_UNLOCK(rt);
1295 			(void) rtrequest(RTM_DELETE, rt_key(rt),
1296 			    rt->rt_gateway, rt_mask(rt), rt->rt_flags, NULL);
1297 		} else {
1298 			RT_UNLOCK(rt);
1299 		}
1300 		/*
1301 		 * A new route can be allocated
1302 		 * the next time output is attempted.
1303 		 */
1304 	}
1305 	ROUTE_RELEASE(&in6p->in6p_route);
1306 }
1307 
1308 /*
1309  * After a routing change, flush old routing
1310  * and allocate a (hopefully) better one.
1311  */
1312 void
in6_rtchange(struct inpcb * inp,int errno)1313 in6_rtchange(struct inpcb *inp, int errno)
1314 {
1315 #pragma unused(errno)
1316 	/*
1317 	 * A new route can be allocated the next time
1318 	 * output is attempted.
1319 	 */
1320 	ROUTE_RELEASE(&inp->in6p_route);
1321 }
1322 
1323 /*
1324  * Check if PCB exists hash list. Also returns uid and gid of socket
1325  */
1326 int
in6_pcblookup_hash_exists(struct inpcbinfo * pcbinfo,struct in6_addr * faddr,u_int fport_arg,uint32_t fifscope,struct in6_addr * laddr,u_int lport_arg,uint32_t lifscope,int wildcard,uid_t * uid,gid_t * gid,struct ifnet * ifp,bool relaxed)1327 in6_pcblookup_hash_exists(struct inpcbinfo *pcbinfo, struct in6_addr *faddr,
1328     u_int fport_arg, uint32_t fifscope, struct in6_addr *laddr, u_int lport_arg, uint32_t lifscope, int wildcard,
1329     uid_t *uid, gid_t *gid, struct ifnet *ifp, bool relaxed)
1330 {
1331 	struct inpcbhead *head;
1332 	struct inpcb *inp;
1333 	uint16_t fport = (uint16_t)fport_arg, lport = (uint16_t)lport_arg;
1334 	int found;
1335 
1336 	*uid = UID_MAX;
1337 	*gid = GID_MAX;
1338 
1339 	lck_rw_lock_shared(&pcbinfo->ipi_lock);
1340 
1341 	/*
1342 	 * First look for an exact match.
1343 	 */
1344 	head = &pcbinfo->ipi_hashbase[INP_PCBHASH(faddr->s6_addr32[3] /* XXX */,
1345 	    lport, fport, pcbinfo->ipi_hashmask)];
1346 	LIST_FOREACH(inp, head, inp_hash) {
1347 		if (!(inp->inp_vflag & INP_IPV6)) {
1348 			continue;
1349 		}
1350 
1351 		if (inp_restricted_recv(inp, ifp)) {
1352 			continue;
1353 		}
1354 
1355 #if NECP
1356 		if (!necp_socket_is_allowed_to_recv_on_interface(inp, ifp)) {
1357 			continue;
1358 		}
1359 #endif /* NECP */
1360 
1361 		if (((in6_are_addr_equal_scoped(&inp->in6p_faddr, faddr, inp->inp_fifscope, fifscope) &&
1362 		    in6_are_addr_equal_scoped(&inp->in6p_laddr, laddr, inp->inp_lifscope, lifscope)) ||
1363 		    (relaxed &&
1364 		    IN6_ARE_ADDR_EQUAL(&inp->in6p_faddr, faddr) &&
1365 		    IN6_ARE_ADDR_EQUAL(&inp->in6p_laddr, laddr))) &&
1366 		    inp->inp_fport == fport &&
1367 		    inp->inp_lport == lport) {
1368 			if ((found = (inp->inp_socket != NULL))) {
1369 				/*
1370 				 * Found. Check if pcb is still valid
1371 				 */
1372 				*uid = kauth_cred_getuid(
1373 					inp->inp_socket->so_cred);
1374 				*gid = kauth_cred_getgid(
1375 					inp->inp_socket->so_cred);
1376 			}
1377 			lck_rw_done(&pcbinfo->ipi_lock);
1378 			return found;
1379 		}
1380 	}
1381 	if (wildcard) {
1382 		struct inpcb *local_wild = NULL;
1383 
1384 		head = &pcbinfo->ipi_hashbase[INP_PCBHASH(INADDR_ANY, lport, 0,
1385 		    pcbinfo->ipi_hashmask)];
1386 		LIST_FOREACH(inp, head, inp_hash) {
1387 			if (!(inp->inp_vflag & INP_IPV6)) {
1388 				continue;
1389 			}
1390 
1391 			if (inp_restricted_recv(inp, ifp)) {
1392 				continue;
1393 			}
1394 
1395 #if NECP
1396 			if (!necp_socket_is_allowed_to_recv_on_interface(inp, ifp)) {
1397 				continue;
1398 			}
1399 #endif /* NECP */
1400 
1401 			if (IN6_IS_ADDR_UNSPECIFIED(&inp->in6p_faddr) &&
1402 			    inp->inp_lport == lport) {
1403 				if (in6_are_addr_equal_scoped(&inp->in6p_laddr,
1404 				    laddr, inp->inp_lifscope, lifscope) ||
1405 				    (relaxed && IN6_ARE_ADDR_EQUAL(&inp->in6p_laddr, laddr))) {
1406 					found = (inp->inp_socket != NULL);
1407 					if (found) {
1408 						*uid = kauth_cred_getuid(
1409 							inp->inp_socket->so_cred);
1410 						*gid = kauth_cred_getgid(
1411 							inp->inp_socket->so_cred);
1412 					}
1413 					lck_rw_done(&pcbinfo->ipi_lock);
1414 					return found;
1415 				} else if (IN6_IS_ADDR_UNSPECIFIED(
1416 					    &inp->in6p_laddr)) {
1417 					local_wild = inp;
1418 				}
1419 			}
1420 		}
1421 		if (local_wild) {
1422 			if ((found = (local_wild->inp_socket != NULL))) {
1423 				*uid = kauth_cred_getuid(
1424 					local_wild->inp_socket->so_cred);
1425 				*gid = kauth_cred_getgid(
1426 					local_wild->inp_socket->so_cred);
1427 			}
1428 			lck_rw_done(&pcbinfo->ipi_lock);
1429 			return found;
1430 		}
1431 	}
1432 
1433 	/*
1434 	 * Not found.
1435 	 */
1436 	lck_rw_done(&pcbinfo->ipi_lock);
1437 	return 0;
1438 }
1439 
1440 /*
1441  * Lookup PCB in hash list.
1442  */
1443 struct inpcb *
in6_pcblookup_hash(struct inpcbinfo * pcbinfo,struct in6_addr * faddr,u_int fport_arg,uint32_t fifscope,struct in6_addr * laddr,u_int lport_arg,uint32_t lifscope,int wildcard,struct ifnet * ifp)1444 in6_pcblookup_hash(struct inpcbinfo *pcbinfo, struct in6_addr *faddr,
1445     u_int fport_arg, uint32_t fifscope, struct in6_addr *laddr, u_int lport_arg, uint32_t lifscope, int wildcard,
1446     struct ifnet *ifp)
1447 {
1448 	struct inpcbhead *head;
1449 	struct inpcb *inp;
1450 	uint16_t fport = (uint16_t)fport_arg, lport = (uint16_t)lport_arg;
1451 
1452 	lck_rw_lock_shared(&pcbinfo->ipi_lock);
1453 
1454 	/*
1455 	 * First look for an exact match.
1456 	 */
1457 	head = &pcbinfo->ipi_hashbase[INP_PCBHASH(faddr->s6_addr32[3] /* XXX */,
1458 	    lport, fport, pcbinfo->ipi_hashmask)];
1459 	LIST_FOREACH(inp, head, inp_hash) {
1460 		if (!(inp->inp_vflag & INP_IPV6)) {
1461 			continue;
1462 		}
1463 
1464 		if (inp_restricted_recv(inp, ifp)) {
1465 			continue;
1466 		}
1467 
1468 #if NECP
1469 		if (!necp_socket_is_allowed_to_recv_on_interface(inp, ifp)) {
1470 			continue;
1471 		}
1472 #endif /* NECP */
1473 
1474 		if (in6_are_addr_equal_scoped(&inp->in6p_faddr, faddr, inp->inp_fifscope, fifscope) &&
1475 		    in6_are_addr_equal_scoped(&inp->in6p_laddr, laddr, inp->inp_lifscope, lifscope) &&
1476 		    inp->inp_fport == fport &&
1477 		    inp->inp_lport == lport) {
1478 			/*
1479 			 * Found. Check if pcb is still valid
1480 			 */
1481 			if (in_pcb_checkstate(inp, WNT_ACQUIRE, 0) !=
1482 			    WNT_STOPUSING) {
1483 				lck_rw_done(&pcbinfo->ipi_lock);
1484 				return inp;
1485 			} else {
1486 				/* it's there but dead, say it isn't found */
1487 				lck_rw_done(&pcbinfo->ipi_lock);
1488 				return NULL;
1489 			}
1490 		}
1491 	}
1492 	if (wildcard) {
1493 		struct inpcb *local_wild = NULL;
1494 
1495 		head = &pcbinfo->ipi_hashbase[INP_PCBHASH(INADDR_ANY, lport, 0,
1496 		    pcbinfo->ipi_hashmask)];
1497 		LIST_FOREACH(inp, head, inp_hash) {
1498 			if (!(inp->inp_vflag & INP_IPV6)) {
1499 				continue;
1500 			}
1501 
1502 			if (inp_restricted_recv(inp, ifp)) {
1503 				continue;
1504 			}
1505 
1506 #if NECP
1507 			if (!necp_socket_is_allowed_to_recv_on_interface(inp, ifp)) {
1508 				continue;
1509 			}
1510 #endif /* NECP */
1511 
1512 			if (IN6_IS_ADDR_UNSPECIFIED(&inp->in6p_faddr) &&
1513 			    inp->inp_lport == lport) {
1514 				if (in6_are_addr_equal_scoped(&inp->in6p_laddr,
1515 				    laddr, inp->inp_lifscope, lifscope)) {
1516 					if (in_pcb_checkstate(inp, WNT_ACQUIRE,
1517 					    0) != WNT_STOPUSING) {
1518 						lck_rw_done(&pcbinfo->ipi_lock);
1519 						return inp;
1520 					} else {
1521 						/* dead; say it isn't found */
1522 						lck_rw_done(&pcbinfo->ipi_lock);
1523 						return NULL;
1524 					}
1525 				} else if (IN6_IS_ADDR_UNSPECIFIED(
1526 					    &inp->in6p_laddr)) {
1527 					local_wild = inp;
1528 				}
1529 			}
1530 		}
1531 		if (local_wild && in_pcb_checkstate(local_wild,
1532 		    WNT_ACQUIRE, 0) != WNT_STOPUSING) {
1533 			lck_rw_done(&pcbinfo->ipi_lock);
1534 			return local_wild;
1535 		} else {
1536 			lck_rw_done(&pcbinfo->ipi_lock);
1537 			return NULL;
1538 		}
1539 	}
1540 
1541 	/*
1542 	 * Not found.
1543 	 */
1544 	lck_rw_done(&pcbinfo->ipi_lock);
1545 	return NULL;
1546 }
1547 
1548 void
init_sin6(struct sockaddr_in6 * sin6,struct mbuf * m)1549 init_sin6(struct sockaddr_in6 *sin6, struct mbuf *m)
1550 {
1551 	struct ip6_hdr *ip;
1552 
1553 	ip = mtod(m, struct ip6_hdr *);
1554 	bzero(sin6, sizeof(*sin6));
1555 	sin6->sin6_len = sizeof(*sin6);
1556 	sin6->sin6_family = AF_INET6;
1557 	sin6->sin6_addr = ip->ip6_src;
1558 	if (IN6_IS_SCOPE_LINKLOCAL(&sin6->sin6_addr)) {
1559 		if (in6_embedded_scope) {
1560 			sin6->sin6_addr.s6_addr16[1] = 0;
1561 		}
1562 		if ((m->m_pkthdr.pkt_flags & (PKTF_LOOP | PKTF_IFAINFO)) ==
1563 		    (PKTF_LOOP | PKTF_IFAINFO)) {
1564 			sin6->sin6_scope_id = m->m_pkthdr.src_ifindex;
1565 		} else if (m->m_pkthdr.rcvif != NULL) {
1566 			sin6->sin6_scope_id = m->m_pkthdr.rcvif->if_index;
1567 		}
1568 	}
1569 }
1570 
1571 /*
1572  * The following routines implement this scheme:
1573  *
1574  * Callers of ip6_output() that intend to cache the route in the inpcb pass
1575  * a local copy of the struct route to ip6_output().  Using a local copy of
1576  * the cached route significantly simplifies things as IP no longer has to
1577  * worry about having exclusive access to the passed in struct route, since
1578  * it's defined in the caller's stack; in essence, this allows for a lock-
1579  * less operation when updating the struct route at the IP level and below,
1580  * whenever necessary. The scheme works as follows:
1581  *
1582  * Prior to dropping the socket's lock and calling ip6_output(), the caller
1583  * copies the struct route from the inpcb into its stack, and adds a reference
1584  * to the cached route entry, if there was any.  The socket's lock is then
1585  * dropped and ip6_output() is called with a pointer to the copy of struct
1586  * route defined on the stack (not to the one in the inpcb.)
1587  *
1588  * Upon returning from ip6_output(), the caller then acquires the socket's
1589  * lock and synchronizes the cache; if there is no route cached in the inpcb,
1590  * it copies the local copy of struct route (which may or may not contain any
1591  * route) back into the cache; otherwise, if the inpcb has a route cached in
1592  * it, the one in the local copy will be freed, if there's any.  Trashing the
1593  * cached route in the inpcb can be avoided because ip6_output() is single-
1594  * threaded per-PCB (i.e. multiple transmits on a PCB are always serialized
1595  * by the socket/transport layer.)
1596  */
1597 void
in6p_route_copyout(struct inpcb * inp,struct route_in6 * dst)1598 in6p_route_copyout(struct inpcb *inp, struct route_in6 *dst)
1599 {
1600 	struct route_in6 *src = &inp->in6p_route;
1601 
1602 	socket_lock_assert_owned(inp->inp_socket);
1603 
1604 	/* Minor sanity check */
1605 	if (src->ro_rt != NULL && rt_key(src->ro_rt)->sa_family != AF_INET6) {
1606 		panic("%s: wrong or corrupted route: %p", __func__, src);
1607 	}
1608 
1609 	route_copyout((struct route *)dst, (struct route *)src, sizeof(*dst));
1610 }
1611 
1612 void
in6p_route_copyin(struct inpcb * inp,struct route_in6 * src)1613 in6p_route_copyin(struct inpcb *inp, struct route_in6 *src)
1614 {
1615 	struct route_in6 *dst = &inp->in6p_route;
1616 
1617 	socket_lock_assert_owned(inp->inp_socket);
1618 
1619 	/* Minor sanity check */
1620 	if (src->ro_rt != NULL && rt_key(src->ro_rt)->sa_family != AF_INET6) {
1621 		panic("%s: wrong or corrupted route: %p", __func__, src);
1622 	}
1623 
1624 	route_copyin((struct route *)src, (struct route *)dst, sizeof(*src));
1625 }
1626