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