xref: /xnu-11215.81.4/bsd/netinet6/nd6_rtr.c (revision d4514f0bc1d3f944c22d92e68b646ac3fb40d452)
1 /*
2  * Copyright (c) 2003-2024 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 /*
30  * Copyright (C) 1995, 1996, 1997, and 1998 WIDE Project.
31  * All rights reserved.
32  *
33  * Redistribution and use in source and binary forms, with or without
34  * modification, are permitted provided that the following conditions
35  * are met:
36  * 1. Redistributions of source code must retain the above copyright
37  *    notice, this list of conditions and the following disclaimer.
38  * 2. Redistributions in binary form must reproduce the above copyright
39  *    notice, this list of conditions and the following disclaimer in the
40  *    documentation and/or other materials provided with the distribution.
41  * 3. Neither the name of the project nor the names of its contributors
42  *    may be used to endorse or promote products derived from this software
43  *    without specific prior written permission.
44  *
45  * THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND
46  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
47  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
48  * ARE DISCLAIMED.  IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE
49  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
50  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
51  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
52  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
53  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
54  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
55  * SUCH DAMAGE.
56  */
57 #include <sys/param.h>
58 #include <sys/systm.h>
59 #include <sys/malloc.h>
60 #include <sys/mbuf.h>
61 #include <sys/socket.h>
62 #include <sys/sockio.h>
63 #include <sys/time.h>
64 #include <sys/kernel.h>
65 #include <sys/errno.h>
66 #include <sys/syslog.h>
67 #include <sys/queue.h>
68 #include <sys/mcache.h>
69 #include <sys/protosw.h>
70 
71 #include <dev/random/randomdev.h>
72 
73 #include <kern/locks.h>
74 #include <kern/zalloc.h>
75 #include <machine/machine_routines.h>
76 
77 #include <net/if.h>
78 #include <net/if_var.h>
79 #include <net/if_types.h>
80 #include <net/if_dl.h>
81 #include <net/route.h>
82 #include <net/radix.h>
83 
84 #include <netinet/in.h>
85 #include <netinet6/in6_var.h>
86 #include <netinet6/in6_ifattach.h>
87 #include <netinet/ip6.h>
88 #include <netinet6/ip6_var.h>
89 #include <netinet6/nd6.h>
90 #include <netinet/icmp6.h>
91 #include <netinet6/scope6_var.h>
92 
93 #include <net/net_osdep.h>
94 
95 #include <net/sockaddr_utils.h>
96 
97 static void defrouter_addreq(struct nd_defrouter *, struct nd_route_info *, boolean_t);
98 static struct nd_defrouter *defrtrlist_update_common(struct nd_defrouter *,
99     struct nd_drhead *, boolean_t);
100 static void pfxrtr_add(struct nd_prefix *, struct nd_defrouter *);
101 static void pfxrtr_del(struct nd_pfxrouter *, struct nd_prefix *);
102 static struct nd_pfxrouter *find_pfxlist_reachable_router(struct nd_prefix *);
103 static void nd6_rtmsg(u_char, struct rtentry *);
104 
105 static int nd6_prefix_onlink_common(struct nd_prefix *, boolean_t,
106     unsigned int);
107 static struct nd_prefix *nd6_prefix_equal_lookup(struct nd_prefix *, boolean_t);
108 static void nd6_prefix_sync(struct ifnet *);
109 
110 static void in6_init_address_ltimes(struct in6_addrlifetime *);
111 static int rt6_deleteroute(struct radix_node *, void *);
112 
113 static struct nd_defrouter *nddr_alloc(zalloc_flags_t);
114 static void nddr_free(struct nd_defrouter *);
115 static void nddr_trace(struct nd_defrouter *, int);
116 
117 static struct nd_prefix *ndpr_alloc(int);
118 static void ndpr_free(struct nd_prefix *);
119 static void ndpr_trace(struct nd_prefix *, int);
120 
121 extern int nd6_recalc_reachtm_interval;
122 
123 static struct ifnet *nd6_defifp = NULL;
124 int nd6_defifindex = 0;
125 static unsigned int nd6_defrouter_genid;
126 
127 int ip6_use_tempaddr = IP6_USE_TMPADDR_DEFAULT; /* use temp addr by default for testing now */
128 int ip6_ula_use_tempaddr = IP6_ULA_USE_TMPADDR_DEFAULT;
129 
130 int nd6_accept_6to4 = 1;
131 
132 int ip6_desync_factor;
133 u_int32_t ip6_temp_preferred_lifetime = DEF_TEMP_PREFERRED_LIFETIME;
134 u_int32_t ip6_temp_valid_lifetime = DEF_TEMP_VALID_LIFETIME;
135 /*
136  * shorter lifetimes for debugging purposes.
137  *	u_int32_t ip6_temp_preferred_lifetime = 800;
138  *	static u_int32_t ip6_temp_valid_lifetime = 1800;
139  */
140 int ip6_temp_regen_advance = TEMPADDR_REGEN_ADVANCE;
141 
142 /* Serialization variables for single thread access to nd_prefix */
143 static boolean_t nd_prefix_busy;
144 static void *nd_prefix_waitchan = &nd_prefix_busy;
145 static int nd_prefix_waiters = 0;
146 
147 /* Serialization variables for single thread access to nd_defrouter */
148 static boolean_t nd_defrouter_busy;
149 static void *nd_defrouter_waitchan = &nd_defrouter_busy;
150 static int nd_defrouter_waiters = 0;
151 
152 #define equal(a1, a2) (bcmp((caddr_t)(a1), (caddr_t)(a2), (a1)->sa_len) == 0)
153 /* RTPREF_MEDIUM has to be 0! */
154 #define RTPREF_HIGH     1
155 #define RTPREF_MEDIUM   0
156 #define RTPREF_LOW      (-1)
157 #define RTPREF_RESERVED (-2)
158 #define RTPREF_INVALID  (-3)    /* internal */
159 
160 #define NDPR_TRACE_HIST_SIZE    32              /* size of trace history */
161 
162 /* For gdb */
163 __private_extern__ unsigned int ndpr_trace_hist_size = NDPR_TRACE_HIST_SIZE;
164 
165 struct nd_prefix_dbg {
166 	struct nd_prefix        ndpr_pr;                /* nd_prefix */
167 	u_int16_t               ndpr_refhold_cnt;       /* # of ref */
168 	u_int16_t               ndpr_refrele_cnt;       /* # of rele */
169 	/*
170 	 * Circular lists of ndpr_addref and ndpr_remref callers.
171 	 */
172 	ctrace_t                ndpr_refhold[NDPR_TRACE_HIST_SIZE];
173 	ctrace_t                ndpr_refrele[NDPR_TRACE_HIST_SIZE];
174 };
175 
176 static unsigned int ndpr_debug;                 /* debug flags */
177 ZONE_DECLARE(ndpr_zone, struct nd_prefix);
178 #define NDPR_ZONE_NAME  "nd6_prefix"            /* zone name */
179 zone_t ndpr_zone = {0};                         /* zone for nd_prefix */
180 
181 #define NDDR_TRACE_HIST_SIZE    32              /* size of trace history */
182 
183 /* For gdb */
184 __private_extern__ unsigned int nddr_trace_hist_size = NDDR_TRACE_HIST_SIZE;
185 
186 struct nd_defrouter_dbg {
187 	struct nd_defrouter     nddr_dr;                /* nd_defrouter */
188 	uint16_t                nddr_refhold_cnt;       /* # of ref */
189 	uint16_t                nddr_refrele_cnt;       /* # of rele */
190 	/*
191 	 * Circular lists of nddr_addref and nddr_remref callers.
192 	 */
193 	ctrace_t                nddr_refhold[NDDR_TRACE_HIST_SIZE];
194 	ctrace_t                nddr_refrele[NDDR_TRACE_HIST_SIZE];
195 };
196 
197 static unsigned int nddr_debug;                 /* debug flags */
198 ZONE_DECLARE(nddr_zone, struct nd_defrouter);
199 #define NDDR_ZONE_NAME  "nd6_defrouter"         /* zone name */
200 zone_t nddr_zone = {0};                         /* zone for nd_defrouter */
201 
202 static KALLOC_TYPE_DEFINE(ndprtr_zone, struct nd_pfxrouter, NET_KT_DEFAULT);
203 
204 #define TWOHOUR         (120*60)
205 extern int nd6_process_rti;                     /* Default to 0 for now */
206 
207 
208 static void
nd6_prefix_glb_init(void)209 nd6_prefix_glb_init(void)
210 {
211 	PE_parse_boot_argn("ifa_debug", &ndpr_debug, sizeof(ndpr_debug));
212 	vm_size_t ndpr_size = (ndpr_debug == 0) ? sizeof(struct nd_prefix) :
213 	    sizeof(struct nd_prefix_dbg);
214 	ndpr_zone = zone_create(NDPR_ZONE_NAME, ndpr_size, ZC_ZFREE_CLEARMEM);
215 }
216 
217 static void
nd6_defrouter_glb_init(void)218 nd6_defrouter_glb_init(void)
219 {
220 	PE_parse_boot_argn("ifa_debug", &nddr_debug, sizeof(nddr_debug));
221 	vm_size_t nddr_size = (nddr_debug == 0) ? sizeof(struct nd_defrouter) :
222 	    sizeof(struct nd_defrouter_dbg);
223 	nddr_zone = zone_create(NDDR_ZONE_NAME, nddr_size, ZC_ZFREE_CLEARMEM);
224 }
225 
226 void
nd6_rtr_init(void)227 nd6_rtr_init(void)
228 {
229 	nd6_prefix_glb_init();
230 	nd6_defrouter_glb_init();
231 }
232 
233 /*
234  * Receive Router Solicitation Message - just for routers.
235  * Router solicitation/advertisement is mostly managed by userland program
236  * (rtadvd) so here we have no function like nd6_ra_output().
237  *
238  * Based on RFC 2461
239  */
240 void
nd6_rs_input(struct mbuf * m,int off,int icmp6len)241 nd6_rs_input(
242 	struct  mbuf *m,
243 	int off,
244 	int icmp6len)
245 {
246 	struct ifnet *ifp = m->m_pkthdr.rcvif;
247 	struct ip6_hdr *ip6 = mtod(m, struct ip6_hdr *);
248 	struct nd_router_solicit *nd_rs = NULL;
249 	struct in6_addr saddr6 = ip6->ip6_src;
250 	char *lladdr = NULL;
251 	int lladdrlen = 0;
252 	union nd_opts ndopts = {};
253 
254 	/* Expect 32-bit aligned data pointer on strict-align platforms */
255 	MBUF_STRICT_DATA_ALIGNMENT_CHECK_32(m);
256 
257 	/* If I'm not a router, ignore it. */
258 	if (!ip6_forwarding || ifp->if_ipv6_router_mode == IPV6_ROUTER_MODE_DISABLED) {
259 		goto freeit;
260 	}
261 
262 	/* Sanity checks */
263 	if (ip6->ip6_hlim != IPV6_MAXHLIM) {
264 		nd6log(error,
265 		    "nd6_rs_input: invalid hlim (%d) from %s to %s on %s\n",
266 		    ip6->ip6_hlim, ip6_sprintf(&ip6->ip6_src),
267 		    ip6_sprintf(&ip6->ip6_dst), if_name(ifp));
268 		goto bad;
269 	}
270 
271 	/*
272 	 * Don't update the neighbor cache, if src = :: or a non-neighbor.
273 	 * The former case indicates that the src has no IP address assigned
274 	 * yet.  See nd6_ns_input() for the latter case.
275 	 */
276 	if (IN6_IS_ADDR_UNSPECIFIED(&ip6->ip6_src)) {
277 		goto freeit;
278 	} else {
279 		struct sockaddr_in6 src_sa6;
280 
281 		SOCKADDR_ZERO(&src_sa6, sizeof(src_sa6));
282 		src_sa6.sin6_family = AF_INET6;
283 		src_sa6.sin6_len = sizeof(src_sa6);
284 		src_sa6.sin6_addr = ip6->ip6_src;
285 		src_sa6.sin6_scope_id = (!in6_embedded_scope && IN6_IS_SCOPE_EMBED(&src_sa6.sin6_addr)) ? ip6_input_getsrcifscope(m) : IFSCOPE_NONE;
286 		if (!nd6_is_addr_neighbor(&src_sa6, ifp, 0)) {
287 			nd6log(info, "nd6_rs_input: "
288 			    "RS packet from non-neighbor\n");
289 			goto freeit;
290 		}
291 	}
292 
293 	IP6_EXTHDR_CHECK(m, off, icmp6len, return );
294 	ip6 = mtod(m, struct ip6_hdr *);
295 	nd_rs = (struct nd_router_solicit *)((caddr_t)ip6 + off);
296 
297 	icmp6len -= sizeof(*nd_rs);
298 
299 	nd6_option_init(nd_rs + 1, icmp6len, &ndopts);
300 	if (nd6_options(&ndopts) < 0) {
301 		nd6log(info,
302 		    "nd6_rs_input: invalid ND option, ignored\n");
303 		/* nd6_options have incremented stats */
304 		goto freeit;
305 	}
306 
307 	if (ndopts.nd_opts_src_lladdr) {
308 		ND_OPT_LLADDR(ndopts.nd_opts_src_lladdr, nd_opt_len, lladdr, lladdrlen);
309 	}
310 
311 	if (lladdr && ((ifp->if_addrlen + 2 + 7) & ~7) != lladdrlen) {
312 		nd6log(info,
313 		    "nd6_rs_input: lladdrlen mismatch for %s "
314 		    "(if %d, RS packet %d)\n",
315 		    ip6_sprintf(&saddr6), ifp->if_addrlen, lladdrlen - 2);
316 		goto bad;
317 	}
318 
319 	nd6_cache_lladdr(ifp, &saddr6, lladdr, lladdrlen, ND_ROUTER_SOLICIT, 0, NULL);
320 
321 freeit:
322 	m_freem(m);
323 	return;
324 
325 bad:
326 	icmp6stat.icp6s_badrs++;
327 	m_freem(m);
328 }
329 
330 #define ND_OPT_LEN_TO_BYTE_SCALE        3 /* ND opt len is in units of 8 octets */
331 
332 #define ND_OPT_LEN_RTI_MIN              1
333 #define ND_OPT_LEN_RTI_MAX              3
334 #define ND_OPT_RTI_PFXLEN_MAX           128
335 /*
336  * Receive Router Advertisement Message.
337  *
338  * Based on RFC 2461
339  * TODO: on-link bit on prefix information
340  * TODO: ND_RA_FLAG_{OTHER,MANAGED} processing
341  */
342 void
nd6_ra_input(struct mbuf * m,int off,int icmp6len)343 nd6_ra_input(
344 	struct mbuf *m,
345 	int off,
346 	int icmp6len)
347 {
348 	ifnet_ref_t ifp = m->m_pkthdr.rcvif;
349 	struct nd_ifinfo *ndi = NULL;
350 	struct ip6_hdr *ip6 = mtod(m, struct ip6_hdr *);
351 	struct nd_router_advert *nd_ra;
352 	struct in6_addr saddr6 = ip6->ip6_src;
353 	int mcast = 0;
354 	union nd_opts ndopts;
355 	struct nd_defrouter *dr = NULL;
356 	u_int32_t mtu = 0;
357 	char *lladdr = NULL;
358 	u_int32_t lladdrlen = 0;
359 	struct nd_prefix_list *nd_prefix_list_head = NULL;
360 	u_int32_t nd_prefix_list_length = 0;
361 	struct in6_ifaddr *ia6 = NULL;
362 	struct nd_prefix_list *__single prfl;
363 	struct nd_defrouter dr0 = {0};
364 	u_int32_t advreachable;
365 	boolean_t rti_defrtr_processed = FALSE;
366 	boolean_t is_local_ra = FALSE;
367 
368 #if (DEVELOPMENT || DEBUG)
369 	if (ip6_accept_rtadv == 0) {
370 		goto freeit;
371 	}
372 #endif /* (DEVELOPMENT || DEBUG) */
373 	/* Expect 32-bit aligned data pointer on strict-align platforms */
374 	MBUF_STRICT_DATA_ALIGNMENT_CHECK_32(m);
375 
376 	/*
377 	 * Accept the RA if IFEF_ACCEPT_RTADV is set, or when
378 	 * the RA is locally generated.
379 	 *
380 	 * For convenience, we allow locally generated (rtadvd)
381 	 * RAs to be processed on the advertising interface, as a router.
382 	 *
383 	 * Note that we don't test against ip6_forwarding as we could be
384 	 * both a host and a router on different interfaces, hence the
385 	 * check against the per-interface flags.
386 	 */
387 
388 	is_local_ra = (ia6 = ifa_foraddr6(&saddr6)) != NULL;
389 	if (ia6 != NULL) {
390 		ifa_remref(&ia6->ia_ifa);
391 		ia6 = NULL;
392 	}
393 
394 	if ((ifp->if_eflags & IFEF_ACCEPT_RTADV) == 0) {
395 		if (is_local_ra) {
396 			/* accept locally generated RA */
397 		} else {
398 			nd6log(debug,
399 			    "%s: skipping RA from %s to %s on %s, accept RA: %d local RA=%d\n",
400 			    __func__,
401 			    ip6_sprintf(&ip6->ip6_src),
402 			    ip6_sprintf(&ip6->ip6_dst), if_name(ifp),
403 			    (ifp->if_eflags & IFEF_ACCEPT_RTADV) == 0, is_local_ra);
404 			goto freeit;
405 		}
406 	}
407 
408 	if (ip6->ip6_hlim != IPV6_MAXHLIM) {
409 		nd6log(error,
410 		    "nd6_ra_input: invalid hlim (%d) from %s to %s on %s\n",
411 		    ip6->ip6_hlim, ip6_sprintf(&ip6->ip6_src),
412 		    ip6_sprintf(&ip6->ip6_dst), if_name(ifp));
413 		goto bad;
414 	}
415 
416 	if (!IN6_IS_ADDR_LINKLOCAL(&saddr6)) {
417 		nd6log(error,
418 		    "nd6_ra_input: src %s is not link-local\n",
419 		    ip6_sprintf(&saddr6));
420 		goto bad;
421 	}
422 
423 	nd6log(debug, "%s: accepting RA from %s to %s on %s, local RA=%d\n",
424 	    __func__,
425 	    ip6_sprintf(&ip6->ip6_src),
426 	    ip6_sprintf(&ip6->ip6_dst), if_name(ifp), is_local_ra);
427 
428 	IP6_EXTHDR_CHECK(m, off, icmp6len, return );
429 	ip6 = mtod(m, struct ip6_hdr *);
430 	nd_ra = (struct nd_router_advert *)((caddr_t)ip6 + off);
431 
432 	icmp6len -= sizeof(*nd_ra);
433 
434 	nd6_option_init(nd_ra + 1, icmp6len, &ndopts);
435 	if (nd6_options(&ndopts) < 0) {
436 		nd6log(info,
437 		    "nd6_ra_input: invalid ND option, ignored\n");
438 		/* nd6_options have incremented stats */
439 		goto freeit;
440 	}
441 
442 	advreachable = nd_ra->nd_ra_reachable;
443 
444 	/* remember if this is a multicasted advertisement */
445 	if (IN6_IS_ADDR_MULTICAST(&ip6->ip6_dst)) {
446 		mcast = 1;
447 	}
448 
449 	ndi = ND_IFINFO(ifp);
450 	VERIFY(NULL != ndi && TRUE == ndi->initialized);
451 	lck_mtx_lock(&ndi->lock);
452 	/* unspecified or not? (RFC 2461 6.3.4) */
453 	if (advreachable) {
454 		advreachable = ntohl(advreachable);
455 		if (advreachable <= MAX_REACHABLE_TIME &&
456 		    ndi->basereachable != advreachable) {
457 			ndi->basereachable = advreachable;
458 			ndi->reachable = ND_COMPUTE_RTIME(ndi->basereachable);
459 			ndi->recalctm = nd6_recalc_reachtm_interval; /* reset */
460 		}
461 	}
462 	if (nd_ra->nd_ra_retransmit) {
463 		ndi->retrans = ntohl(nd_ra->nd_ra_retransmit);
464 	}
465 	if (nd_ra->nd_ra_curhoplimit) {
466 		if (ndi->chlim < nd_ra->nd_ra_curhoplimit) {
467 			ndi->chlim = nd_ra->nd_ra_curhoplimit;
468 		} else if (ndi->chlim != nd_ra->nd_ra_curhoplimit) {
469 			nd6log(error,
470 			    "RA with a lower CurHopLimit sent from "
471 			    "%s on %s (current = %d, received = %d). "
472 			    "Ignored.\n", ip6_sprintf(&ip6->ip6_src),
473 			    if_name(ifp), ndi->chlim,
474 			    nd_ra->nd_ra_curhoplimit);
475 		}
476 	}
477 	lck_mtx_unlock(&ndi->lock);
478 
479 	/* Initialize nd_defrouter invariants for RA processing */
480 	bzero(&dr0, sizeof(dr0));
481 	dr0.rtaddr = saddr6;
482 	dr0.ifp = ifp;
483 	if (is_local_ra == TRUE) {
484 		dr0.stateflags |= NDDRF_LOCAL;
485 	}
486 
487 	/*
488 	 * Route Information Option (RIO)
489 	 */
490 	if (ndopts.nd_opts_rti && IFNET_IS_ETHERNET(ifp)) {
491 		struct nd_opt_hdr *rt = NULL;
492 		struct sockaddr_in6 rti_gateway = {0};
493 
494 		rti_gateway.sin6_family = AF_INET6;
495 		rti_gateway.sin6_len = sizeof(rti_gateway);
496 		memcpy(&rti_gateway.sin6_addr, &saddr6, sizeof(rti_gateway.sin6_addr));
497 
498 		for (rt = TAKE_ND_NEXT_OPT(ndopts.nd_opts_rti, nd_opts_rti, nd_opts_last);
499 		    rt <= (struct nd_opt_hdr *)ndopts.nd_opts_rti_end;
500 		    rt = (struct nd_opt_hdr *)((caddr_t)rt +
501 		    (rt->nd_opt_len << ND_OPT_LEN_TO_BYTE_SCALE))) {
502 			struct sockaddr_in6 rti_prefix = {};
503 			struct nd_route_info rti = {};
504 			struct nd_opt_route_info *rti_opt = NULL;
505 			u_int32_t rounded_prefix_bytes = 0;
506 
507 			if (rt->nd_opt_type != ND_OPT_ROUTE_INFO) {
508 				continue;
509 			}
510 
511 			rti_opt = (struct nd_opt_route_info *)rt;
512 			if ((rti_opt->nd_opt_rti_len < ND_OPT_LEN_RTI_MIN) ||
513 			    (rti_opt->nd_opt_rti_len > ND_OPT_LEN_RTI_MAX)) {
514 				nd6log(info,
515 				    "%s: invalid option "
516 				    "len %d for route information option, "
517 				    "ignored\n", __func__,
518 				    rti_opt->nd_opt_rti_len);
519 				continue;
520 			}
521 
522 			if (rti_opt->nd_opt_rti_prefixlen > ND_OPT_RTI_PFXLEN_MAX) {
523 				nd6log(info,
524 				    "%s: invalid prefix length %d "
525 				    "in the route information option, "
526 				    "ignored\n", __func__, rti_opt->nd_opt_rti_prefixlen);
527 				continue;
528 			}
529 
530 			if (rti_opt->nd_opt_rti_prefixlen != 0 &&
531 			    rti_opt->nd_opt_rti_prefixlen <= 64 &&
532 			    rti_opt->nd_opt_rti_len == ND_OPT_LEN_RTI_MIN) {
533 				nd6log(info,
534 				    "%s: invalid prefix "
535 				    "len %d is OOB for route information option, "
536 				    "with total option length of %d. Ignored.\n",
537 				    __func__, rti_opt->nd_opt_rti_prefixlen,
538 				    rti_opt->nd_opt_rti_len);
539 				continue;
540 			}
541 
542 			if (rti_opt->nd_opt_rti_prefixlen > 64 &&
543 			    rti_opt->nd_opt_rti_len != ND_OPT_LEN_RTI_MAX) {
544 				nd6log(info,
545 				    "%s: invalid prefix "
546 				    "len %d is OOB for route information option, "
547 				    "with total option length of %d. Ignored.\n",
548 				    __func__, rti_opt->nd_opt_rti_prefixlen,
549 				    rti_opt->nd_opt_rti_len);
550 				continue;
551 			}
552 
553 			if ((rti_opt->nd_opt_rti_flags & ND_RA_FLAG_RTPREF_MASK) ==
554 			    ND_RA_FLAG_RTPREF_RSV) {
555 				nd6log(info,
556 				    "%s: using reserved preference mask, "
557 				    "ignored\n", __func__);
558 				continue;
559 			}
560 
561 			rti_prefix.sin6_family = AF_INET6;
562 			rti_prefix.sin6_len = sizeof(rti_prefix);
563 
564 			rounded_prefix_bytes = rti_opt->nd_opt_rti_prefixlen >> 3;
565 			if (rti_opt->nd_opt_rti_prefixlen & 0x7) {
566 				rounded_prefix_bytes++;
567 			}
568 			memcpy(&rti_prefix.sin6_addr, rti_opt + 1, rounded_prefix_bytes);
569 
570 			nd6log(info, "%s: received RA with route opt, "
571 			    "prefix %s/%u pref %u lifetime %u\n", __func__,
572 			    ip6_sprintf(&rti_prefix.sin6_addr),
573 			    rti_opt->nd_opt_rti_prefixlen,
574 			    rti_opt->nd_opt_rti_flags,
575 			    ntohl(rti_opt->nd_opt_rti_lifetime));
576 
577 			dr0.flags  = rti_opt->nd_opt_rti_flags;
578 
579 			/*
580 			 * https://tools.ietf.org/html/rfc4191#section-3.1
581 			 * Type C Host requirements:
582 			 * The Router Preference and Lifetime values in a
583 			 * ::/0 Route Information Option override the
584 			 * preference and lifetime values in the Router
585 			 * Advertisement header.
586 			 */
587 			if (IN6_IS_ADDR_UNSPECIFIED(&rti_prefix.sin6_addr)
588 			    && rti_opt->nd_opt_rti_prefixlen == 0) {
589 				rti_defrtr_processed = TRUE;
590 				/*
591 				 * If the router lifetime is 0, set the state flag
592 				 * to dummy, so that it is skipped and not used as a
593 				 * default router.
594 				 * Set the lifetime to 2 hrs to make sure we get rid
595 				 * of the router eventually if this was indeed for a router
596 				 * going away.
597 				 *
598 				 * We partly have to do this to ensure advertised prefixes
599 				 * stay onlink.
600 				 * A periodic RA would also keep refreshing the cached
601 				 * neighbor cache entry if it contains source link layer
602 				 * information.
603 				 */
604 				if (rti_opt->nd_opt_rti_lifetime == 0) {
605 					dr0.rtlifetime = TWOHOUR;
606 					dr0.stateflags |= NDDRF_INELIGIBLE;
607 				} else {
608 					dr0.rtlifetime = ntohl(rti_opt->nd_opt_rti_lifetime);
609 				}
610 				dr0.expire = net_uptime() + dr0.rtlifetime;
611 
612 				lck_mtx_lock(nd6_mutex);
613 				dr = defrtrlist_update(&dr0, NULL);
614 				if (dr != NULL) {
615 					dr->is_reachable = TRUE;
616 				}
617 				lck_mtx_unlock(nd6_mutex);
618 				continue;
619 			}
620 
621 			dr0.rtlifetime = ntohl(rti_opt->nd_opt_rti_lifetime);
622 			dr0.expire = net_uptime() + dr0.rtlifetime;
623 			bzero(&rti, sizeof(rti));
624 			rti.nd_rti_prefixlen = rti_opt->nd_opt_rti_prefixlen;
625 			rti.nd_rti_prefix = rti_prefix.sin6_addr;
626 			nd6_rtilist_update(&rti, &dr0);
627 		}
628 	}
629 
630 	if (!rti_defrtr_processed) {
631 		dr0.flags = nd_ra->nd_ra_flags_reserved;
632 
633 		/*
634 		 * If the router lifetime is 0, set the state flag
635 		 * to dummy, so that it is skipped and not used as a
636 		 * default router.
637 		 * Set the lifetime to 2 hrs to make sure we get rid
638 		 * of the router eventually if this was indeed for a router
639 		 * going away.
640 		 *
641 		 * We partly have to do this to ensure advertised prefixes
642 		 * stay onlink.
643 		 * A periodic RA would also keep refreshing the cached
644 		 * neighbor cache entry if it contains source link layer
645 		 * information.
646 		 */
647 		if (nd_ra->nd_ra_router_lifetime == 0) {
648 			dr0.rtlifetime = TWOHOUR;
649 			dr0.stateflags |= NDDRF_INELIGIBLE;
650 		} else {
651 			dr0.rtlifetime = ntohs(nd_ra->nd_ra_router_lifetime);
652 		}
653 		dr0.expire = net_uptime() + dr0.rtlifetime;
654 		lck_mtx_lock(nd6_mutex);
655 		dr = defrtrlist_update(&dr0, NULL);
656 		if (dr != NULL) {
657 			dr->is_reachable = TRUE;
658 		}
659 		lck_mtx_unlock(nd6_mutex);
660 	}
661 
662 	/*
663 	 * prefix (PIO)
664 	 */
665 	if (ndopts.nd_opts_pi) {
666 		struct nd_opt_hdr *pt;
667 		struct nd_opt_prefix_info *__single pi = NULL;
668 		struct nd_prefix pr;
669 
670 		for (pt = TAKE_ND_NEXT_OPT(ndopts.nd_opts_pi, nd_opts_pi, nd_opts_last);
671 		    pt <= (struct nd_opt_hdr *)ndopts.nd_opts_pi_end;
672 		    pt = (struct nd_opt_hdr *)((caddr_t)pt +
673 		    (pt->nd_opt_len << ND_OPT_LEN_TO_BYTE_SCALE))) {
674 			struct in6_addr pi_mask;
675 			bzero(&pi_mask, sizeof(pi_mask));
676 
677 			if (pt->nd_opt_type != ND_OPT_PREFIX_INFORMATION) {
678 				continue;
679 			}
680 			pi = (struct nd_opt_prefix_info *)pt;
681 
682 			if (pi->nd_opt_pi_len != 4) {
683 				nd6log(info,
684 				    "nd6_ra_input: invalid option "
685 				    "len %d for prefix information option, "
686 				    "ignored\n", pi->nd_opt_pi_len);
687 				continue;
688 			}
689 
690 			if (128 < pi->nd_opt_pi_prefix_len) {
691 				nd6log(info,
692 				    "nd6_ra_input: invalid prefix "
693 				    "len %d for prefix information option, "
694 				    "ignored\n", pi->nd_opt_pi_prefix_len);
695 				continue;
696 			}
697 
698 			/*
699 			 * To ignore ::/64 make sure bits beyond prefixlen
700 			 * are set to zero
701 			 */
702 			in6_prefixlen2mask(&pi_mask, pi->nd_opt_pi_prefix_len);
703 			pi->nd_opt_pi_prefix.s6_addr32[0] &= pi_mask.s6_addr32[0];
704 			pi->nd_opt_pi_prefix.s6_addr32[1] &= pi_mask.s6_addr32[1];
705 			pi->nd_opt_pi_prefix.s6_addr32[2] &= pi_mask.s6_addr32[2];
706 			pi->nd_opt_pi_prefix.s6_addr32[3] &= pi_mask.s6_addr32[3];
707 
708 			if (IN6_IS_ADDR_UNSPECIFIED(&pi->nd_opt_pi_prefix) ||
709 			    IN6_IS_ADDR_MULTICAST(&pi->nd_opt_pi_prefix) ||
710 			    IN6_IS_ADDR_LINKLOCAL(&pi->nd_opt_pi_prefix)) {
711 				nd6log(info,
712 				    "%s: invalid prefix %s, ignored\n",
713 				    __func__,
714 				    ip6_sprintf(&pi->nd_opt_pi_prefix));
715 				continue;
716 			}
717 
718 			bzero(&pr, sizeof(pr));
719 			lck_mtx_init(&pr.ndpr_lock, &ifa_mtx_grp, &ifa_mtx_attr);
720 			NDPR_LOCK(&pr);
721 			pr.ndpr_prefix.sin6_family = AF_INET6;
722 			pr.ndpr_prefix.sin6_len = sizeof(pr.ndpr_prefix);
723 			pr.ndpr_prefix.sin6_addr = pi->nd_opt_pi_prefix;
724 			pr.ndpr_ifp = m->m_pkthdr.rcvif;
725 
726 			pr.ndpr_raf_onlink = (pi->nd_opt_pi_flags_reserved &
727 			    ND_OPT_PI_FLAG_ONLINK) ? 1 : 0;
728 			pr.ndpr_raf_auto = (pi->nd_opt_pi_flags_reserved &
729 			    ND_OPT_PI_FLAG_AUTO) ? 1 : 0;
730 			pr.ndpr_plen = pi->nd_opt_pi_prefix_len;
731 			pr.ndpr_vltime = ntohl(pi->nd_opt_pi_valid_time);
732 			pr.ndpr_pltime =
733 			    ntohl(pi->nd_opt_pi_preferred_time);
734 
735 			/*
736 			 * Exceptions to stateless autoconfiguration processing:
737 			 * + nd6_accept_6to4 == 0 && address has 6to4 prefix
738 			 * + ip6_only_allow_rfc4193_prefix != 0 &&
739 			 * address not RFC 4193
740 			 */
741 			if (ip6_only_allow_rfc4193_prefix &&
742 			    !IN6_IS_ADDR_UNIQUE_LOCAL(&pi->nd_opt_pi_prefix)) {
743 				nd6log(info,
744 				    "nd6_ra_input: no SLAAC on prefix %s "
745 				    "[not RFC 4193]\n",
746 				    ip6_sprintf(&pi->nd_opt_pi_prefix));
747 				pr.ndpr_raf_auto = 0;
748 			} else if (!nd6_accept_6to4 &&
749 			    IN6_IS_ADDR_6TO4(&pi->nd_opt_pi_prefix)) {
750 				nd6log(info,
751 				    "%s: no SLAAC on prefix %s "
752 				    "[6to4]\n", __func__,
753 				    ip6_sprintf(&pi->nd_opt_pi_prefix));
754 				pr.ndpr_raf_auto = 0;
755 			}
756 
757 			if (in6_init_prefix_ltimes(&pr)) {
758 				NDPR_UNLOCK(&pr);
759 				lck_mtx_destroy(&pr.ndpr_lock, &ifa_mtx_grp);
760 				continue; /* prefix lifetime init failed */
761 			} else {
762 				NDPR_UNLOCK(&pr);
763 			}
764 			(void) prelist_update(&pr, dr, m, mcast);
765 			lck_mtx_destroy(&pr.ndpr_lock, &ifa_mtx_grp);
766 
767 			/*
768 			 * We have to copy the values out after the
769 			 * prelist_update call since some of these values won't
770 			 * be properly set until after the router advertisement
771 			 * updating can vet the values.
772 			 */
773 			prfl = kalloc_type(struct nd_prefix_list,
774 			    Z_WAITOK | Z_ZERO | Z_NOFAIL);
775 
776 			/* this is only for nd6_post_msg(), otherwise unused */
777 			SOCKADDR_COPY(&pr.ndpr_prefix, &prfl->pr.ndpr_prefix,
778 			    sizeof(prfl->pr.ndpr_prefix));
779 			prfl->pr.ndpr_raf = pr.ndpr_raf;
780 			prfl->pr.ndpr_plen = pr.ndpr_plen;
781 			prfl->pr.ndpr_vltime = pr.ndpr_vltime;
782 			prfl->pr.ndpr_pltime = pr.ndpr_pltime;
783 			prfl->pr.ndpr_expire = pr.ndpr_expire;
784 			prfl->pr.ndpr_base_calendartime =
785 			    pr.ndpr_base_calendartime;
786 			prfl->pr.ndpr_base_uptime = pr.ndpr_base_uptime;
787 			prfl->pr.ndpr_stateflags = pr.ndpr_stateflags;
788 			prfl->pr.ndpr_addrcnt = pr.ndpr_addrcnt;
789 			prfl->pr.ndpr_ifp = pr.ndpr_ifp;
790 
791 			prfl->next = nd_prefix_list_head;
792 			nd_prefix_list_head = prfl;
793 			nd_prefix_list_length++;
794 		}
795 	}
796 
797 
798 	/*
799 	 * MTU
800 	 */
801 	if (ndopts.nd_opts_mtu && ndopts.nd_opts_mtu->nd_opt_mtu_len == 1) {
802 		mtu = ntohl(ndopts.nd_opts_mtu->nd_opt_mtu_mtu);
803 		/* lower bound */
804 		if (mtu < IPV6_MMTU) {
805 			nd6log(info, "nd6_ra_input: bogus mtu option "
806 			    "mtu=%d sent from %s, ignoring\n",
807 			    mtu, ip6_sprintf(&ip6->ip6_src));
808 			goto skip;
809 		}
810 
811 		lck_mtx_lock(&ndi->lock);
812 		/* upper bound */
813 		if (ndi->maxmtu) {
814 			if (mtu <= ndi->maxmtu) {
815 				int change = (ndi->linkmtu != mtu);
816 
817 				ndi->linkmtu = mtu;
818 				lck_mtx_unlock(&ndi->lock);
819 				if (change) { /* in6_maxmtu may change */
820 					in6_setmaxmtu();
821 				}
822 			} else {
823 				nd6log(info, "nd6_ra_input: bogus mtu "
824 				    "mtu=%d sent from %s; "
825 				    "exceeds maxmtu %d, ignoring\n",
826 				    mtu, ip6_sprintf(&ip6->ip6_src),
827 				    ndi->maxmtu);
828 				lck_mtx_unlock(&ndi->lock);
829 			}
830 		} else {
831 			lck_mtx_unlock(&ndi->lock);
832 			nd6log(info, "nd6_ra_input: mtu option "
833 			    "mtu=%d sent from %s; maxmtu unknown, "
834 			    "ignoring\n",
835 			    mtu, ip6_sprintf(&ip6->ip6_src));
836 		}
837 	}
838 
839 skip:
840 
841 	/*
842 	 * Source link layer address
843 	 */
844 	if (ndopts.nd_opts_src_lladdr) {
845 		ND_OPT_LLADDR(ndopts.nd_opts_src_lladdr, nd_opt_len, lladdr, lladdrlen);
846 	}
847 
848 	if (lladdr && ((ifp->if_addrlen + 2 + 7) & ~7) != lladdrlen) {
849 		nd6log(info,
850 		    "nd6_ra_input: lladdrlen mismatch for %s "
851 		    "(if %d, RA packet %d)\n",
852 		    ip6_sprintf(&saddr6), ifp->if_addrlen, lladdrlen - 2);
853 		goto bad;
854 	}
855 
856 	if (dr && dr->stateflags & NDDRF_MAPPED) {
857 		saddr6 = dr->rtaddr_mapped;
858 	}
859 
860 	nd6_cache_lladdr(ifp, &saddr6, lladdr, (int)lladdrlen,
861 	    ND_ROUTER_ADVERT, 0, NULL);
862 
863 	/* Post message */
864 	nd6_post_msg(KEV_ND6_RA, nd_prefix_list_head, nd_prefix_list_length,
865 	    mtu);
866 
867 	/*
868 	 * Installing a link-layer address might change the state of the
869 	 * router's neighbor cache, which might also affect our on-link
870 	 * detection of adveritsed prefixes.
871 	 */
872 	lck_mtx_lock(nd6_mutex);
873 	pfxlist_onlink_check();
874 	lck_mtx_unlock(nd6_mutex);
875 
876 freeit:
877 	m_freem(m);
878 	if (dr) {
879 		NDDR_REMREF(dr);
880 	}
881 
882 	prfl = NULL;
883 	while ((prfl = nd_prefix_list_head) != NULL) {
884 		nd_prefix_list_head = prfl->next;
885 		kfree_type(struct nd_prefix_list, prfl);
886 	}
887 
888 	return;
889 
890 bad:
891 	icmp6stat.icp6s_badra++;
892 	goto freeit;
893 }
894 
895 /*
896  * default router list processing sub routines
897  */
898 
899 /* tell the change to user processes watching the routing socket. */
900 static void
nd6_rtmsg(u_char cmd,struct rtentry * rt)901 nd6_rtmsg(u_char cmd, struct rtentry *rt)
902 {
903 	struct rt_addrinfo info;
904 	struct ifnet *ifp = rt->rt_ifp;
905 
906 	RT_LOCK_ASSERT_HELD(rt);
907 
908 	bzero((caddr_t)&info, sizeof(info));
909 	/* It's not necessary to lock ifp for if_lladdr */
910 	info.rti_info[RTAX_DST] = rt_key(rt);
911 	info.rti_info[RTAX_GATEWAY] = rt->rt_gateway;
912 	info.rti_info[RTAX_NETMASK] = rt_mask(rt);
913 	/*
914 	 * ifa_addr pointers for both should always be valid
915 	 * in this context; no need to hold locks.
916 	 */
917 	info.rti_info[RTAX_IFP] = ifp->if_lladdr->ifa_addr;
918 	info.rti_info[RTAX_IFA] = rt->rt_ifa->ifa_addr;
919 
920 	rt_missmsg(cmd, &info, rt->rt_flags, 0);
921 }
922 
923 static void
defrouter_addreq(struct nd_defrouter * new,struct nd_route_info * rti,boolean_t scoped)924 defrouter_addreq(struct nd_defrouter *new, struct nd_route_info *rti, boolean_t scoped)
925 {
926 	struct sockaddr_in6 key, mask, gate;
927 	struct rtentry *newrt __single = NULL;
928 	unsigned int ifscope;
929 	int err;
930 	struct nd_ifinfo *ndi = ND_IFINFO(new->ifp);
931 	int rtflags = RTF_GATEWAY;
932 
933 	LCK_MTX_ASSERT(nd6_mutex, LCK_MTX_ASSERT_NOTOWNED);
934 	NDDR_LOCK_ASSERT_NOTHELD(new);
935 	/*
936 	 * We're free to lock and unlock NDDR because our callers
937 	 * are holding an extra reference for us.
938 	 */
939 
940 	NDDR_LOCK(new);
941 	if (new->stateflags & NDDRF_INSTALLED) {
942 		goto out;
943 	}
944 	if (new->ifp->if_ipv6_router_mode == IPV6_ROUTER_MODE_EXCLUSIVE) {
945 		nd6log2(info, "%s: ignoring router %s, scoped=%d, "
946 		    "static=%d on advertising interface\n", if_name(new->ifp),
947 		    ip6_sprintf(&new->rtaddr), scoped,
948 		    (new->stateflags & NDDRF_STATIC) ? 1 : 0);
949 		goto out;
950 	}
951 
952 	nd6log2(info, "%s: adding default router %s, scoped=%d, "
953 	    "static=%d\n", if_name(new->ifp), ip6_sprintf(&new->rtaddr),
954 	    scoped, (new->stateflags & NDDRF_STATIC) ? 1 : 0);
955 
956 	Bzero(&key, sizeof(key));
957 	Bzero(&mask, sizeof(mask));
958 	Bzero(&gate, sizeof(gate));
959 
960 	key.sin6_len = mask.sin6_len = gate.sin6_len
961 	            = sizeof(struct sockaddr_in6);
962 	key.sin6_family = mask.sin6_family = gate.sin6_family = AF_INET6;
963 
964 	if (rti != NULL) {
965 		key.sin6_addr = rti->nd_rti_prefix;
966 		in6_len2mask(&mask.sin6_addr, rti->nd_rti_prefixlen);
967 		if (rti->nd_rti_prefixlen == ND_OPT_RTI_PFXLEN_MAX) {
968 			rtflags |= RTF_HOST;
969 		} else {
970 			rtflags |= RTF_PRCLONING;
971 		}
972 
973 		if (IN6_IS_SCOPE_EMBED(&key.sin6_addr) ||
974 		    IN6_IS_ADDR_LOOPBACK(&key.sin6_addr)) {
975 			nd6log2(info, "%s: ignoring router %s, rti prefix %s, scoped=%d, "
976 			    "static=%d on advertising interface\n", if_name(new->ifp),
977 			    ip6_sprintf(&new->rtaddr), ip6_sprintf(&rti->nd_rti_prefix), scoped,
978 			    (new->stateflags & NDDRF_STATIC) ? 1 : 0);
979 			goto out;
980 		}
981 	}
982 
983 	if (new->stateflags & NDDRF_MAPPED) {
984 		gate.sin6_addr = new->rtaddr_mapped;
985 	} else {
986 		gate.sin6_addr = new->rtaddr;
987 	}
988 	if (!in6_embedded_scope && IN6_IS_SCOPE_EMBED(&gate.sin6_addr)) {
989 		gate.sin6_scope_id = new->ifp->if_index;
990 	}
991 
992 	ifscope = scoped ? new->ifp->if_index : IFSCOPE_NONE;
993 	NDDR_UNLOCK(new);
994 
995 	/*
996 	 * Cellular networks may have buggy deployments
997 	 * with gateway IPv6 link local address with same
998 	 * interface identifier as the one that has been
999 	 * assigned for the cellular context.
1000 	 * If gateway is same as locally configured link local
1001 	 * interface on cellular interface, generated a different one
1002 	 * and store it in the nd_defrouter entry and use it to work
1003 	 * on routing table
1004 	 */
1005 	if (new->ifp->if_type == IFT_CELLULAR &&
1006 	    !(new->stateflags & NDDRF_STATIC) &&
1007 	    !(new->stateflags & NDDRF_MAPPED) &&
1008 	    IN6_IS_ADDR_LINKLOCAL(&gate.sin6_addr) &&
1009 	    ndi && !(ndi->flags & ND6_IFF_PERFORMNUD)) {
1010 		struct in6_ifaddr *tmp_ia6 = in6ifa_ifpforlinklocal(new->ifp, 0);
1011 
1012 		if (tmp_ia6 != NULL &&
1013 		    !(tmp_ia6->ia6_flags & IN6_IFF_NOTMANUAL) &&
1014 		    IN6_ARE_ADDR_EQUAL(&tmp_ia6->ia_addr.sin6_addr,
1015 		    &gate.sin6_addr)) {
1016 			gate.sin6_addr.s6_addr8[15] += 1;
1017 			new->rtaddr_mapped = gate.sin6_addr;
1018 			new->stateflags |= NDDRF_MAPPED;
1019 
1020 			nd6log(info, "%s: Default router %s mapped "
1021 			    "to ", if_name(new->ifp), ip6_sprintf(&new->rtaddr));
1022 			nd6log(info, "%s\n", ip6_sprintf(&new->rtaddr_mapped));
1023 		}
1024 	}
1025 
1026 	err = rtrequest_scoped(RTM_ADD, SA(&key), SA(&gate), SA(&mask),
1027 	    rtflags, &newrt, ifscope);
1028 
1029 	if (newrt) {
1030 		RT_LOCK(newrt);
1031 		nd6_rtmsg(RTM_ADD, newrt);      /* tell user process */
1032 		RT_REMREF_LOCKED(newrt);
1033 		RT_UNLOCK(newrt);
1034 		NDDR_LOCK(new);
1035 		new->stateflags |= NDDRF_INSTALLED;
1036 		if (ifscope != IFSCOPE_NONE) {
1037 			new->stateflags |= NDDRF_IFSCOPE;
1038 		}
1039 	} else {
1040 		nd6log(error, "%s: failed to add default router "
1041 		    "%s on %s scoped %d (errno = %d)\n", __func__,
1042 		    ip6_sprintf(&gate.sin6_addr), if_name(new->ifp),
1043 		    (ifscope != IFSCOPE_NONE), err);
1044 		NDDR_LOCK(new);
1045 	}
1046 	new->err = err;
1047 
1048 out:
1049 	NDDR_UNLOCK(new);
1050 }
1051 
1052 void
defrouter_set_reachability(struct in6_addr * addr,struct ifnet * ifp,boolean_t is_reachable)1053 defrouter_set_reachability(
1054 	struct in6_addr *addr,
1055 	struct ifnet *ifp,
1056 	boolean_t is_reachable)
1057 {
1058 	struct nd_defrouter *dr = NULL;
1059 
1060 	LCK_MTX_ASSERT(nd6_mutex, LCK_MTX_ASSERT_NOTOWNED);
1061 
1062 	lck_mtx_lock(nd6_mutex);
1063 	dr = defrouter_lookup(NULL, addr, ifp);
1064 	if (dr != NULL) {
1065 		dr->is_reachable = is_reachable;
1066 		NDDR_REMREF(dr);
1067 	}
1068 	lck_mtx_unlock(nd6_mutex);
1069 }
1070 
1071 struct nd_defrouter *
defrouter_lookup(struct nd_drhead * nd_router_listp,struct in6_addr * addr,struct ifnet * ifp)1072 defrouter_lookup(
1073 	struct nd_drhead *nd_router_listp,
1074 	struct in6_addr *addr,
1075 	struct ifnet *ifp)
1076 {
1077 	struct nd_defrouter *dr;
1078 
1079 	LCK_MTX_ASSERT(nd6_mutex, LCK_MTX_ASSERT_OWNED);
1080 
1081 	if (nd_router_listp == NULL) {
1082 		nd_router_listp = &nd_defrouter_list;
1083 	}
1084 
1085 	for (dr = TAILQ_FIRST(nd_router_listp); dr;
1086 	    dr = TAILQ_NEXT(dr, dr_entry)) {
1087 		NDDR_LOCK(dr);
1088 		if (dr->ifp == ifp && IN6_ARE_ADDR_EQUAL(addr, &dr->rtaddr)) {
1089 			NDDR_ADDREF(dr);
1090 			NDDR_UNLOCK(dr);
1091 			return dr;
1092 		}
1093 		NDDR_UNLOCK(dr);
1094 	}
1095 
1096 	return NULL;          /* search failed */
1097 }
1098 
1099 /* Remove the default route for a given router */
1100 void
defrouter_delreq(struct nd_defrouter * dr,struct nd_route_info * rti)1101 defrouter_delreq(struct nd_defrouter *dr, struct nd_route_info *rti)
1102 {
1103 	struct sockaddr_in6 key, mask, gate;
1104 	struct rtentry *oldrt __single = NULL;
1105 	unsigned int ifscope;
1106 	int err;
1107 
1108 	LCK_MTX_ASSERT(nd6_mutex, LCK_MTX_ASSERT_NOTOWNED);
1109 	NDDR_LOCK_ASSERT_NOTHELD(dr);
1110 	/*
1111 	 * We're free to lock and unlock NDDR because our callers
1112 	 * are holding an extra reference for us.
1113 	 */
1114 	NDDR_LOCK(dr);
1115 	/* ifp would be NULL for the "drany" case */
1116 	if (dr->ifp != NULL && !(dr->stateflags & NDDRF_INSTALLED)) {
1117 		goto out;
1118 	}
1119 
1120 	nd6log2(info, "%s: removing default router %s, scoped=%d, "
1121 	    "static=%d\n", dr->ifp != NULL ? if_name(dr->ifp) : "ANY",
1122 	    ip6_sprintf(&dr->rtaddr), (dr->stateflags & NDDRF_IFSCOPE) ? 1 : 0,
1123 	    (dr->stateflags & NDDRF_STATIC) ? 1 : 0);
1124 
1125 	Bzero(&key, sizeof(key));
1126 	Bzero(&mask, sizeof(mask));
1127 	Bzero(&gate, sizeof(gate));
1128 
1129 	key.sin6_len = mask.sin6_len = gate.sin6_len
1130 	            = sizeof(struct sockaddr_in6);
1131 	key.sin6_family = mask.sin6_family = gate.sin6_family = AF_INET6;
1132 
1133 
1134 	if (rti != NULL) {
1135 		key.sin6_addr = rti->nd_rti_prefix;
1136 		in6_len2mask(&mask.sin6_addr, rti->nd_rti_prefixlen);
1137 	}
1138 	/*
1139 	 * The router entry may be mapped to a different address.
1140 	 * If that is the case, use the mapped address as gateway
1141 	 * to do operation on the routing table.
1142 	 * To get more context, read the related comment in
1143 	 * defrouter_addreq
1144 	 */
1145 	if (dr->stateflags & NDDRF_MAPPED) {
1146 		gate.sin6_addr = dr->rtaddr_mapped;
1147 	} else {
1148 		gate.sin6_addr = dr->rtaddr;
1149 	}
1150 
1151 	if (dr->ifp != NULL) {
1152 		ifscope = (dr->stateflags & NDDRF_IFSCOPE) ?
1153 		    dr->ifp->if_index : IFSCOPE_NONE;
1154 	} else {
1155 		ifscope = IFSCOPE_NONE;
1156 	}
1157 	NDDR_UNLOCK(dr);
1158 
1159 	err = rtrequest_scoped(RTM_DELETE, SA(&key), SA(&gate), SA(&mask),
1160 	    RTF_GATEWAY, &oldrt, ifscope);
1161 
1162 	if (oldrt) {
1163 		RT_LOCK(oldrt);
1164 		nd6_rtmsg(RTM_DELETE, oldrt);
1165 		RT_UNLOCK(oldrt);
1166 		rtfree(oldrt);
1167 	} else if (err != ESRCH) {
1168 		nd6log(error, "%s: failed to delete default router "
1169 		    "%s on %s scoped %d (errno = %d)\n", __func__,
1170 		    ip6_sprintf(&gate.sin6_addr), dr->ifp != NULL ?
1171 		    if_name(dr->ifp) : "ANY", (ifscope != IFSCOPE_NONE), err);
1172 	}
1173 	NDDR_LOCK(dr);
1174 	/* ESRCH means it's no longer in the routing table; ignore it */
1175 	if (oldrt != NULL || err == ESRCH) {
1176 		dr->stateflags &= ~NDDRF_INSTALLED;
1177 		if (ifscope != IFSCOPE_NONE) {
1178 			dr->stateflags &= ~NDDRF_IFSCOPE;
1179 		}
1180 	}
1181 	dr->err = 0;
1182 out:
1183 	NDDR_UNLOCK(dr);
1184 }
1185 
1186 
1187 /*
1188  * remove all default routes from default router list
1189  */
1190 void
defrouter_reset(void)1191 defrouter_reset(void)
1192 {
1193 	struct nd_defrouter *dr, drany;
1194 
1195 	LCK_MTX_ASSERT(nd6_mutex, LCK_MTX_ASSERT_OWNED);
1196 
1197 	dr = TAILQ_FIRST(&nd_defrouter_list);
1198 	while (dr) {
1199 		NDDR_LOCK(dr);
1200 		if (dr->stateflags & NDDRF_INSTALLED) {
1201 			NDDR_ADDREF(dr);
1202 			NDDR_UNLOCK(dr);
1203 			lck_mtx_unlock(nd6_mutex);
1204 			defrouter_delreq(dr, NULL);
1205 			lck_mtx_lock(nd6_mutex);
1206 			NDDR_REMREF(dr);
1207 			dr = TAILQ_FIRST(&nd_defrouter_list);
1208 		} else {
1209 			NDDR_UNLOCK(dr);
1210 			dr = TAILQ_NEXT(dr, dr_entry);
1211 		}
1212 	}
1213 
1214 	/* Nuke primary (non-scoped) default router */
1215 	bzero(&drany, sizeof(drany));
1216 	lck_mtx_init(&drany.nddr_lock, &ifa_mtx_grp, &ifa_mtx_attr);
1217 	lck_mtx_unlock(nd6_mutex);
1218 	defrouter_delreq(&drany, NULL);
1219 	lck_mtx_destroy(&drany.nddr_lock, &ifa_mtx_grp);
1220 	lck_mtx_lock(nd6_mutex);
1221 }
1222 
1223 int
defrtrlist_ioctl(u_long cmd,caddr_t __sized_by (IOCPARM_LEN (cmd))data)1224 defrtrlist_ioctl(u_long cmd, caddr_t __sized_by(IOCPARM_LEN(cmd)) data)
1225 {
1226 	struct nd_defrouter dr0;
1227 	unsigned int ifindex;
1228 	struct ifnet *dr_ifp;
1229 	int error = 0, add = 0;
1230 
1231 	/* XXX Handle mapped default router entries */
1232 	switch (cmd) {
1233 	case SIOCDRADD_IN6_32:          /* struct in6_defrouter_32 */
1234 	case SIOCDRADD_IN6_64:          /* struct in6_defrouter_64 */
1235 		++add;
1236 		OS_FALLTHROUGH;
1237 	case SIOCDRDEL_IN6_32:          /* struct in6_defrouter_32 */
1238 	case SIOCDRDEL_IN6_64:          /* struct in6_defrouter_64 */
1239 		bzero(&dr0, sizeof(dr0));
1240 		if (cmd == SIOCDRADD_IN6_64 || cmd == SIOCDRDEL_IN6_64) {
1241 			struct in6_defrouter_64 *r_64 =
1242 			    (struct in6_defrouter_64 *)(void *)data;
1243 			u_int16_t i;
1244 
1245 			bcopy(&r_64->rtaddr.sin6_addr, &dr0.rtaddr,
1246 			    sizeof(dr0.rtaddr));
1247 			dr0.flags = r_64->flags;
1248 			bcopy(&r_64->if_index, &i, sizeof(i));
1249 			ifindex = i;
1250 		} else {
1251 			struct in6_defrouter_32 *__single r_32 =
1252 			    (struct in6_defrouter_32 *)(void *)data;
1253 			u_int16_t i;
1254 
1255 			bcopy(&r_32->rtaddr.sin6_addr, &dr0.rtaddr,
1256 			    sizeof(dr0.rtaddr));
1257 			dr0.flags = r_32->flags;
1258 			bcopy(&r_32->if_index, &i, sizeof(i));
1259 			ifindex = i;
1260 		}
1261 		ifnet_head_lock_shared();
1262 		/* Don't need to check is ifindex is < 0 since it's unsigned */
1263 		if (!IF_INDEX_IN_RANGE(ifindex) ||
1264 		    (dr_ifp = ifindex2ifnet[ifindex]) == NULL) {
1265 			ifnet_head_done();
1266 			error = EINVAL;
1267 			break;
1268 		}
1269 		dr0.ifp = dr_ifp;
1270 		ifnet_head_done();
1271 
1272 		if (ND_IFINFO(dr_ifp) == NULL ||
1273 		    !ND_IFINFO(dr_ifp)->initialized) {
1274 			error = ENXIO;
1275 			break;
1276 		}
1277 
1278 		if (IN6_IS_SCOPE_EMBED(&dr0.rtaddr) && in6_embedded_scope) {
1279 			uint16_t *scope = &dr0.rtaddr.s6_addr16[1];
1280 
1281 			if (*scope == 0) {
1282 				*scope = htons(dr_ifp->if_index);
1283 			} else if (*scope != htons(dr_ifp->if_index)) {
1284 				error = EINVAL;
1285 				break;
1286 			}
1287 		}
1288 		if (add) {
1289 			error = defrtrlist_add_static(&dr0);
1290 		}
1291 		if (!add || error != 0) {
1292 			int err = defrtrlist_del_static(&dr0);
1293 			if (!add) {
1294 				error = err;
1295 			}
1296 		}
1297 		break;
1298 
1299 	default:
1300 		error = EOPNOTSUPP; /* check for safety */
1301 		break;
1302 	}
1303 
1304 	return error;
1305 }
1306 
1307 /*
1308  * XXX Please make sure to remove dr from the
1309  * global default router tailq list before this
1310  * function call.
1311  * Also ensure that you release the list reference
1312  * only after calling this routine.
1313  */
1314 void
defrtrlist_del(struct nd_defrouter * dr,struct nd_drhead * nd_router_listp)1315 defrtrlist_del(struct nd_defrouter *dr, struct nd_drhead *nd_router_listp)
1316 {
1317 #if (DEVELOPMENT || DEBUG)
1318 	struct nd_defrouter *dr_itr = NULL;
1319 #endif
1320 	struct nd_prefix *pr;
1321 	struct ifnet *ifp = dr->ifp;
1322 	struct nd_ifinfo *ndi = NULL;
1323 	boolean_t resetmtu = FALSE;
1324 	struct nd_route_info *rti = NULL;
1325 
1326 	LCK_MTX_ASSERT(nd6_mutex, LCK_MTX_ASSERT_OWNED);
1327 
1328 	if (nd_router_listp == NULL) {
1329 		nd_router_listp = &nd_defrouter_list;
1330 	}
1331 
1332 	if (nd_router_listp != &nd_defrouter_list) {
1333 		rti = (struct nd_route_info *)nd_router_listp;
1334 	}
1335 
1336 #if (DEVELOPMENT || DEBUG)
1337 	/*
1338 	 * Verify that the router is not in the global default
1339 	 * router list.
1340 	 * Can't use defrouter_lookup here because that just works
1341 	 * with address and ifp pointer.
1342 	 * We have to compare the memory here.
1343 	 * Also we can't use ASSERT here as that is not defined
1344 	 * for development builds.
1345 	 */
1346 	TAILQ_FOREACH(dr_itr, nd_router_listp, dr_entry)
1347 	VERIFY(dr != dr_itr);
1348 #endif
1349 	++nd6_defrouter_genid;
1350 	/*
1351 	 * Flush all the routing table entries that use the router
1352 	 * as a next hop.
1353 	 *
1354 	 * XXX Note that for a router advertising itself as default router
1355 	 * and also advertising route information option, the following
1356 	 * code will have the default router entry and router entry of
1357 	 * RTI step over each other.
1358 	 * The following therefore may not be efficient but won't be
1359 	 * causing blocking issues.
1360 	 */
1361 	NDDR_ADDREF(dr);
1362 	lck_mtx_unlock(nd6_mutex);
1363 	if (dr->stateflags & NDDRF_MAPPED) {
1364 		rt6_flush(&dr->rtaddr_mapped, ifp);
1365 	} else {
1366 		rt6_flush(&dr->rtaddr, ifp);
1367 	}
1368 	lck_mtx_lock(nd6_mutex);
1369 	NDDR_REMREF(dr);
1370 	nd6log2(info, "%s: freeing route to %s with gateway %s\n", if_name(dr->ifp),
1371 	    (rti == NULL)? "::" : ip6_sprintf(&rti->nd_rti_prefix),
1372 	    ip6_sprintf(&dr->rtaddr));
1373 	/*
1374 	 * Delete it from the routing table.
1375 	 */
1376 	NDDR_ADDREF(dr);
1377 	lck_mtx_unlock(nd6_mutex);
1378 	defrouter_delreq(dr, rti);
1379 	lck_mtx_lock(nd6_mutex);
1380 	NDDR_REMREF(dr);
1381 
1382 	/*
1383 	 * The following should mostly be limited to when we are working
1384 	 * with a default router entry and not a router entry from
1385 	 * rti router list.
1386 	 */
1387 	if (rti == NULL) {
1388 		/*
1389 		 * Also delete all the pointers to the router in each prefix lists.
1390 		 */
1391 		for (pr = nd_prefix.lh_first; pr; pr = pr->ndpr_next) {
1392 			struct nd_pfxrouter *__single pfxrtr;
1393 
1394 			NDPR_LOCK(pr);
1395 			if ((pfxrtr = pfxrtr_lookup(pr, dr)) != NULL) {
1396 				pfxrtr_del(pfxrtr, pr);
1397 			}
1398 			NDPR_UNLOCK(pr);
1399 		}
1400 		pfxlist_onlink_check();
1401 	}
1402 	ndi = ND_IFINFO(ifp);
1403 	VERIFY(NULL != ndi && TRUE == ndi->initialized);
1404 	lck_mtx_lock(&ndi->lock);
1405 	VERIFY(ndi->ndefrouters >= 0);
1406 	if (ndi->ndefrouters > 0 && --ndi->ndefrouters == 0) {
1407 		nd6_ifreset(ifp);
1408 		resetmtu = TRUE;
1409 	}
1410 	lck_mtx_unlock(&ndi->lock);
1411 	/*
1412 	 * If the router is the primary one, choose a new one.
1413 	 * We always try to pick another eligible router
1414 	 * on this interface as we do scoped routing
1415 	 */
1416 	defrouter_select(ifp, nd_router_listp);
1417 
1418 	if (resetmtu) {
1419 		nd6_setmtu(ifp);
1420 	}
1421 }
1422 
1423 int
defrtrlist_add_static(struct nd_defrouter * new)1424 defrtrlist_add_static(struct nd_defrouter *new)
1425 {
1426 	struct nd_defrouter *dr;
1427 	int err = 0;
1428 
1429 	new->rtlifetime = -1;
1430 	new->stateflags |= NDDRF_STATIC;
1431 
1432 	/* we only want the preference level */
1433 	new->flags &= ND_RA_FLAG_RTPREF_MASK;
1434 
1435 	lck_mtx_lock(nd6_mutex);
1436 	dr = defrouter_lookup(NULL, &new->rtaddr, new->ifp);
1437 	if (dr != NULL && !(dr->stateflags & NDDRF_STATIC)) {
1438 		err = EINVAL;
1439 	} else {
1440 		if (dr != NULL) {
1441 			NDDR_REMREF(dr);
1442 		}
1443 		dr = defrtrlist_update(new, NULL);
1444 		if (dr != NULL) {
1445 			err = dr->err;
1446 		} else {
1447 			err = ENOMEM;
1448 		}
1449 	}
1450 	if (dr != NULL) {
1451 		NDDR_REMREF(dr);
1452 	}
1453 	lck_mtx_unlock(nd6_mutex);
1454 
1455 	return err;
1456 }
1457 
1458 int
defrtrlist_del_static(struct nd_defrouter * new)1459 defrtrlist_del_static(struct nd_defrouter *new)
1460 {
1461 	struct nd_defrouter *dr;
1462 
1463 	lck_mtx_lock(nd6_mutex);
1464 	dr = defrouter_lookup(NULL, &new->rtaddr, new->ifp);
1465 	if (dr == NULL || !(dr->stateflags & NDDRF_STATIC)) {
1466 		if (dr != NULL) {
1467 			NDDR_REMREF(dr);
1468 		}
1469 		dr = NULL;
1470 	} else {
1471 		TAILQ_REMOVE(&nd_defrouter_list, dr, dr_entry);
1472 		defrtrlist_del(dr, NULL);
1473 		NDDR_REMREF(dr);        /* remove list reference */
1474 		NDDR_REMREF(dr);
1475 	}
1476 	lck_mtx_unlock(nd6_mutex);
1477 
1478 	return dr != NULL ? 0 : EINVAL;
1479 }
1480 
1481 /*
1482  * for default router selection
1483  * regards router-preference field as a 2-bit signed integer
1484  */
1485 static int
rtpref(struct nd_defrouter * dr)1486 rtpref(struct nd_defrouter *dr)
1487 {
1488 	switch (dr->flags & ND_RA_FLAG_RTPREF_MASK) {
1489 	case ND_RA_FLAG_RTPREF_HIGH:
1490 		return RTPREF_HIGH;
1491 	case ND_RA_FLAG_RTPREF_MEDIUM:
1492 	case ND_RA_FLAG_RTPREF_RSV:
1493 		return RTPREF_MEDIUM;
1494 	case ND_RA_FLAG_RTPREF_LOW:
1495 		return RTPREF_LOW;
1496 	default:
1497 		/*
1498 		 * This case should never happen.  If it did, it would mean a
1499 		 * serious bug of kernel internal.  We thus always bark here.
1500 		 * Or, can we even panic?
1501 		 */
1502 		log(LOG_ERR, "rtpref: impossible RA flag %x\n", dr->flags);
1503 		return RTPREF_INVALID;
1504 	}
1505 	/* NOTREACHED */
1506 }
1507 
1508 /*
1509  * Default Router Selection according to Section 6.3.6 of RFC 2461 and RFC 4191:
1510  *
1511  * 1) Routers that are reachable or probably reachable should be preferred.
1512  *    If we have more than one (probably) reachable router, prefer ones
1513  *    with the highest router preference.
1514  * 2) When no routers on the list are known to be reachable or
1515  *    probably reachable, routers SHOULD be selected in a round-robin
1516  *    fashion, regardless of router preference values.
1517  * 3) If the Default Router List is empty, assume that all
1518  *    destinations are on-link.
1519  *
1520  * When Scoped Routing is enabled, the selection logic is amended as follows:
1521  *
1522  * a) When a default interface is specified, the primary/non-scoped default
1523  *    router will be set to the reachable router on that link (if any) with
1524  *    the highest router preference.
1525  * b) When there are more than one routers on the same link, the one with
1526  *    the highest router preference will be installed, either as scoped or
1527  *    non-scoped route entry.  If they all share the same preference value,
1528  *    the one installed will be the static or the first encountered reachable
1529  *    router, i.e. static one wins over dynamic.
1530  * c) When no routers on the list are known to be reachable, or probably
1531  *    reachable, no round-robin selection will take place when the default
1532  *    interface is set.
1533  *
1534  * We assume nd_defrouter is sorted by router preference value.
1535  * Since the code below covers both with and without router preference cases,
1536  * we do not need to classify the cases by ifdef.
1537  */
1538 void
defrouter_select(struct ifnet * ifp,struct nd_drhead * nd_router_listp)1539 defrouter_select(struct ifnet *ifp, struct nd_drhead *nd_router_listp)
1540 {
1541 	struct nd_defrouter *dr = NULL;
1542 	struct nd_defrouter *selected_dr = NULL;
1543 	struct nd_defrouter *installed_dr = NULL;
1544 	struct llinfo_nd6 *__single ln = NULL;
1545 	struct rtentry *rt = NULL;
1546 	struct nd_ifinfo *ndi = NULL;
1547 	unsigned int genid = 0;
1548 	boolean_t is_installed_reachable = FALSE;
1549 	struct nd_route_info *rti = NULL;
1550 	boolean_t scoped = TRUE;
1551 	boolean_t is_rti_rtrlist = FALSE;
1552 
1553 	LCK_MTX_ASSERT(nd6_mutex, LCK_MTX_ASSERT_OWNED);
1554 
1555 	if (nd_router_listp == NULL) {
1556 		nd_router_listp = &nd_defrouter_list;
1557 	}
1558 
1559 	if (nd_router_listp != &nd_defrouter_list) {
1560 		rti = (struct nd_route_info *)nd_router_listp;
1561 		/* XXX For now we treat RTI routes as un-scoped */
1562 		scoped = FALSE;
1563 		is_rti_rtrlist = TRUE;
1564 	}
1565 
1566 
1567 	if (ifp == NULL) {
1568 		ifp = nd6_defifp;
1569 		if (ifp == NULL) {
1570 			nd6log2(info,
1571 			    "%s:%d: Return early. NULL interface",
1572 			    __func__, __LINE__);
1573 			return;
1574 		}
1575 		nd6log2(info,
1576 		    "%s:%d: NULL interface passed. Setting to default interface %s.\n",
1577 		    __func__, __LINE__, if_name(ifp));
1578 	}
1579 
1580 	/*
1581 	 * When we are working with RTI router list, the nd6_defifp may be
1582 	 * NULL. That is the scenario when the network may not have WAN
1583 	 * v6 connectivity and the only RAs we may be getting are with lifetime
1584 	 * 0.
1585 	 */
1586 	if (ifp == lo_ifp && !is_rti_rtrlist) {
1587 		nd6log2(info,
1588 		    "%s:%d: Return early. "
1589 		    "Default router select called for loopback.\n",
1590 		    __func__, __LINE__);
1591 		return;
1592 	}
1593 
1594 	if (ifp->if_ipv6_router_mode == IPV6_ROUTER_MODE_EXCLUSIVE) {
1595 		nd6log2(info,
1596 		    "%s:%d: Return early. "
1597 		    "Default router select called for interface"
1598 		    " %s in IPV6_ROUTER_MODE_EXCLUSIVE\n",
1599 		    __func__, __LINE__, if_name(ifp));
1600 		return;
1601 	}
1602 
1603 	/*
1604 	 * Let's handle easy case (3) first:
1605 	 * If default router list is empty, there's nothing to be done.
1606 	 */
1607 	if (!TAILQ_FIRST(nd_router_listp)) {
1608 		nd6log2(info,
1609 		    "%s:%d: Return early. "
1610 		    "Default router is empty.\n", __func__, __LINE__);
1611 		return;
1612 	}
1613 
1614 	/*
1615 	 * Take an early exit if number of routers in nd_ifinfo is
1616 	 * 0 for the interface.
1617 	 */
1618 	ndi = ND_IFINFO(ifp);
1619 	if (!ndi || !ndi->initialized) {
1620 		nd6log2(info,
1621 		    "%s:%d: Return early. "
1622 		    "Interface %s's nd_ifinfo not initialized.\n",
1623 		    __func__, __LINE__, if_name(ifp));
1624 		return;
1625 	}
1626 
1627 	/*
1628 	 * RTI router list routes are installed as unscoped.
1629 	 * Since there can be only one unscoped route, we need to
1630 	 * go through the entire list and consider all interfaces.
1631 	 * Further, for now, RTI option is only processed on Ethernet
1632 	 * type interfaces only.
1633 	 */
1634 	if (ndi->ndefrouters == 0 && !is_rti_rtrlist) {
1635 		nd6log2(info,
1636 		    "%s:%d: Return early. "
1637 		    "%s does not have any default routers.\n",
1638 		    __func__, __LINE__, if_name(ifp));
1639 		return;
1640 	}
1641 
1642 	/*
1643 	 * Due to the number of times we drop nd6_mutex, we need to
1644 	 * serialize this function.
1645 	 */
1646 	while (nd_defrouter_busy) {
1647 		nd_defrouter_waiters++;
1648 		msleep(nd_defrouter_waitchan, nd6_mutex, (PZERO - 1),
1649 		    __func__, NULL);
1650 		LCK_MTX_ASSERT(nd6_mutex, LCK_MTX_ASSERT_OWNED);
1651 	}
1652 	nd_defrouter_busy = TRUE;
1653 
1654 	/*
1655 	 * Search for a (probably) reachable router from the list.
1656 	 * We just pick up the first reachable one (if any), assuming that
1657 	 * the ordering rule of the list described in defrtrlist_update().
1658 	 *
1659 	 * For all intents and purposes of Scoped Routing:
1660 	 *	selected_dr	= candidate for primary router
1661 	 *	installed_dr	= currently installed primary router
1662 	 */
1663 	genid = nd6_defrouter_genid;
1664 	dr = TAILQ_FIRST(nd_router_listp);
1665 
1666 	while (dr != NULL) {
1667 		struct in6_addr rtaddr;
1668 		ifnet_ref_t drifp = NULL;
1669 		struct nd_defrouter *__single drrele = NULL;
1670 		boolean_t nd6_mutex_unlocked = FALSE;
1671 
1672 		NDDR_LOCK(dr);
1673 		drifp = dr->ifp;
1674 		if (drifp != ifp && !is_rti_rtrlist) {
1675 			NDDR_UNLOCK(dr);
1676 			dr = TAILQ_NEXT(dr, dr_entry);
1677 			continue;
1678 		}
1679 
1680 		if (dr->stateflags & NDDRF_INELIGIBLE) {
1681 			NDDR_UNLOCK(dr);
1682 			dr = TAILQ_NEXT(dr, dr_entry);
1683 			nd6log(info, "Ignoring dummy entry for default router.");
1684 			continue;
1685 		}
1686 
1687 		if (dr->ifp->if_type != IFT_CELLULAR &&
1688 		    dr->stateflags & NDDRF_LOCAL) {
1689 			NDDR_UNLOCK(dr);
1690 			nd6log(info, "%s: Ignoring router %s that has locally hosted address.\n",
1691 			    if_name(dr->ifp),
1692 			    ip6_sprintf(&dr->rtaddr));
1693 			dr = TAILQ_NEXT(dr, dr_entry);
1694 			continue;
1695 		}
1696 
1697 		/*
1698 		 * Optimize for the common case.
1699 		 * When the interface has only one default router
1700 		 * there's no point checking for reachability as
1701 		 * there's nothing else to choose from.
1702 		 */
1703 		if (ndi->ndefrouters == 1 && !is_rti_rtrlist) {
1704 			nd6log2(info,
1705 			    "%s:%d: Fast forward default router selection "
1706 			    "as interface %s has learned only one default "
1707 			    "router and there's nothing else to choose from.\n",
1708 			    __func__, __LINE__, if_name(ifp));
1709 			VERIFY(selected_dr == NULL && installed_dr == NULL);
1710 			selected_dr = dr;
1711 			if (dr->stateflags & NDDRF_INSTALLED) {
1712 				installed_dr = dr;
1713 			}
1714 			NDDR_ADDREF(selected_dr);
1715 			NDDR_UNLOCK(dr);
1716 			goto install_route;
1717 		}
1718 
1719 		if (dr->stateflags & NDDRF_MAPPED) {
1720 			rtaddr = dr->rtaddr_mapped;
1721 		} else {
1722 			rtaddr = dr->rtaddr;
1723 		}
1724 
1725 		NDDR_ADDREF(dr); /* for this for loop */
1726 		NDDR_UNLOCK(dr);
1727 
1728 		/* Callee returns a locked route upon success */
1729 		if (selected_dr == NULL) {
1730 			nd6_mutex_unlocked = TRUE;
1731 			lck_mtx_unlock(nd6_mutex);
1732 			if ((rt = nd6_lookup(&rtaddr, 0, drifp, 0)) != NULL &&
1733 			    (ln = rt->rt_llinfo) != NULL &&
1734 			    ND6_IS_LLINFO_PROBREACH(ln)) {
1735 				RT_LOCK_ASSERT_HELD(rt);
1736 				selected_dr = dr;
1737 				NDDR_ADDREF(selected_dr);
1738 			}
1739 		}
1740 
1741 		if (rt) {
1742 			RT_REMREF_LOCKED(rt);
1743 			RT_UNLOCK(rt);
1744 			rt = NULL;
1745 		}
1746 
1747 		if (nd6_mutex_unlocked) {
1748 			lck_mtx_lock(nd6_mutex);
1749 		}
1750 
1751 		/*
1752 		 * Handle case (b)
1753 		 * When there are more than one routers on the same link, the one with
1754 		 * the highest router preference will be installed.
1755 		 * Since the list is in decreasing order of preference:
1756 		 * 1) If selected_dr is not NULL, only use dr if it is static and has
1757 		 *    equal preference and selected_dr is not static.
1758 		 * 2) Else if selected_dr is NULL, and dr is static make selected_dr = dr
1759 		 */
1760 		NDDR_LOCK(dr);
1761 		if (((selected_dr && (rtpref(dr) >= rtpref(selected_dr)) &&
1762 		    !(selected_dr->stateflags & NDDRF_STATIC)) ||
1763 		    (selected_dr == NULL)) &&
1764 		    (dr->stateflags & NDDRF_STATIC)) {
1765 			if (selected_dr) {
1766 				/* Release it later on */
1767 				VERIFY(drrele == NULL);
1768 				drrele = selected_dr;
1769 			}
1770 			selected_dr = dr;
1771 			NDDR_ADDREF(selected_dr);
1772 		}
1773 
1774 		/* Record the currently installed router */
1775 		if (dr->stateflags & NDDRF_INSTALLED) {
1776 			if (installed_dr == NULL) {
1777 				installed_dr = dr;
1778 				NDDR_ADDREF(installed_dr);
1779 				if (dr->stateflags & NDDRF_MAPPED) {
1780 					rtaddr = installed_dr->rtaddr_mapped;
1781 				} else {
1782 					rtaddr = installed_dr->rtaddr;
1783 				}
1784 				NDDR_UNLOCK(dr);
1785 				lck_mtx_unlock(nd6_mutex);
1786 				/* Callee returns a locked route upon success */
1787 				if ((rt = nd6_lookup(&rtaddr, 0, installed_dr->ifp, 0)) != NULL) {
1788 					RT_LOCK_ASSERT_HELD(rt);
1789 					if ((ln = rt->rt_llinfo) != NULL &&
1790 					    ND6_IS_LLINFO_PROBREACH(ln)) {
1791 						is_installed_reachable = TRUE;
1792 					}
1793 
1794 					RT_REMREF_LOCKED(rt);
1795 					RT_UNLOCK(rt);
1796 					rt = NULL;
1797 				}
1798 				lck_mtx_lock(nd6_mutex);
1799 			} else {
1800 				/* this should not happen; warn for diagnosis */
1801 				nd6log(error, "defrouter_select: more than one "
1802 				    "default router is installed for interface :%s.\n",
1803 				    if_name(installed_dr->ifp));
1804 				NDDR_UNLOCK(dr);
1805 			}
1806 		} else {
1807 			NDDR_UNLOCK(dr);
1808 		}
1809 
1810 		NDDR_REMREF(dr);        /* for this for loop */
1811 		if (drrele != NULL) {
1812 			NDDR_REMREF(drrele);
1813 		}
1814 
1815 		/*
1816 		 * Check if the list changed when we gave up
1817 		 * the nd6_mutex lock
1818 		 */
1819 		if (genid != nd6_defrouter_genid) {
1820 			if (selected_dr) {
1821 				NDDR_REMREF(selected_dr);
1822 				selected_dr = NULL;
1823 			}
1824 
1825 			if (installed_dr) {
1826 				NDDR_REMREF(installed_dr);
1827 				installed_dr = NULL;
1828 			}
1829 
1830 			if (ndi->ndefrouters == 0 && !is_rti_rtrlist) {
1831 				nd6log2(info,
1832 				    "%s:%d: Interface %s no longer "
1833 				    "has any default routers. Abort.\n",
1834 				    __func__, __LINE__, if_name(ifp));
1835 				goto out;
1836 			}
1837 			nd6log2(info,
1838 			    "%s:%d: Iterate default router list again "
1839 			    "for interface %s, as the list seems to have "
1840 			    "changed during release-reaquire of global "
1841 			    "nd6_mutex lock.\n",
1842 			    __func__, __LINE__, if_name(ifp));
1843 
1844 			is_installed_reachable = FALSE;
1845 			genid = nd6_defrouter_genid;
1846 			dr = TAILQ_FIRST(nd_router_listp);
1847 		} else {
1848 			dr = TAILQ_NEXT(dr, dr_entry);
1849 		}
1850 	}
1851 
1852 	/*
1853 	 * If none of the default routers was found to be reachable,
1854 	 * round-robin the list regardless of preference.
1855 	 * Please note selected_dr equal to NULL implies that even
1856 	 * installed default router is not reachable
1857 	 */
1858 	if (selected_dr == NULL) {
1859 		if (installed_dr) {
1860 			for (dr = TAILQ_NEXT(installed_dr, dr_entry); dr;
1861 			    dr = TAILQ_NEXT(dr, dr_entry)) {
1862 				if (installed_dr->ifp != dr->ifp && !is_rti_rtrlist) {
1863 					continue;
1864 				}
1865 				if (dr->stateflags & NDDRF_INELIGIBLE) {
1866 					continue;
1867 				}
1868 				selected_dr = dr;
1869 				break;
1870 			}
1871 		}
1872 
1873 		/*
1874 		 * If none was installed or the installed one if the last
1875 		 * one on the list, select the first one from the list
1876 		 */
1877 		if ((installed_dr == NULL) || (selected_dr == NULL)) {
1878 			for (dr = TAILQ_FIRST(nd_router_listp); dr;
1879 			    dr = TAILQ_NEXT(dr, dr_entry)) {
1880 				if (dr->stateflags & NDDRF_INELIGIBLE) {
1881 					continue;
1882 				}
1883 				if (dr->ifp == ifp || is_rti_rtrlist) {
1884 					selected_dr = dr;
1885 					break;
1886 				}
1887 			}
1888 		}
1889 
1890 		if ((selected_dr == NULL) && (installed_dr == NULL)) {
1891 			nd6log2(info,
1892 			    "%s:%d: Between release and re-acquire of global "
1893 			    "nd6_mutex lock, the list seems to have changed "
1894 			    "and it does not have any default routers for "
1895 			    "interface %s.\n",
1896 			    __func__, __LINE__, if_name(ifp));
1897 			goto out;
1898 		}
1899 
1900 		if (selected_dr != installed_dr) {
1901 			NDDR_ADDREF(selected_dr);
1902 		}
1903 	} else if (installed_dr != NULL) {
1904 		if (installed_dr != selected_dr) {
1905 			/*
1906 			 * This means that selected default router is reachable
1907 			 * while installed one may or may not be.
1908 			 * Static router should always be considered as reachable
1909 			 * for router selection process.
1910 			 */
1911 			if ((installed_dr->stateflags & NDDRF_STATIC) &&
1912 			    rtpref(installed_dr) >= rtpref(selected_dr)) {
1913 				NDDR_REMREF(selected_dr);
1914 				selected_dr = installed_dr;
1915 			} else if (is_installed_reachable) {
1916 				if (rtpref(selected_dr) <= rtpref(installed_dr)) {
1917 					NDDR_REMREF(selected_dr);
1918 					selected_dr = installed_dr;
1919 				}
1920 			}
1921 		} else {
1922 			NDDR_REMREF(selected_dr);
1923 		}
1924 	}
1925 
1926 install_route:
1927 	/*
1928 	 * If the selected router is different than the installed one,
1929 	 * remove the installed router and install the selected one.
1930 	 * Note that the selected router is never NULL here.
1931 	 * Else check if the route entry scope has to be changed.
1932 	 */
1933 	lck_mtx_unlock(nd6_mutex);
1934 	if (installed_dr != selected_dr) {
1935 		nd6log(info,
1936 		    "%s:%d: Found a better router for interface "
1937 		    "%s. Installing new default route.\n",
1938 		    __func__, __LINE__, if_name(ifp));
1939 		if (installed_dr != NULL) {
1940 			defrouter_delreq(installed_dr, rti);
1941 		}
1942 		/*
1943 		 * Install scoped route if the interface is not
1944 		 * the default nd6 interface.
1945 		 */
1946 		defrouter_addreq(selected_dr, rti,
1947 		    scoped && (selected_dr->ifp != nd6_defifp));
1948 	} else if (((installed_dr->stateflags & NDDRF_IFSCOPE) &&
1949 	    (installed_dr->ifp == nd6_defifp)) ||
1950 	    (scoped && !(installed_dr->stateflags & NDDRF_IFSCOPE) &&
1951 	    (installed_dr->ifp != nd6_defifp))) {
1952 		nd6log(info,
1953 		    "%s:%d: Need to reinstall default route for interface "
1954 		    "%s as its scope has changed.\n",
1955 		    __func__, __LINE__, if_name(ifp));
1956 		defrouter_delreq(installed_dr, rti);
1957 		defrouter_addreq(installed_dr, rti,
1958 		    scoped && (installed_dr->ifp != nd6_defifp));
1959 	} else {
1960 		nd6log2(info,
1961 		    "%s:%d: No need to change the default "
1962 		    "route for interface %s.\n",
1963 		    __func__, __LINE__, if_name(ifp));
1964 	}
1965 	lck_mtx_lock(nd6_mutex);
1966 out:
1967 	if (selected_dr && (selected_dr != installed_dr)) {
1968 		NDDR_REMREF(selected_dr);
1969 	}
1970 	if (installed_dr) {
1971 		NDDR_REMREF(installed_dr);
1972 	}
1973 	LCK_MTX_ASSERT(nd6_mutex, LCK_MTX_ASSERT_OWNED);
1974 	VERIFY(nd_defrouter_busy);
1975 	nd_defrouter_busy = FALSE;
1976 	if (nd_defrouter_waiters > 0) {
1977 		nd_defrouter_waiters = 0;
1978 		wakeup(nd_defrouter_waitchan);
1979 	}
1980 }
1981 
1982 static struct nd_defrouter *
defrtrlist_update_common(struct nd_defrouter * new,struct nd_drhead * nd_router_listp,boolean_t scoped)1983 defrtrlist_update_common(struct nd_defrouter *new, struct nd_drhead *nd_router_listp, boolean_t scoped)
1984 {
1985 	struct nd_defrouter *dr, *n;
1986 	struct ifnet *ifp = new->ifp;
1987 	struct nd_ifinfo *ndi = NULL;
1988 	struct timeval caltime;
1989 
1990 	LCK_MTX_ASSERT(nd6_mutex, LCK_MTX_ASSERT_OWNED);
1991 
1992 	if (nd_router_listp == NULL) {
1993 		nd_router_listp = &nd_defrouter_list;
1994 	}
1995 
1996 	/*
1997 	 * If we are not operating on default router list,
1998 	 * it implies we are operating on RTI's router list.
1999 	 * XXX For now we manage RTI routes un-scoped.
2000 	 */
2001 	if (nd_router_listp != &nd_defrouter_list) {
2002 		scoped = FALSE;
2003 	}
2004 
2005 	if ((dr = defrouter_lookup(nd_router_listp, &new->rtaddr, ifp)) != NULL) {
2006 		/* entry exists */
2007 		/*
2008 		 * 1. If previous entry was not dummy and new is,
2009 		 * delete it and return NULL.
2010 		 * 2. If previous entry was dummy and the new one
2011 		 * is also dummy, simply return dr.
2012 		 * 3. If previous was dummy but new one is not,
2013 		 * make sure we perform default router selection again.
2014 		 */
2015 		/* If the router was not added as a dummy and there's
2016 		 * been a change (lifetime advertised was 0, communicated
2017 		 * as NDDRF_INELIGIBLE flag), remove the entry.
2018 		 */
2019 		if ((new->stateflags & NDDRF_INELIGIBLE) != 0 &&
2020 		    (dr->stateflags & NDDRF_INELIGIBLE) == 0) {
2021 			TAILQ_REMOVE(nd_router_listp, dr, dr_entry);
2022 			defrtrlist_del(dr, nd_router_listp);
2023 			NDDR_REMREF(dr);        /* remove list reference */
2024 			NDDR_REMREF(dr);
2025 			dr = NULL;
2026 			return NULL;
2027 		} else {
2028 			int oldpref = rtpref(dr);
2029 			struct nd_defrouter *__single p = NULL;
2030 			boolean_t dummy_change = FALSE;
2031 			/*
2032 			 * If new one is not dummy but the old one was,
2033 			 * reset the stateflag.
2034 			 */
2035 			if ((new->stateflags & NDDRF_INELIGIBLE) == 0 &&
2036 			    (dr->stateflags & NDDRF_INELIGIBLE) != 0) {
2037 				dummy_change = TRUE;
2038 				dr->stateflags &= ~NDDRF_INELIGIBLE;
2039 			}
2040 
2041 			/* override */
2042 			dr->flags = new->flags; /* xxx flag check */
2043 			dr->rtlifetime = new->rtlifetime;
2044 			dr->expire = new->expire;
2045 
2046 			/*
2047 			 * If the preference does not change, there's no need
2048 			 * to sort the entries.  If Scoped Routing is enabled,
2049 			 * put the primary/non-scoped router at the top of the
2050 			 * list of routers in the same preference band, unless
2051 			 * it's already at that position.
2052 			 */
2053 			/* same preference and scoped; just return */
2054 			if (rtpref(new) == oldpref && scoped && dummy_change == FALSE) {
2055 				return dr;
2056 			}
2057 
2058 			n = TAILQ_FIRST(nd_router_listp);
2059 			while (n != NULL) {
2060 				/* preference changed; sort it */
2061 				if (rtpref(new) != oldpref) {
2062 					break;
2063 				}
2064 
2065 				/* not at the top of band; sort it */
2066 				if (n != dr && rtpref(n) == oldpref &&
2067 				    (!p || rtpref(p) > rtpref(n))) {
2068 					break;
2069 				}
2070 
2071 				p = n;
2072 				n = TAILQ_NEXT(n, dr_entry);
2073 			}
2074 
2075 			/* nothing has changed, just return */
2076 			if (n == NULL && (scoped ||
2077 			    !(dr->stateflags & NDDRF_IFSCOPE)) && dummy_change == FALSE) {
2078 				return dr;
2079 			}
2080 
2081 			/*
2082 			 * preferred router may be changed, so relocate
2083 			 * this router.
2084 			 * XXX: calling TAILQ_REMOVE directly is a bad manner.
2085 			 * However, since defrtrlist_del() has many side
2086 			 * effects, we intentionally do so here.
2087 			 * defrouter_select() below will handle routing
2088 			 * changes later.
2089 			 */
2090 			TAILQ_REMOVE(nd_router_listp, dr, dr_entry);
2091 			new->stateflags = dr->stateflags;
2092 
2093 			n = dr;
2094 			goto insert;
2095 		}
2096 	}
2097 
2098 	VERIFY(dr == NULL);
2099 	n = nddr_alloc(Z_WAITOK);
2100 
2101 	ndi = ND_IFINFO(ifp);
2102 	VERIFY((NULL != ndi) && (TRUE == ndi->initialized));
2103 	lck_mtx_lock(&ndi->lock);
2104 
2105 	if (ip6_maxifdefrouters >= 0 &&
2106 	    ndi->ndefrouters >= ip6_maxifdefrouters) {
2107 		lck_mtx_unlock(&ndi->lock);
2108 		nddr_free(n);
2109 		nd6log(error, "%s: ignoring router addition as we have hit the "
2110 		    "max limit of %d for max default routers.\n", __func__,
2111 		    ip6_maxifdefrouters);
2112 		return NULL;
2113 	}
2114 
2115 	NDDR_ADDREF(n); /* for the nd_defrouter list */
2116 	NDDR_ADDREF(n); /* for the caller */
2117 
2118 	++nd6_defrouter_genid;
2119 	ndi->ndefrouters++;
2120 	VERIFY(ndi->ndefrouters != 0);
2121 	lck_mtx_unlock(&ndi->lock);
2122 
2123 	nd6log2(info, "%s: allocating defrouter %s\n", if_name(ifp),
2124 	    ip6_sprintf(&new->rtaddr));
2125 
2126 	getmicrotime(&caltime);
2127 	NDDR_LOCK(n);
2128 	memcpy(&n->rtaddr, &new->rtaddr, sizeof(n->rtaddr));
2129 	n->flags = new->flags;
2130 	n->stateflags = new->stateflags;
2131 	n->rtlifetime = new->rtlifetime;
2132 	n->expire = new->expire;
2133 	n->base_calendartime = caltime.tv_sec;
2134 	n->base_uptime = net_uptime();
2135 	n->ifp = new->ifp;
2136 	n->err = new->err;
2137 	n->is_reachable = TRUE;
2138 	NDDR_UNLOCK(n);
2139 insert:
2140 	/* get nd6_service() to be scheduled as soon as it's convenient */
2141 	++nd6_sched_timeout_want;
2142 
2143 	/*
2144 	 * Insert the new router in the Default Router List;
2145 	 * The Default Router List should be in the descending order
2146 	 * of router-preferece.  When Scoped Routing is disabled, routers
2147 	 * with the same preference are sorted in the arriving time order;
2148 	 * otherwise, the first entry in the list of routers having the same
2149 	 * preference is the primary default router, when the interface used
2150 	 * by the entry is the default interface.
2151 	 */
2152 
2153 	/* insert at the end of the group */
2154 	for (dr = TAILQ_FIRST(nd_router_listp); dr;
2155 	    dr = TAILQ_NEXT(dr, dr_entry)) {
2156 		if (rtpref(n) > rtpref(dr) ||
2157 		    (!scoped && rtpref(n) == rtpref(dr))) {
2158 			break;
2159 		}
2160 	}
2161 	if (dr) {
2162 		TAILQ_INSERT_BEFORE(dr, n, dr_entry);
2163 	} else {
2164 		TAILQ_INSERT_TAIL(nd_router_listp, n, dr_entry);
2165 	}
2166 
2167 	defrouter_select(ifp, nd_router_listp);
2168 
2169 	return n;
2170 }
2171 
2172 struct nd_defrouter *
defrtrlist_update(struct nd_defrouter * new,struct nd_drhead * nd_router_list)2173 defrtrlist_update(struct nd_defrouter *new, struct nd_drhead *nd_router_list)
2174 {
2175 	struct nd_defrouter *dr;
2176 
2177 	LCK_MTX_ASSERT(nd6_mutex, LCK_MTX_ASSERT_OWNED);
2178 	dr = defrtrlist_update_common(new, nd_router_list,
2179 	    (nd6_defifp != NULL && new->ifp != nd6_defifp));
2180 
2181 	return dr;
2182 }
2183 
2184 struct nd_pfxrouter *
pfxrtr_lookup(struct nd_prefix * pr,struct nd_defrouter * dr)2185 pfxrtr_lookup(struct nd_prefix *pr, struct nd_defrouter *dr)
2186 {
2187 	struct nd_pfxrouter *search;
2188 
2189 	LCK_MTX_ASSERT(nd6_mutex, LCK_MTX_ASSERT_OWNED);
2190 	NDPR_LOCK_ASSERT_HELD(pr);
2191 
2192 	for (search = pr->ndpr_advrtrs.lh_first; search;
2193 	    search = search->pfr_next) {
2194 		if (search->router == dr) {
2195 			break;
2196 		}
2197 	}
2198 
2199 	return search;
2200 }
2201 
2202 static void
pfxrtr_add(struct nd_prefix * pr,struct nd_defrouter * dr)2203 pfxrtr_add(struct nd_prefix *pr, struct nd_defrouter *dr)
2204 {
2205 	struct nd_pfxrouter *__single new;
2206 
2207 	LCK_MTX_ASSERT(nd6_mutex, LCK_MTX_ASSERT_OWNED);
2208 	NDPR_LOCK_ASSERT_NOTHELD(pr);
2209 
2210 	new = zalloc_flags(ndprtr_zone, Z_WAITOK | Z_ZERO | Z_NOFAIL);
2211 	new->router = dr;
2212 
2213 	NDPR_LOCK(pr);
2214 	LIST_INSERT_HEAD(&pr->ndpr_advrtrs, new, pfr_entry);
2215 	pr->ndpr_genid++;
2216 	NDPR_UNLOCK(pr);
2217 
2218 	pfxlist_onlink_check();
2219 }
2220 
2221 static void
pfxrtr_del(struct nd_pfxrouter * pfr,struct nd_prefix * pr)2222 pfxrtr_del(struct nd_pfxrouter *pfr, struct nd_prefix *pr)
2223 {
2224 	LCK_MTX_ASSERT(nd6_mutex, LCK_MTX_ASSERT_OWNED);
2225 	NDPR_LOCK_ASSERT_HELD(pr);
2226 	pr->ndpr_genid++;
2227 	LIST_REMOVE(pfr, pfr_entry);
2228 	zfree(ndprtr_zone, pfr);
2229 }
2230 
2231 /*
2232  * The routine has been modified to atomically refresh expiry
2233  * time for nd6 prefix as the part of lookup.
2234  * There's a corner case where a system going
2235  * in sleep gets rid of manual addresses configured in the system
2236  * and then schedules the prefix for deletion.
2237  * However before the prefix gets deleted, if system comes out
2238  * from sleep and configures same address before prefix deletion
2239  * , the later prefix deletion will remove the prefix route and
2240  * the system will not be able to communicate with other IPv6
2241  * neighbor nodes in the same subnet.
2242  */
2243 struct nd_prefix *
nd6_prefix_lookup(struct nd_prefix * pr,int nd6_prefix_expiry)2244 nd6_prefix_lookup(struct nd_prefix *pr, int nd6_prefix_expiry)
2245 {
2246 	struct nd_prefix *__single search;
2247 
2248 	lck_mtx_lock(nd6_mutex);
2249 	for (search = nd_prefix.lh_first; search; search = search->ndpr_next) {
2250 		NDPR_LOCK(search);
2251 		if (pr->ndpr_ifp == search->ndpr_ifp &&
2252 		    pr->ndpr_plen == search->ndpr_plen &&
2253 		    in6_are_prefix_equal(&pr->ndpr_prefix.sin6_addr, pr->ndpr_prefix.sin6_scope_id,
2254 		    &search->ndpr_prefix.sin6_addr, search->ndpr_prefix.sin6_scope_id, pr->ndpr_plen)) {
2255 			if (nd6_prefix_expiry != ND6_PREFIX_EXPIRY_UNSPEC) {
2256 				search->ndpr_expire = nd6_prefix_expiry;
2257 			}
2258 			NDPR_ADDREF(search);
2259 			NDPR_UNLOCK(search);
2260 			break;
2261 		}
2262 		NDPR_UNLOCK(search);
2263 	}
2264 	lck_mtx_unlock(nd6_mutex);
2265 
2266 	return search;
2267 }
2268 
2269 int
nd6_prelist_add(struct nd_prefix * pr,struct nd_defrouter * dr,struct nd_prefix ** newp,boolean_t force_scoped)2270 nd6_prelist_add(struct nd_prefix *pr, struct nd_defrouter *dr,
2271     struct nd_prefix **newp, boolean_t force_scoped)
2272 {
2273 	struct nd_prefix *__single new = NULL;
2274 	ifnet_ref_t ifp = pr->ndpr_ifp;
2275 	struct nd_ifinfo *__single ndi = NULL;
2276 	int i, error;
2277 
2278 	if (ip6_maxifprefixes >= 0) {
2279 		ndi = ND_IFINFO(ifp);
2280 		VERIFY((NULL != ndi) && (TRUE == ndi->initialized));
2281 		lck_mtx_lock(&ndi->lock);
2282 		if (ndi->nprefixes >= ip6_maxifprefixes) {
2283 			lck_mtx_unlock(&ndi->lock);
2284 			return ENOMEM;
2285 		}
2286 		lck_mtx_unlock(&ndi->lock);
2287 	}
2288 
2289 	new = ndpr_alloc(M_WAITOK);
2290 	if (new == NULL) {
2291 		return ENOMEM;
2292 	}
2293 
2294 	NDPR_LOCK(new);
2295 	NDPR_LOCK(pr);
2296 	new->ndpr_ifp = pr->ndpr_ifp;
2297 	new->ndpr_prefix = pr->ndpr_prefix;
2298 	new->ndpr_plen = pr->ndpr_plen;
2299 	new->ndpr_vltime = pr->ndpr_vltime;
2300 	new->ndpr_pltime = pr->ndpr_pltime;
2301 	new->ndpr_flags = pr->ndpr_flags;
2302 	if (pr->ndpr_stateflags & NDPRF_STATIC) {
2303 		new->ndpr_stateflags |= NDPRF_STATIC;
2304 	}
2305 	NDPR_UNLOCK(pr);
2306 	if ((error = in6_init_prefix_ltimes(new)) != 0) {
2307 		NDPR_UNLOCK(new);
2308 		ndpr_free(new);
2309 		return error;
2310 	}
2311 	new->ndpr_lastupdate = net_uptime();
2312 	if (newp != NULL) {
2313 		*newp = new;
2314 		NDPR_ADDREF(new);        /* for caller */
2315 	}
2316 	/* initialization */
2317 	LIST_INIT(&new->ndpr_advrtrs);
2318 	in6_prefixlen2mask(&new->ndpr_mask, new->ndpr_plen);
2319 	/* make prefix in the canonical form */
2320 	for (i = 0; i < 4; i++) {
2321 		new->ndpr_prefix.sin6_addr.s6_addr32[i] &=
2322 		    new->ndpr_mask.s6_addr32[i];
2323 	}
2324 
2325 	NDPR_UNLOCK(new);
2326 
2327 	/* get nd6_service() to be scheduled as soon as it's convenient */
2328 	++nd6_sched_timeout_want;
2329 
2330 	lck_mtx_lock(nd6_mutex);
2331 	/* link ndpr_entry to nd_prefix list */
2332 	LIST_INSERT_HEAD(&nd_prefix, new, ndpr_entry);
2333 	new->ndpr_debug |= IFD_ATTACHED;
2334 	NDPR_ADDREF(new);       /* for nd_prefix list */
2335 
2336 	lck_mtx_lock(&ndi->lock);
2337 	ndi->nprefixes++;
2338 	VERIFY(ndi->nprefixes != 0);
2339 	lck_mtx_unlock(&ndi->lock);
2340 
2341 	/* ND_OPT_PI_FLAG_ONLINK processing */
2342 	if (new->ndpr_raf_onlink) {
2343 		int e;
2344 
2345 		if ((e = nd6_prefix_onlink_common(new, force_scoped,
2346 		    new->ndpr_ifp->if_index)) != 0) {
2347 			nd6log(error, "nd6_prelist_add: failed to make "
2348 			    "the prefix %s/%d on-link %s on %s (errno=%d)\n",
2349 			    ip6_sprintf(&new->ndpr_prefix.sin6_addr),
2350 			    new->ndpr_plen, force_scoped ? "scoped" :
2351 			    "non-scoped", if_name(ifp), e);
2352 			/* proceed anyway. XXX: is it correct? */
2353 		}
2354 	}
2355 
2356 	if (dr) {
2357 		pfxrtr_add(new, dr);
2358 	}
2359 
2360 	lck_mtx_unlock(nd6_mutex);
2361 
2362 	return 0;
2363 }
2364 
2365 /*
2366  * Caller must have held an extra reference on nd_prefix.
2367  */
2368 void
prelist_remove(struct nd_prefix * pr)2369 prelist_remove(struct nd_prefix *pr)
2370 {
2371 	struct nd_pfxrouter *__single pfr = NULL, *__single next = NULL;
2372 	ifnet_ref_t ifp = pr->ndpr_ifp;
2373 	struct nd_ifinfo *__single ndi = NULL;
2374 	struct nd_prefix *__single tmp_pr = NULL;
2375 	boolean_t pr_scoped;
2376 	int err;
2377 
2378 	LCK_MTX_ASSERT(nd6_mutex, LCK_MTX_ASSERT_OWNED);
2379 	NDPR_LOCK_ASSERT_HELD(pr);
2380 
2381 	if (pr->ndpr_stateflags & NDPRF_DEFUNCT) {
2382 		return;
2383 	}
2384 
2385 	pr_scoped = (pr->ndpr_stateflags & NDPRF_IFSCOPE) != 0;
2386 	/*
2387 	 * If there are no more addresses, defunct the prefix.  This is needed
2388 	 * because we don't want multiple threads calling prelist_remove() for
2389 	 * the same prefix and this might happen because we unlock nd6_mutex
2390 	 * down below.
2391 	 */
2392 	if (pr->ndpr_addrcnt == 0) {
2393 		pr->ndpr_stateflags |= NDPRF_DEFUNCT;
2394 	}
2395 
2396 	/* make sure to invalidate the prefix until it is really freed. */
2397 	pr->ndpr_vltime = 0;
2398 	pr->ndpr_pltime = 0;
2399 
2400 	/*
2401 	 * Though these flags are now meaningless, we'd rather keep the value
2402 	 * of pr->ndpr_raf_onlink and pr->ndpr_raf_auto not to confuse users
2403 	 * when executing "ndp -p".
2404 	 */
2405 	if (pr->ndpr_stateflags & NDPRF_ONLINK) {
2406 		int error = 0;
2407 		NDPR_ADDREF(pr);
2408 		NDPR_UNLOCK(pr);
2409 		lck_mtx_unlock(nd6_mutex);
2410 		if ((error = nd6_prefix_offlink(pr)) != 0) {
2411 			nd6log(error, "prelist_remove: failed to make "
2412 			    "%s/%d offlink on %s, errno=%d\n",
2413 			    ip6_sprintf(&pr->ndpr_prefix.sin6_addr),
2414 			    pr->ndpr_plen, if_name(ifp), error);
2415 			/* what should we do? */
2416 		}
2417 		lck_mtx_lock(nd6_mutex);
2418 		NDPR_LOCK(pr);
2419 		if (NDPR_REMREF(pr) == NULL) {
2420 			return;
2421 		}
2422 	}
2423 
2424 	/*
2425 	 * Check if there is a scoped version of this PR, if so
2426 	 * make it unscoped.
2427 	 */
2428 	if (!pr_scoped && IN6_IS_ADDR_UNIQUE_LOCAL(&pr->ndpr_prefix.sin6_addr)) {
2429 		tmp_pr = nd6_prefix_equal_lookup(pr, FALSE);
2430 		if (tmp_pr != NULL) {
2431 			NDPR_ADDREF(pr);
2432 			NDPR_UNLOCK(pr);
2433 
2434 			lck_mtx_unlock(nd6_mutex);
2435 			err = nd6_prefix_offlink(tmp_pr);
2436 			lck_mtx_lock(nd6_mutex);
2437 			if (err != 0) {
2438 				nd6log(error,
2439 				    "%s: failed to make %s/%d offlink on %s, "
2440 				    "errno=%d\n", __func__,
2441 				    ip6_sprintf(&tmp_pr->ndpr_prefix.sin6_addr),
2442 				    tmp_pr->ndpr_plen, if_name(tmp_pr->ndpr_ifp), err);
2443 			}
2444 
2445 			err = nd6_prefix_onlink_scoped(tmp_pr, IFSCOPE_NONE);
2446 			if (err != 0) {
2447 				nd6log(error,
2448 				    "%s: failed to make %s/%d onlink on %s, errno=%d\n",
2449 				    __func__, ip6_sprintf(&tmp_pr->ndpr_prefix.sin6_addr),
2450 				    tmp_pr->ndpr_plen, if_name(tmp_pr->ndpr_ifp), err);
2451 			}
2452 
2453 			if (err != 0) {
2454 				nd6log(error,
2455 				    "%s: error unscoping %s/%d from %s\n",
2456 				    __func__, ip6_sprintf(&tmp_pr->ndpr_prefix.sin6_addr),
2457 				    tmp_pr->ndpr_plen, if_name(tmp_pr->ndpr_ifp));
2458 			} else {
2459 				nd6log2(info,
2460 				    "%s: %s/%d unscoped, previously on %s\n",
2461 				    __func__, ip6_sprintf(&tmp_pr->ndpr_prefix.sin6_addr),
2462 				    tmp_pr->ndpr_plen, if_name(tmp_pr->ndpr_ifp));
2463 			}
2464 
2465 			NDPR_REMREF(tmp_pr);
2466 
2467 			NDPR_LOCK(pr);
2468 			if (NDPR_REMREF(pr) == NULL) {
2469 				return;
2470 			}
2471 		}
2472 	}
2473 
2474 	if (pr->ndpr_addrcnt > 0) {
2475 		/*
2476 		 * The state might have changed if we called
2477 		 * nd6_prefix_offlink().
2478 		 */
2479 		pr->ndpr_stateflags &= ~NDPRF_DEFUNCT;
2480 		return; /* notice here? */
2481 	}
2482 
2483 	/* unlink ndpr_entry from nd_prefix list */
2484 	LIST_REMOVE(pr, ndpr_entry);
2485 	pr->ndpr_debug &= ~IFD_ATTACHED;
2486 
2487 	/* free list of routers that adversed the prefix */
2488 	for (pfr = pr->ndpr_advrtrs.lh_first; pfr; pfr = next) {
2489 		next = pfr->pfr_next;
2490 		pfxrtr_del(pfr, pr);
2491 	}
2492 
2493 	ndi = ND_IFINFO(ifp);
2494 	VERIFY((NULL != ndi) && (TRUE == ndi->initialized));
2495 	lck_mtx_lock(&ndi->lock);
2496 	VERIFY(ndi->nprefixes > 0);
2497 	ndi->nprefixes--;
2498 	lck_mtx_unlock(&ndi->lock);
2499 
2500 	/* This must not be the last reference to the nd_prefix */
2501 	if (NDPR_REMREF(pr) == NULL) {
2502 		panic("%s: unexpected (missing) refcnt ndpr=%p", __func__, pr);
2503 		/* NOTREACHED */
2504 	}
2505 
2506 	/*
2507 	 * Don't call pfxlist_onlink_check() here because we are
2508 	 * holding the NDPR lock and this could cause a deadlock when
2509 	 * there are multiple threads executing pfxlist_onlink_check().
2510 	 */
2511 }
2512 
2513 int
prelist_update(struct nd_prefix * new,struct nd_defrouter * dr,struct mbuf * m,int mcast)2514 prelist_update(
2515 	struct nd_prefix *new,
2516 	struct nd_defrouter *dr, /* may be NULL */
2517 	struct mbuf *m,
2518 	int mcast)
2519 {
2520 	struct in6_ifaddr *__single ia6 = NULL, *__single ia6_match = NULL;
2521 	struct ifaddr *__single ifa;
2522 	ifnet_ref_t ifp = new->ndpr_ifp;
2523 	struct nd_prefix *__single pr;
2524 	int error = 0;
2525 	int newprefix = 0;
2526 	int auth;
2527 	uint64_t timenow = net_uptime();
2528 
2529 	/* no need to lock "new" here, as it is local to the caller */
2530 	NDPR_LOCK_ASSERT_NOTHELD(new);
2531 
2532 	auth = 0;
2533 	if (m) {
2534 		/*
2535 		 * Authenticity for NA consists authentication for
2536 		 * both IP header and IP datagrams, doesn't it ?
2537 		 */
2538 #if defined(M_AUTHIPHDR) && defined(M_AUTHIPDGM)
2539 		auth = (m->m_flags & M_AUTHIPHDR) && (m->m_flags & M_AUTHIPDGM);
2540 #endif
2541 	}
2542 
2543 	if ((pr = nd6_prefix_lookup(new, ND6_PREFIX_EXPIRY_UNSPEC)) != NULL) {
2544 		/*
2545 		 * nd6_prefix_lookup() ensures that pr and new have the same
2546 		 * prefix on a same interface.
2547 		 */
2548 
2549 		/*
2550 		 * Update prefix information.  Note that the on-link (L) bit
2551 		 * and the autonomous (A) bit should NOT be changed from 1
2552 		 * to 0.
2553 		 */
2554 		lck_mtx_lock(nd6_mutex);
2555 		NDPR_LOCK(pr);
2556 		if (new->ndpr_raf_onlink == 1) {
2557 			pr->ndpr_raf_onlink = 1;
2558 		}
2559 		if (new->ndpr_raf_auto == 1) {
2560 			pr->ndpr_raf_auto = 1;
2561 		}
2562 		if (new->ndpr_raf_onlink) {
2563 			pr->ndpr_vltime = new->ndpr_vltime;
2564 			pr->ndpr_pltime = new->ndpr_pltime;
2565 			(void) in6_init_prefix_ltimes(pr); /* XXX error case? */
2566 			pr->ndpr_lastupdate = net_uptime();
2567 		}
2568 
2569 		NDPR_ADDREF(pr);
2570 		if (new->ndpr_raf_onlink &&
2571 		    (pr->ndpr_stateflags & NDPRF_ONLINK) == 0) {
2572 			int e;
2573 
2574 			NDPR_UNLOCK(pr);
2575 			if ((e = nd6_prefix_onlink(pr)) != 0) {
2576 				nd6log(error,
2577 				    "prelist_update: failed to make "
2578 				    "the prefix %s/%d on-link on %s "
2579 				    "(errno=%d)\n",
2580 				    ip6_sprintf(&pr->ndpr_prefix.sin6_addr),
2581 				    pr->ndpr_plen, if_name(pr->ndpr_ifp), e);
2582 				/* proceed anyway. XXX: is it correct? */
2583 			}
2584 			NDPR_LOCK(pr);
2585 		}
2586 
2587 		if (dr && pfxrtr_lookup(pr, dr) == NULL) {
2588 			NDPR_UNLOCK(pr);
2589 			pfxrtr_add(pr, dr);
2590 		} else {
2591 			NDPR_UNLOCK(pr);
2592 		}
2593 		NDPR_REMREF(pr);
2594 		lck_mtx_unlock(nd6_mutex);
2595 	} else {
2596 		newprefix = 1;
2597 
2598 		if (new->ndpr_vltime == 0) {
2599 			goto end;
2600 		}
2601 		if (new->ndpr_raf_onlink == 0 && new->ndpr_raf_auto == 0) {
2602 			goto end;
2603 		}
2604 
2605 		bzero(&new->ndpr_addr, sizeof(struct in6_addr));
2606 
2607 		error = nd6_prelist_add(new, dr, &pr, FALSE);
2608 		if (error != 0 || pr == NULL) {
2609 			nd6log(info, "prelist_update: "
2610 			    "nd6_prelist_add failed for %s/%d on %s "
2611 			    "errno=%d, returnpr=0x%llx\n",
2612 			    ip6_sprintf(&new->ndpr_prefix.sin6_addr),
2613 			    new->ndpr_plen, if_name(new->ndpr_ifp),
2614 			    error, (uint64_t)VM_KERNEL_ADDRPERM(pr));
2615 			goto end; /* we should just give up in this case. */
2616 		}
2617 	}
2618 
2619 	/*
2620 	 * Address autoconfiguration based on Section 5.5.3 of RFC 4862.
2621 	 * Note that pr must be non NULL at this point.
2622 	 */
2623 
2624 	/* 5.5.3 (a). Ignore the prefix without the A bit set. */
2625 	if (!new->ndpr_raf_auto) {
2626 		goto end;
2627 	}
2628 
2629 	/*
2630 	 * 5.5.3 (b). the link-local prefix should have been ignored in
2631 	 * nd6_ra_input.
2632 	 */
2633 
2634 	/* 5.5.3 (c). Consistency check on lifetimes: pltime <= vltime. */
2635 	if (new->ndpr_pltime > new->ndpr_vltime) {
2636 		error = EINVAL; /* XXX: won't be used */
2637 		goto end;
2638 	}
2639 
2640 	/*
2641 	 * 5.5.3 (d).  If the prefix advertised is not equal to the prefix of
2642 	 * an address configured by stateless autoconfiguration already in the
2643 	 * list of addresses associated with the interface, and the Valid
2644 	 * Lifetime is not 0, form an address.  We first check if we have
2645 	 * a matching prefix.
2646 	 */
2647 	ifnet_lock_shared(ifp);
2648 	TAILQ_FOREACH(ifa, &ifp->if_addrlist, ifa_list) {
2649 		struct in6_ifaddr *__single ifa6 = NULL;
2650 		u_int32_t remaininglifetime = 0;
2651 		struct in6_addrlifetime lt6_tmp = {};
2652 
2653 		IFA_LOCK(ifa);
2654 		if (ifa->ifa_addr->sa_family != AF_INET6) {
2655 			IFA_UNLOCK(ifa);
2656 			continue;
2657 		}
2658 		ifa6 = ifatoia6(ifa);
2659 
2660 		/*
2661 		 * We only consider autoconfigured addresses as per RFC 4862.
2662 		 */
2663 		if (!(ifa6->ia6_flags & IN6_IFF_AUTOCONF)) {
2664 			IFA_UNLOCK(ifa);
2665 			continue;
2666 		}
2667 		/*
2668 		 * Spec is not clear here, but I believe we should concentrate
2669 		 * on unicast (i.e. not anycast) addresses.
2670 		 * XXX: other ia6_flags? detached or duplicated?
2671 		 */
2672 		if ((ifa6->ia6_flags & IN6_IFF_ANYCAST) != 0) {
2673 			IFA_UNLOCK(ifa);
2674 			continue;
2675 		}
2676 		/*
2677 		 * Ignore the address if it is not associated with a prefix
2678 		 * or is associated with a prefix that is different from this
2679 		 * one.  (pr is never NULL here)
2680 		 */
2681 		if (ifa6->ia6_ndpr != pr) {
2682 			IFA_UNLOCK(ifa);
2683 			continue;
2684 		}
2685 
2686 		if (ia6_match == NULL) { /* remember the first one */
2687 			ia6_match = ifa6;
2688 			ifa_addref(ifa); /* for ia6_match */
2689 		}
2690 
2691 		/*
2692 		 * An already autoconfigured address matched.  Now that we
2693 		 * are sure there is at least one matched address, we can
2694 		 * proceed to 5.5.3. (e): update the lifetimes according to the
2695 		 * "two hours" rule and the privacy extension.
2696 		 */
2697 		/* retrieve time as uptime (last arg is 0) */
2698 		in6ifa_getlifetime(ifa6, &lt6_tmp, 0);
2699 
2700 		if (lt6_tmp.ia6t_vltime == ND6_INFINITE_LIFETIME) {
2701 			remaininglifetime = ND6_INFINITE_LIFETIME;
2702 		} else if (timenow - ifa6->ia6_updatetime > lt6_tmp.ia6t_vltime) {
2703 			/*
2704 			 * The case of "invalid" address.  We should usually
2705 			 * not see this case.
2706 			 */
2707 			remaininglifetime = 0;
2708 		} else {
2709 			remaininglifetime = lt6_tmp.ia6t_vltime -
2710 			    (uint32_t)(timenow - ifa6->ia6_updatetime);
2711 		}
2712 		/* when not updating, keep the current stored lifetime. */
2713 		lt6_tmp.ia6t_vltime = remaininglifetime;
2714 
2715 		if (TWOHOUR < new->ndpr_vltime ||
2716 		    remaininglifetime < new->ndpr_vltime) {
2717 			lt6_tmp.ia6t_vltime = new->ndpr_vltime;
2718 		} else if (remaininglifetime <= TWOHOUR) {
2719 			if (auth) {
2720 				lt6_tmp.ia6t_vltime = new->ndpr_vltime;
2721 			}
2722 		} else {
2723 			/*
2724 			 * new->ndpr_vltime <= TWOHOUR &&
2725 			 * TWOHOUR < remaininglifetime
2726 			 */
2727 			lt6_tmp.ia6t_vltime = TWOHOUR;
2728 		}
2729 
2730 		/* The 2 hour rule is not imposed for preferred lifetime. */
2731 		lt6_tmp.ia6t_pltime = new->ndpr_pltime;
2732 
2733 		/* Special handling for lifetimes of temporary addresses. */
2734 		if ((ifa6->ia6_flags & IN6_IFF_TEMPORARY) != 0) {
2735 			u_int32_t maxvltime, maxpltime;
2736 
2737 			/* Constrain lifetimes to system limits. */
2738 			if (lt6_tmp.ia6t_vltime > ip6_temp_valid_lifetime) {
2739 				lt6_tmp.ia6t_vltime = ip6_temp_valid_lifetime;
2740 			}
2741 			if (lt6_tmp.ia6t_pltime > ip6_temp_preferred_lifetime) {
2742 				lt6_tmp.ia6t_pltime =
2743 				    ip6_temp_preferred_lifetime -
2744 				    ip6_desync_factor;
2745 			}
2746 
2747 			/*
2748 			 * According to RFC 4941, section 3.3 (1), we only
2749 			 * update the lifetimes when they are in the maximum
2750 			 * intervals.
2751 			 */
2752 			if (ip6_temp_valid_lifetime >
2753 			    (u_int32_t)((timenow - ifa6->ia6_createtime) +
2754 			    ip6_desync_factor)) {
2755 				maxvltime = ip6_temp_valid_lifetime -
2756 				    (uint32_t)((timenow - ifa6->ia6_createtime) +
2757 				    ip6_desync_factor);
2758 			} else {
2759 				maxvltime = 0;
2760 			}
2761 			if (ip6_temp_preferred_lifetime >
2762 			    (u_int32_t)((timenow - ifa6->ia6_createtime) +
2763 			    ip6_desync_factor)) {
2764 				maxpltime = ip6_temp_preferred_lifetime -
2765 				    (uint32_t)((timenow - ifa6->ia6_createtime) +
2766 				    ip6_desync_factor);
2767 			} else {
2768 				maxpltime = 0;
2769 			}
2770 
2771 			if (lt6_tmp.ia6t_vltime == ND6_INFINITE_LIFETIME ||
2772 			    lt6_tmp.ia6t_vltime > maxvltime) {
2773 				lt6_tmp.ia6t_vltime = maxvltime;
2774 			}
2775 
2776 			if (lt6_tmp.ia6t_pltime == ND6_INFINITE_LIFETIME ||
2777 			    lt6_tmp.ia6t_pltime > maxpltime) {
2778 				lt6_tmp.ia6t_pltime = maxpltime;
2779 			}
2780 		}
2781 
2782 		in6_init_address_ltimes(&lt6_tmp);
2783 		in6ifa_setlifetime(ifa6, &lt6_tmp);
2784 		ifa6->ia6_updatetime = timenow;
2785 		IFA_UNLOCK(ifa);
2786 	}
2787 	ifnet_lock_done(ifp);
2788 	if (ia6_match == NULL && new->ndpr_vltime) {
2789 		/*
2790 		 * 5.5.3 (d) (continued)
2791 		 * No address matched and the valid lifetime is non-zero.
2792 		 * Create a new address.
2793 		 */
2794 		if ((ia6 = in6_pfx_newpersistaddr(new, mcast, &error, FALSE, 0))
2795 		    != NULL) {
2796 			/*
2797 			 * note that we should use pr (not new) for reference.
2798 			 */
2799 			IFA_LOCK(&ia6->ia_ifa);
2800 			NDPR_LOCK(pr);
2801 			ia6->ia6_ndpr = pr;
2802 			NDPR_ADDREF(pr); /* for addr reference */
2803 			pr->ndpr_addrcnt++;
2804 			VERIFY(pr->ndpr_addrcnt != 0);
2805 			NDPR_UNLOCK(pr);
2806 			IFA_UNLOCK(&ia6->ia_ifa);
2807 
2808 			/*
2809 			 * RFC 4941 3.3 (2).
2810 			 * When a new public address is created as described
2811 			 * in RFC 4862, also create a new temporary address.
2812 			 *
2813 			 * RFC 4941 3.5.
2814 			 * When an interface connects to a new link, a new
2815 			 * randomized interface identifier should be generated
2816 			 * immediately together with a new set of temporary
2817 			 * addresses.  Thus, we specify 1 as the 2nd arg of
2818 			 * in6_tmpifadd().
2819 			 */
2820 			if (ip6_use_tempaddr &&
2821 			    (!IN6_IS_ADDR_UNIQUE_LOCAL(&new->ndpr_prefix.sin6_addr)
2822 			    || ip6_ula_use_tempaddr)) {
2823 				int e;
2824 				if ((e = in6_tmpifadd(ia6, 1)) != 0) {
2825 					nd6log(info, "prelist_update: "
2826 					    "failed to create a temporary "
2827 					    "address, errno=%d\n",
2828 					    e);
2829 				}
2830 			}
2831 			ifa_remref(&ia6->ia_ifa);
2832 			ia6 = NULL;
2833 
2834 			/*
2835 			 * If the interface is marked for CLAT46 configuration
2836 			 * try and configure the reserved IPv6 address for
2837 			 * stateless translation.
2838 			 */
2839 			if (IS_INTF_CLAT46(ifp)) {
2840 				if ((ia6 = in6_pfx_newpersistaddr(new, mcast,
2841 				    &error, TRUE, CLAT46_COLLISION_COUNT_OFFSET))
2842 				    != NULL) {
2843 					IFA_LOCK(&ia6->ia_ifa);
2844 					NDPR_LOCK(pr);
2845 					ia6->ia6_ndpr = pr;
2846 					NDPR_ADDREF(pr); /* for addr reference */
2847 					pr->ndpr_addrcnt++;
2848 					VERIFY(pr->ndpr_addrcnt != 0);
2849 					pr->ndpr_stateflags |= NDPRF_CLAT46;
2850 					NDPR_UNLOCK(pr);
2851 					IFA_UNLOCK(&ia6->ia_ifa);
2852 					ifa_remref(&ia6->ia_ifa);
2853 					ia6 = NULL;
2854 				} else if (error != EEXIST) {
2855 					uuid_t tmp_uuid = {};
2856 					/*
2857 					 * Only report the error if it is not
2858 					 * EEXIST.
2859 					 */
2860 					ip6stat.ip6s_clat464_v6addr_conffail++;
2861 					in6_clat46_event_enqueue_nwk_wq_entry(
2862 						IN6_CLAT46_EVENT_V6_ADDR_CONFFAIL,
2863 						0,
2864 						tmp_uuid);
2865 					nd6log0(error, "Could not configure CLAT46 address on interface %s.\n", ifp->if_xname);
2866 				}
2867 				/*
2868 				 * Reset the error as we do not want to
2869 				 * treat failure of CLAT46 address configuration
2870 				 * as complete failure in prelist update path.
2871 				 */
2872 				error = 0;
2873 			}
2874 
2875 			/*
2876 			 * A newly added address might affect the status
2877 			 * of other addresses, so we check and update it.
2878 			 * XXX: what if address duplication happens?
2879 			 */
2880 			lck_mtx_lock(nd6_mutex);
2881 			pfxlist_onlink_check();
2882 			lck_mtx_unlock(nd6_mutex);
2883 		}
2884 	}
2885 end:
2886 	if (pr != NULL) {
2887 		NDPR_REMREF(pr);
2888 	}
2889 	if (ia6_match != NULL) {
2890 		ifa_remref(&ia6_match->ia_ifa);
2891 	}
2892 	return error;
2893 }
2894 
2895 /*
2896  * Neighbor Discover Default Router structure reference counting routines.
2897  */
2898 static struct nd_defrouter *
nddr_alloc(zalloc_flags_t how)2899 nddr_alloc(zalloc_flags_t how)
2900 {
2901 	struct nd_defrouter *__single dr;
2902 
2903 	dr = zalloc_flags(nddr_zone, how | Z_ZERO);
2904 	if (dr) {
2905 		lck_mtx_init(&dr->nddr_lock, &ifa_mtx_grp, &ifa_mtx_attr);
2906 		lck_mtx_init(&dr->nddr_ref_lock, &ifa_mtx_grp, &ifa_mtx_attr);
2907 		dr->nddr_debug |= IFD_ALLOC;
2908 		if (nddr_debug != 0) {
2909 			dr->nddr_debug |= IFD_DEBUG;
2910 			dr->nddr_trace = nddr_trace;
2911 		}
2912 	}
2913 	return dr;
2914 }
2915 
2916 static void
nddr_free(struct nd_defrouter * dr)2917 nddr_free(struct nd_defrouter *dr)
2918 {
2919 	if (dr->nddr_debug & IFD_ATTACHED) {
2920 		panic("%s: attached nddr %p is being freed", __func__, dr);
2921 		/* NOTREACHED */
2922 	} else if (!(dr->nddr_debug & IFD_ALLOC)) {
2923 		panic("%s: nddr %p cannot be freed", __func__, dr);
2924 		/* NOTREACHED */
2925 	}
2926 	dr->nddr_debug &= ~IFD_ALLOC;
2927 	lck_mtx_destroy(&dr->nddr_lock, &ifa_mtx_grp);
2928 	lck_mtx_destroy(&dr->nddr_ref_lock, &ifa_mtx_grp);
2929 	zfree(nddr_zone, dr);
2930 }
2931 
2932 static void
nddr_trace(struct nd_defrouter * dr,int refhold)2933 nddr_trace(struct nd_defrouter *dr, int refhold)
2934 {
2935 	struct nd_defrouter_dbg *__single dr_dbg = (struct nd_defrouter_dbg *)dr;
2936 	ctrace_t *tr;
2937 	uint32_t idx;
2938 	uint16_t *cnt;
2939 
2940 	if (!(dr->nddr_debug & IFD_DEBUG)) {
2941 		panic("%s: nddr %p has no debug structure", __func__, dr);
2942 		/* NOTREACHED */
2943 	}
2944 	if (refhold) {
2945 		cnt = &dr_dbg->nddr_refhold_cnt;
2946 		tr = dr_dbg->nddr_refhold;
2947 	} else {
2948 		cnt = &dr_dbg->nddr_refrele_cnt;
2949 		tr = dr_dbg->nddr_refrele;
2950 	}
2951 
2952 	idx = os_atomic_inc_orig(cnt, relaxed) % NDDR_TRACE_HIST_SIZE;
2953 	ctrace_record(&tr[idx]);
2954 }
2955 
2956 void
nddr_addref(struct nd_defrouter * nddr)2957 nddr_addref(struct nd_defrouter *nddr)
2958 {
2959 	NDDR_REF_LOCK_SPIN(nddr);
2960 	if (++nddr->nddr_refcount == 0) {
2961 		panic("%s: nddr %p wraparound refcnt", __func__, nddr);
2962 		/* NOTREACHED */
2963 	} else if (nddr->nddr_trace != NULL) {
2964 		(*nddr->nddr_trace)(nddr, TRUE);
2965 	}
2966 	NDDR_REF_UNLOCK(nddr);
2967 }
2968 
2969 struct nd_defrouter *
nddr_remref(struct nd_defrouter * nddr)2970 nddr_remref(struct nd_defrouter *nddr)
2971 {
2972 	NDDR_REF_LOCK_SPIN(nddr);
2973 	if (nddr->nddr_refcount == 0) {
2974 		panic("%s: nddr %p negative refcnt", __func__, nddr);
2975 		/* NOTREACHED */
2976 	} else if (nddr->nddr_trace != NULL) {
2977 		(*nddr->nddr_trace)(nddr, FALSE);
2978 	}
2979 
2980 	if (--nddr->nddr_refcount == 0) {
2981 		NDDR_REF_UNLOCK(nddr);
2982 		nddr_free(nddr);
2983 		nddr = NULL;
2984 	} else {
2985 		NDDR_REF_UNLOCK(nddr);
2986 	}
2987 	return nddr;
2988 }
2989 
2990 uint64_t
nddr_getexpire(struct nd_defrouter * dr)2991 nddr_getexpire(struct nd_defrouter *dr)
2992 {
2993 	struct timeval caltime;
2994 	uint64_t expiry;
2995 
2996 	if (dr->expire != 0) {
2997 		/* account for system time change */
2998 		getmicrotime(&caltime);
2999 
3000 		dr->base_calendartime +=
3001 		    NET_CALCULATE_CLOCKSKEW(caltime,
3002 		    dr->base_calendartime, net_uptime(), dr->base_uptime);
3003 
3004 		expiry = dr->base_calendartime +
3005 		    dr->expire - dr->base_uptime;
3006 	} else {
3007 		expiry = 0;
3008 	}
3009 	return expiry;
3010 }
3011 
3012 /*
3013  * Neighbor Discover Prefix structure reference counting routines.
3014  */
3015 static struct nd_prefix *
ndpr_alloc(int how)3016 ndpr_alloc(int how)
3017 {
3018 	struct nd_prefix *__single pr;
3019 
3020 	pr = zalloc_flags(ndpr_zone, how | Z_ZERO);
3021 	if (pr != NULL) {
3022 		lck_mtx_init(&pr->ndpr_lock, &ifa_mtx_grp, &ifa_mtx_attr);
3023 		lck_mtx_init(&pr->ndpr_ref_lock, &ifa_mtx_grp, &ifa_mtx_attr);
3024 		RB_INIT(&pr->ndpr_prproxy_sols);
3025 		pr->ndpr_debug |= IFD_ALLOC;
3026 		if (ndpr_debug != 0) {
3027 			pr->ndpr_debug |= IFD_DEBUG;
3028 			pr->ndpr_trace = ndpr_trace;
3029 		}
3030 	}
3031 	return pr;
3032 }
3033 
3034 static void
ndpr_free(struct nd_prefix * pr)3035 ndpr_free(struct nd_prefix *pr)
3036 {
3037 	if (pr->ndpr_debug & IFD_ATTACHED) {
3038 		panic("%s: attached ndpr %p is being freed", __func__, pr);
3039 		/* NOTREACHED */
3040 	} else if (!(pr->ndpr_debug & IFD_ALLOC)) {
3041 		panic("%s: ndpr %p cannot be freed", __func__, pr);
3042 		/* NOTREACHED */
3043 	} else if (pr->ndpr_rt != NULL) {
3044 		panic("%s: ndpr %p route %p not freed", __func__, pr,
3045 		    pr->ndpr_rt);
3046 		/* NOTREACHED */
3047 	} else if (pr->ndpr_prproxy_sols_cnt != 0) {
3048 		panic("%s: ndpr %p non-zero solicitors count (%d)",
3049 		    __func__, pr, pr->ndpr_prproxy_sols_cnt);
3050 		/* NOTREACHED */
3051 	} else if (!RB_EMPTY(&pr->ndpr_prproxy_sols)) {
3052 		panic("%s: ndpr %p non-empty solicitors tree", __func__, pr);
3053 		/* NOTREACHED */
3054 	}
3055 	pr->ndpr_debug &= ~IFD_ALLOC;
3056 	lck_mtx_destroy(&pr->ndpr_lock, &ifa_mtx_grp);
3057 	lck_mtx_destroy(&pr->ndpr_ref_lock, &ifa_mtx_grp);
3058 	zfree(ndpr_zone, pr);
3059 }
3060 
3061 static void
ndpr_trace(struct nd_prefix * pr,int refhold)3062 ndpr_trace(struct nd_prefix *pr, int refhold)
3063 {
3064 	struct nd_prefix_dbg *__single pr_dbg = (struct nd_prefix_dbg *)pr;
3065 	ctrace_t *tr;
3066 	u_int32_t idx;
3067 	u_int16_t *cnt;
3068 
3069 	if (!(pr->ndpr_debug & IFD_DEBUG)) {
3070 		panic("%s: ndpr %p has no debug structure", __func__, pr);
3071 		/* NOTREACHED */
3072 	}
3073 	if (refhold) {
3074 		cnt = &pr_dbg->ndpr_refhold_cnt;
3075 		tr = pr_dbg->ndpr_refhold;
3076 	} else {
3077 		cnt = &pr_dbg->ndpr_refrele_cnt;
3078 		tr = pr_dbg->ndpr_refrele;
3079 	}
3080 
3081 	idx = os_atomic_inc_orig(cnt, relaxed) % NDPR_TRACE_HIST_SIZE;
3082 	ctrace_record(&tr[idx]);
3083 }
3084 
3085 void
ndpr_addref(struct nd_prefix * ndpr)3086 ndpr_addref(struct nd_prefix *ndpr)
3087 {
3088 	NDPR_REF_LOCK_SPIN(ndpr);
3089 	if (++ndpr->ndpr_refcount == 0) {
3090 		panic("%s: ndpr %p wraparound refcnt", __func__, ndpr);
3091 		/* NOTREACHED */
3092 	} else if (ndpr->ndpr_trace != NULL) {
3093 		(*ndpr->ndpr_trace)(ndpr, TRUE);
3094 	}
3095 	NDPR_REF_UNLOCK(ndpr);
3096 }
3097 
3098 struct nd_prefix *
ndpr_remref(struct nd_prefix * ndpr)3099 ndpr_remref(struct nd_prefix *ndpr)
3100 {
3101 	NDPR_REF_LOCK_SPIN(ndpr);
3102 	if (ndpr->ndpr_refcount == 0) {
3103 		panic("%s: ndpr %p negative refcnt", __func__, ndpr);
3104 		/* NOTREACHED */
3105 	} else if (ndpr->ndpr_trace != NULL) {
3106 		(*ndpr->ndpr_trace)(ndpr, FALSE);
3107 	}
3108 
3109 	if (--ndpr->ndpr_refcount == 0) {
3110 		if (ndpr->ndpr_addrcnt != 0) {
3111 			panic("%s: freeing ndpr %p with outstanding address "
3112 			    "reference (%d)", __func__, ndpr,
3113 			    ndpr->ndpr_addrcnt);
3114 			/* NOTREACHED */
3115 		}
3116 		NDPR_REF_UNLOCK(ndpr);
3117 		ndpr_free(ndpr);
3118 		ndpr = NULL;
3119 	} else {
3120 		NDPR_REF_UNLOCK(ndpr);
3121 	}
3122 	return ndpr;
3123 }
3124 
3125 uint64_t
ndpr_getexpire(struct nd_prefix * pr)3126 ndpr_getexpire(struct nd_prefix *pr)
3127 {
3128 	struct timeval caltime;
3129 	uint64_t expiry;
3130 
3131 	if (pr->ndpr_expire != 0 && pr->ndpr_vltime != ND6_INFINITE_LIFETIME) {
3132 		/* account for system time change */
3133 		getmicrotime(&caltime);
3134 
3135 		pr->ndpr_base_calendartime +=
3136 		    NET_CALCULATE_CLOCKSKEW(caltime,
3137 		    pr->ndpr_base_calendartime, net_uptime(),
3138 		    pr->ndpr_base_uptime);
3139 
3140 		expiry = pr->ndpr_base_calendartime +
3141 		    pr->ndpr_expire - pr->ndpr_base_uptime;
3142 	} else {
3143 		expiry = 0;
3144 	}
3145 	return expiry;
3146 }
3147 
3148 /*
3149  * A supplement function used in the on-link detection below;
3150  * detect if a given prefix has a (probably) reachable advertising router.
3151  * XXX: lengthy function name...
3152  */
3153 static struct nd_pfxrouter *
find_pfxlist_reachable_router(struct nd_prefix * pr)3154 find_pfxlist_reachable_router(struct nd_prefix *pr)
3155 {
3156 	struct nd_pfxrouter *__single pfxrtr = NULL;
3157 	ifnet_ref_t ifp = NULL;
3158 
3159 	LCK_MTX_ASSERT(nd6_mutex, LCK_MTX_ASSERT_OWNED);
3160 	NDPR_LOCK_ASSERT_HELD(pr);
3161 
3162 	pfxrtr = LIST_FIRST(&pr->ndpr_advrtrs);
3163 	while (pfxrtr) {
3164 		/* XXX This should be same as prefixes interface. */
3165 		ifp = pfxrtr->router->ifp;
3166 
3167 		/*
3168 		 * As long as there's a router advertisting this prefix
3169 		 * on cellular (for that matter any interface that is point
3170 		 * to point really), we treat the router as reachable.
3171 		 */
3172 		if (ifp != NULL && ifp->if_type == IFT_CELLULAR) {
3173 			break;
3174 		}
3175 
3176 		if (pfxrtr->router->is_reachable) {
3177 			break;
3178 		}
3179 		pfxrtr = LIST_NEXT(pfxrtr, pfr_entry);
3180 	}
3181 	return pfxrtr;
3182 }
3183 
3184 /*
3185  * Check if each prefix in the prefix list has at least one available router
3186  * that advertised the prefix (a router is "available" if its neighbor cache
3187  * entry is reachable or probably reachable).
3188  * If the check fails, the prefix may be off-link, because, for example,
3189  * we have moved from the network but the lifetime of the prefix has not
3190  * expired yet.  So we should not use the prefix if there is another prefix
3191  * that has an available router.
3192  * But, if there is no prefix that has an available router, we still regards
3193  * all the prefixes as on-link.  This is because we can't tell if all the
3194  * routers are simply dead or if we really moved from the network and there
3195  * is no router around us.
3196  */
3197 void
pfxlist_onlink_check(void)3198 pfxlist_onlink_check(void)
3199 {
3200 	struct nd_prefix *__single pr, *__single prclear;
3201 	struct in6_ifaddr *__single ifa;
3202 	struct nd_defrouter *__single dr;
3203 	struct nd_pfxrouter *__single pfxrtr = NULL;
3204 	int err, i, found = 0;
3205 	u_int16_t addresses_count;
3206 	struct ifaddr **__single __counted_by(addresses_count) ifap = NULL;
3207 	struct nd_prefix *__single ndpr;
3208 	u_int64_t timenow = net_uptime();
3209 
3210 	LCK_MTX_ASSERT(nd6_mutex, LCK_MTX_ASSERT_OWNED);
3211 
3212 	while (nd_prefix_busy) {
3213 		nd_prefix_waiters++;
3214 		msleep(nd_prefix_waitchan, nd6_mutex, (PZERO - 1),
3215 		    __func__, NULL);
3216 		LCK_MTX_ASSERT(nd6_mutex, LCK_MTX_ASSERT_OWNED);
3217 	}
3218 	nd_prefix_busy = TRUE;
3219 
3220 	/*
3221 	 * Check if there is a prefix that has a reachable advertising
3222 	 * router.
3223 	 */
3224 	pr = nd_prefix.lh_first;
3225 	while (pr) {
3226 		NDPR_LOCK(pr);
3227 		if (pr->ndpr_raf_onlink && find_pfxlist_reachable_router(pr) &&
3228 		    (pr->ndpr_debug & IFD_ATTACHED)) {
3229 			NDPR_UNLOCK(pr);
3230 			break;
3231 		}
3232 		NDPR_UNLOCK(pr);
3233 		pr = pr->ndpr_next;
3234 	}
3235 	/*
3236 	 * If we have no such prefix, check whether we still have a router
3237 	 * that does not advertise any prefixes.
3238 	 */
3239 	if (pr == NULL) {
3240 		for (dr = TAILQ_FIRST(&nd_defrouter_list); dr;
3241 		    dr = TAILQ_NEXT(dr, dr_entry)) {
3242 			struct nd_prefix *__single pr0;
3243 
3244 			for (pr0 = nd_prefix.lh_first; pr0;
3245 			    pr0 = pr0->ndpr_next) {
3246 				NDPR_LOCK(pr0);
3247 				if ((pfxrtr = pfxrtr_lookup(pr0, dr)) != NULL) {
3248 					NDPR_UNLOCK(pr0);
3249 					break;
3250 				}
3251 				NDPR_UNLOCK(pr0);
3252 			}
3253 			if (pfxrtr != NULL) {
3254 				break;
3255 			}
3256 		}
3257 	}
3258 	if (pr != NULL || (TAILQ_FIRST(&nd_defrouter_list) && pfxrtr == NULL)) {
3259 		/*
3260 		 * There is at least one prefix that has a reachable router,
3261 		 * or at least a router which probably does not advertise
3262 		 * any prefixes.  The latter would be the case when we move
3263 		 * to a new link where we have a router that does not provide
3264 		 * prefixes and we configure an address by hand.
3265 		 * Detach prefixes which have no reachable advertising
3266 		 * router, and attach other prefixes.
3267 		 */
3268 		pr = nd_prefix.lh_first;
3269 		while (pr) {
3270 			NDPR_LOCK(pr);
3271 			/*
3272 			 * We aren't interested prefixes already processed,
3273 			 * nor in prefixes without the L bit
3274 			 * set nor in static prefixes
3275 			 */
3276 			if (pr->ndpr_raf_onlink == 0 ||
3277 			    pr->ndpr_stateflags & NDPRF_STATIC) {
3278 				NDPR_UNLOCK(pr);
3279 				pr = pr->ndpr_next;
3280 				continue;
3281 			}
3282 			if ((pr->ndpr_stateflags & NDPRF_DETACHED) == 0 &&
3283 			    find_pfxlist_reachable_router(pr) == NULL &&
3284 			    (pr->ndpr_debug & IFD_ATTACHED)) {
3285 				pr->ndpr_stateflags |= NDPRF_DETACHED;
3286 			}
3287 			if ((pr->ndpr_stateflags & NDPRF_DETACHED) != 0 &&
3288 			    find_pfxlist_reachable_router(pr) != NULL &&
3289 			    (pr->ndpr_debug & IFD_ATTACHED)) {
3290 				pr->ndpr_stateflags &= ~NDPRF_DETACHED;
3291 			}
3292 			NDPR_UNLOCK(pr);
3293 			pr = pr->ndpr_next;
3294 		}
3295 	} else {
3296 		/* there is no prefix that has a reachable router */
3297 		for (pr = nd_prefix.lh_first; pr; pr = pr->ndpr_next) {
3298 			NDPR_LOCK(pr);
3299 			if (pr->ndpr_raf_onlink == 0 ||
3300 			    pr->ndpr_stateflags & NDPRF_STATIC) {
3301 				NDPR_UNLOCK(pr);
3302 				continue;
3303 			}
3304 			if ((pr->ndpr_stateflags & NDPRF_DETACHED) != 0) {
3305 				pr->ndpr_stateflags &= ~NDPRF_DETACHED;
3306 			}
3307 			NDPR_UNLOCK(pr);
3308 		}
3309 	}
3310 	/*
3311 	 * Instead of removing interface route for detached prefix,
3312 	 * keep the route and treat unreachability similar to the processing
3313 	 * of an RA that has just deprecated the prefix.
3314 	 * Keep around the detached flag just to be able to be able
3315 	 * to differentiate the scenario from explicit RA deprecation
3316 	 * of prefix.
3317 	 * Keep the logic to install the interface route for a (just) attached
3318 	 * prefix. Note that all attempt of reinstallation does not
3319 	 * necessarily success, when a same prefix is shared among multiple
3320 	 * interfaces.  Such cases will be handled in nd6_prefix_onlink,
3321 	 * so we don't have to care about them.
3322 	 */
3323 	pr = nd_prefix.lh_first;
3324 	while (pr) {
3325 		int error;
3326 
3327 		NDPR_LOCK(pr);
3328 		if (pr->ndpr_raf_onlink == 0 ||
3329 		    pr->ndpr_stateflags & NDPRF_STATIC ||
3330 		    pr->ndpr_stateflags & NDPRF_PROCESSED_ONLINK ||
3331 		    pr->ndpr_stateflags & NDPRF_DEFUNCT) {
3332 			NDPR_UNLOCK(pr);
3333 			pr = pr->ndpr_next;
3334 			continue;
3335 		}
3336 		pr->ndpr_stateflags |= NDPRF_PROCESSED_ONLINK;
3337 		NDPR_ADDREF(pr);
3338 		if (pr->ndpr_stateflags & NDPRF_DETACHED) {
3339 			/*
3340 			 * When a prefix is detached, make it deprecated by setting pltime
3341 			 * to 0, and let it expire according to its advertised vltime.
3342 			 * If its original vltime is infinite or longer than 2hr,
3343 			 * set it to 2hr.
3344 			 */
3345 			pr->ndpr_pltime = 0;
3346 			uint32_t pr_remaining_lifetime;
3347 			uint32_t original_lifetime = (uint32_t)(timenow - pr->ndpr_base_uptime);
3348 			if (pr->ndpr_vltime > original_lifetime) {
3349 				pr_remaining_lifetime = pr->ndpr_vltime - original_lifetime;
3350 			} else {
3351 				pr_remaining_lifetime = 0;
3352 			}
3353 			if (pr->ndpr_vltime == ND6_INFINITE_LIFETIME ||
3354 			    pr_remaining_lifetime >= TWOHOUR) {
3355 				pr->ndpr_vltime = TWOHOUR;
3356 			} else {
3357 				pr->ndpr_vltime = pr_remaining_lifetime;
3358 			}
3359 			in6_init_prefix_ltimes(pr);
3360 			NDPR_UNLOCK(pr);
3361 		} else if ((pr->ndpr_stateflags & NDPRF_DETACHED) == 0 &&
3362 		    (pr->ndpr_stateflags & NDPRF_ONLINK) == 0 &&
3363 		    pr->ndpr_raf_onlink) {
3364 			NDPR_UNLOCK(pr);
3365 			if ((error = nd6_prefix_onlink(pr)) != 0) {
3366 				nd6log(error,
3367 				    "pfxlist_onlink_check: failed to "
3368 				    "make %s/%d offlink, errno=%d\n",
3369 				    ip6_sprintf(&pr->ndpr_prefix.sin6_addr),
3370 				    pr->ndpr_plen, error);
3371 			}
3372 			NDPR_REMREF(pr);
3373 			pr = nd_prefix.lh_first;
3374 			continue;
3375 		} else {
3376 			NDPR_UNLOCK(pr);
3377 		}
3378 		NDPR_REMREF(pr);
3379 		pr = pr->ndpr_next;
3380 	}
3381 	LIST_FOREACH(prclear, &nd_prefix, ndpr_entry) {
3382 		NDPR_LOCK(prclear);
3383 		prclear->ndpr_stateflags &= ~NDPRF_PROCESSED_ONLINK;
3384 		NDPR_UNLOCK(prclear);
3385 	}
3386 	VERIFY(nd_prefix_busy);
3387 	nd_prefix_busy = FALSE;
3388 	if (nd_prefix_waiters > 0) {
3389 		nd_prefix_waiters = 0;
3390 		wakeup(nd_prefix_waitchan);
3391 	}
3392 
3393 	/*
3394 	 * Changes on the prefix status might affect address status as well.
3395 	 * Make sure that all addresses derived from an attached prefix are
3396 	 * attached, and that all addresses derived from a detached prefix are
3397 	 * detached.  Note, however, that a manually configured address should
3398 	 * always be attached.
3399 	 * The precise detection logic is same as the one for prefixes.
3400 	 *
3401 	 * ifnet_get_address_list_family_internal() may fail due to memory
3402 	 * pressure, but we will eventually be called again when we receive
3403 	 * another NA, RA, or when the link status changes.
3404 	 */
3405 	err = ifnet_get_address_list_family_internal(NULL, &ifap, &addresses_count,
3406 	    AF_INET6, 0, M_NOWAIT, 0);
3407 	if (err != 0 || ifap == NULL) {
3408 		nd6log(error, "%s: ifnet_get_address_list_family_internal "
3409 		    "failed", __func__);
3410 		return;
3411 	}
3412 	for (i = 0; ifap[i]; i++) {
3413 		ifa = ifatoia6(ifap[i]);
3414 		IFA_LOCK(&ifa->ia_ifa);
3415 		if ((ifa->ia6_flags & IN6_IFF_AUTOCONF) == 0 ||
3416 		    (ifap[i]->ifa_debug & IFD_ATTACHED) == 0) {
3417 			IFA_UNLOCK(&ifa->ia_ifa);
3418 			continue;
3419 		}
3420 		if ((ndpr = ifa->ia6_ndpr) == NULL) {
3421 			/*
3422 			 * This can happen when we first configure the address
3423 			 * (i.e. the address exists, but the prefix does not).
3424 			 * XXX: complicated relationships...
3425 			 */
3426 			IFA_UNLOCK(&ifa->ia_ifa);
3427 			continue;
3428 		}
3429 		IFA_UNLOCK(&ifa->ia_ifa);
3430 
3431 		NDPR_LOCK(ndpr);
3432 		if (find_pfxlist_reachable_router(ndpr)) {
3433 			NDPR_UNLOCK(ndpr);
3434 			found = 1;
3435 			break;
3436 		}
3437 		NDPR_UNLOCK(ndpr);
3438 	}
3439 	if (found) {
3440 		for (i = 0; ifap[i]; i++) {
3441 			struct in6_addrlifetime lt6_tmp = {};
3442 
3443 			ifa = ifatoia6(ifap[i]);
3444 			IFA_LOCK(&ifa->ia_ifa);
3445 			if ((ifa->ia6_flags & IN6_IFF_AUTOCONF) == 0 ||
3446 			    (ifap[i]->ifa_debug & IFD_ATTACHED) == 0) {
3447 				IFA_UNLOCK(&ifa->ia_ifa);
3448 				continue;
3449 			}
3450 			if ((ndpr = ifa->ia6_ndpr) == NULL) {
3451 				/* XXX: see above. */
3452 				IFA_UNLOCK(&ifa->ia_ifa);
3453 				continue;
3454 			}
3455 			IFA_UNLOCK(&ifa->ia_ifa);
3456 			NDPR_LOCK(ndpr);
3457 			if (find_pfxlist_reachable_router(ndpr) == NULL) {
3458 				/*
3459 				 * When the prefix of an addr is detached, make the address
3460 				 * deprecated by setting pltime to 0, and let it expire according
3461 				 * to its advertised vltime. If its original vltime is infinite
3462 				 * or longer than 2hr, set it to 2hr.
3463 				 */
3464 				NDPR_UNLOCK(ndpr);
3465 				IFA_LOCK(&ifa->ia_ifa);
3466 				in6ifa_getlifetime(ifa, &lt6_tmp, 0);
3467 				/* We want to immediately deprecate the address */
3468 				lt6_tmp.ia6t_pltime = 0;
3469 				/* Do not extend its valid lifetime */
3470 				uint32_t remaining_lifetime;
3471 				uint32_t original_lifetime = (uint32_t)(timenow - ifa->ia6_updatetime);
3472 				if (lt6_tmp.ia6t_vltime > original_lifetime) {
3473 					remaining_lifetime = lt6_tmp.ia6t_vltime - original_lifetime;
3474 				} else {
3475 					remaining_lifetime = 0;
3476 				}
3477 				if (lt6_tmp.ia6t_vltime == ND6_INFINITE_LIFETIME || remaining_lifetime >= TWOHOUR) {
3478 					lt6_tmp.ia6t_vltime = TWOHOUR;
3479 				} else {
3480 					lt6_tmp.ia6t_vltime = remaining_lifetime;
3481 				}
3482 
3483 				in6_init_address_ltimes(&lt6_tmp);
3484 				in6ifa_setlifetime(ifa, &lt6_tmp);
3485 				ifa->ia6_updatetime = timenow;
3486 
3487 				/*
3488 				 * The next nd6 service timer expiry will take
3489 				 * care of marking the addresses as deprecated
3490 				 * and issuing the notifications as well.
3491 				 */
3492 				IFA_UNLOCK(&ifa->ia_ifa);
3493 			} else {
3494 				NDPR_UNLOCK(ndpr);
3495 			}
3496 		}
3497 	}
3498 	ifnet_address_list_free_counted_by(ifap, addresses_count);
3499 }
3500 
3501 static struct nd_prefix *
nd6_prefix_equal_lookup(struct nd_prefix * pr,boolean_t primary_only)3502 nd6_prefix_equal_lookup(struct nd_prefix *pr, boolean_t primary_only)
3503 {
3504 	struct nd_prefix *__single opr;
3505 
3506 	LCK_MTX_ASSERT(nd6_mutex, LCK_MTX_ASSERT_OWNED);
3507 
3508 	for (opr = nd_prefix.lh_first; opr; opr = opr->ndpr_next) {
3509 		if (opr == pr) {
3510 			continue;
3511 		}
3512 
3513 		NDPR_LOCK(opr);
3514 		if ((opr->ndpr_stateflags & NDPRF_ONLINK) == 0) {
3515 			NDPR_UNLOCK(opr);
3516 			continue;
3517 		}
3518 		if (opr->ndpr_plen == pr->ndpr_plen &&
3519 		    in6_are_prefix_equal(&pr->ndpr_prefix.sin6_addr, pr->ndpr_prefix.sin6_scope_id,
3520 		    &opr->ndpr_prefix.sin6_addr, opr->ndpr_prefix.sin6_scope_id, pr->ndpr_plen) &&
3521 		    (!primary_only ||
3522 		    !(opr->ndpr_stateflags & NDPRF_IFSCOPE))) {
3523 			NDPR_ADDREF(opr);
3524 			NDPR_UNLOCK(opr);
3525 			return opr;
3526 		}
3527 		NDPR_UNLOCK(opr);
3528 	}
3529 	return NULL;
3530 }
3531 
3532 /*
3533  * Synchronize the interface routes of similar prefixes on different
3534  * interfaces; the one using the default interface would be (re)installed
3535  * as a primary/non-scoped entry, and the rest as scoped entri(es).
3536  */
3537 static void
nd6_prefix_sync(struct ifnet * ifp)3538 nd6_prefix_sync(struct ifnet *ifp)
3539 {
3540 	struct nd_prefix *__single pr, *__single opr;
3541 	int err = 0;
3542 
3543 	LCK_MTX_ASSERT(nd6_mutex, LCK_MTX_ASSERT_OWNED);
3544 
3545 	if (ifp == NULL) {
3546 		return;
3547 	}
3548 
3549 	for (pr = nd_prefix.lh_first; pr; pr = pr->ndpr_next) {
3550 		NDPR_LOCK(pr);
3551 		if (!(pr->ndpr_stateflags & NDPRF_ONLINK)) {
3552 			NDPR_UNLOCK(pr);
3553 			continue;
3554 		}
3555 		if (pr->ndpr_ifp == ifp &&
3556 		    (pr->ndpr_stateflags & NDPRF_IFSCOPE) &&
3557 		    !IN6_IS_ADDR_LINKLOCAL(&pr->ndpr_prefix.sin6_addr)) {
3558 			NDPR_UNLOCK(pr);
3559 			break;
3560 		}
3561 		NDPR_UNLOCK(pr);
3562 	}
3563 
3564 	if (pr == NULL) {
3565 		return;
3566 	}
3567 
3568 	/* Remove conflicting entries */
3569 	opr = nd6_prefix_equal_lookup(pr, TRUE);
3570 	if (opr != NULL) {
3571 		lck_mtx_unlock(nd6_mutex);
3572 		err = nd6_prefix_offlink(opr);
3573 		lck_mtx_lock(nd6_mutex);
3574 		if (err != 0) {
3575 			nd6log(error,
3576 			    "%s: failed to make %s/%d offlink on %s, "
3577 			    "errno=%d\n", __func__,
3578 			    ip6_sprintf(&opr->ndpr_prefix.sin6_addr),
3579 			    opr->ndpr_plen, if_name(opr->ndpr_ifp), err);
3580 		}
3581 	} else {
3582 		nd6log(error,
3583 		    "%s: scoped %s/%d on %s has no matching unscoped prefix\n",
3584 		    __func__, ip6_sprintf(&pr->ndpr_prefix.sin6_addr),
3585 		    pr->ndpr_plen, if_name(pr->ndpr_ifp));
3586 	}
3587 
3588 	lck_mtx_unlock(nd6_mutex);
3589 	err = nd6_prefix_offlink(pr);
3590 	lck_mtx_lock(nd6_mutex);
3591 	if (err != 0) {
3592 		nd6log(error,
3593 		    "%s: failed to make %s/%d offlink on %s, errno=%d\n",
3594 		    __func__, ip6_sprintf(&pr->ndpr_prefix.sin6_addr),
3595 		    pr->ndpr_plen, if_name(pr->ndpr_ifp), err);
3596 	}
3597 
3598 	/* Add the entries back */
3599 	if (opr != NULL) {
3600 		err = nd6_prefix_onlink_scoped(opr, opr->ndpr_ifp->if_index);
3601 		if (err != 0) {
3602 			nd6log(error,
3603 			    "%s: failed to make %s/%d scoped onlink on %s, "
3604 			    "errno=%d\n", __func__,
3605 			    ip6_sprintf(&opr->ndpr_prefix.sin6_addr),
3606 			    opr->ndpr_plen, if_name(opr->ndpr_ifp), err);
3607 		}
3608 	}
3609 
3610 	err = nd6_prefix_onlink_scoped(pr, IFSCOPE_NONE);
3611 	if (err != 0) {
3612 		nd6log(error,
3613 		    "%s: failed to make %s/%d onlink on %s, errno=%d\n",
3614 		    __func__, ip6_sprintf(&pr->ndpr_prefix.sin6_addr),
3615 		    pr->ndpr_plen, if_name(pr->ndpr_ifp), err);
3616 	}
3617 
3618 	if (err != 0) {
3619 		nd6log(error,
3620 		    "%s: error promoting %s/%d to %s from %s\n",
3621 		    __func__, ip6_sprintf(&pr->ndpr_prefix.sin6_addr),
3622 		    pr->ndpr_plen, if_name(pr->ndpr_ifp),
3623 		    (opr != NULL) ? if_name(opr->ndpr_ifp) : "NONE");
3624 	} else {
3625 		nd6log2(info,
3626 		    "%s: %s/%d promoted, previously on %s\n",
3627 		    if_name(pr->ndpr_ifp),
3628 		    ip6_sprintf(&pr->ndpr_prefix.sin6_addr), pr->ndpr_plen,
3629 		    (opr != NULL) ? if_name(opr->ndpr_ifp) : "NONE");
3630 	}
3631 
3632 	if (opr != NULL) {
3633 		NDPR_REMREF(opr);
3634 	}
3635 }
3636 
3637 static int
nd6_prefix_onlink_common(struct nd_prefix * pr,boolean_t force_scoped,unsigned int ifscope)3638 nd6_prefix_onlink_common(struct nd_prefix *pr, boolean_t force_scoped,
3639     unsigned int ifscope)
3640 {
3641 	struct ifaddr *__single ifa;
3642 	ifnet_ref_t ifp = pr->ndpr_ifp;
3643 	struct sockaddr_in6 mask6, prefix;
3644 	struct nd_prefix *__single opr;
3645 	u_int32_t rtflags;
3646 	int error = 0, prproxy = 0;
3647 	rtentry_ref_t rt = NULL;
3648 	u_char prefix_len = 0;
3649 
3650 	LCK_MTX_ASSERT(nd6_mutex, LCK_MTX_ASSERT_OWNED);
3651 
3652 	/* sanity check */
3653 	NDPR_LOCK(pr);
3654 	if ((pr->ndpr_stateflags & NDPRF_ONLINK) != 0) {
3655 		nd6log(error,
3656 		    "%s: %s/%d on %s scoped=%d is already on-link\n",
3657 		    __func__, ip6_sprintf(&pr->ndpr_prefix.sin6_addr),
3658 		    pr->ndpr_plen, if_name(pr->ndpr_ifp),
3659 		    (pr->ndpr_stateflags & NDPRF_IFSCOPE) ? 1 : 0);
3660 		NDPR_UNLOCK(pr);
3661 		return EEXIST;
3662 	}
3663 	NDPR_UNLOCK(pr);
3664 
3665 	/*
3666 	 * Add the interface route associated with the prefix.  Before
3667 	 * installing the route, check if there's the same prefix on another
3668 	 * interface, and the prefix has already installed the interface route.
3669 	 */
3670 	opr = nd6_prefix_equal_lookup(pr, FALSE);
3671 	if (opr != NULL) {
3672 		NDPR_REMREF(opr);
3673 	}
3674 
3675 	if (!force_scoped) {
3676 		/*
3677 		 * If a primary/non-scoped interface route already exists,
3678 		 * install the new one as a scoped entry.  If the existing
3679 		 * interface route is scoped, install new as non-scoped.
3680 		 */
3681 		ifscope = (opr != NULL) ? ifp->if_index : IFSCOPE_NONE;
3682 		opr = nd6_prefix_equal_lookup(pr, TRUE);
3683 		if (opr != NULL) {
3684 			NDPR_REMREF(opr);
3685 		} else if (ifscope != IFSCOPE_NONE) {
3686 			ifscope = IFSCOPE_NONE;
3687 		}
3688 	}
3689 
3690 	/*
3691 	 * We prefer link-local addresses as the associated interface address.
3692 	 */
3693 	/* search for a link-local addr */
3694 	ifa = (struct ifaddr *)in6ifa_ifpforlinklocal(ifp,
3695 	    IN6_IFF_NOTREADY | IN6_IFF_ANYCAST);
3696 	if (ifa == NULL) {
3697 		struct in6_ifaddr *__single ia6;
3698 		ifnet_lock_shared(ifp);
3699 		IFP_TO_IA6(ifp, ia6);
3700 		ifnet_lock_done(ifp);
3701 		if (ia6 != NULL) {
3702 			ifa = &ia6->ia_ifa;
3703 		}
3704 		/* should we care about ia6_flags? */
3705 	}
3706 	NDPR_LOCK(pr);
3707 	if (ifa == NULL) {
3708 		/*
3709 		 * This can still happen, when, for example, we receive an RA
3710 		 * containing a prefix with the L bit set and the A bit clear,
3711 		 * after removing all IPv6 addresses on the receiving
3712 		 * interface.  This should, of course, be rare though.
3713 		 */
3714 		nd6log(info,
3715 		    "nd6_prefix_onlink: failed to find any ifaddr"
3716 		    " to add route for a prefix(%s/%d) on %s\n",
3717 		    ip6_sprintf(&pr->ndpr_prefix.sin6_addr),
3718 		    pr->ndpr_plen, if_name(ifp));
3719 		NDPR_UNLOCK(pr);
3720 		return 0;
3721 	}
3722 
3723 	/*
3724 	 * in6_ifinit() sets nd6_rtrequest to ifa_rtrequest for all ifaddrs.
3725 	 * ifa->ifa_rtrequest = nd6_rtrequest;
3726 	 */
3727 	SOCKADDR_ZERO(&mask6, sizeof(mask6));
3728 	mask6.sin6_len = sizeof(mask6);
3729 	mask6.sin6_addr = pr->ndpr_mask;
3730 	prefix = pr->ndpr_prefix;
3731 	prefix_len = pr->ndpr_plen;
3732 	if ((rt = pr->ndpr_rt) != NULL) {
3733 		pr->ndpr_rt = NULL;
3734 	}
3735 	NDPR_ADDREF(pr);         /* keep reference for this routine */
3736 	NDPR_UNLOCK(pr);
3737 
3738 	IFA_LOCK_SPIN(ifa);
3739 	rtflags = ifa->ifa_flags | RTF_CLONING | RTF_UP;
3740 	IFA_UNLOCK(ifa);
3741 	if (nd6_need_cache(ifp)) {
3742 		/* explicitly set in case ifa_flags does not set the flag. */
3743 		rtflags |= RTF_CLONING;
3744 	} else {
3745 		/*
3746 		 * explicitly clear the cloning bit in case ifa_flags sets it.
3747 		 */
3748 		rtflags &= ~RTF_CLONING;
3749 	}
3750 
3751 	lck_mtx_unlock(nd6_mutex);
3752 
3753 	/*
3754 	 * check if it conflicts with a indirect prefix route added by RIO
3755 	 * if so, remove the rti entry.
3756 	 */
3757 	if (ifscope == IFSCOPE_NONE) {
3758 		rtentry_ref_t temp_route = NULL;
3759 		LCK_MTX_ASSERT(rnh_lock, LCK_MTX_ASSERT_NOTOWNED);
3760 		lck_mtx_lock(rnh_lock);
3761 		temp_route = rt_lookup(TRUE, SA(&prefix), SA(&mask6), rt_tables[AF_INET6], IFSCOPE_NONE);
3762 		lck_mtx_unlock(rnh_lock);
3763 
3764 		if (temp_route != NULL && temp_route->rt_flags & RTF_GATEWAY && temp_route->rt_ifp != NULL) {
3765 			struct nd_route_info rti = {};
3766 			bzero(&rti, sizeof(rti));
3767 			rti.nd_rti_prefixlen = prefix_len;
3768 			rti.nd_rti_prefix = prefix.sin6_addr;
3769 			lck_mtx_lock(nd6_mutex);
3770 			nd6_rti_delreq(&rti);
3771 			lck_mtx_unlock(nd6_mutex);
3772 		}
3773 		if (temp_route != NULL) {
3774 			rtfree(temp_route);
3775 		}
3776 	}
3777 
3778 	if (rt != NULL) {
3779 		rtfree(rt);
3780 		rt = NULL;
3781 	}
3782 
3783 	error = rtrequest_scoped(RTM_ADD, SA(&prefix), ifa->ifa_addr, SA(&mask6),
3784 	    rtflags, &rt, ifscope);
3785 
3786 	/*
3787 	 * Serialize the setting of NDPRF_PRPROXY.
3788 	 */
3789 	lck_mtx_lock(&proxy6_lock);
3790 
3791 	if (rt != NULL) {
3792 		RT_LOCK(rt);
3793 		nd6_rtmsg(RTM_ADD, rt);
3794 		RT_UNLOCK(rt);
3795 		NDPR_LOCK(pr);
3796 	} else {
3797 		NDPR_LOCK(pr);
3798 		nd6log(error, "nd6_prefix_onlink: failed to add route for a"
3799 		    " prefix (%s/%d) on %s, gw=%s, mask=%s, flags=%x,"
3800 		    " scoped=%d, errno = %d\n",
3801 		    ip6_sprintf(&pr->ndpr_prefix.sin6_addr),
3802 		    pr->ndpr_plen, if_name(ifp),
3803 		    ip6_sprintf(&SIN6(ifa->ifa_addr)->sin6_addr),
3804 		    ip6_sprintf(&mask6.sin6_addr), rtflags,
3805 		    (ifscope != IFSCOPE_NONE), error);
3806 	}
3807 	NDPR_LOCK_ASSERT_HELD(pr);
3808 
3809 	pr->ndpr_stateflags &= ~(NDPRF_IFSCOPE | NDPRF_PRPROXY);
3810 
3811 	/*
3812 	 * TODO: If the prefix route exists, we should really find it and
3813 	 * refer the prefix to it; otherwise ndpr_rt is NULL.
3814 	 */
3815 	if (!(pr->ndpr_stateflags & NDPRF_DEFUNCT) &&
3816 	    (rt != NULL || error == EEXIST)) {
3817 		struct nd_ifinfo *__single ndi = NULL;
3818 
3819 		VERIFY(pr->ndpr_prproxy_sols_cnt == 0);
3820 		VERIFY(RB_EMPTY(&pr->ndpr_prproxy_sols));
3821 
3822 		ndi = ND_IFINFO(ifp);
3823 		VERIFY((NULL != ndi) && (TRUE == ndi->initialized));
3824 		lck_mtx_lock(&ndi->lock);
3825 
3826 		pr->ndpr_rt = rt;       /* keep reference from rtrequest */
3827 		pr->ndpr_stateflags |= NDPRF_ONLINK;
3828 		if (ifscope != IFSCOPE_NONE) {
3829 			pr->ndpr_stateflags |= NDPRF_IFSCOPE;
3830 		} else if ((rtflags & RTF_CLONING) &&
3831 		    (ndi->flags & ND6_IFF_PROXY_PREFIXES) &&
3832 		    !IN6_IS_ADDR_LINKLOCAL(&pr->ndpr_prefix.sin6_addr)) {
3833 			/*
3834 			 * At present, in order for the prefix to be eligible
3835 			 * as a proxying/proxied prefix, we require that the
3836 			 * prefix route entry be marked as a cloning route with
3837 			 * RTF_PROXY; i.e. nd6_need_cache() needs to return
3838 			 * true for the interface type, hence the test for
3839 			 * RTF_CLONING above.
3840 			 */
3841 			pr->ndpr_stateflags |= NDPRF_PRPROXY;
3842 		}
3843 
3844 		lck_mtx_unlock(&ndi->lock);
3845 	} else if (rt != NULL && pr->ndpr_stateflags & NDPRF_DEFUNCT) {
3846 		rtfree(rt);
3847 	}
3848 
3849 	prproxy = (pr->ndpr_stateflags & NDPRF_PRPROXY);
3850 	VERIFY(!prproxy || !(pr->ndpr_stateflags & NDPRF_IFSCOPE));
3851 	NDPR_UNLOCK(pr);
3852 
3853 	ifa_remref(ifa);
3854 
3855 	/*
3856 	 * If this is an upstream prefix, find the downstream ones (if any)
3857 	 * and re-configure their prefix routes accordingly.  Otherwise,
3858 	 * this could be potentially be a downstream prefix, and so find the
3859 	 * upstream prefix, if any.
3860 	 */
3861 	nd6_prproxy_prelist_update(pr, prproxy ? pr : NULL);
3862 
3863 	NDPR_REMREF(pr);        /* release reference for this routine */
3864 	lck_mtx_unlock(&proxy6_lock);
3865 
3866 	lck_mtx_lock(nd6_mutex);
3867 
3868 	return error;
3869 }
3870 
3871 int
nd6_prefix_onlink(struct nd_prefix * pr)3872 nd6_prefix_onlink(struct nd_prefix *pr)
3873 {
3874 	return nd6_prefix_onlink_common(pr, FALSE, IFSCOPE_NONE);
3875 }
3876 
3877 int
nd6_prefix_onlink_scoped(struct nd_prefix * pr,unsigned int ifscope)3878 nd6_prefix_onlink_scoped(struct nd_prefix *pr, unsigned int ifscope)
3879 {
3880 	return nd6_prefix_onlink_common(pr, TRUE, ifscope);
3881 }
3882 
3883 int
nd6_prefix_offlink(struct nd_prefix * pr)3884 nd6_prefix_offlink(struct nd_prefix *pr)
3885 {
3886 	int error = 0, prproxy;
3887 	ifnet_ref_t ifp = pr->ndpr_ifp;
3888 	struct sockaddr_in6 sa6, mask6, prefix;
3889 	rtentry_ref_t rt = NULL, ndpr_rt = NULL;
3890 	unsigned int ifscope;
3891 	u_char prefix_len = 0;
3892 
3893 	LCK_MTX_ASSERT(nd6_mutex, LCK_MTX_ASSERT_NOTOWNED);
3894 
3895 	/* sanity check */
3896 	NDPR_LOCK(pr);
3897 	if ((pr->ndpr_stateflags & NDPRF_ONLINK) == 0) {
3898 		nd6log(error,
3899 		    "nd6_prefix_offlink: %s/%d on %s scoped=%d is already "
3900 		    "off-link\n", ip6_sprintf(&pr->ndpr_prefix.sin6_addr),
3901 		    pr->ndpr_plen, if_name(pr->ndpr_ifp),
3902 		    (pr->ndpr_stateflags & NDPRF_IFSCOPE) ? 1 : 0);
3903 		NDPR_UNLOCK(pr);
3904 		return EEXIST;
3905 	}
3906 
3907 	SOCKADDR_ZERO(&sa6, sizeof(sa6));
3908 	sa6.sin6_family = AF_INET6;
3909 	sa6.sin6_len = sizeof(sa6);
3910 	bcopy(&pr->ndpr_prefix.sin6_addr, &sa6.sin6_addr,
3911 	    sizeof(struct in6_addr));
3912 	SOCKADDR_ZERO(&mask6, sizeof(mask6));
3913 	mask6.sin6_family = AF_INET6;
3914 	mask6.sin6_len = sizeof(sa6);
3915 	bcopy(&pr->ndpr_mask, &mask6.sin6_addr, sizeof(struct in6_addr));
3916 	prefix = pr->ndpr_prefix;
3917 	prefix_len = pr->ndpr_plen;
3918 	if ((ndpr_rt = pr->ndpr_rt) != NULL) {
3919 		pr->ndpr_rt = NULL;
3920 	}
3921 	NDPR_ADDREF(pr);         /* keep reference for this routine */
3922 	NDPR_UNLOCK(pr);
3923 
3924 	ifscope = (pr->ndpr_stateflags & NDPRF_IFSCOPE) ?
3925 	    ifp->if_index : IFSCOPE_NONE;
3926 
3927 	error = rtrequest_scoped(RTM_DELETE, SA(&sa6), NULL, SA(&mask6),
3928 	    0, &rt, ifscope);
3929 
3930 	if (rt != NULL) {
3931 		/* report the route deletion to the routing socket. */
3932 		RT_LOCK(rt);
3933 		nd6_rtmsg(RTM_DELETE, rt);
3934 		RT_UNLOCK(rt);
3935 		rtfree(rt);
3936 	} else {
3937 		nd6log(error,
3938 		    "nd6_prefix_offlink: failed to delete route: "
3939 		    "%s/%d on %s, scoped %d, (errno = %d)\n",
3940 		    ip6_sprintf(&sa6.sin6_addr), prefix_len, if_name(ifp),
3941 		    (ifscope != IFSCOPE_NONE), error);
3942 	}
3943 
3944 	struct nd_route_info rti = {};
3945 	bzero(&rti, sizeof(rti));
3946 	rti.nd_rti_prefixlen = prefix_len;
3947 	rti.nd_rti_prefix = prefix.sin6_addr;
3948 
3949 	lck_mtx_lock(nd6_mutex);
3950 	nd6_rti_select(&rti, ifp);
3951 	lck_mtx_unlock(nd6_mutex);
3952 
3953 	if (ndpr_rt != NULL) {
3954 		rtfree(ndpr_rt);
3955 	}
3956 
3957 	lck_mtx_lock(&proxy6_lock);
3958 
3959 	NDPR_LOCK(pr);
3960 	prproxy = (pr->ndpr_stateflags & NDPRF_PRPROXY);
3961 	VERIFY(!prproxy || !(pr->ndpr_stateflags & NDPRF_IFSCOPE));
3962 	pr->ndpr_stateflags &= ~(NDPRF_ONLINK | NDPRF_IFSCOPE | NDPRF_PRPROXY);
3963 	if (pr->ndpr_prproxy_sols_cnt > 0) {
3964 		VERIFY(prproxy);
3965 		nd6_prproxy_sols_reap(pr);
3966 		VERIFY(pr->ndpr_prproxy_sols_cnt == 0);
3967 		VERIFY(RB_EMPTY(&pr->ndpr_prproxy_sols));
3968 	}
3969 	NDPR_UNLOCK(pr);
3970 
3971 	/*
3972 	 * If this was an upstream prefix, find the downstream ones and do
3973 	 * some cleanups.  If this was a downstream prefix, the prefix route
3974 	 * has been removed from the routing table above, but there may be
3975 	 * other tasks to perform.
3976 	 */
3977 	nd6_prproxy_prelist_update(pr, prproxy ? pr : NULL);
3978 
3979 	NDPR_REMREF(pr);        /* release reference for this routine */
3980 	lck_mtx_unlock(&proxy6_lock);
3981 
3982 	return error;
3983 }
3984 
3985 struct in6_ifaddr *
in6_pfx_newpersistaddr(struct nd_prefix * pr,int mcast,int * errorp,boolean_t is_clat46,uint8_t collision_count)3986 in6_pfx_newpersistaddr(struct nd_prefix *pr, int mcast, int *errorp,
3987     boolean_t is_clat46, uint8_t collision_count)
3988 {
3989 	struct in6_ifaddr *__single ia6 = NULL;
3990 	ifnet_ref_t ifp = NULL;
3991 	struct nd_ifinfo *__single ndi = NULL;
3992 	struct in6_addr mask;
3993 	struct in6_aliasreq ifra;
3994 	int error, ifaupdate, iidlen, notcga;
3995 
3996 	VERIFY(pr != NULL);
3997 	VERIFY(errorp != NULL);
3998 
3999 	NDPR_LOCK(pr);
4000 	ifp = pr->ndpr_ifp;
4001 	ia6 = NULL;
4002 	error = 0;
4003 
4004 	/*
4005 	 * Prefix Length check:
4006 	 * If the sum of the prefix length and interface identifier
4007 	 * length does not equal 128 bits, the Prefix Information
4008 	 * option MUST be ignored.  The length of the interface
4009 	 * identifier is defined in a separate link-type specific
4010 	 * document.
4011 	 */
4012 	iidlen = in6_if2idlen(ifp);
4013 	if (iidlen < 0) {
4014 		error = EADDRNOTAVAIL;
4015 		/* this should not happen, so we always log it. */
4016 		log(LOG_ERR, "%s: IID length undefined (%s)\n",
4017 		    __func__, if_name(ifp));
4018 		goto unlock1;
4019 	} else if (iidlen != 64) {
4020 		error = EADDRNOTAVAIL;
4021 		/*
4022 		 * stateless autoconfiguration not yet well-defined for IID
4023 		 * lengths other than 64 octets. Just give up for now.
4024 		 */
4025 		nd6log(info, "%s: IID length not 64 octets (%s)\n",
4026 		    __func__, if_name(ifp));
4027 		goto unlock1;
4028 	}
4029 
4030 	if (iidlen + pr->ndpr_plen != 128) {
4031 		error = EADDRNOTAVAIL;
4032 		nd6log(info,
4033 		    "%s: invalid prefix length %d for %s, ignored\n",
4034 		    __func__, pr->ndpr_plen, if_name(ifp));
4035 		goto unlock1;
4036 	}
4037 
4038 	bzero(&ifra, sizeof(ifra));
4039 	strlcpy(ifra.ifra_name, if_name(ifp), sizeof(ifra.ifra_name));
4040 	ifra.ifra_addr.sin6_family = AF_INET6;
4041 	ifra.ifra_addr.sin6_len = sizeof(struct sockaddr_in6);
4042 
4043 	/* prefix */
4044 	bcopy(&pr->ndpr_prefix.sin6_addr, &ifra.ifra_addr.sin6_addr,
4045 	    sizeof(ifra.ifra_addr.sin6_addr));
4046 	in6_len2mask(&mask, pr->ndpr_plen);
4047 	ifra.ifra_addr.sin6_addr.s6_addr32[0] &= mask.s6_addr32[0];
4048 	ifra.ifra_addr.sin6_addr.s6_addr32[1] &= mask.s6_addr32[1];
4049 	ifra.ifra_addr.sin6_addr.s6_addr32[2] &= mask.s6_addr32[2];
4050 	ifra.ifra_addr.sin6_addr.s6_addr32[3] &= mask.s6_addr32[3];
4051 
4052 	ndi = ND_IFINFO(ifp);
4053 	VERIFY(ndi->initialized);
4054 	lck_mtx_lock(&ndi->lock);
4055 
4056 	notcga = nd6_send_opstate == ND6_SEND_OPMODE_DISABLED ||
4057 	    (ndi->flags & ND6_IFF_INSECURE) != 0;
4058 
4059 	lck_mtx_unlock(&ndi->lock);
4060 	NDPR_UNLOCK(pr);
4061 
4062 	if (notcga && !is_clat46) {
4063 		ia6 = in6ifa_ifpforlinklocal(ifp, 0);
4064 		if (ia6 == NULL) {
4065 			error = EADDRNOTAVAIL;
4066 			nd6log(info, "%s: no link-local address (%s)\n",
4067 			    __func__, if_name(ifp));
4068 			goto done;
4069 		}
4070 
4071 		IFA_LOCK(&ia6->ia_ifa);
4072 		ifra.ifra_addr.sin6_addr.s6_addr32[0] |=
4073 		    (ia6->ia_addr.sin6_addr.s6_addr32[0] & ~mask.s6_addr32[0]);
4074 		ifra.ifra_addr.sin6_addr.s6_addr32[1] |=
4075 		    (ia6->ia_addr.sin6_addr.s6_addr32[1] & ~mask.s6_addr32[1]);
4076 		ifra.ifra_addr.sin6_addr.s6_addr32[2] |=
4077 		    (ia6->ia_addr.sin6_addr.s6_addr32[2] & ~mask.s6_addr32[2]);
4078 		ifra.ifra_addr.sin6_addr.s6_addr32[3] |=
4079 		    (ia6->ia_addr.sin6_addr.s6_addr32[3] & ~mask.s6_addr32[3]);
4080 		IFA_UNLOCK(&ia6->ia_ifa);
4081 		ifa_remref(&ia6->ia_ifa);
4082 		ia6 = NULL;
4083 	} else {
4084 		struct in6_cga_prepare local_cga_prepare;
4085 		struct in6_cga_prepare *__single prepare_p;
4086 
4087 
4088 		in6_cga_node_lock();
4089 
4090 		if (ndi->cga_initialized) {
4091 			bcopy(&(ndi->local_cga_modifier),
4092 			    &(local_cga_prepare.cga_modifier),
4093 			    sizeof(local_cga_prepare.cga_modifier));
4094 			prepare_p = &local_cga_prepare;
4095 		} else {
4096 			prepare_p = NULL;
4097 		}
4098 		error = in6_cga_generate(prepare_p, collision_count,
4099 		    &ifra.ifra_addr.sin6_addr, ifp);
4100 		in6_cga_node_unlock();
4101 		if (error == 0) {
4102 			ifra.ifra_flags |= IN6_IFF_SECURED;
4103 			if (is_clat46) {
4104 				ifra.ifra_flags |= IN6_IFF_CLAT46;
4105 			}
4106 		} else {
4107 			if (!is_clat46) {
4108 				nd6log(error, "%s: no CGA available (%s)\n",
4109 				    __func__, if_name(ifp));
4110 			} else {
4111 				nd6log(error, "%s: no CLAT46 available (%s)\n",
4112 				    __func__, if_name(ifp));
4113 			}
4114 			goto done;
4115 		}
4116 	}
4117 
4118 	VERIFY(ia6 == NULL);
4119 
4120 	/* new prefix mask. */
4121 	ifra.ifra_prefixmask.sin6_len = sizeof(struct sockaddr_in6);
4122 	ifra.ifra_prefixmask.sin6_family = AF_INET6;
4123 	bcopy(&mask, &ifra.ifra_prefixmask.sin6_addr,
4124 	    sizeof(ifra.ifra_prefixmask.sin6_addr));
4125 
4126 	/* lifetimes. */
4127 	ifra.ifra_lifetime.ia6t_vltime = pr->ndpr_vltime;
4128 	ifra.ifra_lifetime.ia6t_pltime = pr->ndpr_pltime;
4129 
4130 	/* address flags */
4131 	ifra.ifra_flags |= IN6_IFF_AUTOCONF; /* obey autoconf */
4132 
4133 	/*
4134 	 * Make sure that we do not have this address already.  This should
4135 	 * usually not happen, but we can still see this case, e.g., if we
4136 	 * have manually configured the exact address to be configured.
4137 	 */
4138 	if ((ia6 = in6ifa_ifpwithaddr(ifp, &ifra.ifra_addr.sin6_addr))
4139 	    != NULL) {
4140 		error = EEXIST;
4141 		ifa_remref(&ia6->ia_ifa);
4142 		ia6 = NULL;
4143 
4144 		/* this should be rare enough to make an explicit log */
4145 		log(LOG_INFO, "%s: %s is already configured!\n",
4146 		    __func__, ip6_sprintf(&ifra.ifra_addr.sin6_addr));
4147 		goto done;
4148 	}
4149 
4150 	/*
4151 	 * Allocate ifaddr structure, link into chain, etc.
4152 	 * If we are going to create a new address upon receiving a multicasted
4153 	 * RA, we need to impose a random delay before starting DAD.
4154 	 * [RFC 4862, Section 5.4.2]
4155 	 */
4156 	ifaupdate = IN6_IFAUPDATE_NOWAIT;
4157 	if (mcast) {
4158 		ifaupdate |= IN6_IFAUPDATE_DADDELAY;
4159 	}
4160 	error = in6_update_ifa(ifp, &ifra, ifaupdate, &ia6);
4161 	if (error != 0) {
4162 		nd6log(error,
4163 		    "%s: failed to make ifaddr %s on %s (errno=%d)\n",
4164 		    __func__, ip6_sprintf(&ifra.ifra_addr.sin6_addr),
4165 		    if_name(ifp), error);
4166 		error = EADDRNOTAVAIL;
4167 		goto done;
4168 	} else {
4169 		/* remember the collision count */
4170 		ia6->ia6_cga_collision_count = collision_count;
4171 	}
4172 
4173 	VERIFY(ia6 != NULL);
4174 	in6_post_msg(ifp, KEV_INET6_NEW_RTADV_ADDR, ia6, NULL, 0);
4175 	goto done;
4176 
4177 unlock1:
4178 	NDPR_UNLOCK(pr);
4179 
4180 done:
4181 	*errorp = error;
4182 	return ia6;
4183 }
4184 
4185 #define IA6_NONCONST(ifa) __DECONST(struct in6_ifaddr *, (ifa))
4186 
4187 int
in6_tmpifadd(const struct in6_ifaddr * ia0,int forcegen)4188 in6_tmpifadd(const struct in6_ifaddr *ia0, int forcegen)
4189 {
4190 	ifnet_ref_t ifp = ia0->ia_ifa.ifa_ifp;
4191 	struct in6_ifaddr *__single ia, *__single newia;
4192 	struct in6_aliasreq ifra;
4193 	int i, error, ifaupdate;
4194 	int trylimit = 3;       /* XXX: adhoc value */
4195 	u_int32_t randid[2];
4196 	uint32_t vltime0, pltime0;
4197 	uint64_t timenow = net_uptime();
4198 	struct in6_addr addr;
4199 	struct nd_prefix *__single ndpr;
4200 
4201 	bzero(&ifra, sizeof(ifra));
4202 	strlcpy(ifra.ifra_name, if_name(ifp), sizeof(ifra.ifra_name));
4203 	IFA_LOCK(&IA6_NONCONST(ia0)->ia_ifa);
4204 	ifra.ifra_addr = ia0->ia_addr;
4205 	/* copy prefix mask */
4206 	ifra.ifra_prefixmask = ia0->ia_prefixmask;
4207 	/* clear the old IFID */
4208 	for (i = 0; i < 4; i++) {
4209 		ifra.ifra_addr.sin6_addr.s6_addr32[i]
4210 		        &= ifra.ifra_prefixmask.sin6_addr.s6_addr32[i];
4211 	}
4212 	addr = ia0->ia_addr.sin6_addr;
4213 	IFA_UNLOCK(&IA6_NONCONST(ia0)->ia_ifa);
4214 
4215 again:
4216 	in6_iid_mktmp(ifp, (u_int8_t *)randid,
4217 	    (const u_int8_t *)&addr.s6_addr[8], forcegen);
4218 
4219 	ifra.ifra_addr.sin6_addr.s6_addr32[2] |=
4220 	    (randid[0] & ~(ifra.ifra_prefixmask.sin6_addr.s6_addr32[2]));
4221 	ifra.ifra_addr.sin6_addr.s6_addr32[3] |=
4222 	    (randid[1] & ~(ifra.ifra_prefixmask.sin6_addr.s6_addr32[3]));
4223 
4224 	/*
4225 	 * in6_iid_mktmp() quite likely provided a unique interface ID.
4226 	 * However, we may still have a chance to see collision, because
4227 	 * there may be a time lag between generation of the ID and generation
4228 	 * of the address.  So, we'll do one more sanity check.
4229 	 */
4230 	if ((ia = in6ifa_ifpwithaddr(ifp, &ifra.ifra_addr.sin6_addr)) != NULL) {
4231 		ifa_remref(&ia->ia_ifa);
4232 		if (trylimit-- == 0) {
4233 			nd6log(info, "in6_tmpifadd: failed to find "
4234 			    "a unique random IFID\n");
4235 			return EEXIST;
4236 		}
4237 		forcegen = 1;
4238 		goto again;
4239 	}
4240 
4241 	/*
4242 	 * The Valid Lifetime is the lower of the Valid Lifetime of the
4243 	 * public address or TEMP_VALID_LIFETIME.
4244 	 * The Preferred Lifetime is the lower of the Preferred Lifetime
4245 	 * of the public address or TEMP_PREFERRED_LIFETIME -
4246 	 * DESYNC_FACTOR.
4247 	 */
4248 	IFA_LOCK(&IA6_NONCONST(ia0)->ia_ifa);
4249 	if (ia0->ia6_lifetime.ia6ti_vltime != ND6_INFINITE_LIFETIME) {
4250 		vltime0 = IFA6_IS_INVALID(ia0, timenow) ? 0 :
4251 		    (ia0->ia6_lifetime.ia6ti_vltime -
4252 		    (uint32_t)(timenow - ia0->ia6_updatetime));
4253 		if (vltime0 > ip6_temp_valid_lifetime) {
4254 			vltime0 = ip6_temp_valid_lifetime;
4255 		}
4256 	} else {
4257 		vltime0 = ip6_temp_valid_lifetime;
4258 	}
4259 	if (ia0->ia6_lifetime.ia6ti_pltime != ND6_INFINITE_LIFETIME) {
4260 		pltime0 = IFA6_IS_DEPRECATED(ia0, timenow) ? 0 :
4261 		    (ia0->ia6_lifetime.ia6ti_pltime -
4262 		    (uint32_t)(timenow - ia0->ia6_updatetime));
4263 		if (pltime0 > ip6_temp_preferred_lifetime - ip6_desync_factor) {
4264 			pltime0 = ip6_temp_preferred_lifetime -
4265 			    ip6_desync_factor;
4266 		}
4267 	} else {
4268 		pltime0 = ip6_temp_preferred_lifetime - ip6_desync_factor;
4269 	}
4270 	ifra.ifra_lifetime.ia6t_vltime = vltime0;
4271 	ifra.ifra_lifetime.ia6t_pltime = pltime0;
4272 	IFA_UNLOCK(&IA6_NONCONST(ia0)->ia_ifa);
4273 	/*
4274 	 * A temporary address is created only if this calculated Preferred
4275 	 * Lifetime is greater than REGEN_ADVANCE time units.
4276 	 */
4277 	if (ifra.ifra_lifetime.ia6t_pltime <= ip6_temp_regen_advance) {
4278 		return 0;
4279 	}
4280 
4281 	/* XXX: scope zone ID? */
4282 
4283 	ifra.ifra_flags |= (IN6_IFF_AUTOCONF | IN6_IFF_TEMPORARY);
4284 
4285 	/* allocate ifaddr structure, link into chain, etc. */
4286 	ifaupdate = IN6_IFAUPDATE_NOWAIT | IN6_IFAUPDATE_DADDELAY;
4287 	error = in6_update_ifa(ifp, &ifra, ifaupdate, &newia);
4288 	if (error != 0) {
4289 		nd6log(error, "in6_tmpifadd: failed to add address.\n");
4290 		return error;
4291 	}
4292 	VERIFY(newia != NULL);
4293 
4294 	IFA_LOCK(&IA6_NONCONST(ia0)->ia_ifa);
4295 	ndpr = ia0->ia6_ndpr;
4296 	if (ndpr == NULL) {
4297 		/*
4298 		 * We lost the race with another thread that has purged
4299 		 * ia0 address; in this case, purge the tmp addr as well.
4300 		 */
4301 		nd6log(error, "in6_tmpifadd: no public address\n");
4302 		VERIFY(!(ia0->ia6_flags & IN6_IFF_AUTOCONF));
4303 		IFA_UNLOCK(&IA6_NONCONST(ia0)->ia_ifa);
4304 		in6_purgeaddr(&newia->ia_ifa);
4305 		ifa_remref(&newia->ia_ifa);
4306 		return EADDRNOTAVAIL;
4307 	}
4308 	NDPR_ADDREF(ndpr);      /* for us */
4309 	IFA_UNLOCK(&IA6_NONCONST(ia0)->ia_ifa);
4310 	IFA_LOCK(&newia->ia_ifa);
4311 	if (newia->ia6_ndpr != NULL) {
4312 		NDPR_LOCK(newia->ia6_ndpr);
4313 		VERIFY(newia->ia6_ndpr->ndpr_addrcnt != 0);
4314 		newia->ia6_ndpr->ndpr_addrcnt--;
4315 		NDPR_UNLOCK(newia->ia6_ndpr);
4316 		NDPR_REMREF(newia->ia6_ndpr);   /* release addr reference */
4317 	}
4318 	newia->ia6_ndpr = ndpr;
4319 	NDPR_LOCK(newia->ia6_ndpr);
4320 	newia->ia6_ndpr->ndpr_addrcnt++;
4321 	VERIFY(newia->ia6_ndpr->ndpr_addrcnt != 0);
4322 	NDPR_ADDREF(newia->ia6_ndpr);    /* for addr reference */
4323 	NDPR_UNLOCK(newia->ia6_ndpr);
4324 	IFA_UNLOCK(&newia->ia_ifa);
4325 	/*
4326 	 * A newly added address might affect the status of other addresses.
4327 	 * XXX: when the temporary address is generated with a new public
4328 	 * address, the onlink check is redundant.  However, it would be safe
4329 	 * to do the check explicitly everywhere a new address is generated,
4330 	 * and, in fact, we surely need the check when we create a new
4331 	 * temporary address due to deprecation of an old temporary address.
4332 	 */
4333 	lck_mtx_lock(nd6_mutex);
4334 	pfxlist_onlink_check();
4335 	lck_mtx_unlock(nd6_mutex);
4336 	ifa_remref(&newia->ia_ifa);
4337 
4338 	/* remove our reference */
4339 	NDPR_REMREF(ndpr);
4340 
4341 	return 0;
4342 }
4343 #undef IA6_NONCONST
4344 
4345 int
in6_init_prefix_ltimes(struct nd_prefix * ndpr)4346 in6_init_prefix_ltimes(struct nd_prefix *ndpr)
4347 {
4348 	struct timeval caltime;
4349 	u_int64_t timenow = net_uptime();
4350 
4351 	NDPR_LOCK_ASSERT_HELD(ndpr);
4352 
4353 	getmicrotime(&caltime);
4354 	ndpr->ndpr_base_calendartime = caltime.tv_sec;
4355 	ndpr->ndpr_base_uptime = timenow;
4356 
4357 	/* check if preferred lifetime > valid lifetime.  RFC 4862 5.5.3 (c) */
4358 	if (ndpr->ndpr_pltime > ndpr->ndpr_vltime) {
4359 		nd6log(info, "in6_init_prefix_ltimes: preferred lifetime"
4360 		    "(%d) is greater than valid lifetime(%d)\n",
4361 		    (u_int)ndpr->ndpr_pltime, (u_int)ndpr->ndpr_vltime);
4362 		return EINVAL;
4363 	}
4364 	if (ndpr->ndpr_pltime == ND6_INFINITE_LIFETIME) {
4365 		ndpr->ndpr_preferred = 0;
4366 	} else {
4367 		ndpr->ndpr_preferred = timenow + ndpr->ndpr_pltime;
4368 	}
4369 	if (ndpr->ndpr_vltime == ND6_INFINITE_LIFETIME) {
4370 		ndpr->ndpr_expire = 0;
4371 	} else {
4372 		ndpr->ndpr_expire = timenow + ndpr->ndpr_vltime;
4373 	}
4374 
4375 	return 0;
4376 }
4377 
4378 static void
in6_init_address_ltimes(struct in6_addrlifetime * lt6)4379 in6_init_address_ltimes(struct in6_addrlifetime *lt6)
4380 {
4381 	uint64_t timenow = net_uptime();
4382 
4383 	/* Valid lifetime must not be updated unless explicitly specified. */
4384 	/* init ia6t_expire */
4385 	if (lt6->ia6t_vltime == ND6_INFINITE_LIFETIME) {
4386 		lt6->ia6t_expire = 0;
4387 	} else {
4388 		lt6->ia6t_expire = timenow;
4389 		lt6->ia6t_expire += lt6->ia6t_vltime;
4390 	}
4391 
4392 	/* init ia6t_preferred */
4393 	if (lt6->ia6t_pltime == ND6_INFINITE_LIFETIME) {
4394 		lt6->ia6t_preferred = 0;
4395 	} else {
4396 		lt6->ia6t_preferred = timenow;
4397 		lt6->ia6t_preferred += lt6->ia6t_pltime;
4398 	}
4399 }
4400 
4401 /*
4402  * Delete all the routing table entries that use the specified gateway.
4403  * XXX: this function causes search through all entries of routing table, so
4404  * it shouldn't be called when acting as a router.
4405  *
4406  * This should really be working on entries that have a specific
4407  * parent route.
4408  */
4409 void
rt6_flush(struct in6_addr * gateway,struct ifnet * ifp)4410 rt6_flush(
4411 	struct in6_addr *gateway,
4412 	struct ifnet *ifp)
4413 {
4414 	radix_node_head_ref_t rnh = rt_tables[AF_INET6];
4415 
4416 	/* We'll care only link-local addresses */
4417 	if (!IN6_IS_ADDR_LINKLOCAL(gateway)) {
4418 		return;
4419 	}
4420 	lck_mtx_lock(rnh_lock);
4421 	/* XXX: hack for KAME's link-local address kludge */
4422 	if (in6_embedded_scope) {
4423 		gateway->s6_addr16[1] = htons(ifp->if_index);
4424 	}
4425 
4426 	rnh->rnh_walktree(rnh, rt6_deleteroute, (void *)gateway);
4427 	lck_mtx_unlock(rnh_lock);
4428 }
4429 
4430 static int
rt6_deleteroute(struct radix_node * rn,void * arg)4431 rt6_deleteroute(
4432 	struct radix_node *rn,
4433 	void *arg)
4434 {
4435 	rtentry_ref_t rt = (struct rtentry *)rn;
4436 	struct in6_addr *__single gate = (struct in6_addr *)arg;
4437 
4438 	LCK_MTX_ASSERT(rnh_lock, LCK_MTX_ASSERT_OWNED);
4439 
4440 	RT_LOCK(rt);
4441 	if (rt->rt_gateway == NULL || rt->rt_gateway->sa_family != AF_INET6) {
4442 		RT_UNLOCK(rt);
4443 		return 0;
4444 	}
4445 
4446 	if (!IN6_ARE_ADDR_EQUAL(gate, &SIN6(rt->rt_gateway)->sin6_addr)) {
4447 		RT_UNLOCK(rt);
4448 		return 0;
4449 	}
4450 	/*
4451 	 * Do not delete a static route.
4452 	 * XXX: this seems to be a bit ad-hoc. Should we consider the
4453 	 * 'cloned' bit instead?
4454 	 */
4455 	if ((rt->rt_flags & RTF_STATIC) != 0) {
4456 		RT_UNLOCK(rt);
4457 		return 0;
4458 	}
4459 	/*
4460 	 * We delete only host route. This means, in particular, we don't
4461 	 * delete default route.
4462 	 */
4463 	if ((rt->rt_flags & RTF_HOST) == 0) {
4464 		RT_UNLOCK(rt);
4465 		return 0;
4466 	}
4467 
4468 	/*
4469 	 * Safe to drop rt_lock and use rt_key, rt_gateway, since holding
4470 	 * rnh_lock here prevents another thread from calling rt_setgate()
4471 	 * on this route.
4472 	 */
4473 	RT_UNLOCK(rt);
4474 	return rtrequest_locked(RTM_DELETE, rt_key(rt), rt->rt_gateway,
4475 	           rt_mask(rt), rt->rt_flags, 0);
4476 }
4477 
4478 int
nd6_setdefaultiface(int ifindex)4479 nd6_setdefaultiface(
4480 	int ifindex)
4481 {
4482 	int error = 0;
4483 	ifnet_t def_ifp = NULL;
4484 
4485 	LCK_MTX_ASSERT(nd6_mutex, LCK_MTX_ASSERT_NOTOWNED);
4486 
4487 	ifnet_head_lock_shared();
4488 	if (!IF_INDEX_IN_RANGE(ifindex)) {
4489 		ifnet_head_done();
4490 		return EINVAL;
4491 	}
4492 	def_ifp = ifindex2ifnet[ifindex];
4493 	ifnet_head_done();
4494 
4495 	lck_mtx_lock(nd6_mutex);
4496 	if (nd6_defifindex != ifindex) {
4497 		ifnet_ref_t odef_ifp = nd6_defifp;
4498 
4499 		nd6_defifindex = ifindex;
4500 		if (nd6_defifindex > 0) {
4501 			nd6_defifp = def_ifp;
4502 		} else {
4503 			nd6_defifp = NULL;
4504 		}
4505 
4506 		if (nd6_defifp != NULL) {
4507 			nd6log(info, "%s: is now the default "
4508 			    "interface (was %s)\n", if_name(nd6_defifp),
4509 			    odef_ifp != NULL ? if_name(odef_ifp) : "NONE");
4510 		} else {
4511 			nd6log(info, "No default interface set\n");
4512 		}
4513 
4514 		/*
4515 		 * If the Default Router List is empty, install a route
4516 		 * to the specified interface as default or remove the default
4517 		 * route when the default interface becomes canceled.
4518 		 * The check for the queue is actually redundant, but
4519 		 * we do this here to avoid re-install the default route
4520 		 * if the list is NOT empty.
4521 		 */
4522 		if (odef_ifp != NULL) {
4523 			defrouter_select(odef_ifp, NULL);
4524 		}
4525 
4526 		if (nd6_defifp != NULL) {
4527 			defrouter_select(nd6_defifp, NULL);
4528 			nd6_prefix_sync(nd6_defifp);
4529 		}
4530 
4531 		/*
4532 		 * XXX For now we managed RTI routes as un-scoped.
4533 		 * Therefore we ignore the change in nd6_defifindex
4534 		 * for RTI routes for now.
4535 		 */
4536 		/*
4537 		 * Our current implementation assumes one-to-one mapping between
4538 		 * interfaces and links, so it would be natural to use the
4539 		 * default interface as the default link.
4540 		 */
4541 		scope6_setdefault(nd6_defifp);
4542 	}
4543 	lck_mtx_unlock(nd6_mutex);
4544 	return error;
4545 }
4546