1 /*
2 * Copyright (c) 2000-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
58 /*
59 * XXX
60 * KAME 970409 note:
61 * BSD/OS version heavily modifies this code, related to llinfo.
62 * Since we don't have BSD/OS version of net/route.c in our hand,
63 * I left the code mostly as it was in 970310. -- itojun
64 */
65
66 #include <sys/param.h>
67 #include <sys/systm.h>
68 #include <sys/malloc.h>
69 #include <sys/mbuf.h>
70 #include <sys/socket.h>
71 #include <sys/sockio.h>
72 #include <sys/time.h>
73 #include <sys/kernel.h>
74 #include <sys/sysctl.h>
75 #include <sys/errno.h>
76 #include <sys/syslog.h>
77 #include <sys/protosw.h>
78 #include <sys/proc.h>
79 #include <sys/mcache.h>
80
81 #include <dev/random/randomdev.h>
82
83 #include <kern/queue.h>
84 #include <kern/zalloc.h>
85
86 #include <net/if.h>
87 #include <net/if_dl.h>
88 #include <net/if_types.h>
89 #include <net/if_llreach.h>
90 #include <net/route.h>
91 #include <net/dlil.h>
92 #include <net/ntstat.h>
93 #include <net/net_osdep.h>
94 #include <net/nwk_wq.h>
95
96 #include <netinet/in.h>
97 #include <netinet/in_arp.h>
98 #include <netinet/if_ether.h>
99 #include <netinet6/in6_var.h>
100 #include <netinet/ip6.h>
101 #include <netinet6/ip6_var.h>
102 #include <netinet6/nd6.h>
103 #include <netinet6/scope6_var.h>
104 #include <netinet/icmp6.h>
105
106 #include <os/log.h>
107
108 #include "loop.h"
109
110 #define ND6_SLOWTIMER_INTERVAL (60 * 60) /* 1 hour */
111 #define ND6_RECALC_REACHTM_INTERVAL (60 * 120) /* 2 hours */
112
113 #define equal(a1, a2) (bcmp((caddr_t)(a1), (caddr_t)(a2), (a1)->sa_len) == 0)
114
115 /* timer values */
116 int nd6_prune = 1; /* walk list every 1 seconds */
117 int nd6_prune_lazy = 5; /* lazily walk list every 5 seconds */
118 int nd6_delay = 5; /* delay first probe time 5 second */
119 int nd6_umaxtries = 3; /* maximum unicast query */
120 int nd6_mmaxtries = 3; /* maximum multicast query */
121 int nd6_useloopback = 1; /* use loopback interface for local traffic */
122 int nd6_gctimer = (60 * 60 * 24); /* 1 day: garbage collection timer */
123
124 /* preventing too many loops in ND option parsing */
125 int nd6_maxndopt = 10; /* max # of ND options allowed */
126
127 int nd6_maxqueuelen = 1; /* max # of packets cached in unresolved ND entries */
128
129 #if ND6_DEBUG
130 int nd6_debug = 1;
131 #else
132 int nd6_debug = 0;
133 #endif
134
135 int nd6_optimistic_dad = ND6_OPTIMISTIC_DAD_DEFAULT;
136
137 /* for debugging? */
138 static int nd6_inuse, nd6_allocated;
139
140 /*
141 * Synchronization notes:
142 *
143 * The global list of ND entries are stored in llinfo_nd6; an entry
144 * gets inserted into the list when the route is created and gets
145 * removed from the list when it is deleted; this is done as part
146 * of RTM_ADD/RTM_RESOLVE/RTM_DELETE in nd6_rtrequest().
147 *
148 * Because rnh_lock and rt_lock for the entry are held during those
149 * operations, the same locks (and thus lock ordering) must be used
150 * elsewhere to access the relevant data structure fields:
151 *
152 * ln_next, ln_prev, ln_rt
153 *
154 * - Routing lock (rnh_lock)
155 *
156 * ln_hold, ln_asked, ln_expire, ln_state, ln_router, ln_flags,
157 * ln_llreach, ln_lastused
158 *
159 * - Routing entry lock (rt_lock)
160 *
161 * Due to the dependency on rt_lock, llinfo_nd6 has the same lifetime
162 * as the route entry itself. When a route is deleted (RTM_DELETE),
163 * it is simply removed from the global list but the memory is not
164 * freed until the route itself is freed.
165 */
166 struct llinfo_nd6 llinfo_nd6 = {
167 .ln_next = &llinfo_nd6,
168 .ln_prev = &llinfo_nd6,
169 };
170
171 static LCK_GRP_DECLARE(nd_if_lock_grp, "nd_if_lock");
172 static LCK_ATTR_DECLARE(nd_if_lock_attr, 0, 0);
173
174 /* Protected by nd6_mutex */
175 struct nd_drhead nd_defrouter_list;
176 struct nd_prhead nd_prefix = { .lh_first = 0 };
177 struct nd_rtihead nd_rti_list;
178 /*
179 * nd6_timeout() is scheduled on a demand basis. nd6_timeout_run is used
180 * to indicate whether or not a timeout has been scheduled. The rnh_lock
181 * mutex is used to protect this scheduling; it is a natural choice given
182 * the work done in the timer callback. Unfortunately, there are cases
183 * when nd6_timeout() needs to be scheduled while rnh_lock cannot be easily
184 * held, due to lock ordering. In those cases, we utilize a "demand" counter
185 * nd6_sched_timeout_want which can be atomically incremented without
186 * having to hold rnh_lock. On places where we acquire rnh_lock, such as
187 * nd6_rtrequest(), we check this counter and schedule the timer if it is
188 * non-zero. The increment happens on various places when we allocate
189 * new ND entries, default routers, prefixes and addresses.
190 */
191 static int nd6_timeout_run; /* nd6_timeout is scheduled to run */
192 static void nd6_timeout(void *);
193 int nd6_sched_timeout_want; /* demand count for timer to be sched */
194 static boolean_t nd6_fast_timer_on = FALSE;
195
196 /* Serialization variables for nd6_service(), protected by rnh_lock */
197 static boolean_t nd6_service_busy;
198 static void *nd6_service_wc = &nd6_service_busy;
199 static int nd6_service_waiters = 0;
200
201 int nd6_recalc_reachtm_interval = ND6_RECALC_REACHTM_INTERVAL;
202 static struct sockaddr_in6 all1_sa;
203
204 static int regen_tmpaddr(struct in6_ifaddr *);
205
206 static struct llinfo_nd6 *nd6_llinfo_alloc(zalloc_flags_t);
207 static void nd6_llinfo_free(void *);
208 static void nd6_llinfo_purge(struct rtentry *);
209 static void nd6_llinfo_get_ri(struct rtentry *, struct rt_reach_info *);
210 static void nd6_llinfo_get_iflri(struct rtentry *, struct ifnet_llreach_info *);
211 static void nd6_llinfo_refresh(struct rtentry *);
212 static uint64_t ln_getexpire(struct llinfo_nd6 *);
213
214 static void nd6_service(void *);
215 static void nd6_slowtimo(void *);
216 static int nd6_is_new_addr_neighbor(struct sockaddr_in6 *, struct ifnet *);
217 static int nd6_siocgdrlst(void *, int);
218 static int nd6_siocgprlst(void *, int);
219
220 static void nd6_router_select_rti_entries(struct ifnet *);
221 static void nd6_purge_interface_default_routers(struct ifnet *);
222 static void nd6_purge_interface_rti_entries(struct ifnet *);
223 static void nd6_purge_interface_prefixes(struct ifnet *);
224 static void nd6_purge_interface_llinfo(struct ifnet *);
225
226 static int nd6_sysctl_drlist SYSCTL_HANDLER_ARGS;
227 static int nd6_sysctl_prlist SYSCTL_HANDLER_ARGS;
228
229 /*
230 * Insertion and removal from llinfo_nd6 must be done with rnh_lock held.
231 */
232 #define LN_DEQUEUE(_ln) do { \
233 LCK_MTX_ASSERT(rnh_lock, LCK_MTX_ASSERT_OWNED); \
234 RT_LOCK_ASSERT_HELD((_ln)->ln_rt); \
235 (_ln)->ln_next->ln_prev = (_ln)->ln_prev; \
236 (_ln)->ln_prev->ln_next = (_ln)->ln_next; \
237 (_ln)->ln_prev = (_ln)->ln_next = NULL; \
238 (_ln)->ln_flags &= ~ND6_LNF_IN_USE; \
239 } while (0)
240
241 #define LN_INSERTHEAD(_ln) do { \
242 LCK_MTX_ASSERT(rnh_lock, LCK_MTX_ASSERT_OWNED); \
243 RT_LOCK_ASSERT_HELD((_ln)->ln_rt); \
244 (_ln)->ln_next = llinfo_nd6.ln_next; \
245 llinfo_nd6.ln_next = (_ln); \
246 (_ln)->ln_prev = &llinfo_nd6; \
247 (_ln)->ln_next->ln_prev = (_ln); \
248 (_ln)->ln_flags |= ND6_LNF_IN_USE; \
249 } while (0)
250
251 static KALLOC_TYPE_DEFINE(llinfo_nd6_zone, struct llinfo_nd6, NET_KT_DEFAULT);
252
253 extern int tvtohz(struct timeval *);
254
255 static int nd6_init_done;
256
257 SYSCTL_DECL(_net_inet6_icmp6);
258
259 SYSCTL_PROC(_net_inet6_icmp6, ICMPV6CTL_ND6_DRLIST, nd6_drlist,
260 CTLTYPE_STRUCT | CTLFLAG_RD | CTLFLAG_LOCKED, 0, 0,
261 nd6_sysctl_drlist, "S,in6_defrouter", "");
262
263 SYSCTL_PROC(_net_inet6_icmp6, ICMPV6CTL_ND6_PRLIST, nd6_prlist,
264 CTLTYPE_STRUCT | CTLFLAG_RD | CTLFLAG_LOCKED, 0, 0,
265 nd6_sysctl_prlist, "S,in6_defrouter", "");
266
267 SYSCTL_DECL(_net_inet6_ip6);
268
269 static int ip6_maxchainsent = 0;
270 SYSCTL_INT(_net_inet6_ip6, OID_AUTO, maxchainsent,
271 CTLFLAG_RW | CTLFLAG_LOCKED, &ip6_maxchainsent, 0,
272 "use dlil_output_list");
273
274 SYSCTL_DECL(_net_inet6_icmp6);
275 int nd6_process_rti = ND6_PROCESS_RTI_DEFAULT;
276
277 SYSCTL_INT(_net_inet6_icmp6, OID_AUTO, nd6_process_rti, CTLFLAG_RW | CTLFLAG_LOCKED,
278 &nd6_process_rti, 0,
279 "Enable/disable processing of Route Information Option in the "
280 "IPv6 Router Advertisement.");
281
282 void
nd6_init(void)283 nd6_init(void)
284 {
285 int i;
286
287 VERIFY(!nd6_init_done);
288
289 all1_sa.sin6_family = AF_INET6;
290 all1_sa.sin6_len = sizeof(struct sockaddr_in6);
291 for (i = 0; i < sizeof(all1_sa.sin6_addr); i++) {
292 all1_sa.sin6_addr.s6_addr[i] = 0xff;
293 }
294
295 /* initialization of the default router list */
296 TAILQ_INIT(&nd_defrouter_list);
297 TAILQ_INIT(&nd_rti_list);
298
299 nd6_nbr_init();
300 nd6_rtr_init();
301
302 nd6_init_done = 1;
303
304 /* start timer */
305 timeout(nd6_slowtimo, NULL, ND6_SLOWTIMER_INTERVAL * hz);
306 }
307
308 static struct llinfo_nd6 *
nd6_llinfo_alloc(zalloc_flags_t how)309 nd6_llinfo_alloc(zalloc_flags_t how)
310 {
311 return zalloc_flags(llinfo_nd6_zone, how | Z_ZERO);
312 }
313
314 static void
nd6_llinfo_free(void * arg)315 nd6_llinfo_free(void *arg)
316 {
317 struct llinfo_nd6 *ln = arg;
318
319 if (ln->ln_next != NULL || ln->ln_prev != NULL) {
320 panic("%s: trying to free %p when it is in use", __func__, ln);
321 /* NOTREACHED */
322 }
323
324 /* Just in case there's anything there, free it */
325 if (ln->ln_hold != NULL) {
326 m_freem_list(ln->ln_hold);
327 ln->ln_hold = NULL;
328 }
329
330 /* Purge any link-layer info caching */
331 VERIFY(ln->ln_rt->rt_llinfo == ln);
332 if (ln->ln_rt->rt_llinfo_purge != NULL) {
333 ln->ln_rt->rt_llinfo_purge(ln->ln_rt);
334 }
335
336 zfree(llinfo_nd6_zone, ln);
337 }
338
339 static void
nd6_llinfo_purge(struct rtentry * rt)340 nd6_llinfo_purge(struct rtentry *rt)
341 {
342 struct llinfo_nd6 *ln = rt->rt_llinfo;
343
344 RT_LOCK_ASSERT_HELD(rt);
345 VERIFY(rt->rt_llinfo_purge == nd6_llinfo_purge && ln != NULL);
346
347 if (ln->ln_llreach != NULL) {
348 RT_CONVERT_LOCK(rt);
349 ifnet_llreach_free(ln->ln_llreach);
350 ln->ln_llreach = NULL;
351 }
352 ln->ln_lastused = 0;
353 }
354
355 static void
nd6_llinfo_get_ri(struct rtentry * rt,struct rt_reach_info * ri)356 nd6_llinfo_get_ri(struct rtentry *rt, struct rt_reach_info *ri)
357 {
358 struct llinfo_nd6 *ln = rt->rt_llinfo;
359 struct if_llreach *lr = ln->ln_llreach;
360
361 if (lr == NULL) {
362 bzero(ri, sizeof(*ri));
363 ri->ri_rssi = IFNET_RSSI_UNKNOWN;
364 ri->ri_lqm = IFNET_LQM_THRESH_OFF;
365 ri->ri_npm = IFNET_NPM_THRESH_UNKNOWN;
366 } else {
367 IFLR_LOCK(lr);
368 /* Export to rt_reach_info structure */
369 ifnet_lr2ri(lr, ri);
370 /* Export ND6 send expiration (calendar) time */
371 ri->ri_snd_expire =
372 ifnet_llreach_up2calexp(lr, ln->ln_lastused);
373 IFLR_UNLOCK(lr);
374 }
375 }
376
377 static void
nd6_llinfo_get_iflri(struct rtentry * rt,struct ifnet_llreach_info * iflri)378 nd6_llinfo_get_iflri(struct rtentry *rt, struct ifnet_llreach_info *iflri)
379 {
380 struct llinfo_nd6 *ln = rt->rt_llinfo;
381 struct if_llreach *lr = ln->ln_llreach;
382
383 if (lr == NULL) {
384 bzero(iflri, sizeof(*iflri));
385 iflri->iflri_rssi = IFNET_RSSI_UNKNOWN;
386 iflri->iflri_lqm = IFNET_LQM_THRESH_OFF;
387 iflri->iflri_npm = IFNET_NPM_THRESH_UNKNOWN;
388 } else {
389 IFLR_LOCK(lr);
390 /* Export to ifnet_llreach_info structure */
391 ifnet_lr2iflri(lr, iflri);
392 /* Export ND6 send expiration (uptime) time */
393 iflri->iflri_snd_expire =
394 ifnet_llreach_up2upexp(lr, ln->ln_lastused);
395 IFLR_UNLOCK(lr);
396 }
397 }
398
399 static void
nd6_llinfo_refresh(struct rtentry * rt)400 nd6_llinfo_refresh(struct rtentry *rt)
401 {
402 struct llinfo_nd6 *ln = rt->rt_llinfo;
403 uint64_t timenow = net_uptime();
404 struct ifnet *ifp = rt->rt_ifp;
405 /*
406 * Can't refresh permanent, static or entries that are
407 * not direct host entries. Also skip if the entry is for
408 * host over an interface that has alternate neighbor cache
409 * management mechanisms (AWDL/NAN)
410 */
411 if (!ln || ln->ln_expire == 0 || (rt->rt_flags & RTF_STATIC) ||
412 !(rt->rt_flags & RTF_LLINFO) || !ifp ||
413 (ifp->if_eflags & IFEF_IPV6_ND6ALT)) {
414 return;
415 }
416
417 if ((ln->ln_state > ND6_LLINFO_INCOMPLETE) &&
418 (ln->ln_state < ND6_LLINFO_PROBE)) {
419 if (ln->ln_expire > timenow) {
420 ln_setexpire(ln, timenow);
421 ND6_CACHE_STATE_TRANSITION(ln, ND6_LLINFO_PROBE);
422 }
423 }
424 return;
425 }
426
427 const char *
ndcache_state2str(short ndp_state)428 ndcache_state2str(short ndp_state)
429 {
430 const char *ndp_state_str = "UNKNOWN";
431 switch (ndp_state) {
432 case ND6_LLINFO_PURGE:
433 ndp_state_str = "ND6_LLINFO_PURGE";
434 break;
435 case ND6_LLINFO_NOSTATE:
436 ndp_state_str = "ND6_LLINFO_NOSTATE";
437 break;
438 case ND6_LLINFO_INCOMPLETE:
439 ndp_state_str = "ND6_LLINFO_INCOMPLETE";
440 break;
441 case ND6_LLINFO_REACHABLE:
442 ndp_state_str = "ND6_LLINFO_REACHABLE";
443 break;
444 case ND6_LLINFO_STALE:
445 ndp_state_str = "ND6_LLINFO_STALE";
446 break;
447 case ND6_LLINFO_DELAY:
448 ndp_state_str = "ND6_LLINFO_DELAY";
449 break;
450 case ND6_LLINFO_PROBE:
451 ndp_state_str = "ND6_LLINFO_PROBE";
452 break;
453 default:
454 /* Init'd to UNKNOWN */
455 break;
456 }
457 return ndp_state_str;
458 }
459
460 void
ln_setexpire(struct llinfo_nd6 * ln,uint64_t expiry)461 ln_setexpire(struct llinfo_nd6 *ln, uint64_t expiry)
462 {
463 ln->ln_expire = expiry;
464 }
465
466 static uint64_t
ln_getexpire(struct llinfo_nd6 * ln)467 ln_getexpire(struct llinfo_nd6 *ln)
468 {
469 struct timeval caltime;
470 uint64_t expiry;
471
472 if (ln->ln_expire != 0) {
473 struct rtentry *rt = ln->ln_rt;
474
475 VERIFY(rt != NULL);
476 /* account for system time change */
477 getmicrotime(&caltime);
478
479 rt->base_calendartime +=
480 NET_CALCULATE_CLOCKSKEW(caltime,
481 rt->base_calendartime, net_uptime(), rt->base_uptime);
482
483 expiry = rt->base_calendartime +
484 ln->ln_expire - rt->base_uptime;
485 } else {
486 expiry = 0;
487 }
488 return expiry;
489 }
490
491 void
nd6_ifreset(struct ifnet * ifp)492 nd6_ifreset(struct ifnet *ifp)
493 {
494 struct nd_ifinfo *ndi = ND_IFINFO(ifp);
495 VERIFY(NULL != ndi);
496 VERIFY(ndi->initialized);
497
498 LCK_MTX_ASSERT(&ndi->lock, LCK_MTX_ASSERT_OWNED);
499 ndi->linkmtu = ifp->if_mtu;
500 ndi->chlim = IPV6_DEFHLIM;
501 ndi->basereachable = REACHABLE_TIME;
502 ndi->reachable = ND_COMPUTE_RTIME(ndi->basereachable);
503 ndi->retrans = RETRANS_TIMER;
504 }
505
506 void
nd6_ifattach(struct ifnet * ifp)507 nd6_ifattach(struct ifnet *ifp)
508 {
509 struct nd_ifinfo *ndi = ND_IFINFO(ifp);
510
511 VERIFY(NULL != ndi);
512 if (!ndi->initialized) {
513 lck_mtx_init(&ndi->lock, &nd_if_lock_grp, &nd_if_lock_attr);
514 ndi->flags = ND6_IFF_PERFORMNUD;
515 ndi->flags |= ND6_IFF_DAD;
516 ndi->initialized = TRUE;
517 }
518
519 lck_mtx_lock(&ndi->lock);
520
521 if (!(ifp->if_flags & IFF_MULTICAST)) {
522 ndi->flags |= ND6_IFF_IFDISABLED;
523 }
524
525 nd6_ifreset(ifp);
526 lck_mtx_unlock(&ndi->lock);
527 nd6_setmtu(ifp);
528
529 nd6log0(info,
530 "Reinit'd ND information for interface %s\n",
531 if_name(ifp));
532 return;
533 }
534
535 #if 0
536 /*
537 * XXX Look more into this. Especially since we recycle ifnets and do delayed
538 * cleanup
539 */
540 void
541 nd6_ifdetach(struct nd_ifinfo *nd)
542 {
543 /* XXX destroy nd's lock? */
544 FREE(nd, M_IP6NDP);
545 }
546 #endif
547
548 void
nd6_setmtu(struct ifnet * ifp)549 nd6_setmtu(struct ifnet *ifp)
550 {
551 struct nd_ifinfo *ndi = ND_IFINFO(ifp);
552 u_int32_t oldmaxmtu, maxmtu;
553
554 if ((NULL == ndi) || (FALSE == ndi->initialized)) {
555 return;
556 }
557
558 lck_mtx_lock(&ndi->lock);
559 oldmaxmtu = ndi->maxmtu;
560
561 /*
562 * The ND level maxmtu is somewhat redundant to the interface MTU
563 * and is an implementation artifact of KAME. Instead of hard-
564 * limiting the maxmtu based on the interface type here, we simply
565 * take the if_mtu value since SIOCSIFMTU would have taken care of
566 * the sanity checks related to the maximum MTU allowed for the
567 * interface (a value that is known only by the interface layer),
568 * by sending the request down via ifnet_ioctl(). The use of the
569 * ND level maxmtu and linkmtu are done via IN6_LINKMTU() which
570 * does further checking against if_mtu.
571 */
572 maxmtu = ndi->maxmtu = ifp->if_mtu;
573
574 /*
575 * Decreasing the interface MTU under IPV6 minimum MTU may cause
576 * undesirable situation. We thus notify the operator of the change
577 * explicitly. The check for oldmaxmtu is necessary to restrict the
578 * log to the case of changing the MTU, not initializing it.
579 */
580 if (oldmaxmtu >= IPV6_MMTU && ndi->maxmtu < IPV6_MMTU) {
581 log(LOG_NOTICE, "nd6_setmtu: "
582 "new link MTU on %s (%u) is too small for IPv6\n",
583 if_name(ifp), (uint32_t)ndi->maxmtu);
584 }
585 ndi->linkmtu = ifp->if_mtu;
586 lck_mtx_unlock(&ndi->lock);
587
588 /* also adjust in6_maxmtu if necessary. */
589 if (maxmtu > in6_maxmtu) {
590 in6_setmaxmtu();
591 }
592 }
593
594 void
nd6_option_init(void * opt,int icmp6len,union nd_opts * ndopts)595 nd6_option_init(void *opt, int icmp6len, union nd_opts *ndopts)
596 {
597 bzero(ndopts, sizeof(*ndopts));
598 ndopts->nd_opts_search = (struct nd_opt_hdr *)opt;
599 ndopts->nd_opts_last =
600 (struct nd_opt_hdr *)(((u_char *)opt) + icmp6len);
601
602 if (icmp6len == 0) {
603 ndopts->nd_opts_done = 1;
604 ndopts->nd_opts_search = NULL;
605 }
606 }
607
608 /*
609 * Take one ND option.
610 */
611 struct nd_opt_hdr *
nd6_option(union nd_opts * ndopts)612 nd6_option(union nd_opts *ndopts)
613 {
614 struct nd_opt_hdr *nd_opt;
615 int olen;
616
617 if (!ndopts) {
618 panic("ndopts == NULL in nd6_option");
619 }
620 if (!ndopts->nd_opts_last) {
621 panic("uninitialized ndopts in nd6_option");
622 }
623 if (!ndopts->nd_opts_search) {
624 return NULL;
625 }
626 if (ndopts->nd_opts_done) {
627 return NULL;
628 }
629
630 nd_opt = ndopts->nd_opts_search;
631
632 /* make sure nd_opt_len is inside the buffer */
633 if ((caddr_t)&nd_opt->nd_opt_len >= (caddr_t)ndopts->nd_opts_last) {
634 bzero(ndopts, sizeof(*ndopts));
635 return NULL;
636 }
637
638 olen = nd_opt->nd_opt_len << 3;
639 if (olen == 0) {
640 /*
641 * Message validation requires that all included
642 * options have a length that is greater than zero.
643 */
644 bzero(ndopts, sizeof(*ndopts));
645 return NULL;
646 }
647
648 ndopts->nd_opts_search = (struct nd_opt_hdr *)((caddr_t)nd_opt + olen);
649 if (ndopts->nd_opts_search > ndopts->nd_opts_last) {
650 /* option overruns the end of buffer, invalid */
651 bzero(ndopts, sizeof(*ndopts));
652 return NULL;
653 } else if (ndopts->nd_opts_search == ndopts->nd_opts_last) {
654 /* reached the end of options chain */
655 ndopts->nd_opts_done = 1;
656 ndopts->nd_opts_search = NULL;
657 }
658 return nd_opt;
659 }
660
661 /*
662 * Parse multiple ND options.
663 * This function is much easier to use, for ND routines that do not need
664 * multiple options of the same type.
665 */
666 int
nd6_options(union nd_opts * ndopts)667 nd6_options(union nd_opts *ndopts)
668 {
669 struct nd_opt_hdr *nd_opt;
670 int i = 0;
671
672 if (ndopts == NULL) {
673 panic("ndopts == NULL in nd6_options");
674 }
675 if (ndopts->nd_opts_last == NULL) {
676 panic("uninitialized ndopts in nd6_options");
677 }
678 if (ndopts->nd_opts_search == NULL) {
679 return 0;
680 }
681
682 while (1) {
683 nd_opt = nd6_option(ndopts);
684 if (nd_opt == NULL && ndopts->nd_opts_last == NULL) {
685 /*
686 * Message validation requires that all included
687 * options have a length that is greater than zero.
688 */
689 icmp6stat.icp6s_nd_badopt++;
690 bzero(ndopts, sizeof(*ndopts));
691 return -1;
692 }
693
694 if (nd_opt == NULL) {
695 goto skip1;
696 }
697
698 switch (nd_opt->nd_opt_type) {
699 case ND_OPT_SOURCE_LINKADDR:
700 case ND_OPT_TARGET_LINKADDR:
701 case ND_OPT_MTU:
702 case ND_OPT_REDIRECTED_HEADER:
703 case ND_OPT_NONCE:
704 if (ndopts->nd_opt_array[nd_opt->nd_opt_type]) {
705 nd6log(error,
706 "duplicated ND6 option found (type=%d)\n",
707 nd_opt->nd_opt_type);
708 /* XXX bark? */
709 } else {
710 ndopts->nd_opt_array[nd_opt->nd_opt_type] =
711 nd_opt;
712 }
713 break;
714 case ND_OPT_PREFIX_INFORMATION:
715 if (ndopts->nd_opt_array[nd_opt->nd_opt_type] == 0) {
716 ndopts->nd_opt_array[nd_opt->nd_opt_type] =
717 nd_opt;
718 }
719 ndopts->nd_opts_pi_end =
720 (struct nd_opt_prefix_info *)nd_opt;
721 break;
722 case ND_OPT_RDNSS:
723 case ND_OPT_DNSSL:
724 case ND_OPT_CAPTIVE_PORTAL:
725 /* ignore */
726 break;
727 case ND_OPT_ROUTE_INFO:
728 if (nd6_process_rti) {
729 if (ndopts->nd_opt_array[nd_opt->nd_opt_type] == 0) {
730 ndopts->nd_opt_array[nd_opt->nd_opt_type]
731 = nd_opt;
732 }
733 ndopts->nd_opts_rti_end =
734 (struct nd_opt_route_info *)nd_opt;
735 break;
736 }
737 OS_FALLTHROUGH;
738 default:
739 /*
740 * Unknown options must be silently ignored,
741 * to accomodate future extension to the protocol.
742 */
743 nd6log(debug,
744 "nd6_options: unsupported option %d - "
745 "option ignored\n", nd_opt->nd_opt_type);
746 }
747
748 skip1:
749 i++;
750 if (i > nd6_maxndopt) {
751 icmp6stat.icp6s_nd_toomanyopt++;
752 nd6log(info, "too many loop in nd opt\n");
753 break;
754 }
755
756 if (ndopts->nd_opts_done) {
757 break;
758 }
759 }
760
761 return 0;
762 }
763
764 struct nd6svc_arg {
765 int draining;
766 uint32_t killed;
767 uint32_t aging_lazy;
768 uint32_t aging;
769 uint32_t sticky;
770 uint32_t found;
771 };
772
773
774 static void
nd6_service_neighbor_cache(struct nd6svc_arg * ap,uint64_t timenow)775 nd6_service_neighbor_cache(struct nd6svc_arg *ap, uint64_t timenow)
776 {
777 struct llinfo_nd6 *ln;
778 struct ifnet *ifp = NULL;
779 boolean_t send_nc_failure_kev = FALSE;
780 struct radix_node_head *rnh = rt_tables[AF_INET6];
781
782 LCK_MTX_ASSERT(rnh_lock, LCK_MTX_ASSERT_OWNED);
783 again:
784 /*
785 * send_nc_failure_kev gets set when default router's IPv6 address
786 * can't be resolved.
787 * That can happen either:
788 * 1. When the entry has resolved once but can't be
789 * resolved later and the neighbor cache entry for gateway is deleted
790 * after max probe attempts.
791 *
792 * 2. When the entry is in ND6_LLINFO_INCOMPLETE but can not be resolved
793 * after max neighbor address resolution attempts.
794 *
795 * Both set send_nc_failure_kev to true. ifp is also set to the previous
796 * neighbor cache entry's route's ifp.
797 * Once we are done sending the notification, set send_nc_failure_kev
798 * to false to stop sending false notifications for non default router
799 * neighbors.
800 *
801 * We may to send more information like Gateway's IP that could not be
802 * resolved, however right now we do not install more than one default
803 * route per interface in the routing table.
804 */
805 if (send_nc_failure_kev && ifp != NULL &&
806 ifp->if_addrlen == IF_LLREACH_MAXLEN) {
807 struct kev_msg ev_msg;
808 struct kev_nd6_ndfailure nd6_ndfailure;
809 bzero(&ev_msg, sizeof(ev_msg));
810 bzero(&nd6_ndfailure, sizeof(nd6_ndfailure));
811 ev_msg.vendor_code = KEV_VENDOR_APPLE;
812 ev_msg.kev_class = KEV_NETWORK_CLASS;
813 ev_msg.kev_subclass = KEV_ND6_SUBCLASS;
814 ev_msg.event_code = KEV_ND6_NDFAILURE;
815
816 nd6_ndfailure.link_data.if_family = ifp->if_family;
817 nd6_ndfailure.link_data.if_unit = ifp->if_unit;
818 strlcpy(nd6_ndfailure.link_data.if_name,
819 ifp->if_name,
820 sizeof(nd6_ndfailure.link_data.if_name));
821 ev_msg.dv[0].data_ptr = &nd6_ndfailure;
822 ev_msg.dv[0].data_length =
823 sizeof(nd6_ndfailure);
824 dlil_post_complete_msg(NULL, &ev_msg);
825 }
826
827 send_nc_failure_kev = FALSE;
828 ifp = NULL;
829 /*
830 * The global list llinfo_nd6 is modified by nd6_request() and is
831 * therefore protected by rnh_lock. For obvious reasons, we cannot
832 * hold rnh_lock across calls that might lead to code paths which
833 * attempt to acquire rnh_lock, else we deadlock. Hence for such
834 * cases we drop rt_lock and rnh_lock, make the calls, and repeat the
835 * loop. To ensure that we don't process the same entry more than
836 * once in a single timeout, we mark the "already-seen" entries with
837 * ND6_LNF_TIMER_SKIP flag. At the end of the loop, we do a second
838 * pass thru the entries and clear the flag so they can be processed
839 * during the next timeout.
840 */
841 LCK_MTX_ASSERT(rnh_lock, LCK_MTX_ASSERT_OWNED);
842
843 ln = llinfo_nd6.ln_next;
844 while (ln != NULL && ln != &llinfo_nd6) {
845 struct rtentry *rt;
846 struct sockaddr_in6 *dst;
847 struct llinfo_nd6 *next;
848 u_int32_t retrans, flags;
849 struct nd_ifinfo *ndi = NULL;
850 boolean_t is_router = FALSE;
851
852 /* ln_next/prev/rt is protected by rnh_lock */
853 next = ln->ln_next;
854 rt = ln->ln_rt;
855 RT_LOCK(rt);
856
857 /* We've seen this already; skip it */
858 if (ln->ln_flags & ND6_LNF_TIMER_SKIP) {
859 RT_UNLOCK(rt);
860 ln = next;
861 continue;
862 }
863 ap->found++;
864
865 /* rt->rt_ifp should never be NULL */
866 if ((ifp = rt->rt_ifp) == NULL) {
867 panic("%s: ln(%p) rt(%p) rt_ifp == NULL", __func__,
868 ln, rt);
869 /* NOTREACHED */
870 }
871
872 /* rt_llinfo must always be equal to ln */
873 if ((struct llinfo_nd6 *)rt->rt_llinfo != ln) {
874 panic("%s: rt_llinfo(%p) is not equal to ln(%p)",
875 __func__, rt->rt_llinfo, ln);
876 /* NOTREACHED */
877 }
878
879 /* rt_key should never be NULL */
880 dst = SIN6(rt_key(rt));
881 if (dst == NULL) {
882 panic("%s: rt(%p) key is NULL ln(%p)", __func__,
883 rt, ln);
884 /* NOTREACHED */
885 }
886
887 /* Set the flag in case we jump to "again" */
888 ln->ln_flags |= ND6_LNF_TIMER_SKIP;
889
890 /*
891 * Do not touch neighbor cache entries that are permanent,
892 * static or are for interfaces that manage neighbor cache
893 * entries via alternate NDP means.
894 */
895 if (ln->ln_expire == 0 || (rt->rt_flags & RTF_STATIC) ||
896 (rt->rt_ifp->if_eflags & IFEF_IPV6_ND6ALT)) {
897 ap->sticky++;
898 } else if (ap->draining && (rt->rt_refcnt == 0)) {
899 /*
900 * If we are draining, immediately purge non-static
901 * entries without oustanding route refcnt.
902 */
903 if (ln->ln_state > ND6_LLINFO_INCOMPLETE) {
904 ND6_CACHE_STATE_TRANSITION(ln, (short)ND6_LLINFO_STALE);
905 } else {
906 ND6_CACHE_STATE_TRANSITION(ln, ND6_LLINFO_PURGE);
907 }
908 ln_setexpire(ln, timenow);
909 }
910
911 /*
912 * If the entry has not expired, skip it. Take note on the
913 * state, as entries that are in the STALE state are simply
914 * waiting to be garbage collected, in which case we can
915 * relax the callout scheduling (use nd6_prune_lazy).
916 */
917 if (ln->ln_expire > timenow) {
918 switch (ln->ln_state) {
919 case ND6_LLINFO_STALE:
920 ap->aging_lazy++;
921 break;
922 default:
923 ap->aging++;
924 break;
925 }
926 RT_UNLOCK(rt);
927 ln = next;
928 continue;
929 }
930
931 ndi = ND_IFINFO(ifp);
932 /*
933 * The IPv6 initialization of the loopback interface
934 * may happen after another interface gets assigned
935 * an IPv6 address
936 */
937 if (ndi == NULL && ifp == lo_ifp) {
938 RT_UNLOCK(rt);
939 ln = next;
940 continue;
941 }
942 VERIFY(ndi->initialized);
943 retrans = ndi->retrans;
944 flags = ndi->flags;
945
946 RT_LOCK_ASSERT_HELD(rt);
947 is_router = (rt->rt_flags & RTF_ROUTER) ? TRUE : FALSE;
948
949 switch (ln->ln_state) {
950 case ND6_LLINFO_INCOMPLETE:
951 if (ln->ln_asked < nd6_mmaxtries) {
952 struct ifnet *exclifp = ln->ln_exclifp;
953 ln->ln_asked++;
954 ln_setexpire(ln, timenow + retrans / 1000);
955 RT_ADDREF_LOCKED(rt);
956 RT_UNLOCK(rt);
957 lck_mtx_unlock(rnh_lock);
958 if (ip6_forwarding) {
959 nd6_prproxy_ns_output(ifp, exclifp,
960 NULL, &dst->sin6_addr, ln);
961 } else {
962 nd6_ns_output(ifp, NULL,
963 &dst->sin6_addr, ln, NULL);
964 }
965 RT_REMREF(rt);
966 ap->aging++;
967 lck_mtx_lock(rnh_lock);
968 } else {
969 struct mbuf *m = ln->ln_hold;
970 ln->ln_hold = NULL;
971 send_nc_failure_kev = is_router;
972 if (m != NULL) {
973 RT_ADDREF_LOCKED(rt);
974 RT_UNLOCK(rt);
975 lck_mtx_unlock(rnh_lock);
976
977 struct mbuf *mnext;
978 while (m) {
979 mnext = m->m_nextpkt;
980 m->m_nextpkt = NULL;
981 m->m_pkthdr.rcvif = ifp;
982 icmp6_error_flag(m, ICMP6_DST_UNREACH,
983 ICMP6_DST_UNREACH_ADDR, 0, 0);
984 m = mnext;
985 }
986 } else {
987 RT_ADDREF_LOCKED(rt);
988 RT_UNLOCK(rt);
989 lck_mtx_unlock(rnh_lock);
990 }
991
992 /*
993 * Enqueue work item to invoke callback for
994 * this route entry
995 */
996 route_event_enqueue_nwk_wq_entry(rt, NULL,
997 ROUTE_LLENTRY_UNREACH, NULL, FALSE);
998 defrouter_set_reachability(&SIN6(rt_key(rt))->sin6_addr, rt->rt_ifp,
999 FALSE);
1000 nd6_free(rt);
1001 ap->killed++;
1002 lck_mtx_lock(rnh_lock);
1003 /*
1004 * nd6_free above would flush out the routing table of
1005 * any cloned routes with same next-hop.
1006 * Walk the tree anyways as there could be static routes
1007 * left.
1008 *
1009 * We also already have a reference to rt that gets freed right
1010 * after the block below executes. Don't need an extra reference
1011 * on rt here.
1012 */
1013 if (is_router) {
1014 struct route_event rt_ev;
1015 route_event_init(&rt_ev, rt, NULL, ROUTE_LLENTRY_UNREACH);
1016 (void) rnh->rnh_walktree(rnh, route_event_walktree, (void *)&rt_ev);
1017 }
1018 rtfree_locked(rt);
1019 }
1020 LCK_MTX_ASSERT(rnh_lock, LCK_MTX_ASSERT_OWNED);
1021 goto again;
1022
1023 case ND6_LLINFO_REACHABLE:
1024 if (ln->ln_expire != 0) {
1025 ND6_CACHE_STATE_TRANSITION(ln, ND6_LLINFO_STALE);
1026 ln_setexpire(ln, timenow + nd6_gctimer);
1027 ap->aging_lazy++;
1028 /*
1029 * Enqueue work item to invoke callback for
1030 * this route entry
1031 */
1032 route_event_enqueue_nwk_wq_entry(rt, NULL,
1033 ROUTE_LLENTRY_STALE, NULL, TRUE);
1034
1035 RT_ADDREF_LOCKED(rt);
1036 RT_UNLOCK(rt);
1037 if (is_router) {
1038 struct route_event rt_ev;
1039 route_event_init(&rt_ev, rt, NULL, ROUTE_LLENTRY_STALE);
1040 (void) rnh->rnh_walktree(rnh, route_event_walktree, (void *)&rt_ev);
1041 }
1042 rtfree_locked(rt);
1043 } else {
1044 RT_UNLOCK(rt);
1045 }
1046 break;
1047
1048 case ND6_LLINFO_STALE:
1049 case ND6_LLINFO_PURGE:
1050 /* Garbage Collection(RFC 4861 5.3) */
1051 if (ln->ln_expire != 0) {
1052 RT_ADDREF_LOCKED(rt);
1053 RT_UNLOCK(rt);
1054 lck_mtx_unlock(rnh_lock);
1055 nd6_free(rt);
1056 ap->killed++;
1057 lck_mtx_lock(rnh_lock);
1058 rtfree_locked(rt);
1059 goto again;
1060 } else {
1061 RT_UNLOCK(rt);
1062 }
1063 break;
1064
1065 case ND6_LLINFO_DELAY:
1066 if ((flags & ND6_IFF_PERFORMNUD) != 0) {
1067 /* We need NUD */
1068 ln->ln_asked = 1;
1069 ND6_CACHE_STATE_TRANSITION(ln, ND6_LLINFO_PROBE);
1070 ln_setexpire(ln, timenow + retrans / 1000);
1071 RT_ADDREF_LOCKED(rt);
1072 RT_UNLOCK(rt);
1073 lck_mtx_unlock(rnh_lock);
1074 nd6_ns_output(ifp, &dst->sin6_addr,
1075 &dst->sin6_addr, ln, NULL);
1076 RT_REMREF(rt);
1077 ap->aging++;
1078 lck_mtx_lock(rnh_lock);
1079 goto again;
1080 }
1081 ND6_CACHE_STATE_TRANSITION(ln, ND6_LLINFO_STALE); /* XXX */
1082 ln_setexpire(ln, timenow + nd6_gctimer);
1083 RT_UNLOCK(rt);
1084 ap->aging_lazy++;
1085 break;
1086
1087 case ND6_LLINFO_PROBE:
1088 if (ln->ln_asked < nd6_umaxtries) {
1089 ln->ln_asked++;
1090 ln_setexpire(ln, timenow + retrans / 1000);
1091 RT_ADDREF_LOCKED(rt);
1092 RT_UNLOCK(rt);
1093 lck_mtx_unlock(rnh_lock);
1094 nd6_ns_output(ifp, &dst->sin6_addr,
1095 &dst->sin6_addr, ln, NULL);
1096 RT_REMREF(rt);
1097 ap->aging++;
1098 lck_mtx_lock(rnh_lock);
1099 } else {
1100 is_router = (rt->rt_flags & RTF_ROUTER) ? TRUE : FALSE;
1101 send_nc_failure_kev = is_router;
1102 RT_ADDREF_LOCKED(rt);
1103 RT_UNLOCK(rt);
1104 lck_mtx_unlock(rnh_lock);
1105 nd6_free(rt);
1106 ap->killed++;
1107
1108 /*
1109 * Enqueue work item to invoke callback for
1110 * this route entry
1111 */
1112 route_event_enqueue_nwk_wq_entry(rt, NULL,
1113 ROUTE_LLENTRY_UNREACH, NULL, FALSE);
1114 defrouter_set_reachability(&SIN6(rt_key(rt))->sin6_addr, rt->rt_ifp,
1115 FALSE);
1116 lck_mtx_lock(rnh_lock);
1117 /*
1118 * nd6_free above would flush out the routing table of
1119 * any cloned routes with same next-hop.
1120 * Walk the tree anyways as there could be static routes
1121 * left.
1122 *
1123 * We also already have a reference to rt that gets freed right
1124 * after the block below executes. Don't need an extra reference
1125 * on rt here.
1126 */
1127 if (is_router) {
1128 struct route_event rt_ev;
1129 route_event_init(&rt_ev, rt, NULL, ROUTE_LLENTRY_UNREACH);
1130 (void) rnh->rnh_walktree(rnh,
1131 route_event_walktree, (void *)&rt_ev);
1132 }
1133 rtfree_locked(rt);
1134 }
1135 LCK_MTX_ASSERT(rnh_lock, LCK_MTX_ASSERT_OWNED);
1136 goto again;
1137
1138 default:
1139 RT_UNLOCK(rt);
1140 break;
1141 }
1142 ln = next;
1143 }
1144 LCK_MTX_ASSERT(rnh_lock, LCK_MTX_ASSERT_OWNED);
1145
1146 /* Now clear the flag from all entries */
1147 ln = llinfo_nd6.ln_next;
1148 while (ln != NULL && ln != &llinfo_nd6) {
1149 struct rtentry *rt = ln->ln_rt;
1150 struct llinfo_nd6 *next = ln->ln_next;
1151
1152 RT_LOCK_SPIN(rt);
1153 if (ln->ln_flags & ND6_LNF_TIMER_SKIP) {
1154 ln->ln_flags &= ~ND6_LNF_TIMER_SKIP;
1155 }
1156 RT_UNLOCK(rt);
1157 ln = next;
1158 }
1159 }
1160
1161 static void
nd6_service_expired_default_router(struct nd6svc_arg * ap,uint64_t timenow)1162 nd6_service_expired_default_router(struct nd6svc_arg *ap, uint64_t timenow)
1163 {
1164 struct nd_defrouter *dr = NULL;
1165 struct nd_defrouter *ndr = NULL;
1166 struct nd_drhead nd_defrouter_tmp;
1167 /* expire default router list */
1168 TAILQ_INIT(&nd_defrouter_tmp);
1169
1170 LCK_MTX_ASSERT(rnh_lock, LCK_MTX_ASSERT_NOTOWNED);
1171 lck_mtx_lock(nd6_mutex);
1172
1173 TAILQ_FOREACH_SAFE(dr, &nd_defrouter_list, dr_entry, ndr) {
1174 ap->found++;
1175 if (dr->expire != 0 && dr->expire < timenow) {
1176 VERIFY(dr->ifp != NULL);
1177 in6_ifstat_inc(dr->ifp, ifs6_defrtr_expiry_cnt);
1178 if ((dr->stateflags & NDDRF_INELIGIBLE) == 0) {
1179 in6_event_enqueue_nwk_wq_entry(IN6_NDP_RTR_EXPIRY, dr->ifp,
1180 &dr->rtaddr, dr->rtlifetime);
1181 }
1182 if (dr->ifp != NULL &&
1183 dr->ifp->if_type == IFT_CELLULAR) {
1184 /*
1185 * Some buggy cellular gateways may not send
1186 * periodic router advertisements.
1187 * Or they may send it with router lifetime
1188 * value that is less than the configured Max and Min
1189 * Router Advertisement interval.
1190 * To top that an idle device may not wake up
1191 * when periodic RA is received on cellular
1192 * interface.
1193 * We could send RS on every wake but RFC
1194 * 4861 precludes that.
1195 * The addresses are of infinite lifetimes
1196 * and are tied to the lifetime of the bearer,
1197 * so keeping the addresses and just getting rid of
1198 * the router does not help us anyways.
1199 * If there's network renumbering, a lifetime with
1200 * value 0 would remove the default router.
1201 * Also it will get deleted as part of purge when
1202 * the PDP context is torn down and configured again.
1203 * For that reason, do not expire the default router
1204 * learned on cellular interface. Ever.
1205 */
1206 dr->expire += dr->rtlifetime;
1207 nd6log2(debug,
1208 "%s: Refreshing expired default router entry "
1209 "%s for interface %s\n", __func__,
1210 ip6_sprintf(&dr->rtaddr), if_name(dr->ifp));
1211 } else {
1212 ap->killed++;
1213 /*
1214 * Remove the entry from default router list
1215 * and add it to the temp list.
1216 * nd_defrouter_tmp will be a local temporary
1217 * list as no one else can get the same
1218 * removed entry once it is removed from default
1219 * router list.
1220 * Remove the reference after calling defrtrlist_del
1221 */
1222 TAILQ_REMOVE(&nd_defrouter_list, dr, dr_entry);
1223 TAILQ_INSERT_TAIL(&nd_defrouter_tmp, dr, dr_entry);
1224 }
1225 } else {
1226 if (dr->expire == 0 || (dr->stateflags & NDDRF_STATIC)) {
1227 ap->sticky++;
1228 } else {
1229 ap->aging_lazy++;
1230 }
1231 }
1232 }
1233
1234 /*
1235 * Keep the following separate from the above
1236 * iteration of nd_defrouter because it's not safe
1237 * to call defrtrlist_del while iterating global default
1238 * router list. Global list has to be traversed
1239 * while holding nd6_mutex throughout.
1240 *
1241 * The following call to defrtrlist_del should be
1242 * safe as we are iterating a local list of
1243 * default routers.
1244 */
1245 TAILQ_FOREACH_SAFE(dr, &nd_defrouter_tmp, dr_entry, ndr) {
1246 TAILQ_REMOVE(&nd_defrouter_tmp, dr, dr_entry);
1247 defrtrlist_del(dr, NULL);
1248 NDDR_REMREF(dr); /* remove list reference */
1249 }
1250
1251 /* XXX TBD: Also iterate through RTI router lists */
1252 /*
1253 * Also check if default router selection needs to be triggered
1254 * for default interface, to avoid an issue with co-existence of
1255 * static un-scoped default route configuration and default router
1256 * discovery/selection.
1257 */
1258 if (trigger_v6_defrtr_select) {
1259 defrouter_select(NULL, NULL);
1260 trigger_v6_defrtr_select = FALSE;
1261 }
1262 lck_mtx_unlock(nd6_mutex);
1263 }
1264
1265 static void
nd6_service_expired_route_info(struct nd6svc_arg * ap,uint64_t timenow)1266 nd6_service_expired_route_info(struct nd6svc_arg *ap, uint64_t timenow)
1267 {
1268 struct nd_route_info *rti = NULL;
1269 struct nd_route_info *rti_next = NULL;
1270
1271 LCK_MTX_ASSERT(rnh_lock, LCK_MTX_ASSERT_NOTOWNED);
1272 lck_mtx_lock(nd6_mutex);
1273 nd6_rti_list_wait(__func__);
1274
1275 TAILQ_FOREACH_SAFE(rti, &nd_rti_list, nd_rti_entry, rti_next) {
1276 struct nd_defrouter *dr = NULL;
1277 struct nd_defrouter *ndr = NULL;
1278 struct nd_route_info rti_tmp = {};
1279
1280 rti_tmp.nd_rti_prefix = rti->nd_rti_prefix;
1281 rti_tmp.nd_rti_prefixlen = rti->nd_rti_prefixlen;
1282 TAILQ_INIT(&rti_tmp.nd_rti_router_list);
1283
1284 TAILQ_FOREACH_SAFE(dr, &rti->nd_rti_router_list, dr_entry, ndr) {
1285 ap->found++;
1286 if (dr->expire != 0 && dr->expire < timenow) {
1287 VERIFY(dr->ifp != NULL);
1288 if (dr->ifp != NULL &&
1289 dr->ifp->if_type == IFT_CELLULAR) {
1290 /*
1291 * Don't expire these routes over cellular.
1292 * XXX Should we change this for non default routes?
1293 */
1294 dr->expire += dr->rtlifetime;
1295 nd6log2(debug,
1296 "%s: Refreshing expired default router entry "
1297 "%s for interface %s\n", __func__,
1298 ip6_sprintf(&dr->rtaddr), if_name(dr->ifp));
1299 } else {
1300 ap->killed++;
1301 /*
1302 * Remove the entry from rti entry's router list
1303 * and add it to the temp list.
1304 * Remove the reference after calling defrtrlist_del
1305 */
1306 TAILQ_REMOVE(&rti->nd_rti_router_list, dr, dr_entry);
1307 TAILQ_INSERT_TAIL(&rti_tmp.nd_rti_router_list, dr, dr_entry);
1308 }
1309 } else {
1310 if (dr->expire == 0 || (dr->stateflags & NDDRF_STATIC)) {
1311 ap->sticky++;
1312 } else {
1313 ap->aging_lazy++;
1314 }
1315 }
1316 }
1317
1318 /*
1319 * Keep the following separate from the above
1320 * iteration of nd_defrouter because it's not safe
1321 * to call defrtrlist_del while iterating global default
1322 * router list. Global list has to be traversed
1323 * while holding nd6_mutex throughout.
1324 *
1325 * The following call to defrtrlist_del should be
1326 * safe as we are iterating a local list of
1327 * default routers.
1328 */
1329 TAILQ_FOREACH_SAFE(dr, &rti_tmp.nd_rti_router_list, dr_entry, ndr) {
1330 TAILQ_REMOVE(&rti_tmp.nd_rti_router_list, dr, dr_entry);
1331 defrtrlist_del(dr, &rti->nd_rti_router_list);
1332 NDDR_REMREF(dr); /* remove list reference */
1333 }
1334
1335 /*
1336 * The above may have removed an entry from default router list.
1337 * If it did and the list is now empty, remove the rti as well.
1338 */
1339 if (TAILQ_EMPTY(&rti->nd_rti_router_list)) {
1340 TAILQ_REMOVE(&nd_rti_list, rti, nd_rti_entry);
1341 ndrti_free(rti);
1342 }
1343 }
1344
1345 LCK_MTX_ASSERT(nd6_mutex, LCK_MTX_ASSERT_OWNED);
1346 nd6_rti_list_signal_done();
1347 lck_mtx_unlock(nd6_mutex);
1348 }
1349
1350
1351 /*
1352 * @function nd6_handle_duplicated_ip6_addr
1353 *
1354 * @brief
1355 * Handle a duplicated IPv6 secured non-termporary address
1356 *
1357 * @discussion
1358 * If the collision count hasn't been exceeded, removes the old
1359 * conflicting IPv6 address, increments the collision count,
1360 * and allocates a new address.
1361 *
1362 * Returns TRUE if the old address was removed, and the locks
1363 * (in6_ifaddr_rwlock, ia6->ia_ifa) were unlocked.
1364 */
1365 static boolean_t
nd6_handle_duplicated_ip6_addr(struct in6_ifaddr * ia6)1366 nd6_handle_duplicated_ip6_addr(struct in6_ifaddr *ia6)
1367 {
1368 uint8_t collision_count;
1369 int error = 0;
1370 struct in6_ifaddr *new_ia6;
1371 struct nd_prefix *pr;
1372 struct ifnet *ifp;
1373
1374 LCK_RW_ASSERT(&in6_ifaddr_rwlock, LCK_RW_ASSERT_EXCLUSIVE);
1375 IFA_LOCK_ASSERT_HELD(&ia6->ia_ifa);
1376
1377 /* don't retry too many times */
1378 collision_count = ia6->ia6_cga_collision_count;
1379 if (collision_count >= ip6_cga_conflict_retries) {
1380 return FALSE;
1381 }
1382
1383 /* need the prefix to allocate a new address */
1384 pr = ia6->ia6_ndpr;
1385 if (pr == NULL) {
1386 return FALSE;
1387 }
1388 NDPR_ADDREF(pr);
1389 ifp = pr->ndpr_ifp;
1390 log(LOG_DEBUG,
1391 "%s: %s duplicated (collision count %d)\n",
1392 ifp->if_xname, ip6_sprintf(&ia6->ia_addr.sin6_addr),
1393 collision_count);
1394
1395 /* remove the old address */
1396 IFA_UNLOCK(&ia6->ia_ifa);
1397 lck_rw_done(&in6_ifaddr_rwlock);
1398 in6_purgeaddr(&ia6->ia_ifa);
1399
1400 /* allocate a new address with new collision count */
1401 collision_count++;
1402 new_ia6 = in6_pfx_newpersistaddr(pr, 1, &error, FALSE, collision_count);
1403 if (new_ia6 != NULL) {
1404 log(LOG_DEBUG,
1405 "%s: %s new (collision count %d)\n",
1406 ifp->if_xname, ip6_sprintf(&new_ia6->ia_addr.sin6_addr),
1407 collision_count);
1408 IFA_LOCK(&new_ia6->ia_ifa);
1409 NDPR_LOCK(pr);
1410 new_ia6->ia6_ndpr = pr;
1411 NDPR_ADDREF(pr); /* for addr reference */
1412 pr->ndpr_addrcnt++;
1413 VERIFY(pr->ndpr_addrcnt != 0);
1414 NDPR_UNLOCK(pr);
1415 IFA_UNLOCK(&new_ia6->ia_ifa);
1416 IFA_REMREF(&new_ia6->ia_ifa);
1417 } else {
1418 log(LOG_ERR, "%s: in6_pfx_newpersistaddr failed %d\n",
1419 __func__, error);
1420 }
1421
1422 /* release extra prefix reference */
1423 NDPR_REMREF(pr);
1424 return TRUE;
1425 }
1426
1427 static boolean_t
secured_address_is_duplicated(int flags)1428 secured_address_is_duplicated(int flags)
1429 {
1430 #define _IN6_IFF_DUPLICATED_AUTOCONF_SECURED \
1431 (IN6_IFF_DUPLICATED | IN6_IFF_AUTOCONF | IN6_IFF_SECURED)
1432 return (flags & _IN6_IFF_DUPLICATED_AUTOCONF_SECURED) ==
1433 _IN6_IFF_DUPLICATED_AUTOCONF_SECURED;
1434 }
1435
1436 static void
nd6_service_ip6_addr(struct nd6svc_arg * ap,uint64_t timenow)1437 nd6_service_ip6_addr(struct nd6svc_arg *ap, uint64_t timenow)
1438 {
1439 struct in6_ifaddr *ia6 = NULL;
1440 struct in6_ifaddr *nia6 = NULL;
1441 /*
1442 * expire interface addresses.
1443 * in the past the loop was inside prefix expiry processing.
1444 * However, from a stricter spec-conformance standpoint, we should
1445 * rather separate address lifetimes and prefix lifetimes.
1446 */
1447
1448 addrloop:
1449 lck_rw_lock_exclusive(&in6_ifaddr_rwlock);
1450
1451 TAILQ_FOREACH_SAFE(ia6, &in6_ifaddrhead, ia6_link, nia6) {
1452 int oldflags = ia6->ia6_flags;
1453 ap->found++;
1454 IFA_LOCK(&ia6->ia_ifa);
1455 /*
1456 * Extra reference for ourselves; it's no-op if
1457 * we don't have to regenerate temporary address,
1458 * otherwise it protects the address from going
1459 * away since we drop in6_ifaddr_rwlock below.
1460 */
1461 IFA_ADDREF_LOCKED(&ia6->ia_ifa);
1462
1463 /*
1464 * Check for duplicated secured address
1465 *
1466 * nd6_handle_duplicated_ip6_addr attempts to regenerate
1467 * secure address in the event of a collision.
1468 * On successful generation this returns success
1469 * and we restart the loop.
1470 *
1471 * When we hit the maximum attempts, this returns
1472 * false.
1473 */
1474 if (secured_address_is_duplicated(ia6->ia6_flags) &&
1475 nd6_handle_duplicated_ip6_addr(ia6)) {
1476 /*
1477 * nd6_handle_duplicated_ip6_addr() unlocked
1478 * (in6_ifaddr_rwlock, ia6->ia_ifa) already.
1479 * Still need to release extra reference on
1480 * ia6->ia_ifa taken above.
1481 */
1482 IFA_REMREF(&ia6->ia_ifa);
1483 goto addrloop;
1484 }
1485
1486 /* check address lifetime */
1487 if (IFA6_IS_INVALID(ia6, timenow)) {
1488 /*
1489 * If the expiring address is temporary, try
1490 * regenerating a new one. This would be useful when
1491 * we suspended a laptop PC, then turned it on after a
1492 * period that could invalidate all temporary
1493 * addresses. Although we may have to restart the
1494 * loop (see below), it must be after purging the
1495 * address. Otherwise, we'd see an infinite loop of
1496 * regeneration.
1497 */
1498 if (ip6_use_tempaddr &&
1499 (ia6->ia6_flags & IN6_IFF_TEMPORARY) != 0) {
1500 /*
1501 * NOTE: We have to drop the lock here
1502 * because regen_tmpaddr() eventually calls
1503 * in6_update_ifa(), which must take the lock
1504 * and would otherwise cause a hang. This is
1505 * safe because the goto addrloop leads to a
1506 * re-evaluation of the in6_ifaddrs list
1507 */
1508 IFA_UNLOCK(&ia6->ia_ifa);
1509 lck_rw_done(&in6_ifaddr_rwlock);
1510 (void) regen_tmpaddr(ia6);
1511 } else {
1512 IFA_UNLOCK(&ia6->ia_ifa);
1513 lck_rw_done(&in6_ifaddr_rwlock);
1514 }
1515
1516 /*
1517 * Purging the address would have caused
1518 * in6_ifaddr_rwlock to be dropped and reacquired;
1519 * therefore search again from the beginning
1520 * of in6_ifaddrs list.
1521 */
1522 in6_purgeaddr(&ia6->ia_ifa);
1523 ap->killed++;
1524
1525 if ((ia6->ia6_flags & IN6_IFF_TEMPORARY) == 0) {
1526 in6_ifstat_inc(ia6->ia_ifa.ifa_ifp, ifs6_addr_expiry_cnt);
1527 in6_event_enqueue_nwk_wq_entry(IN6_NDP_ADDR_EXPIRY,
1528 ia6->ia_ifa.ifa_ifp, &ia6->ia_addr.sin6_addr,
1529 0);
1530 }
1531 /* Release extra reference taken above */
1532 IFA_REMREF(&ia6->ia_ifa);
1533 goto addrloop;
1534 }
1535 /*
1536 * The lazy timer runs every nd6_prune_lazy seconds with at
1537 * most "2 * nd6_prune_lazy - 1" leeway. We consider the worst
1538 * case here and make sure we schedule the regular timer if an
1539 * interface address is about to expire.
1540 */
1541 if (IFA6_IS_INVALID(ia6, timenow + 3 * nd6_prune_lazy)) {
1542 ap->aging++;
1543 } else {
1544 ap->aging_lazy++;
1545 }
1546 IFA_LOCK_ASSERT_HELD(&ia6->ia_ifa);
1547 if (IFA6_IS_DEPRECATED(ia6, timenow)) {
1548 ia6->ia6_flags |= IN6_IFF_DEPRECATED;
1549
1550 if ((oldflags & IN6_IFF_DEPRECATED) == 0) {
1551 #if SKYWALK
1552 SK_NXS_MS_IF_ADDR_GENCNT_INC(ia6->ia_ifp);
1553 #endif /* SKYWALK */
1554 /*
1555 * Only enqueue the Deprecated event when the address just
1556 * becomes deprecated.
1557 * Keep it limited to the stable address as it is common for
1558 * older temporary addresses to get deprecated while we generate
1559 * new ones.
1560 */
1561 if ((ia6->ia6_flags & IN6_IFF_TEMPORARY) == 0) {
1562 in6_event_enqueue_nwk_wq_entry(IN6_ADDR_MARKED_DEPRECATED,
1563 ia6->ia_ifa.ifa_ifp, &ia6->ia_addr.sin6_addr,
1564 0);
1565 }
1566 }
1567 /*
1568 * If a temporary address has just become deprecated,
1569 * regenerate a new one if possible.
1570 */
1571 if (ip6_use_tempaddr &&
1572 (ia6->ia6_flags & IN6_IFF_TEMPORARY) != 0 &&
1573 (oldflags & IN6_IFF_DEPRECATED) == 0) {
1574 /* see NOTE above */
1575 IFA_UNLOCK(&ia6->ia_ifa);
1576 lck_rw_done(&in6_ifaddr_rwlock);
1577 if (regen_tmpaddr(ia6) == 0) {
1578 /*
1579 * A new temporary address is
1580 * generated.
1581 * XXX: this means the address chain
1582 * has changed while we are still in
1583 * the loop. Although the change
1584 * would not cause disaster (because
1585 * it's not a deletion, but an
1586 * addition,) we'd rather restart the
1587 * loop just for safety. Or does this
1588 * significantly reduce performance??
1589 */
1590 /* Release extra reference */
1591 IFA_REMREF(&ia6->ia_ifa);
1592 goto addrloop;
1593 }
1594 lck_rw_lock_exclusive(&in6_ifaddr_rwlock);
1595 } else {
1596 IFA_UNLOCK(&ia6->ia_ifa);
1597 }
1598 } else {
1599 /*
1600 * A new RA might have made a deprecated address
1601 * preferred.
1602 */
1603 ia6->ia6_flags &= ~IN6_IFF_DEPRECATED;
1604 #if SKYWALK
1605 if ((oldflags & IN6_IFF_DEPRECATED) != 0) {
1606 SK_NXS_MS_IF_ADDR_GENCNT_INC(ia6->ia_ifp);
1607 }
1608 #endif /* SKYWALK */
1609 IFA_UNLOCK(&ia6->ia_ifa);
1610 }
1611 LCK_RW_ASSERT(&in6_ifaddr_rwlock, LCK_RW_ASSERT_EXCLUSIVE);
1612 /* Release extra reference taken above */
1613 IFA_REMREF(&ia6->ia_ifa);
1614 }
1615 lck_rw_done(&in6_ifaddr_rwlock);
1616 }
1617
1618 static void
nd6_service_expired_prefix(struct nd6svc_arg * ap,uint64_t timenow)1619 nd6_service_expired_prefix(struct nd6svc_arg *ap, uint64_t timenow)
1620 {
1621 struct nd_prefix *pr = NULL;
1622
1623 LCK_MTX_ASSERT(rnh_lock, LCK_MTX_ASSERT_NOTOWNED);
1624 lck_mtx_lock(nd6_mutex);
1625 /* expire prefix list */
1626 pr = nd_prefix.lh_first;
1627 while (pr != NULL) {
1628 ap->found++;
1629 /*
1630 * Skip already processed or defunct prefixes
1631 * We may iterate the prefix list from head again
1632 * so, we are trying to not revisit the same prefix
1633 * for the same instance of nd6_service
1634 */
1635 NDPR_LOCK(pr);
1636 if (pr->ndpr_stateflags & NDPRF_PROCESSED_SERVICE ||
1637 pr->ndpr_stateflags & NDPRF_DEFUNCT) {
1638 pr->ndpr_stateflags |= NDPRF_PROCESSED_SERVICE;
1639 NDPR_UNLOCK(pr);
1640 pr = pr->ndpr_next;
1641 continue;
1642 }
1643
1644 /*
1645 * If there are still manual addresses configured in the system
1646 * that are associated with the prefix, ignore prefix expiry
1647 */
1648 if (pr->ndpr_manual_addrcnt != 0) {
1649 pr->ndpr_stateflags |= NDPRF_PROCESSED_SERVICE;
1650 NDPR_UNLOCK(pr);
1651 pr = pr->ndpr_next;
1652 continue;
1653 }
1654
1655 /*
1656 * check prefix lifetime.
1657 * since pltime is just for autoconf, pltime processing for
1658 * prefix is not necessary.
1659 */
1660 if (pr->ndpr_expire != 0 && pr->ndpr_expire < timenow) {
1661 /*
1662 * address expiration and prefix expiration are
1663 * separate. NEVER perform in6_purgeaddr here.
1664 */
1665 pr->ndpr_stateflags |= NDPRF_PROCESSED_SERVICE;
1666 NDPR_ADDREF(pr);
1667 prelist_remove(pr);
1668 NDPR_UNLOCK(pr);
1669
1670 in6_ifstat_inc(pr->ndpr_ifp, ifs6_pfx_expiry_cnt);
1671 in6_event_enqueue_nwk_wq_entry(IN6_NDP_PFX_EXPIRY,
1672 pr->ndpr_ifp, &pr->ndpr_prefix.sin6_addr,
1673 0);
1674 NDPR_REMREF(pr);
1675 pfxlist_onlink_check();
1676 pr = nd_prefix.lh_first;
1677 ap->killed++;
1678 } else {
1679 if (pr->ndpr_expire == 0 ||
1680 (pr->ndpr_stateflags & NDPRF_STATIC)) {
1681 ap->sticky++;
1682 } else {
1683 ap->aging_lazy++;
1684 }
1685 pr->ndpr_stateflags |= NDPRF_PROCESSED_SERVICE;
1686 NDPR_UNLOCK(pr);
1687 pr = pr->ndpr_next;
1688 }
1689 }
1690 LIST_FOREACH(pr, &nd_prefix, ndpr_entry) {
1691 NDPR_LOCK(pr);
1692 pr->ndpr_stateflags &= ~NDPRF_PROCESSED_SERVICE;
1693 NDPR_UNLOCK(pr);
1694 }
1695 lck_mtx_unlock(nd6_mutex);
1696 }
1697
1698
1699 /*
1700 * ND6 service routine to expire default route list and prefix list
1701 */
1702 static void
nd6_service(void * arg)1703 nd6_service(void *arg)
1704 {
1705 struct nd6svc_arg *ap = arg;
1706 uint64_t timenow;
1707
1708 LCK_MTX_ASSERT(rnh_lock, LCK_MTX_ASSERT_OWNED);
1709 /*
1710 * Since we may drop rnh_lock and nd6_mutex below, we want
1711 * to run this entire operation single threaded.
1712 */
1713 while (nd6_service_busy) {
1714 nd6log2(debug, "%s: %s is blocked by %d waiters\n",
1715 __func__, ap->draining ? "drainer" : "timer",
1716 nd6_service_waiters);
1717 nd6_service_waiters++;
1718 (void) msleep(nd6_service_wc, rnh_lock, (PZERO - 1),
1719 __func__, NULL);
1720 LCK_MTX_ASSERT(rnh_lock, LCK_MTX_ASSERT_OWNED);
1721 }
1722
1723 /* We are busy now; tell everyone else to go away */
1724 nd6_service_busy = TRUE;
1725 net_update_uptime();
1726 timenow = net_uptime();
1727
1728 /* Iterate and service neighbor cache entries */
1729 nd6_service_neighbor_cache(ap, timenow);
1730
1731 /*
1732 * There is lock ordering requirement and rnh_lock
1733 * has to be released before acquiring nd6_mutex.
1734 */
1735 lck_mtx_unlock(rnh_lock);
1736
1737 /* Iterate and service expired default router */
1738 nd6_service_expired_default_router(ap, timenow);
1739 /* Iterate and service expired route information entries */
1740 nd6_service_expired_route_info(ap, timenow);
1741
1742 /* Iterate and service expired/duplicated IPv6 address */
1743 nd6_service_ip6_addr(ap, timenow);
1744
1745 /* Iterate and service expired IPv6 prefixes */
1746 nd6_service_expired_prefix(ap, timenow);
1747
1748 lck_mtx_lock(rnh_lock);
1749 /* We're done; let others enter */
1750 nd6_service_busy = FALSE;
1751 if (nd6_service_waiters > 0) {
1752 nd6_service_waiters = 0;
1753 wakeup(nd6_service_wc);
1754 }
1755 }
1756
1757 static int nd6_need_draining = 0;
1758
1759 void
nd6_drain(void * arg)1760 nd6_drain(void *arg)
1761 {
1762 #pragma unused(arg)
1763 nd6log2(debug, "%s: draining ND6 entries\n", __func__);
1764
1765 lck_mtx_lock(rnh_lock);
1766 nd6_need_draining = 1;
1767 nd6_sched_timeout(NULL, NULL);
1768 lck_mtx_unlock(rnh_lock);
1769 }
1770
1771 /*
1772 * We use the ``arg'' variable to decide whether or not the timer we're
1773 * running is the fast timer. We do this to reset the nd6_fast_timer_on
1774 * variable so that later we don't end up ignoring a ``fast timer''
1775 * request if the 5 second timer is running (see nd6_sched_timeout).
1776 */
1777 static void
nd6_timeout(void * arg)1778 nd6_timeout(void *arg)
1779 {
1780 struct nd6svc_arg sarg;
1781 uint32_t buf;
1782
1783 lck_mtx_lock(rnh_lock);
1784 bzero(&sarg, sizeof(sarg));
1785 if (nd6_need_draining != 0) {
1786 nd6_need_draining = 0;
1787 sarg.draining = 1;
1788 }
1789 nd6_service(&sarg);
1790 nd6log2(debug, "%s: found %u, aging_lazy %u, aging %u, "
1791 "sticky %u, killed %u\n", __func__, sarg.found, sarg.aging_lazy,
1792 sarg.aging, sarg.sticky, sarg.killed);
1793 /* re-arm the timer if there's work to do */
1794 nd6_timeout_run--;
1795 VERIFY(nd6_timeout_run >= 0 && nd6_timeout_run < 2);
1796 if (arg == &nd6_fast_timer_on) {
1797 nd6_fast_timer_on = FALSE;
1798 }
1799 if (sarg.aging_lazy > 0 || sarg.aging > 0 || nd6_sched_timeout_want) {
1800 struct timeval atv, ltv, *leeway;
1801 int lazy = nd6_prune_lazy;
1802
1803 if (sarg.aging > 0 || lazy < 1) {
1804 atv.tv_usec = 0;
1805 atv.tv_sec = nd6_prune;
1806 leeway = NULL;
1807 } else {
1808 VERIFY(lazy >= 1);
1809 atv.tv_usec = 0;
1810 atv.tv_sec = MAX(nd6_prune, lazy);
1811 ltv.tv_usec = 0;
1812 read_frandom(&buf, sizeof(buf));
1813 ltv.tv_sec = MAX(buf % lazy, 1) * 2;
1814 leeway = <v;
1815 }
1816 nd6_sched_timeout(&atv, leeway);
1817 } else if (nd6_debug) {
1818 nd6log2(debug, "%s: not rescheduling timer\n", __func__);
1819 }
1820 lck_mtx_unlock(rnh_lock);
1821 }
1822
1823 void
nd6_sched_timeout(struct timeval * atv,struct timeval * ltv)1824 nd6_sched_timeout(struct timeval *atv, struct timeval *ltv)
1825 {
1826 struct timeval tv;
1827
1828 LCK_MTX_ASSERT(rnh_lock, LCK_MTX_ASSERT_OWNED);
1829 if (atv == NULL) {
1830 tv.tv_usec = 0;
1831 tv.tv_sec = MAX(nd6_prune, 1);
1832 atv = &tv;
1833 ltv = NULL; /* ignore leeway */
1834 }
1835 /* see comments on top of this file */
1836 if (nd6_timeout_run == 0) {
1837 if (ltv == NULL) {
1838 nd6log2(debug, "%s: timer scheduled in "
1839 "T+%llus.%lluu (demand %d)\n", __func__,
1840 (uint64_t)atv->tv_sec, (uint64_t)atv->tv_usec,
1841 nd6_sched_timeout_want);
1842 nd6_fast_timer_on = TRUE;
1843 timeout(nd6_timeout, &nd6_fast_timer_on, tvtohz(atv));
1844 } else {
1845 nd6log2(debug, "%s: timer scheduled in "
1846 "T+%llus.%lluu with %llus.%lluu leeway "
1847 "(demand %d)\n", __func__, (uint64_t)atv->tv_sec,
1848 (uint64_t)atv->tv_usec, (uint64_t)ltv->tv_sec,
1849 (uint64_t)ltv->tv_usec, nd6_sched_timeout_want);
1850 nd6_fast_timer_on = FALSE;
1851 timeout_with_leeway(nd6_timeout, NULL,
1852 tvtohz(atv), tvtohz(ltv));
1853 }
1854 nd6_timeout_run++;
1855 nd6_sched_timeout_want = 0;
1856 } else if (nd6_timeout_run == 1 && ltv == NULL &&
1857 nd6_fast_timer_on == FALSE) {
1858 nd6log2(debug, "%s: fast timer scheduled in "
1859 "T+%llus.%lluu (demand %d)\n", __func__,
1860 (uint64_t)atv->tv_sec, (uint64_t)atv->tv_usec,
1861 nd6_sched_timeout_want);
1862 nd6_fast_timer_on = TRUE;
1863 nd6_sched_timeout_want = 0;
1864 nd6_timeout_run++;
1865 timeout(nd6_timeout, &nd6_fast_timer_on, tvtohz(atv));
1866 } else {
1867 if (ltv == NULL) {
1868 nd6log2(debug, "%s: not scheduling timer: "
1869 "timers %d, fast_timer %d, T+%llus.%lluu\n",
1870 __func__, nd6_timeout_run, nd6_fast_timer_on,
1871 (uint64_t)atv->tv_sec, (uint64_t)atv->tv_usec);
1872 } else {
1873 nd6log2(debug, "%s: not scheduling timer: "
1874 "timers %d, fast_timer %d, T+%llus.%lluu "
1875 "with %llus.%lluu leeway\n", __func__,
1876 nd6_timeout_run, nd6_fast_timer_on,
1877 (uint64_t)atv->tv_sec, (uint64_t)atv->tv_usec,
1878 (uint64_t)ltv->tv_sec, (uint64_t)ltv->tv_usec);
1879 }
1880 }
1881 }
1882
1883 /*
1884 * ND6 router advertisement kernel notification
1885 */
1886 void
nd6_post_msg(u_int32_t code,struct nd_prefix_list * prefix_list,u_int32_t list_length,u_int32_t mtu)1887 nd6_post_msg(u_int32_t code, struct nd_prefix_list *prefix_list,
1888 u_int32_t list_length, u_int32_t mtu)
1889 {
1890 struct kev_msg ev_msg;
1891 struct kev_nd6_ra_data nd6_ra_msg_data;
1892 struct nd_prefix_list *itr = prefix_list;
1893
1894 bzero(&ev_msg, sizeof(struct kev_msg));
1895 ev_msg.vendor_code = KEV_VENDOR_APPLE;
1896 ev_msg.kev_class = KEV_NETWORK_CLASS;
1897 ev_msg.kev_subclass = KEV_ND6_SUBCLASS;
1898 ev_msg.event_code = code;
1899
1900 bzero(&nd6_ra_msg_data, sizeof(nd6_ra_msg_data));
1901
1902 if (mtu > 0 && mtu >= IPV6_MMTU) {
1903 nd6_ra_msg_data.mtu = mtu;
1904 nd6_ra_msg_data.flags |= KEV_ND6_DATA_VALID_MTU;
1905 }
1906
1907 if (list_length > 0 && prefix_list != NULL) {
1908 nd6_ra_msg_data.list_length = list_length;
1909 nd6_ra_msg_data.flags |= KEV_ND6_DATA_VALID_PREFIX;
1910 }
1911
1912 while (itr != NULL && nd6_ra_msg_data.list_index < list_length) {
1913 bcopy(&itr->pr.ndpr_prefix, &nd6_ra_msg_data.prefix.prefix,
1914 sizeof(nd6_ra_msg_data.prefix.prefix));
1915 nd6_ra_msg_data.prefix.raflags = itr->pr.ndpr_raf;
1916 nd6_ra_msg_data.prefix.prefixlen = itr->pr.ndpr_plen;
1917 nd6_ra_msg_data.prefix.origin = PR_ORIG_RA;
1918 nd6_ra_msg_data.prefix.vltime = itr->pr.ndpr_vltime;
1919 nd6_ra_msg_data.prefix.pltime = itr->pr.ndpr_pltime;
1920 nd6_ra_msg_data.prefix.expire = ndpr_getexpire(&itr->pr);
1921 nd6_ra_msg_data.prefix.flags = itr->pr.ndpr_stateflags;
1922 nd6_ra_msg_data.prefix.refcnt = itr->pr.ndpr_addrcnt;
1923 nd6_ra_msg_data.prefix.if_index = itr->pr.ndpr_ifp->if_index;
1924
1925 /* send the message up */
1926 ev_msg.dv[0].data_ptr = &nd6_ra_msg_data;
1927 ev_msg.dv[0].data_length = sizeof(nd6_ra_msg_data);
1928 ev_msg.dv[1].data_length = 0;
1929 dlil_post_complete_msg(NULL, &ev_msg);
1930
1931 /* clean up for the next prefix */
1932 bzero(&nd6_ra_msg_data.prefix, sizeof(nd6_ra_msg_data.prefix));
1933 itr = itr->next;
1934 nd6_ra_msg_data.list_index++;
1935 }
1936 }
1937
1938 /*
1939 * Regenerate deprecated/invalidated temporary address
1940 */
1941 static int
regen_tmpaddr(struct in6_ifaddr * ia6)1942 regen_tmpaddr(struct in6_ifaddr *ia6)
1943 {
1944 struct ifaddr *ifa;
1945 struct ifnet *ifp;
1946 struct in6_ifaddr *public_ifa6 = NULL;
1947 uint64_t timenow = net_uptime();
1948
1949 ifp = ia6->ia_ifa.ifa_ifp;
1950 ifnet_lock_shared(ifp);
1951 TAILQ_FOREACH(ifa, &ifp->if_addrlist, ifa_list) {
1952 struct in6_ifaddr *it6;
1953
1954 IFA_LOCK(ifa);
1955 if (ifa->ifa_addr->sa_family != AF_INET6) {
1956 IFA_UNLOCK(ifa);
1957 continue;
1958 }
1959 it6 = (struct in6_ifaddr *)ifa;
1960
1961 /* ignore no autoconf addresses. */
1962 if ((it6->ia6_flags & IN6_IFF_AUTOCONF) == 0) {
1963 IFA_UNLOCK(ifa);
1964 continue;
1965 }
1966 /* ignore autoconf addresses with different prefixes. */
1967 if (it6->ia6_ndpr == NULL || it6->ia6_ndpr != ia6->ia6_ndpr) {
1968 IFA_UNLOCK(ifa);
1969 continue;
1970 }
1971 /*
1972 * Now we are looking at an autoconf address with the same
1973 * prefix as ours. If the address is temporary and is still
1974 * preferred, do not create another one. It would be rare, but
1975 * could happen, for example, when we resume a laptop PC after
1976 * a long period.
1977 */
1978 if ((it6->ia6_flags & IN6_IFF_TEMPORARY) != 0 &&
1979 !IFA6_IS_DEPRECATED(it6, timenow)) {
1980 IFA_UNLOCK(ifa);
1981 if (public_ifa6 != NULL) {
1982 IFA_REMREF(&public_ifa6->ia_ifa);
1983 }
1984 public_ifa6 = NULL;
1985 break;
1986 }
1987
1988 /*
1989 * This is a public autoconf address that has the same prefix
1990 * as ours. If it is preferred, keep it. We can't break the
1991 * loop here, because there may be a still-preferred temporary
1992 * address with the prefix.
1993 */
1994 if (!IFA6_IS_DEPRECATED(it6, timenow)) {
1995 IFA_ADDREF_LOCKED(ifa); /* for public_ifa6 */
1996 IFA_UNLOCK(ifa);
1997 if (public_ifa6 != NULL) {
1998 IFA_REMREF(&public_ifa6->ia_ifa);
1999 }
2000 public_ifa6 = it6;
2001 } else {
2002 IFA_UNLOCK(ifa);
2003 }
2004 }
2005 ifnet_lock_done(ifp);
2006
2007 if (public_ifa6 != NULL) {
2008 int e;
2009
2010 if ((e = in6_tmpifadd(public_ifa6, 0)) != 0) {
2011 log(LOG_NOTICE, "regen_tmpaddr: failed to create a new"
2012 " tmp addr,errno=%d\n", e);
2013 IFA_REMREF(&public_ifa6->ia_ifa);
2014 return -1;
2015 }
2016 IFA_REMREF(&public_ifa6->ia_ifa);
2017 return 0;
2018 }
2019
2020 return -1;
2021 }
2022
2023 static void
nd6_purge_interface_default_routers(struct ifnet * ifp)2024 nd6_purge_interface_default_routers(struct ifnet *ifp)
2025 {
2026 struct nd_defrouter *dr = NULL;
2027 struct nd_defrouter *ndr = NULL;
2028 struct nd_drhead nd_defrouter_tmp = {};
2029
2030 TAILQ_INIT(&nd_defrouter_tmp);
2031
2032 LCK_MTX_ASSERT(nd6_mutex, LCK_MTX_ASSERT_OWNED);
2033
2034 TAILQ_FOREACH_SAFE(dr, &nd_defrouter_list, dr_entry, ndr) {
2035 if (dr->ifp != ifp) {
2036 continue;
2037 }
2038 /*
2039 * Remove the entry from default router list
2040 * and add it to the temp list.
2041 * nd_defrouter_tmp will be a local temporary
2042 * list as no one else can get the same
2043 * removed entry once it is removed from default
2044 * router list.
2045 * Remove the reference after calling defrtrlist_del.
2046 *
2047 * The uninstalled entries have to be iterated first
2048 * when we call defrtrlist_del.
2049 * This is to ensure that we don't end up calling
2050 * default router selection when there are other
2051 * uninstalled candidate default routers on
2052 * the interface.
2053 * If we don't respect that order, we may end
2054 * up missing out on some entries.
2055 *
2056 * For that reason, installed ones must be inserted
2057 * at the tail and uninstalled ones at the head
2058 */
2059 TAILQ_REMOVE(&nd_defrouter_list, dr, dr_entry);
2060
2061 if (dr->stateflags & NDDRF_INSTALLED) {
2062 TAILQ_INSERT_TAIL(&nd_defrouter_tmp, dr, dr_entry);
2063 } else {
2064 TAILQ_INSERT_HEAD(&nd_defrouter_tmp, dr, dr_entry);
2065 }
2066 }
2067
2068 /*
2069 * The following call to defrtrlist_del should be
2070 * safe as we are iterating a local list of
2071 * default routers.
2072 *
2073 * We don't really need nd6_mutex here but keeping
2074 * it as it is to avoid changing assertios held in
2075 * the functions in the call-path.
2076 */
2077 TAILQ_FOREACH_SAFE(dr, &nd_defrouter_tmp, dr_entry, ndr) {
2078 TAILQ_REMOVE(&nd_defrouter_tmp, dr, dr_entry);
2079 defrtrlist_del(dr, NULL);
2080 NDDR_REMREF(dr); /* remove list reference */
2081 }
2082 }
2083
2084 static void
nd6_purge_interface_prefixes(struct ifnet * ifp)2085 nd6_purge_interface_prefixes(struct ifnet *ifp)
2086 {
2087 boolean_t removed = FALSE;
2088 struct nd_prefix *pr = NULL;
2089 struct nd_prefix *npr = NULL;
2090
2091 LCK_MTX_ASSERT(nd6_mutex, LCK_MTX_ASSERT_OWNED);
2092
2093 /* Nuke prefix list entries toward ifp */
2094 for (pr = nd_prefix.lh_first; pr; pr = npr) {
2095 NDPR_LOCK(pr);
2096 npr = pr->ndpr_next;
2097 if (pr->ndpr_ifp == ifp &&
2098 !(pr->ndpr_stateflags & NDPRF_DEFUNCT)) {
2099 /*
2100 * Because if_detach() does *not* release prefixes
2101 * while purging addresses the reference count will
2102 * still be above zero. We therefore reset it to
2103 * make sure that the prefix really gets purged.
2104 */
2105 pr->ndpr_addrcnt = 0;
2106
2107 /*
2108 * Previously, pr->ndpr_addr is removed as well,
2109 * but I strongly believe we don't have to do it.
2110 * nd6_purge() is only called from in6_ifdetach(),
2111 * which removes all the associated interface addresses
2112 * by itself.
2113 * ([email protected] 20010129)
2114 */
2115 NDPR_ADDREF(pr);
2116 prelist_remove(pr);
2117 NDPR_UNLOCK(pr);
2118 NDPR_REMREF(pr);
2119 removed = TRUE;
2120 npr = nd_prefix.lh_first;
2121 } else {
2122 NDPR_UNLOCK(pr);
2123 }
2124 }
2125 if (removed) {
2126 pfxlist_onlink_check();
2127 }
2128 }
2129
2130 static void
nd6_router_select_rti_entries(struct ifnet * ifp)2131 nd6_router_select_rti_entries(struct ifnet *ifp)
2132 {
2133 struct nd_route_info *rti = NULL;
2134 struct nd_route_info *rti_next = NULL;
2135
2136 nd6_rti_list_wait(__func__);
2137
2138 TAILQ_FOREACH_SAFE(rti, &nd_rti_list, nd_rti_entry, rti_next) {
2139 defrouter_select(ifp, &rti->nd_rti_router_list);
2140 }
2141
2142 nd6_rti_list_signal_done();
2143 }
2144
2145 static void
nd6_purge_interface_rti_entries(struct ifnet * ifp)2146 nd6_purge_interface_rti_entries(struct ifnet *ifp)
2147 {
2148 struct nd_route_info *rti = NULL;
2149 struct nd_route_info *rti_next = NULL;
2150
2151 nd6_rti_list_wait(__func__);
2152
2153 TAILQ_FOREACH_SAFE(rti, &nd_rti_list, nd_rti_entry, rti_next) {
2154 struct nd_route_info rti_tmp = {};
2155 struct nd_defrouter *dr = NULL;
2156 struct nd_defrouter *ndr = NULL;
2157
2158 rti_tmp.nd_rti_prefix = rti->nd_rti_prefix;
2159 rti_tmp.nd_rti_prefixlen = rti->nd_rti_prefixlen;
2160 TAILQ_INIT(&rti_tmp.nd_rti_router_list);
2161
2162 TAILQ_FOREACH_SAFE(dr, &rti->nd_rti_router_list, dr_entry, ndr) {
2163 /*
2164 * If ifp is provided, skip the entries that don't match.
2165 * Else it is treated as a purge.
2166 */
2167 if (ifp != NULL && dr->ifp != ifp) {
2168 continue;
2169 }
2170
2171 /*
2172 * Remove the entry from rti's router list
2173 * and add it to the temp list.
2174 * Remove the reference after calling defrtrlist_del.
2175 *
2176 * The uninstalled entries have to be iterated first
2177 * when we call defrtrlist_del.
2178 * This is to ensure that we don't end up calling
2179 * router selection when there are other
2180 * uninstalled candidate default routers on
2181 * the interface.
2182 * If we don't respect that order, we may end
2183 * up missing out on some entries.
2184 *
2185 * For that reason, installed ones must be inserted
2186 * at the tail and uninstalled ones at the head
2187 */
2188
2189 TAILQ_REMOVE(&rti->nd_rti_router_list, dr, dr_entry);
2190 if (dr->stateflags & NDDRF_INSTALLED) {
2191 TAILQ_INSERT_TAIL(&rti_tmp.nd_rti_router_list, dr, dr_entry);
2192 } else {
2193 TAILQ_INSERT_HEAD(&rti_tmp.nd_rti_router_list, dr, dr_entry);
2194 }
2195 }
2196
2197 /*
2198 * The following call to defrtrlist_del should be
2199 * safe as we are iterating a local list of
2200 * routers.
2201 *
2202 * We don't really need nd6_mutex here but keeping
2203 * it as it is to avoid changing assertios held in
2204 * the functions in the call-path.
2205 */
2206 TAILQ_FOREACH_SAFE(dr, &rti_tmp.nd_rti_router_list, dr_entry, ndr) {
2207 TAILQ_REMOVE(&rti_tmp.nd_rti_router_list, dr, dr_entry);
2208 defrtrlist_del(dr, &rti->nd_rti_router_list);
2209 NDDR_REMREF(dr); /* remove list reference */
2210 }
2211 /*
2212 * The above may have removed an entry from default router list.
2213 * If it did and the list is now empty, remove the rti as well.
2214 */
2215 if (TAILQ_EMPTY(&rti->nd_rti_router_list)) {
2216 TAILQ_REMOVE(&nd_rti_list, rti, nd_rti_entry);
2217 ndrti_free(rti);
2218 }
2219 }
2220
2221 nd6_rti_list_signal_done();
2222 }
2223
2224 static void
nd6_purge_interface_llinfo(struct ifnet * ifp)2225 nd6_purge_interface_llinfo(struct ifnet *ifp)
2226 {
2227 struct llinfo_nd6 *ln = NULL;
2228 /* Note that rt->rt_ifp may not be the same as ifp,
2229 * due to KAME goto ours hack. See RTM_RESOLVE case in
2230 * nd6_rtrequest(), and ip6_input().
2231 */
2232 again:
2233 lck_mtx_lock(rnh_lock);
2234 ln = llinfo_nd6.ln_next;
2235 while (ln != NULL && ln != &llinfo_nd6) {
2236 struct rtentry *rt;
2237 struct llinfo_nd6 *nln;
2238
2239 nln = ln->ln_next;
2240 rt = ln->ln_rt;
2241 RT_LOCK(rt);
2242 if (rt->rt_gateway != NULL &&
2243 rt->rt_gateway->sa_family == AF_LINK &&
2244 SDL(rt->rt_gateway)->sdl_index == ifp->if_index) {
2245 RT_ADDREF_LOCKED(rt);
2246 RT_UNLOCK(rt);
2247 lck_mtx_unlock(rnh_lock);
2248 /*
2249 * See comments on nd6_service() for reasons why
2250 * this loop is repeated; we bite the costs of
2251 * going thru the same llinfo_nd6 more than once
2252 * here, since this purge happens during detach,
2253 * and that unlike the timer case, it's possible
2254 * there's more than one purges happening at the
2255 * same time (thus a flag wouldn't buy anything).
2256 */
2257 nd6_free(rt);
2258 RT_REMREF(rt);
2259 LCK_MTX_ASSERT(rnh_lock, LCK_MTX_ASSERT_NOTOWNED);
2260 goto again;
2261 } else {
2262 RT_UNLOCK(rt);
2263 }
2264 ln = nln;
2265 }
2266 lck_mtx_unlock(rnh_lock);
2267 }
2268
2269 /*
2270 * Nuke neighbor cache/prefix/default router management table, right before
2271 * ifp goes away.
2272 */
2273 void
nd6_purge(struct ifnet * ifp)2274 nd6_purge(struct ifnet *ifp)
2275 {
2276 LCK_MTX_ASSERT(rnh_lock, LCK_MTX_ASSERT_NOTOWNED);
2277 lck_mtx_lock(nd6_mutex);
2278
2279 /* Nuke default router list entries toward ifp */
2280 nd6_purge_interface_default_routers(ifp);
2281
2282 /* Nuke prefix list entries toward ifp */
2283 nd6_purge_interface_prefixes(ifp);
2284
2285 /* Nuke route info option entries toward ifp */
2286 nd6_purge_interface_rti_entries(ifp);
2287
2288 lck_mtx_unlock(nd6_mutex);
2289
2290 /* cancel default outgoing interface setting */
2291 if (nd6_defifindex == ifp->if_index) {
2292 nd6_setdefaultiface(0);
2293 }
2294
2295 /*
2296 * Perform default router selection even when we are a router,
2297 * if Scoped Routing is enabled.
2298 * XXX ?Should really not be needed since when defrouter_select
2299 * was changed to work on interface.
2300 */
2301 lck_mtx_lock(nd6_mutex);
2302 /* refresh default router list */
2303 defrouter_select(ifp, NULL);
2304 lck_mtx_unlock(nd6_mutex);
2305
2306 /* Nuke neighbor cache entries for the ifp. */
2307 nd6_purge_interface_llinfo(ifp);
2308 }
2309
2310 /*
2311 * Upon success, the returned route will be locked and the caller is
2312 * responsible for releasing the reference and doing RT_UNLOCK(rt).
2313 * This routine does not require rnh_lock to be held by the caller,
2314 * although it needs to be indicated of such a case in order to call
2315 * the correct variant of the relevant routing routines.
2316 */
2317 struct rtentry *
nd6_lookup(struct in6_addr * addr6,int create,struct ifnet * ifp,int rt_locked)2318 nd6_lookup(struct in6_addr *addr6, int create, struct ifnet *ifp, int rt_locked)
2319 {
2320 struct rtentry *rt;
2321 struct sockaddr_in6 sin6;
2322 unsigned int ifscope;
2323
2324 bzero(&sin6, sizeof(sin6));
2325 sin6.sin6_len = sizeof(struct sockaddr_in6);
2326 sin6.sin6_family = AF_INET6;
2327 sin6.sin6_addr = *addr6;
2328
2329 ifscope = (ifp != NULL) ? ifp->if_index : IFSCOPE_NONE;
2330 if (rt_locked) {
2331 LCK_MTX_ASSERT(rnh_lock, LCK_MTX_ASSERT_OWNED);
2332 rt = rtalloc1_scoped_locked(SA(&sin6), create, 0, ifscope);
2333 } else {
2334 rt = rtalloc1_scoped(SA(&sin6), create, 0, ifscope);
2335 }
2336
2337 if (rt != NULL) {
2338 RT_LOCK(rt);
2339 if ((rt->rt_flags & RTF_LLINFO) == 0) {
2340 /*
2341 * This is the case for the default route.
2342 * If we want to create a neighbor cache for the
2343 * address, we should free the route for the
2344 * destination and allocate an interface route.
2345 */
2346 if (create) {
2347 RT_UNLOCK(rt);
2348 if (rt_locked) {
2349 rtfree_locked(rt);
2350 } else {
2351 rtfree(rt);
2352 }
2353 rt = NULL;
2354 }
2355 }
2356 }
2357 if (rt == NULL) {
2358 if (create && ifp) {
2359 struct ifaddr *ifa;
2360 u_int32_t ifa_flags;
2361 int e;
2362
2363 /*
2364 * If no route is available and create is set,
2365 * we allocate a host route for the destination
2366 * and treat it like an interface route.
2367 * This hack is necessary for a neighbor which can't
2368 * be covered by our own prefix.
2369 */
2370 ifa = ifaof_ifpforaddr(SA(&sin6), ifp);
2371 if (ifa == NULL) {
2372 return NULL;
2373 }
2374
2375 /*
2376 * Create a new route. RTF_LLINFO is necessary
2377 * to create a Neighbor Cache entry for the
2378 * destination in nd6_rtrequest which will be
2379 * called in rtrequest via ifa->ifa_rtrequest.
2380 */
2381 if (!rt_locked) {
2382 lck_mtx_lock(rnh_lock);
2383 }
2384 IFA_LOCK_SPIN(ifa);
2385 ifa_flags = ifa->ifa_flags;
2386 IFA_UNLOCK(ifa);
2387 if ((e = rtrequest_scoped_locked(RTM_ADD,
2388 SA(&sin6), ifa->ifa_addr, SA(&all1_sa),
2389 (ifa_flags | RTF_HOST | RTF_LLINFO) &
2390 ~RTF_CLONING, &rt, ifscope)) != 0) {
2391 if (e != EEXIST) {
2392 log(LOG_ERR, "%s: failed to add route "
2393 "for a neighbor(%s), errno=%d\n",
2394 __func__, ip6_sprintf(addr6), e);
2395 }
2396 }
2397 if (!rt_locked) {
2398 lck_mtx_unlock(rnh_lock);
2399 }
2400 IFA_REMREF(ifa);
2401 if (rt == NULL) {
2402 return NULL;
2403 }
2404
2405 RT_LOCK(rt);
2406 if (rt->rt_llinfo) {
2407 struct llinfo_nd6 *ln = rt->rt_llinfo;
2408 boolean_t nud_enabled = FALSE;
2409
2410 /*
2411 * The IPv6 initialization of the loopback interface
2412 * may happen after another interface gets assigned
2413 * an IPv6 address.
2414 * To avoid asserting treat local routes as special
2415 * case.
2416 */
2417 if (rt->rt_ifp != lo_ifp) {
2418 struct nd_ifinfo *ndi = ND_IFINFO(rt->rt_ifp);
2419 VERIFY((NULL != ndi) && (TRUE == ndi->initialized));
2420 nud_enabled = !!(ndi->flags & ND6_IFF_PERFORMNUD);
2421 }
2422
2423 /*
2424 * For interface's that do not perform NUD
2425 * neighbor cache entres must always be marked
2426 * reachable with no expiry
2427 */
2428 if (nud_enabled) {
2429 ND6_CACHE_STATE_TRANSITION(ln, ND6_LLINFO_NOSTATE);
2430 } else {
2431 ND6_CACHE_STATE_TRANSITION(ln, ND6_LLINFO_REACHABLE);
2432 ln_setexpire(ln, 0);
2433 }
2434 }
2435 } else {
2436 return NULL;
2437 }
2438 }
2439 RT_LOCK_ASSERT_HELD(rt);
2440 /*
2441 * Validation for the entry.
2442 * Note that the check for rt_llinfo is necessary because a cloned
2443 * route from a parent route that has the L flag (e.g. the default
2444 * route to a p2p interface) may have the flag, too, while the
2445 * destination is not actually a neighbor.
2446 * XXX: we can't use rt->rt_ifp to check for the interface, since
2447 * it might be the loopback interface if the entry is for our
2448 * own address on a non-loopback interface. Instead, we should
2449 * use rt->rt_ifa->ifa_ifp, which would specify the REAL
2450 * interface.
2451 * Note also that ifa_ifp and ifp may differ when we connect two
2452 * interfaces to a same link, install a link prefix to an interface,
2453 * and try to install a neighbor cache on an interface that does not
2454 * have a route to the prefix.
2455 *
2456 * If the address is from a proxied prefix, the ifa_ifp and ifp might
2457 * not match, because nd6_na_input() could have modified the ifp
2458 * of the route to point to the interface where the NA arrived on,
2459 * hence the test for RTF_PROXY.
2460 */
2461 if ((rt->rt_flags & RTF_GATEWAY) || (rt->rt_flags & RTF_LLINFO) == 0 ||
2462 rt->rt_gateway->sa_family != AF_LINK || rt->rt_llinfo == NULL ||
2463 (ifp && rt->rt_ifa->ifa_ifp != ifp &&
2464 !(rt->rt_flags & RTF_PROXY))) {
2465 RT_REMREF_LOCKED(rt);
2466 RT_UNLOCK(rt);
2467 if (create) {
2468 log(LOG_DEBUG, "%s: failed to lookup %s "
2469 "(if = %s)\n", __func__, ip6_sprintf(addr6),
2470 ifp ? if_name(ifp) : "unspec");
2471 /* xxx more logs... kazu */
2472 }
2473 return NULL;
2474 }
2475 /*
2476 * Caller needs to release reference and call RT_UNLOCK(rt).
2477 */
2478 return rt;
2479 }
2480
2481 /*
2482 * Test whether a given IPv6 address is a neighbor or not, ignoring
2483 * the actual neighbor cache. The neighbor cache is ignored in order
2484 * to not reenter the routing code from within itself.
2485 */
2486 static int
nd6_is_new_addr_neighbor(struct sockaddr_in6 * addr,struct ifnet * ifp)2487 nd6_is_new_addr_neighbor(struct sockaddr_in6 *addr, struct ifnet *ifp)
2488 {
2489 struct nd_prefix *pr;
2490 struct ifaddr *dstaddr;
2491
2492 LCK_MTX_ASSERT(nd6_mutex, LCK_MTX_ASSERT_OWNED);
2493
2494 /*
2495 * A link-local address is always a neighbor.
2496 * XXX: a link does not necessarily specify a single interface.
2497 */
2498 if (IN6_IS_ADDR_LINKLOCAL(&addr->sin6_addr)) {
2499 struct sockaddr_in6 sin6_copy;
2500 u_int32_t zone;
2501
2502 /*
2503 * We need sin6_copy since sa6_recoverscope() may modify the
2504 * content (XXX).
2505 */
2506 sin6_copy = *addr;
2507 if (sa6_recoverscope(&sin6_copy, FALSE)) {
2508 return 0; /* XXX: should be impossible */
2509 }
2510 if (in6_setscope(&sin6_copy.sin6_addr, ifp, &zone)) {
2511 return 0;
2512 }
2513 if (sin6_copy.sin6_scope_id == zone) {
2514 return 1;
2515 } else {
2516 return 0;
2517 }
2518 }
2519
2520 /*
2521 * If the address matches one of our addresses,
2522 * it should be a neighbor.
2523 * If the address matches one of our on-link prefixes, it should be a
2524 * neighbor.
2525 */
2526 for (pr = nd_prefix.lh_first; pr; pr = pr->ndpr_next) {
2527 NDPR_LOCK(pr);
2528 if (pr->ndpr_ifp != ifp) {
2529 NDPR_UNLOCK(pr);
2530 continue;
2531 }
2532 if (!(pr->ndpr_stateflags & NDPRF_ONLINK)) {
2533 NDPR_UNLOCK(pr);
2534 continue;
2535 }
2536 if (in6_are_masked_addr_scope_equal(&pr->ndpr_prefix.sin6_addr, pr->ndpr_prefix.sin6_scope_id,
2537 &addr->sin6_addr, addr->sin6_scope_id, &pr->ndpr_mask)) {
2538 NDPR_UNLOCK(pr);
2539 return 1;
2540 }
2541 NDPR_UNLOCK(pr);
2542 }
2543
2544 /*
2545 * If the address is assigned on the node of the other side of
2546 * a p2p interface, the address should be a neighbor.
2547 */
2548 dstaddr = ifa_ifwithdstaddr(SA(addr));
2549 if (dstaddr != NULL) {
2550 if (dstaddr->ifa_ifp == ifp) {
2551 IFA_REMREF(dstaddr);
2552 return 1;
2553 }
2554 IFA_REMREF(dstaddr);
2555 dstaddr = NULL;
2556 }
2557
2558 return 0;
2559 }
2560
2561
2562 /*
2563 * Detect if a given IPv6 address identifies a neighbor on a given link.
2564 * XXX: should take care of the destination of a p2p link?
2565 */
2566 int
nd6_is_addr_neighbor(struct sockaddr_in6 * addr,struct ifnet * ifp,int rt_locked)2567 nd6_is_addr_neighbor(struct sockaddr_in6 *addr, struct ifnet *ifp,
2568 int rt_locked)
2569 {
2570 struct rtentry *rt;
2571
2572 LCK_MTX_ASSERT(nd6_mutex, LCK_MTX_ASSERT_NOTOWNED);
2573 lck_mtx_lock(nd6_mutex);
2574 if (nd6_is_new_addr_neighbor(addr, ifp)) {
2575 lck_mtx_unlock(nd6_mutex);
2576 return 1;
2577 }
2578 lck_mtx_unlock(nd6_mutex);
2579
2580 /*
2581 * Even if the address matches none of our addresses, it might be
2582 * in the neighbor cache.
2583 */
2584 if ((rt = nd6_lookup(&addr->sin6_addr, 0, ifp, rt_locked)) != NULL) {
2585 RT_LOCK_ASSERT_HELD(rt);
2586 RT_REMREF_LOCKED(rt);
2587 RT_UNLOCK(rt);
2588 return 1;
2589 }
2590
2591 return 0;
2592 }
2593
2594 /*
2595 * Free an nd6 llinfo entry.
2596 * Since the function would cause significant changes in the kernel, DO NOT
2597 * make it global, unless you have a strong reason for the change, and are sure
2598 * that the change is safe.
2599 */
2600 void
nd6_free(struct rtentry * rt)2601 nd6_free(struct rtentry *rt)
2602 {
2603 struct llinfo_nd6 *ln = NULL;
2604 struct in6_addr in6 = {};
2605 struct nd_defrouter *dr = NULL;
2606
2607 LCK_MTX_ASSERT(rnh_lock, LCK_MTX_ASSERT_NOTOWNED);
2608 RT_LOCK_ASSERT_NOTHELD(rt);
2609 lck_mtx_lock(nd6_mutex);
2610
2611 RT_LOCK(rt);
2612 RT_ADDREF_LOCKED(rt); /* Extra ref */
2613 ln = rt->rt_llinfo;
2614 in6 = SIN6(rt_key(rt))->sin6_addr;
2615
2616 /*
2617 * Prevent another thread from modifying rt_key, rt_gateway
2618 * via rt_setgate() after the rt_lock is dropped by marking
2619 * the route as defunct.
2620 */
2621 rt->rt_flags |= RTF_CONDEMNED;
2622
2623 /*
2624 * We used to have pfctlinput(PRC_HOSTDEAD) here. Even though it is
2625 * not harmful, it was not really necessary. Perform default router
2626 * selection even when we are a router, if Scoped Routing is enabled.
2627 */
2628 /* XXX TDB Handle lists in route information option as well */
2629 dr = defrouter_lookup(NULL, &SIN6(rt_key(rt))->sin6_addr, rt->rt_ifp);
2630
2631 if ((ln && ln->ln_router) || dr) {
2632 /*
2633 * rt6_flush must be called whether or not the neighbor
2634 * is in the Default Router List.
2635 * See a corresponding comment in nd6_na_input().
2636 */
2637 RT_UNLOCK(rt);
2638 lck_mtx_unlock(nd6_mutex);
2639 rt6_flush(&in6, rt->rt_ifp);
2640 lck_mtx_lock(nd6_mutex);
2641 } else {
2642 RT_UNLOCK(rt);
2643 }
2644
2645 if (dr) {
2646 NDDR_REMREF(dr);
2647 /*
2648 * Unreachablity of a router might affect the default
2649 * router selection and on-link detection of advertised
2650 * prefixes.
2651 */
2652
2653 /*
2654 * Temporarily fake the state to choose a new default
2655 * router and to perform on-link determination of
2656 * prefixes correctly.
2657 * Below the state will be set correctly,
2658 * or the entry itself will be deleted.
2659 */
2660 RT_LOCK_SPIN(rt);
2661 ND6_CACHE_STATE_TRANSITION(ln, ND6_LLINFO_INCOMPLETE);
2662
2663 /*
2664 * Since defrouter_select() does not affect the
2665 * on-link determination and MIP6 needs the check
2666 * before the default router selection, we perform
2667 * the check now.
2668 */
2669 RT_UNLOCK(rt);
2670 pfxlist_onlink_check();
2671
2672 /*
2673 * refresh default router list
2674 */
2675 defrouter_select(rt->rt_ifp, NULL);
2676
2677 /* Loop through all RTI's as well and trigger router selection. */
2678 nd6_router_select_rti_entries(rt->rt_ifp);
2679 }
2680 RT_LOCK_ASSERT_NOTHELD(rt);
2681 lck_mtx_unlock(nd6_mutex);
2682 /*
2683 * Detach the route from the routing tree and the list of neighbor
2684 * caches, and disable the route entry not to be used in already
2685 * cached routes.
2686 */
2687 (void) rtrequest(RTM_DELETE, rt_key(rt), NULL, rt_mask(rt), 0, NULL);
2688
2689 /* Extra ref held above; now free it */
2690 rtfree(rt);
2691 }
2692
2693 void
nd6_rtrequest(int req,struct rtentry * rt,struct sockaddr * sa)2694 nd6_rtrequest(int req, struct rtentry *rt, struct sockaddr *sa)
2695 {
2696 #pragma unused(sa)
2697 struct sockaddr *gate = rt->rt_gateway;
2698 struct llinfo_nd6 *ln = rt->rt_llinfo;
2699 static struct sockaddr_dl null_sdl =
2700 { .sdl_len = sizeof(null_sdl), .sdl_family = AF_LINK };
2701 struct ifnet *ifp = rt->rt_ifp;
2702 struct ifaddr *ifa;
2703 uint64_t timenow;
2704 char buf[MAX_IPv6_STR_LEN];
2705 boolean_t nud_enabled = FALSE;
2706
2707 /*
2708 * The IPv6 initialization of the loopback interface
2709 * may happen after another interface gets assigned
2710 * an IPv6 address.
2711 * To avoid asserting treat local routes as special
2712 * case.
2713 */
2714 if (rt->rt_ifp != lo_ifp) {
2715 struct nd_ifinfo *ndi = ND_IFINFO(rt->rt_ifp);
2716 VERIFY((NULL != ndi) && (TRUE == ndi->initialized));
2717 nud_enabled = !!(ndi->flags & ND6_IFF_PERFORMNUD);
2718 }
2719
2720 VERIFY(nd6_init_done);
2721 LCK_MTX_ASSERT(rnh_lock, LCK_MTX_ASSERT_OWNED);
2722 RT_LOCK_ASSERT_HELD(rt);
2723
2724 /*
2725 * We have rnh_lock held, see if we need to schedule the timer;
2726 * we might do this again below during RTM_RESOLVE, but doing it
2727 * now handles all other cases.
2728 */
2729 if (nd6_sched_timeout_want) {
2730 nd6_sched_timeout(NULL, NULL);
2731 }
2732
2733 if (rt->rt_flags & RTF_GATEWAY) {
2734 return;
2735 }
2736
2737 if (!nd6_need_cache(ifp) && !(rt->rt_flags & RTF_HOST)) {
2738 /*
2739 * This is probably an interface direct route for a link
2740 * which does not need neighbor caches (e.g. fe80::%lo0/64).
2741 * We do not need special treatment below for such a route.
2742 * Moreover, the RTF_LLINFO flag which would be set below
2743 * would annoy the ndp(8) command.
2744 */
2745 return;
2746 }
2747
2748 if (req == RTM_RESOLVE) {
2749 int no_nd_cache;
2750
2751 if (!nd6_need_cache(ifp)) { /* stf case */
2752 no_nd_cache = 1;
2753 } else {
2754 struct sockaddr_in6 sin6;
2755
2756 rtkey_to_sa6(rt, &sin6);
2757 /*
2758 * nd6_is_addr_neighbor() may call nd6_lookup(),
2759 * therefore we drop rt_lock to avoid deadlock
2760 * during the lookup.
2761 */
2762 RT_ADDREF_LOCKED(rt);
2763 RT_UNLOCK(rt);
2764 no_nd_cache = !nd6_is_addr_neighbor(&sin6, ifp, 1);
2765 RT_LOCK(rt);
2766 RT_REMREF_LOCKED(rt);
2767 }
2768
2769 /*
2770 * FreeBSD and BSD/OS often make a cloned host route based
2771 * on a less-specific route (e.g. the default route).
2772 * If the less specific route does not have a "gateway"
2773 * (this is the case when the route just goes to a p2p or an
2774 * stf interface), we'll mistakenly make a neighbor cache for
2775 * the host route, and will see strange neighbor solicitation
2776 * for the corresponding destination. In order to avoid the
2777 * confusion, we check if the destination of the route is
2778 * a neighbor in terms of neighbor discovery, and stop the
2779 * process if not. Additionally, we remove the LLINFO flag
2780 * so that ndp(8) will not try to get the neighbor information
2781 * of the destination.
2782 */
2783 if (no_nd_cache) {
2784 rt->rt_flags &= ~RTF_LLINFO;
2785 return;
2786 }
2787 }
2788
2789 timenow = net_uptime();
2790
2791 switch (req) {
2792 case RTM_ADD:
2793 /*
2794 * There is no backward compatibility :)
2795 *
2796 * if ((rt->rt_flags & RTF_HOST) == 0 &&
2797 * SIN(rt_mask(rt))->sin_addr.s_addr != 0xffffffff)
2798 * rt->rt_flags |= RTF_CLONING;
2799 */
2800 if ((rt->rt_flags & RTF_CLONING) ||
2801 ((rt->rt_flags & RTF_LLINFO) && ln == NULL)) {
2802 /*
2803 * Case 1: This route should come from a route to
2804 * interface (RTF_CLONING case) or the route should be
2805 * treated as on-link but is currently not
2806 * (RTF_LLINFO && ln == NULL case).
2807 */
2808 if (rt_setgate(rt, rt_key(rt), SA(&null_sdl)) == 0) {
2809 gate = rt->rt_gateway;
2810 SDL(gate)->sdl_type = ifp->if_type;
2811 SDL(gate)->sdl_index = ifp->if_index;
2812 /*
2813 * In case we're called before 1.0 sec.
2814 * has elapsed.
2815 */
2816 if (ln != NULL) {
2817 ln_setexpire(ln,
2818 (ifp->if_eflags & IFEF_IPV6_ND6ALT)
2819 ? 0 : MAX(timenow, 1));
2820 }
2821 }
2822 if (rt->rt_flags & RTF_CLONING) {
2823 break;
2824 }
2825 }
2826 /*
2827 * In IPv4 code, we try to annonuce new RTF_ANNOUNCE entry here.
2828 * We don't do that here since llinfo is not ready yet.
2829 *
2830 * There are also couple of other things to be discussed:
2831 * - unsolicited NA code needs improvement beforehand
2832 * - RFC4861 says we MAY send multicast unsolicited NA
2833 * (7.2.6 paragraph 4), however, it also says that we
2834 * SHOULD provide a mechanism to prevent multicast NA storm.
2835 * we don't have anything like it right now.
2836 * note that the mechanism needs a mutual agreement
2837 * between proxies, which means that we need to implement
2838 * a new protocol, or a new kludge.
2839 * - from RFC4861 6.2.4, host MUST NOT send an unsolicited RA.
2840 * we need to check ip6forwarding before sending it.
2841 * (or should we allow proxy ND configuration only for
2842 * routers? there's no mention about proxy ND from hosts)
2843 */
2844 OS_FALLTHROUGH;
2845 case RTM_RESOLVE:
2846 if (!(ifp->if_flags & (IFF_POINTOPOINT | IFF_LOOPBACK))) {
2847 /*
2848 * Address resolution isn't necessary for a point to
2849 * point link, so we can skip this test for a p2p link.
2850 */
2851 if (gate->sa_family != AF_LINK ||
2852 gate->sa_len < sizeof(null_sdl)) {
2853 /* Don't complain in case of RTM_ADD */
2854 if (req == RTM_RESOLVE) {
2855 log(LOG_ERR, "%s: route to %s has bad "
2856 "gateway address (sa_family %u "
2857 "sa_len %u) on %s\n", __func__,
2858 inet_ntop(AF_INET6,
2859 &SIN6(rt_key(rt))->sin6_addr, buf,
2860 sizeof(buf)), gate->sa_family,
2861 gate->sa_len, if_name(ifp));
2862 }
2863 break;
2864 }
2865 SDL(gate)->sdl_type = ifp->if_type;
2866 SDL(gate)->sdl_index = ifp->if_index;
2867 }
2868 if (ln != NULL) {
2869 break; /* This happens on a route change */
2870 }
2871 /*
2872 * Case 2: This route may come from cloning, or a manual route
2873 * add with a LL address.
2874 */
2875 rt->rt_llinfo = ln = nd6_llinfo_alloc(Z_WAITOK);
2876
2877 nd6_allocated++;
2878 rt->rt_llinfo_get_ri = nd6_llinfo_get_ri;
2879 rt->rt_llinfo_get_iflri = nd6_llinfo_get_iflri;
2880 rt->rt_llinfo_purge = nd6_llinfo_purge;
2881 rt->rt_llinfo_free = nd6_llinfo_free;
2882 rt->rt_llinfo_refresh = nd6_llinfo_refresh;
2883 rt->rt_flags |= RTF_LLINFO;
2884 ln->ln_rt = rt;
2885 /* this is required for "ndp" command. - shin */
2886 /*
2887 * For interface's that do not perform NUD
2888 * neighbor cache entries must always be marked
2889 * reachable with no expiry
2890 */
2891 if ((req == RTM_ADD) || !nud_enabled) {
2892 /*
2893 * gate should have some valid AF_LINK entry,
2894 * and ln->ln_expire should have some lifetime
2895 * which is specified by ndp command.
2896 */
2897 ND6_CACHE_STATE_TRANSITION(ln, ND6_LLINFO_REACHABLE);
2898 ln_setexpire(ln, 0);
2899 } else {
2900 /*
2901 * When req == RTM_RESOLVE, rt is created and
2902 * initialized in rtrequest(), so rt_expire is 0.
2903 */
2904 ND6_CACHE_STATE_TRANSITION(ln, ND6_LLINFO_NOSTATE);
2905 /* In case we're called before 1.0 sec. has elapsed */
2906 ln_setexpire(ln, (ifp->if_eflags & IFEF_IPV6_ND6ALT) ?
2907 0 : MAX(timenow, 1));
2908 }
2909 LN_INSERTHEAD(ln);
2910 nd6_inuse++;
2911
2912 /* We have at least one entry; arm the timer if not already */
2913 nd6_sched_timeout(NULL, NULL);
2914
2915 /*
2916 * If we have too many cache entries, initiate immediate
2917 * purging for some "less recently used" entries. Note that
2918 * we cannot directly call nd6_free() here because it would
2919 * cause re-entering rtable related routines triggering an LOR
2920 * problem.
2921 */
2922 if (ip6_neighborgcthresh > 0 &&
2923 nd6_inuse >= ip6_neighborgcthresh) {
2924 int i;
2925
2926 for (i = 0; i < 10 && llinfo_nd6.ln_prev != ln; i++) {
2927 struct llinfo_nd6 *ln_end = llinfo_nd6.ln_prev;
2928 struct rtentry *rt_end = ln_end->ln_rt;
2929
2930 /* Move this entry to the head */
2931 RT_LOCK(rt_end);
2932 LN_DEQUEUE(ln_end);
2933 LN_INSERTHEAD(ln_end);
2934
2935 if (ln_end->ln_expire == 0) {
2936 RT_UNLOCK(rt_end);
2937 continue;
2938 }
2939 if (ln_end->ln_state > ND6_LLINFO_INCOMPLETE) {
2940 ND6_CACHE_STATE_TRANSITION(ln_end, ND6_LLINFO_STALE);
2941 } else {
2942 ND6_CACHE_STATE_TRANSITION(ln_end, ND6_LLINFO_PURGE);
2943 }
2944 ln_setexpire(ln_end, timenow);
2945 RT_UNLOCK(rt_end);
2946 }
2947 }
2948
2949 /*
2950 * check if rt_key(rt) is one of my address assigned
2951 * to the interface.
2952 */
2953 ifa = (struct ifaddr *)in6ifa_ifpwithaddr(rt->rt_ifp,
2954 &SIN6(rt_key(rt))->sin6_addr);
2955 if (ifa != NULL) {
2956 caddr_t macp = nd6_ifptomac(ifp);
2957 ln_setexpire(ln, 0);
2958 ND6_CACHE_STATE_TRANSITION(ln, ND6_LLINFO_REACHABLE);
2959 if (macp != NULL) {
2960 Bcopy(macp, LLADDR(SDL(gate)), ifp->if_addrlen);
2961 SDL(gate)->sdl_alen = ifp->if_addrlen;
2962 }
2963 if (nd6_useloopback) {
2964 if (rt->rt_ifp != lo_ifp) {
2965 /*
2966 * Purge any link-layer info caching.
2967 */
2968 if (rt->rt_llinfo_purge != NULL) {
2969 rt->rt_llinfo_purge(rt);
2970 }
2971
2972 /*
2973 * Adjust route ref count for the
2974 * interfaces.
2975 */
2976 if (rt->rt_if_ref_fn != NULL) {
2977 rt->rt_if_ref_fn(lo_ifp, 1);
2978 rt->rt_if_ref_fn(rt->rt_ifp,
2979 -1);
2980 }
2981 }
2982 rt->rt_ifp = lo_ifp;
2983 /*
2984 * If rmx_mtu is not locked, update it
2985 * to the MTU used by the new interface.
2986 */
2987 if (!(rt->rt_rmx.rmx_locks & RTV_MTU)) {
2988 rt->rt_rmx.rmx_mtu = rt->rt_ifp->if_mtu;
2989 }
2990 /*
2991 * Make sure rt_ifa be equal to the ifaddr
2992 * corresponding to the address.
2993 * We need this because when we refer
2994 * rt_ifa->ia6_flags in ip6_input, we assume
2995 * that the rt_ifa points to the address instead
2996 * of the loopback address.
2997 */
2998 if (ifa != rt->rt_ifa) {
2999 rtsetifa(rt, ifa);
3000 }
3001 }
3002 IFA_REMREF(ifa);
3003 } else if (rt->rt_flags & RTF_ANNOUNCE) {
3004 ln_setexpire(ln, 0);
3005 ND6_CACHE_STATE_TRANSITION(ln, ND6_LLINFO_REACHABLE);
3006
3007 /* join solicited node multicast for proxy ND */
3008 if (ifp->if_flags & IFF_MULTICAST) {
3009 struct in6_addr llsol;
3010 struct in6_multi *in6m;
3011 int error;
3012
3013 llsol = SIN6(rt_key(rt))->sin6_addr;
3014 llsol.s6_addr32[0] = IPV6_ADDR_INT32_MLL;
3015 llsol.s6_addr32[1] = 0;
3016 llsol.s6_addr32[2] = htonl(1);
3017 llsol.s6_addr8[12] = 0xff;
3018 if (in6_setscope(&llsol, ifp, NULL)) {
3019 break;
3020 }
3021 error = in6_mc_join(ifp, &llsol,
3022 NULL, &in6m, 0);
3023 if (error) {
3024 nd6log(error, "%s: failed to join "
3025 "%s (errno=%d)\n", if_name(ifp),
3026 ip6_sprintf(&llsol), error);
3027 } else {
3028 IN6M_REMREF(in6m);
3029 }
3030 }
3031 }
3032 break;
3033
3034 case RTM_DELETE:
3035 if (ln == NULL) {
3036 break;
3037 }
3038 /* leave from solicited node multicast for proxy ND */
3039 if ((rt->rt_flags & RTF_ANNOUNCE) &&
3040 (ifp->if_flags & IFF_MULTICAST)) {
3041 struct in6_addr llsol;
3042 struct in6_multi *in6m;
3043
3044 llsol = SIN6(rt_key(rt))->sin6_addr;
3045 llsol.s6_addr32[0] = IPV6_ADDR_INT32_MLL;
3046 llsol.s6_addr32[1] = 0;
3047 llsol.s6_addr32[2] = htonl(1);
3048 llsol.s6_addr8[12] = 0xff;
3049 if (in6_setscope(&llsol, ifp, NULL) == 0) {
3050 in6_multihead_lock_shared();
3051 IN6_LOOKUP_MULTI(&llsol, ifp, in6m);
3052 in6_multihead_lock_done();
3053 if (in6m != NULL) {
3054 in6_mc_leave(in6m, NULL);
3055 IN6M_REMREF(in6m);
3056 }
3057 }
3058 }
3059 nd6_inuse--;
3060 /*
3061 * Unchain it but defer the actual freeing until the route
3062 * itself is to be freed. rt->rt_llinfo still points to
3063 * llinfo_nd6, and likewise, ln->ln_rt stil points to this
3064 * route entry, except that RTF_LLINFO is now cleared.
3065 */
3066 if (ln->ln_flags & ND6_LNF_IN_USE) {
3067 LN_DEQUEUE(ln);
3068 }
3069
3070 /*
3071 * Purge any link-layer info caching.
3072 */
3073 if (rt->rt_llinfo_purge != NULL) {
3074 rt->rt_llinfo_purge(rt);
3075 }
3076
3077 rt->rt_flags &= ~RTF_LLINFO;
3078 if (ln->ln_hold != NULL) {
3079 m_freem_list(ln->ln_hold);
3080 ln->ln_hold = NULL;
3081 }
3082 }
3083 }
3084
3085 static int
nd6_siocgdrlst(void * data,int data_is_64)3086 nd6_siocgdrlst(void *data, int data_is_64)
3087 {
3088 struct in6_drlist_32 *drl_32;
3089 struct nd_defrouter *dr;
3090 int i = 0;
3091
3092 LCK_MTX_ASSERT(nd6_mutex, LCK_MTX_ASSERT_OWNED);
3093
3094 dr = TAILQ_FIRST(&nd_defrouter_list);
3095
3096 /* XXX Handle mapped defrouter entries */
3097 /* For 64-bit process */
3098 if (data_is_64) {
3099 struct in6_drlist_64 *drl_64;
3100
3101 drl_64 = kalloc_type(struct in6_drlist_64,
3102 Z_WAITOK | Z_ZERO | Z_NOFAIL);
3103
3104 /* preserve the interface name */
3105 bcopy(data, drl_64, sizeof(drl_64->ifname));
3106
3107 while (dr && i < DRLSTSIZ) {
3108 drl_64->defrouter[i].rtaddr = dr->rtaddr;
3109 if (IN6_IS_ADDR_LINKLOCAL(
3110 &drl_64->defrouter[i].rtaddr)) {
3111 /* XXX: need to this hack for KAME stack */
3112 drl_64->defrouter[i].rtaddr.s6_addr16[1] = 0;
3113 } else {
3114 log(LOG_ERR,
3115 "default router list contains a "
3116 "non-linklocal address(%s)\n",
3117 ip6_sprintf(&drl_64->defrouter[i].rtaddr));
3118 }
3119 drl_64->defrouter[i].flags = dr->flags;
3120 drl_64->defrouter[i].rtlifetime = (u_short)dr->rtlifetime;
3121 drl_64->defrouter[i].expire = (u_long)nddr_getexpire(dr);
3122 drl_64->defrouter[i].if_index = dr->ifp->if_index;
3123 i++;
3124 dr = TAILQ_NEXT(dr, dr_entry);
3125 }
3126 bcopy(drl_64, data, sizeof(*drl_64));
3127 kfree_type(struct in6_drlist_64, drl_64);
3128 return 0;
3129 }
3130
3131 /* For 32-bit process */
3132 drl_32 = kalloc_type(struct in6_drlist_32, Z_WAITOK | Z_ZERO | Z_NOFAIL);
3133
3134 /* preserve the interface name */
3135 bcopy(data, drl_32, sizeof(drl_32->ifname));
3136
3137 while (dr != NULL && i < DRLSTSIZ) {
3138 drl_32->defrouter[i].rtaddr = dr->rtaddr;
3139 if (IN6_IS_ADDR_LINKLOCAL(&drl_32->defrouter[i].rtaddr)) {
3140 /* XXX: need to this hack for KAME stack */
3141 drl_32->defrouter[i].rtaddr.s6_addr16[1] = 0;
3142 } else {
3143 log(LOG_ERR,
3144 "default router list contains a "
3145 "non-linklocal address(%s)\n",
3146 ip6_sprintf(&drl_32->defrouter[i].rtaddr));
3147 }
3148 drl_32->defrouter[i].flags = dr->flags;
3149 drl_32->defrouter[i].rtlifetime = (u_short)dr->rtlifetime;
3150 drl_32->defrouter[i].expire = (u_int32_t)nddr_getexpire(dr);
3151 drl_32->defrouter[i].if_index = dr->ifp->if_index;
3152 i++;
3153 dr = TAILQ_NEXT(dr, dr_entry);
3154 }
3155 bcopy(drl_32, data, sizeof(*drl_32));
3156 kfree_type(struct in6_drlist_32, drl_32);
3157 return 0;
3158 }
3159
3160 /*
3161 * XXX meaning of fields, especialy "raflags", is very
3162 * differnet between RA prefix list and RR/static prefix list.
3163 * how about separating ioctls into two?
3164 */
3165 static int
nd6_siocgprlst(void * data,int data_is_64)3166 nd6_siocgprlst(void *data, int data_is_64)
3167 {
3168 struct in6_prlist_32 *prl_32;
3169 struct nd_prefix *pr;
3170 int i = 0;
3171
3172 LCK_MTX_ASSERT(nd6_mutex, LCK_MTX_ASSERT_OWNED);
3173
3174 pr = nd_prefix.lh_first;
3175
3176 /* XXX Handle mapped defrouter entries */
3177 /* For 64-bit process */
3178 if (data_is_64) {
3179 struct in6_prlist_64 *prl_64;
3180
3181 prl_64 = kalloc_type(struct in6_prlist_64,
3182 Z_WAITOK | Z_ZERO | Z_NOFAIL);
3183
3184 /* preserve the interface name */
3185 bcopy(data, prl_64, sizeof(prl_64->ifname));
3186
3187 while (pr && i < PRLSTSIZ) {
3188 struct nd_pfxrouter *pfr;
3189 int j;
3190 uint32_t ifscope;
3191
3192 NDPR_LOCK(pr);
3193 (void) in6_embedscope(&prl_64->prefix[i].prefix,
3194 &pr->ndpr_prefix, NULL, NULL, NULL, &ifscope);
3195 prl_64->prefix[i].prefix.s6_addr16[1] = htons((uint16_t)ifscope);
3196 prl_64->prefix[i].raflags = pr->ndpr_raf;
3197 prl_64->prefix[i].prefixlen = pr->ndpr_plen;
3198 prl_64->prefix[i].vltime = pr->ndpr_vltime;
3199 prl_64->prefix[i].pltime = pr->ndpr_pltime;
3200 prl_64->prefix[i].if_index = pr->ndpr_ifp->if_index;
3201 prl_64->prefix[i].expire = (u_long)ndpr_getexpire(pr);
3202
3203 pfr = pr->ndpr_advrtrs.lh_first;
3204 j = 0;
3205 while (pfr) {
3206 if (j < DRLSTSIZ) {
3207 #define RTRADDR prl_64->prefix[i].advrtr[j]
3208 RTRADDR = pfr->router->rtaddr;
3209 if (IN6_IS_ADDR_LINKLOCAL(&RTRADDR)) {
3210 /* XXX: hack for KAME */
3211 RTRADDR.s6_addr16[1] = 0;
3212 } else {
3213 log(LOG_ERR,
3214 "a router(%s) advertises "
3215 "a prefix with "
3216 "non-link local address\n",
3217 ip6_sprintf(&RTRADDR));
3218 }
3219 #undef RTRADDR
3220 }
3221 j++;
3222 pfr = pfr->pfr_next;
3223 }
3224 ASSERT(j <= USHRT_MAX);
3225 prl_64->prefix[i].advrtrs = (u_short)j;
3226 prl_64->prefix[i].origin = PR_ORIG_RA;
3227 NDPR_UNLOCK(pr);
3228
3229 i++;
3230 pr = pr->ndpr_next;
3231 }
3232 bcopy(prl_64, data, sizeof(*prl_64));
3233 kfree_type(struct in6_prlist_64, prl_64);
3234 return 0;
3235 }
3236
3237 /* For 32-bit process */
3238 prl_32 = kalloc_type(struct in6_prlist_32, Z_WAITOK | Z_ZERO | Z_NOFAIL);
3239
3240 /* preserve the interface name */
3241 bcopy(data, prl_32, sizeof(prl_32->ifname));
3242
3243 while (pr && i < PRLSTSIZ) {
3244 struct nd_pfxrouter *pfr;
3245 int j;
3246 uint32_t ifscope;
3247
3248 NDPR_LOCK(pr);
3249 (void) in6_embedscope(&prl_32->prefix[i].prefix,
3250 &pr->ndpr_prefix, NULL, NULL, NULL, &ifscope);
3251 prl_32->prefix[i].prefix.s6_addr16[1] = htons((uint16_t)ifscope);
3252 prl_32->prefix[i].raflags = pr->ndpr_raf;
3253 prl_32->prefix[i].prefixlen = pr->ndpr_plen;
3254 prl_32->prefix[i].vltime = pr->ndpr_vltime;
3255 prl_32->prefix[i].pltime = pr->ndpr_pltime;
3256 prl_32->prefix[i].if_index = pr->ndpr_ifp->if_index;
3257 prl_32->prefix[i].expire = (u_int32_t)ndpr_getexpire(pr);
3258
3259 pfr = pr->ndpr_advrtrs.lh_first;
3260 j = 0;
3261 while (pfr) {
3262 if (j < DRLSTSIZ) {
3263 #define RTRADDR prl_32->prefix[i].advrtr[j]
3264 RTRADDR = pfr->router->rtaddr;
3265 if (IN6_IS_ADDR_LINKLOCAL(&RTRADDR)) {
3266 /* XXX: hack for KAME */
3267 RTRADDR.s6_addr16[1] = 0;
3268 } else {
3269 log(LOG_ERR,
3270 "a router(%s) advertises "
3271 "a prefix with "
3272 "non-link local address\n",
3273 ip6_sprintf(&RTRADDR));
3274 }
3275 #undef RTRADDR
3276 }
3277 j++;
3278 pfr = pfr->pfr_next;
3279 }
3280 ASSERT(j <= USHRT_MAX);
3281 prl_32->prefix[i].advrtrs = (u_short)j;
3282 prl_32->prefix[i].origin = PR_ORIG_RA;
3283 NDPR_UNLOCK(pr);
3284
3285 i++;
3286 pr = pr->ndpr_next;
3287 }
3288 bcopy(prl_32, data, sizeof(*prl_32));
3289 kfree_type(struct in6_prlist_32, prl_32);
3290 return 0;
3291 }
3292
3293 int
nd6_ioctl(u_long cmd,caddr_t data,struct ifnet * ifp)3294 nd6_ioctl(u_long cmd, caddr_t data, struct ifnet *ifp)
3295 {
3296 struct nd_defrouter *dr;
3297 struct nd_prefix *pr;
3298 struct rtentry *rt;
3299 int error = 0;
3300
3301 VERIFY(ifp != NULL);
3302
3303 switch (cmd) {
3304 case SIOCGDRLST_IN6_32: /* struct in6_drlist_32 */
3305 case SIOCGDRLST_IN6_64: /* struct in6_drlist_64 */
3306 /*
3307 * obsolete API, use sysctl under net.inet6.icmp6
3308 */
3309 lck_mtx_lock(nd6_mutex);
3310 error = nd6_siocgdrlst(data, cmd == SIOCGDRLST_IN6_64);
3311 lck_mtx_unlock(nd6_mutex);
3312 break;
3313
3314 case SIOCGPRLST_IN6_32: /* struct in6_prlist_32 */
3315 case SIOCGPRLST_IN6_64: /* struct in6_prlist_64 */
3316 /*
3317 * obsolete API, use sysctl under net.inet6.icmp6
3318 */
3319 lck_mtx_lock(nd6_mutex);
3320 error = nd6_siocgprlst(data, cmd == SIOCGPRLST_IN6_64);
3321 lck_mtx_unlock(nd6_mutex);
3322 break;
3323
3324 case OSIOCGIFINFO_IN6: /* struct in6_ondireq */
3325 case SIOCGIFINFO_IN6: { /* struct in6_ondireq */
3326 u_int32_t linkmtu;
3327 struct in6_ondireq *ondi = (struct in6_ondireq *)(void *)data;
3328 struct nd_ifinfo *ndi;
3329 /*
3330 * SIOCGIFINFO_IN6 ioctl is encoded with in6_ondireq
3331 * instead of in6_ndireq, so we treat it as such.
3332 */
3333 ndi = ND_IFINFO(ifp);
3334 if ((NULL == ndi) || (FALSE == ndi->initialized)) {
3335 error = EINVAL;
3336 break;
3337 }
3338 lck_mtx_lock(&ndi->lock);
3339 linkmtu = IN6_LINKMTU(ifp);
3340 bcopy(&linkmtu, &ondi->ndi.linkmtu, sizeof(linkmtu));
3341 bcopy(&ndi->maxmtu, &ondi->ndi.maxmtu,
3342 sizeof(u_int32_t));
3343 bcopy(&ndi->basereachable, &ondi->ndi.basereachable,
3344 sizeof(u_int32_t));
3345 bcopy(&ndi->reachable, &ondi->ndi.reachable,
3346 sizeof(u_int32_t));
3347 bcopy(&ndi->retrans, &ondi->ndi.retrans,
3348 sizeof(u_int32_t));
3349 bcopy(&ndi->flags, &ondi->ndi.flags,
3350 sizeof(u_int32_t));
3351 bcopy(&ndi->recalctm, &ondi->ndi.recalctm,
3352 sizeof(int));
3353 ondi->ndi.chlim = ndi->chlim;
3354 /*
3355 * The below truncation is fine as we mostly use it for
3356 * debugging purpose.
3357 */
3358 ondi->ndi.receivedra = (uint8_t)ndi->ndefrouters;
3359 ondi->ndi.collision_count = (uint8_t)ndi->cga_collision_count;
3360 lck_mtx_unlock(&ndi->lock);
3361 break;
3362 }
3363
3364 case SIOCSIFINFO_FLAGS: { /* struct in6_ndireq */
3365 /*
3366 * XXX BSD has a bunch of checks here to ensure
3367 * that interface disabled flag is not reset if
3368 * link local address has failed DAD.
3369 * Investigate that part.
3370 */
3371 struct in6_ndireq *cndi = (struct in6_ndireq *)(void *)data;
3372 u_int32_t oflags, flags;
3373 struct nd_ifinfo *ndi = ND_IFINFO(ifp);
3374
3375 /* XXX: almost all other fields of cndi->ndi is unused */
3376 if ((NULL == ndi) || !ndi->initialized) {
3377 error = EINVAL;
3378 break;
3379 }
3380
3381 lck_mtx_lock(&ndi->lock);
3382 oflags = ndi->flags;
3383 bcopy(&cndi->ndi.flags, &(ndi->flags), sizeof(flags));
3384 flags = ndi->flags;
3385 lck_mtx_unlock(&ndi->lock);
3386
3387 if (oflags == flags) {
3388 break;
3389 }
3390
3391 error = nd6_setifinfo(ifp, oflags, flags);
3392 break;
3393 }
3394
3395 case SIOCSNDFLUSH_IN6: /* struct in6_ifreq */
3396 /* flush default router list */
3397 /*
3398 * xxx sumikawa: should not delete route if default
3399 * route equals to the top of default router list
3400 *
3401 * XXX TODO: Needs to be done for RTI as well
3402 * Is very specific flush command with ndp for default routers.
3403 */
3404 lck_mtx_lock(nd6_mutex);
3405 defrouter_reset();
3406 defrouter_select(ifp, NULL);
3407 lck_mtx_unlock(nd6_mutex);
3408 /* xxx sumikawa: flush prefix list */
3409 break;
3410
3411 case SIOCSPFXFLUSH_IN6: { /* struct in6_ifreq */
3412 /* flush all the prefix advertised by routers */
3413 struct nd_prefix *next = NULL;
3414
3415 lck_mtx_lock(nd6_mutex);
3416 for (pr = nd_prefix.lh_first; pr; pr = next) {
3417 struct in6_ifaddr *ia = NULL;
3418 bool iterate_pfxlist_again = false;
3419
3420 next = pr->ndpr_next;
3421
3422 NDPR_LOCK(pr);
3423 if (IN6_IS_ADDR_LINKLOCAL(&pr->ndpr_prefix.sin6_addr)) {
3424 NDPR_UNLOCK(pr);
3425 continue; /* XXX */
3426 }
3427 if (ifp != lo_ifp && pr->ndpr_ifp != ifp) {
3428 NDPR_UNLOCK(pr);
3429 continue;
3430 }
3431 /* do we really have to remove addresses as well? */
3432 NDPR_ADDREF(pr);
3433 NDPR_UNLOCK(pr);
3434 lck_rw_lock_exclusive(&in6_ifaddr_rwlock);
3435 bool from_begining = true;
3436 while (from_begining) {
3437 from_begining = false;
3438 TAILQ_FOREACH(ia, &in6_ifaddrhead, ia6_link) {
3439 IFA_LOCK(&ia->ia_ifa);
3440 if ((ia->ia6_flags & IN6_IFF_AUTOCONF) == 0) {
3441 IFA_UNLOCK(&ia->ia_ifa);
3442 continue;
3443 }
3444
3445 if (ia->ia6_ndpr == pr) {
3446 IFA_ADDREF_LOCKED(&ia->ia_ifa);
3447 IFA_UNLOCK(&ia->ia_ifa);
3448 lck_rw_done(&in6_ifaddr_rwlock);
3449 lck_mtx_unlock(nd6_mutex);
3450 in6_purgeaddr(&ia->ia_ifa);
3451 IFA_REMREF(&ia->ia_ifa);
3452 lck_mtx_lock(nd6_mutex);
3453 lck_rw_lock_exclusive(
3454 &in6_ifaddr_rwlock);
3455 /*
3456 * Purging the address caused
3457 * in6_ifaddr_rwlock to be
3458 * dropped and
3459 * reacquired; therefore search again
3460 * from the beginning of in6_ifaddrs.
3461 * The same applies for the prefix list.
3462 */
3463 iterate_pfxlist_again = true;
3464 from_begining = true;
3465 break;
3466 }
3467 IFA_UNLOCK(&ia->ia_ifa);
3468 }
3469 }
3470 lck_rw_done(&in6_ifaddr_rwlock);
3471 NDPR_LOCK(pr);
3472 prelist_remove(pr);
3473 NDPR_UNLOCK(pr);
3474 pfxlist_onlink_check();
3475 NDPR_REMREF(pr);
3476 if (iterate_pfxlist_again) {
3477 next = nd_prefix.lh_first;
3478 }
3479 }
3480 lck_mtx_unlock(nd6_mutex);
3481 break;
3482 }
3483
3484 case SIOCSRTRFLUSH_IN6: { /* struct in6_ifreq */
3485 /* flush all the default routers */
3486 struct nd_defrouter *next;
3487 struct nd_drhead nd_defrouter_tmp;
3488
3489 TAILQ_INIT(&nd_defrouter_tmp);
3490 lck_mtx_lock(nd6_mutex);
3491 if ((dr = TAILQ_FIRST(&nd_defrouter_list)) != NULL) {
3492 /*
3493 * The first entry of the list may be stored in
3494 * the routing table, so we'll delete it later.
3495 */
3496 for (dr = TAILQ_NEXT(dr, dr_entry); dr; dr = next) {
3497 next = TAILQ_NEXT(dr, dr_entry);
3498 if (ifp == lo_ifp || dr->ifp == ifp) {
3499 /*
3500 * Remove the entry from default router list
3501 * and add it to the temp list.
3502 * nd_defrouter_tmp will be a local temporary
3503 * list as no one else can get the same
3504 * removed entry once it is removed from default
3505 * router list.
3506 * Remove the reference after calling defrtrlist_de
3507 */
3508 TAILQ_REMOVE(&nd_defrouter_list, dr, dr_entry);
3509 TAILQ_INSERT_TAIL(&nd_defrouter_tmp, dr, dr_entry);
3510 }
3511 }
3512
3513 dr = TAILQ_FIRST(&nd_defrouter_list);
3514 if (ifp == lo_ifp ||
3515 dr->ifp == ifp) {
3516 TAILQ_REMOVE(&nd_defrouter_list, dr, dr_entry);
3517 TAILQ_INSERT_TAIL(&nd_defrouter_tmp, dr, dr_entry);
3518 }
3519 }
3520
3521 /*
3522 * Keep the following separate from the above iteration of
3523 * nd_defrouter because it's not safe to call
3524 * defrtrlist_del while iterating global default
3525 * router list. Global list has to be traversed
3526 * while holding nd6_mutex throughout.
3527 *
3528 * The following call to defrtrlist_del should be
3529 * safe as we are iterating a local list of
3530 * default routers.
3531 */
3532 TAILQ_FOREACH_SAFE(dr, &nd_defrouter_tmp, dr_entry, next) {
3533 TAILQ_REMOVE(&nd_defrouter_tmp, dr, dr_entry);
3534 defrtrlist_del(dr, NULL);
3535 NDDR_REMREF(dr); /* remove list reference */
3536 }
3537
3538 /* For now flush RTI routes here as well to avoid any regressions */
3539 nd6_purge_interface_rti_entries((ifp == lo_ifp) ? NULL : ifp);
3540
3541 lck_mtx_unlock(nd6_mutex);
3542 break;
3543 }
3544
3545 case SIOCGNBRINFO_IN6_32: { /* struct in6_nbrinfo_32 */
3546 struct llinfo_nd6 *ln;
3547 struct in6_nbrinfo_32 nbi_32;
3548 struct in6_addr nb_addr; /* make local for safety */
3549
3550 bcopy(data, &nbi_32, sizeof(nbi_32));
3551 nb_addr = nbi_32.addr;
3552 /*
3553 * XXX: KAME specific hack for scoped addresses
3554 * XXXX: for other scopes than link-local?
3555 */
3556 if (in6_embedded_scope && (IN6_IS_ADDR_LINKLOCAL(&nbi_32.addr) ||
3557 IN6_IS_ADDR_MC_LINKLOCAL(&nbi_32.addr))) {
3558 u_int16_t *idp =
3559 (u_int16_t *)(void *)&nb_addr.s6_addr[2];
3560
3561 if (*idp == 0) {
3562 *idp = htons(ifp->if_index);
3563 }
3564 }
3565
3566 /* Callee returns a locked route upon success */
3567 if ((rt = nd6_lookup(&nb_addr, 0, ifp, 0)) == NULL) {
3568 error = EINVAL;
3569 break;
3570 }
3571 RT_LOCK_ASSERT_HELD(rt);
3572 ln = rt->rt_llinfo;
3573 nbi_32.state = ln->ln_state;
3574 nbi_32.asked = ln->ln_asked;
3575 nbi_32.isrouter = ln->ln_router;
3576 nbi_32.expire = (int)ln_getexpire(ln);
3577 RT_REMREF_LOCKED(rt);
3578 RT_UNLOCK(rt);
3579 bcopy(&nbi_32, data, sizeof(nbi_32));
3580 break;
3581 }
3582
3583 case SIOCGNBRINFO_IN6_64: { /* struct in6_nbrinfo_64 */
3584 struct llinfo_nd6 *ln;
3585 struct in6_nbrinfo_64 nbi_64;
3586 struct in6_addr nb_addr; /* make local for safety */
3587
3588 bcopy(data, &nbi_64, sizeof(nbi_64));
3589 nb_addr = nbi_64.addr;
3590 /*
3591 * XXX: KAME specific hack for scoped addresses
3592 * XXXX: for other scopes than link-local?
3593 */
3594 if (in6_embedded_scope && (IN6_IS_ADDR_LINKLOCAL(&nbi_64.addr) ||
3595 IN6_IS_ADDR_MC_LINKLOCAL(&nbi_64.addr))) {
3596 u_int16_t *idp =
3597 (u_int16_t *)(void *)&nb_addr.s6_addr[2];
3598
3599 if (*idp == 0) {
3600 *idp = htons(ifp->if_index);
3601 }
3602 }
3603
3604 /* Callee returns a locked route upon success */
3605 if ((rt = nd6_lookup(&nb_addr, 0, ifp, 0)) == NULL) {
3606 error = EINVAL;
3607 break;
3608 }
3609 RT_LOCK_ASSERT_HELD(rt);
3610 ln = rt->rt_llinfo;
3611 nbi_64.state = ln->ln_state;
3612 nbi_64.asked = ln->ln_asked;
3613 nbi_64.isrouter = ln->ln_router;
3614 nbi_64.expire = (int)ln_getexpire(ln);
3615 RT_REMREF_LOCKED(rt);
3616 RT_UNLOCK(rt);
3617 bcopy(&nbi_64, data, sizeof(nbi_64));
3618 break;
3619 }
3620
3621 case SIOCGDEFIFACE_IN6_32: /* struct in6_ndifreq_32 */
3622 case SIOCGDEFIFACE_IN6_64: { /* struct in6_ndifreq_64 */
3623 struct in6_ndifreq_64 *ndif_64 =
3624 (struct in6_ndifreq_64 *)(void *)data;
3625 struct in6_ndifreq_32 *ndif_32 =
3626 (struct in6_ndifreq_32 *)(void *)data;
3627
3628 if (cmd == SIOCGDEFIFACE_IN6_64) {
3629 u_int64_t j = nd6_defifindex;
3630 __nochk_bcopy(&j, &ndif_64->ifindex, sizeof(j));
3631 } else {
3632 bcopy(&nd6_defifindex, &ndif_32->ifindex,
3633 sizeof(u_int32_t));
3634 }
3635 break;
3636 }
3637
3638 case SIOCSDEFIFACE_IN6_32: /* struct in6_ndifreq_32 */
3639 case SIOCSDEFIFACE_IN6_64: { /* struct in6_ndifreq_64 */
3640 struct in6_ndifreq_64 *ndif_64 =
3641 (struct in6_ndifreq_64 *)(void *)data;
3642 struct in6_ndifreq_32 *ndif_32 =
3643 (struct in6_ndifreq_32 *)(void *)data;
3644 u_int32_t idx;
3645
3646 if (cmd == SIOCSDEFIFACE_IN6_64) {
3647 u_int64_t j;
3648 __nochk_bcopy(&ndif_64->ifindex, &j, sizeof(j));
3649 idx = (u_int32_t)j;
3650 } else {
3651 bcopy(&ndif_32->ifindex, &idx, sizeof(idx));
3652 }
3653
3654 error = nd6_setdefaultiface(idx);
3655 return error;
3656 /* NOTREACHED */
3657 }
3658 case SIOCGIFCGAPREP_IN6_32:
3659 case SIOCGIFCGAPREP_IN6_64: {
3660 /* get CGA parameters */
3661 union {
3662 struct in6_cgareq_32 *cga32;
3663 struct in6_cgareq_64 *cga64;
3664 void *data;
3665 } cgareq_u;
3666 struct nd_ifinfo *ndi;
3667 struct in6_cga_modifier *ndi_cga_mod;
3668 struct in6_cga_modifier *req_cga_mod;
3669
3670 ndi = ND_IFINFO(ifp);
3671 if ((NULL == ndi) || !ndi->initialized) {
3672 error = EINVAL;
3673 break;
3674 }
3675 cgareq_u.data = data;
3676 req_cga_mod = (cmd == SIOCGIFCGAPREP_IN6_64)
3677 ? &(cgareq_u.cga64->cgar_cgaprep.cga_modifier)
3678 : &(cgareq_u.cga32->cgar_cgaprep.cga_modifier);
3679 lck_mtx_lock(&ndi->lock);
3680 ndi_cga_mod = &(ndi->local_cga_modifier);
3681 bcopy(ndi_cga_mod, req_cga_mod, sizeof(*req_cga_mod));
3682 lck_mtx_unlock(&ndi->lock);
3683 break;
3684 }
3685 case SIOCSIFCGAPREP_IN6_32:
3686 case SIOCSIFCGAPREP_IN6_64:
3687 {
3688 /* set CGA parameters */
3689 struct in6_cgareq cgareq;
3690 int is64;
3691 struct nd_ifinfo *ndi;
3692 struct in6_cga_modifier *ndi_cga_mod;
3693 struct in6_cga_modifier *req_cga_mod;
3694
3695 ndi = ND_IFINFO(ifp);
3696 if ((NULL == ndi) || !ndi->initialized) {
3697 error = EINVAL;
3698 break;
3699 }
3700 is64 = (cmd == SIOCSIFCGAPREP_IN6_64);
3701 in6_cgareq_copy_from_user(data, is64, &cgareq);
3702 req_cga_mod = &cgareq.cgar_cgaprep.cga_modifier;
3703 lck_mtx_lock(&ndi->lock);
3704 ndi_cga_mod = &(ndi->local_cga_modifier);
3705 bcopy(req_cga_mod, ndi_cga_mod, sizeof(*ndi_cga_mod));
3706 ndi->cga_initialized = TRUE;
3707 ndi->cga_collision_count = 0;
3708 lck_mtx_unlock(&ndi->lock);
3709 break;
3710 }
3711 default:
3712 break;
3713 }
3714 return error;
3715 }
3716
3717 /*
3718 * Create neighbor cache entry and cache link-layer address,
3719 * on reception of inbound ND6 packets. (RS/RA/NS/redirect)
3720 */
3721 void
nd6_cache_lladdr(struct ifnet * ifp,struct in6_addr * from,char * lladdr,int lladdrlen,int type,int code,int * did_update)3722 nd6_cache_lladdr(struct ifnet *ifp, struct in6_addr *from, char *lladdr,
3723 int lladdrlen, int type, int code, int *did_update)
3724 {
3725 #pragma unused(lladdrlen)
3726 struct rtentry *rt = NULL;
3727 struct llinfo_nd6 *ln = NULL;
3728 int is_newentry;
3729 struct sockaddr_dl *sdl = NULL;
3730 int do_update;
3731 int olladdr;
3732 int llchange;
3733 short newstate = 0;
3734 uint64_t timenow;
3735 boolean_t sched_timeout = FALSE;
3736 struct nd_ifinfo *ndi = NULL;
3737
3738 if (ifp == NULL) {
3739 panic("ifp == NULL in nd6_cache_lladdr");
3740 }
3741 if (from == NULL) {
3742 panic("from == NULL in nd6_cache_lladdr");
3743 }
3744
3745 if (did_update != NULL) {
3746 did_update = 0;
3747 }
3748
3749 /* nothing must be updated for unspecified address */
3750 if (IN6_IS_ADDR_UNSPECIFIED(from)) {
3751 return;
3752 }
3753
3754 /*
3755 * Validation about ifp->if_addrlen and lladdrlen must be done in
3756 * the caller.
3757 */
3758 timenow = net_uptime();
3759
3760 rt = nd6_lookup(from, 0, ifp, 0);
3761 if (rt == NULL) {
3762 if ((rt = nd6_lookup(from, 1, ifp, 0)) == NULL) {
3763 return;
3764 }
3765 RT_LOCK_ASSERT_HELD(rt);
3766 is_newentry = 1;
3767 } else {
3768 RT_LOCK_ASSERT_HELD(rt);
3769 /* do nothing if static ndp is set */
3770 if (rt->rt_flags & RTF_STATIC) {
3771 RT_REMREF_LOCKED(rt);
3772 RT_UNLOCK(rt);
3773 return;
3774 }
3775 is_newentry = 0;
3776 }
3777
3778 if ((rt->rt_flags & (RTF_GATEWAY | RTF_LLINFO)) != RTF_LLINFO) {
3779 fail:
3780 RT_UNLOCK(rt);
3781 nd6_free(rt);
3782 rtfree(rt);
3783 return;
3784 }
3785 ln = (struct llinfo_nd6 *)rt->rt_llinfo;
3786 if (ln == NULL) {
3787 goto fail;
3788 }
3789 if (rt->rt_gateway == NULL) {
3790 goto fail;
3791 }
3792 if (rt->rt_gateway->sa_family != AF_LINK) {
3793 goto fail;
3794 }
3795 sdl = SDL(rt->rt_gateway);
3796
3797 olladdr = (sdl->sdl_alen) ? 1 : 0;
3798 if (olladdr && lladdr) {
3799 if (bcmp(lladdr, LLADDR(sdl), ifp->if_addrlen)) {
3800 llchange = 1;
3801 } else {
3802 llchange = 0;
3803 }
3804 } else {
3805 llchange = 0;
3806 }
3807
3808 /*
3809 * newentry olladdr lladdr llchange (*=record)
3810 * 0 n n -- (1)
3811 * 0 y n -- (2)
3812 * 0 n y -- (3) * STALE
3813 * 0 y y n (4) *
3814 * 0 y y y (5) * STALE
3815 * 1 -- n -- (6) NOSTATE(= PASSIVE)
3816 * 1 -- y -- (7) * STALE
3817 */
3818
3819 if (lladdr != NULL) { /* (3-5) and (7) */
3820 /*
3821 * Record source link-layer address
3822 * XXX is it dependent to ifp->if_type?
3823 */
3824 sdl->sdl_alen = ifp->if_addrlen;
3825 bcopy(lladdr, LLADDR(sdl), ifp->if_addrlen);
3826
3827 /* cache the gateway (sender HW) address */
3828 nd6_llreach_alloc(rt, ifp, LLADDR(sdl), sdl->sdl_alen, FALSE);
3829 }
3830
3831 if (is_newentry == 0) {
3832 if ((!olladdr && lladdr != NULL) || /* (3) */
3833 (olladdr && lladdr != NULL && llchange)) { /* (5) */
3834 do_update = 1;
3835 newstate = ND6_LLINFO_STALE;
3836 } else { /* (1-2,4) */
3837 do_update = 0;
3838 }
3839 } else {
3840 do_update = 1;
3841 if (lladdr == NULL) { /* (6) */
3842 newstate = ND6_LLINFO_NOSTATE;
3843 } else { /* (7) */
3844 newstate = ND6_LLINFO_STALE;
3845 }
3846 }
3847
3848 /*
3849 * For interface's that do not perform NUD or NDP
3850 * neighbor cache entres must always be marked
3851 * reachable with no expiry
3852 */
3853 ndi = ND_IFINFO(ifp);
3854 VERIFY((NULL != ndi) && (TRUE == ndi->initialized));
3855
3856 if ((ndi && !(ndi->flags & ND6_IFF_PERFORMNUD)) ||
3857 (ifp->if_eflags & IFEF_IPV6_ND6ALT)) {
3858 newstate = ND6_LLINFO_REACHABLE;
3859 ln_setexpire(ln, 0);
3860 }
3861
3862 if (do_update) {
3863 /*
3864 * Update the state of the neighbor cache.
3865 */
3866 ND6_CACHE_STATE_TRANSITION(ln, newstate);
3867
3868 if ((ln->ln_state == ND6_LLINFO_STALE) ||
3869 (ln->ln_state == ND6_LLINFO_REACHABLE)) {
3870 struct mbuf *m = ln->ln_hold;
3871 /*
3872 * XXX: since nd6_output() below will cause
3873 * state tansition to DELAY and reset the timer,
3874 * we must set the timer now, although it is actually
3875 * meaningless.
3876 */
3877 if (ln->ln_state == ND6_LLINFO_STALE) {
3878 ln_setexpire(ln, timenow + nd6_gctimer);
3879 }
3880
3881 ln->ln_hold = NULL;
3882 if (m != NULL) {
3883 struct sockaddr_in6 sin6;
3884
3885 rtkey_to_sa6(rt, &sin6);
3886 /*
3887 * we assume ifp is not a p2p here, so just
3888 * set the 2nd argument as the 1st one.
3889 */
3890 RT_UNLOCK(rt);
3891 nd6_output_list(ifp, ifp, m, &sin6, rt, NULL);
3892 RT_LOCK(rt);
3893 }
3894 } else if (ln->ln_state == ND6_LLINFO_INCOMPLETE) {
3895 /* probe right away */
3896 ln_setexpire(ln, timenow);
3897 sched_timeout = TRUE;
3898 }
3899 }
3900
3901 /*
3902 * ICMP6 type dependent behavior.
3903 *
3904 * NS: clear IsRouter if new entry
3905 * RS: clear IsRouter
3906 * RA: set IsRouter if there's lladdr
3907 * redir: clear IsRouter if new entry
3908 *
3909 * RA case, (1):
3910 * The spec says that we must set IsRouter in the following cases:
3911 * - If lladdr exist, set IsRouter. This means (1-5).
3912 * - If it is old entry (!newentry), set IsRouter. This means (7).
3913 * So, based on the spec, in (1-5) and (7) cases we must set IsRouter.
3914 * A quetion arises for (1) case. (1) case has no lladdr in the
3915 * neighbor cache, this is similar to (6).
3916 * This case is rare but we figured that we MUST NOT set IsRouter.
3917 *
3918 * newentry olladdr lladdr llchange NS RS RA redir
3919 * D R
3920 * 0 n n -- (1) c ? s
3921 * 0 y n -- (2) c s s
3922 * 0 n y -- (3) c s s
3923 * 0 y y n (4) c s s
3924 * 0 y y y (5) c s s
3925 * 1 -- n -- (6) c c c s
3926 * 1 -- y -- (7) c c s c s
3927 *
3928 * (c=clear s=set)
3929 */
3930 switch (type & 0xff) {
3931 case ND_NEIGHBOR_SOLICIT:
3932 /*
3933 * New entry must have is_router flag cleared.
3934 */
3935 if (is_newentry) { /* (6-7) */
3936 ln->ln_router = 0;
3937 }
3938 break;
3939 case ND_REDIRECT:
3940 /*
3941 * If the ICMP message is a Redirect to a better router, always
3942 * set the is_router flag. Otherwise, if the entry is newly
3943 * created, then clear the flag. [RFC 4861, sec 8.3]
3944 */
3945 if (code == ND_REDIRECT_ROUTER) {
3946 ln->ln_router = 1;
3947 } else if (is_newentry) { /* (6-7) */
3948 ln->ln_router = 0;
3949 }
3950 break;
3951 case ND_ROUTER_SOLICIT:
3952 /*
3953 * is_router flag must always be cleared.
3954 */
3955 ln->ln_router = 0;
3956 break;
3957 case ND_ROUTER_ADVERT:
3958 /*
3959 * Mark an entry with lladdr as a router.
3960 */
3961 if ((!is_newentry && (olladdr || lladdr)) || /* (2-5) */
3962 (is_newentry && lladdr)) { /* (7) */
3963 ln->ln_router = 1;
3964 }
3965 break;
3966 }
3967
3968 if (do_update) {
3969 int route_ev_code = 0;
3970
3971 if (llchange) {
3972 route_ev_code = ROUTE_LLENTRY_CHANGED;
3973 } else {
3974 route_ev_code = ROUTE_LLENTRY_RESOLVED;
3975 }
3976
3977 /* Enqueue work item to invoke callback for this route entry */
3978 route_event_enqueue_nwk_wq_entry(rt, NULL, route_ev_code, NULL, TRUE);
3979
3980 if (ln->ln_router || (rt->rt_flags & RTF_ROUTER)) {
3981 struct radix_node_head *rnh = NULL;
3982 struct in6_addr rt_addr = SIN6(rt_key(rt))->sin6_addr;
3983 struct ifnet *rt_ifp = rt->rt_ifp;
3984 struct route_event rt_ev;
3985 route_event_init(&rt_ev, rt, NULL, llchange ? ROUTE_LLENTRY_CHANGED :
3986 ROUTE_LLENTRY_RESOLVED);
3987 /*
3988 * We already have a valid reference on rt.
3989 * The function frees that before returning.
3990 * We therefore don't need an extra reference here
3991 */
3992 RT_UNLOCK(rt);
3993 defrouter_set_reachability(&rt_addr, rt_ifp, TRUE);
3994 lck_mtx_lock(rnh_lock);
3995
3996 rnh = rt_tables[AF_INET6];
3997 if (rnh != NULL) {
3998 (void) rnh->rnh_walktree(rnh, route_event_walktree,
3999 (void *)&rt_ev);
4000 }
4001 lck_mtx_unlock(rnh_lock);
4002 RT_LOCK(rt);
4003 }
4004 }
4005
4006 if (did_update != NULL) {
4007 *did_update = do_update;
4008 }
4009
4010 /*
4011 * When the link-layer address of a router changes, select the
4012 * best router again. In particular, when the neighbor entry is newly
4013 * created, it might affect the selection policy.
4014 * Question: can we restrict the first condition to the "is_newentry"
4015 * case?
4016 *
4017 * Note: Perform default router selection even when we are a router,
4018 * if Scoped Routing is enabled.
4019 */
4020 if (do_update && ln->ln_router) {
4021 /*
4022 * XXX TODO: This should also be iterated over router list
4023 * for route information option's router lists as well.
4024 */
4025 RT_REMREF_LOCKED(rt);
4026 RT_UNLOCK(rt);
4027 lck_mtx_lock(nd6_mutex);
4028 defrouter_select(ifp, NULL);
4029 nd6_router_select_rti_entries(ifp);
4030 lck_mtx_unlock(nd6_mutex);
4031 } else {
4032 RT_REMREF_LOCKED(rt);
4033 RT_UNLOCK(rt);
4034 }
4035 if (sched_timeout) {
4036 lck_mtx_lock(rnh_lock);
4037 nd6_sched_timeout(NULL, NULL);
4038 lck_mtx_unlock(rnh_lock);
4039 }
4040 }
4041
4042 static void
nd6_slowtimo(void * arg)4043 nd6_slowtimo(void *arg)
4044 {
4045 #pragma unused(arg)
4046 struct nd_ifinfo *nd6if = NULL;
4047 struct ifnet *ifp = NULL;
4048
4049 ifnet_head_lock_shared();
4050 for (ifp = ifnet_head.tqh_first; ifp;
4051 ifp = ifp->if_link.tqe_next) {
4052 nd6if = ND_IFINFO(ifp);
4053 if ((NULL == nd6if) || (FALSE == nd6if->initialized)) {
4054 continue;
4055 }
4056
4057 lck_mtx_lock(&nd6if->lock);
4058 if (nd6if->basereachable && /* already initialized */
4059 (nd6if->recalctm -= ND6_SLOWTIMER_INTERVAL) <= 0) {
4060 /*
4061 * Since reachable time rarely changes by router
4062 * advertisements, we SHOULD insure that a new random
4063 * value gets recomputed at least once every few hours.
4064 * (RFC 4861, 6.3.4)
4065 */
4066 nd6if->recalctm = nd6_recalc_reachtm_interval;
4067 nd6if->reachable =
4068 ND_COMPUTE_RTIME(nd6if->basereachable);
4069 }
4070 lck_mtx_unlock(&nd6if->lock);
4071 }
4072 ifnet_head_done();
4073 timeout(nd6_slowtimo, NULL, ND6_SLOWTIMER_INTERVAL * hz);
4074 }
4075
4076 int
nd6_output(struct ifnet * ifp,struct ifnet * origifp,struct mbuf * m0,struct sockaddr_in6 * dst,struct rtentry * hint0,struct flowadv * adv)4077 nd6_output(struct ifnet *ifp, struct ifnet *origifp, struct mbuf *m0,
4078 struct sockaddr_in6 *dst, struct rtentry *hint0, struct flowadv *adv)
4079 {
4080 return nd6_output_list(ifp, origifp, m0, dst, hint0, adv);
4081 }
4082
4083 /*
4084 * nd6_output_list()
4085 *
4086 * Assumption: route determination for first packet can be correctly applied to
4087 * all packets in the chain.
4088 */
4089 #define senderr(e) { error = (e); goto bad; }
4090 int
nd6_output_list(struct ifnet * ifp,struct ifnet * origifp,struct mbuf * m0,struct sockaddr_in6 * dst,struct rtentry * hint0,struct flowadv * adv)4091 nd6_output_list(struct ifnet *ifp, struct ifnet *origifp, struct mbuf *m0,
4092 struct sockaddr_in6 *dst, struct rtentry *hint0, struct flowadv *adv)
4093 {
4094 struct rtentry *rt = hint0, *hint = hint0;
4095 struct llinfo_nd6 *ln = NULL;
4096 int error = 0;
4097 uint64_t timenow;
4098 struct rtentry *rtrele = NULL;
4099 struct nd_ifinfo *ndi = NULL;
4100
4101 if (rt != NULL) {
4102 RT_LOCK_SPIN(rt);
4103 RT_ADDREF_LOCKED(rt);
4104 }
4105
4106 if (IN6_IS_ADDR_MULTICAST(&dst->sin6_addr) || !nd6_need_cache(ifp)) {
4107 if (rt != NULL) {
4108 RT_UNLOCK(rt);
4109 }
4110 goto sendpkt;
4111 }
4112
4113 /*
4114 * Next hop determination. Because we may involve the gateway route
4115 * in addition to the original route, locking is rather complicated.
4116 * The general concept is that regardless of whether the route points
4117 * to the original route or to the gateway route, this routine takes
4118 * an extra reference on such a route. This extra reference will be
4119 * released at the end.
4120 *
4121 * Care must be taken to ensure that the "hint0" route never gets freed
4122 * via rtfree(), since the caller may have stored it inside a struct
4123 * route with a reference held for that placeholder.
4124 *
4125 * This logic is similar to, though not exactly the same as the one
4126 * used by route_to_gwroute().
4127 */
4128 if (rt != NULL) {
4129 /*
4130 * We have a reference to "rt" by now (or below via rtalloc1),
4131 * which will either be released or freed at the end of this
4132 * routine.
4133 */
4134 RT_LOCK_ASSERT_HELD(rt);
4135 if (!(rt->rt_flags & RTF_UP)) {
4136 RT_REMREF_LOCKED(rt);
4137 RT_UNLOCK(rt);
4138 if ((hint = rt = rtalloc1_scoped(SA(dst), 1, 0,
4139 ifp->if_index)) != NULL) {
4140 RT_LOCK_SPIN(rt);
4141 if (rt->rt_ifp != ifp) {
4142 /* XXX: loop care? */
4143 RT_UNLOCK(rt);
4144 error = nd6_output_list(ifp, origifp, m0,
4145 dst, rt, adv);
4146 rtfree(rt);
4147 return error;
4148 }
4149 } else {
4150 senderr(EHOSTUNREACH);
4151 }
4152 }
4153
4154 if (rt->rt_flags & RTF_GATEWAY) {
4155 struct rtentry *gwrt;
4156 struct in6_ifaddr *ia6 = NULL;
4157 struct sockaddr_in6 gw6;
4158
4159 rtgw_to_sa6(rt, &gw6);
4160 /*
4161 * Must drop rt_lock since nd6_is_addr_neighbor()
4162 * calls nd6_lookup() and acquires rnh_lock.
4163 */
4164 RT_UNLOCK(rt);
4165
4166 /*
4167 * We skip link-layer address resolution and NUD
4168 * if the gateway is not a neighbor from ND point
4169 * of view, regardless of the value of nd_ifinfo.flags.
4170 * The second condition is a bit tricky; we skip
4171 * if the gateway is our own address, which is
4172 * sometimes used to install a route to a p2p link.
4173 */
4174 if (!nd6_is_addr_neighbor(&gw6, ifp, 0) ||
4175 (ia6 = in6ifa_ifpwithaddr(ifp, &gw6.sin6_addr))) {
4176 /*
4177 * We allow this kind of tricky route only
4178 * when the outgoing interface is p2p.
4179 * XXX: we may need a more generic rule here.
4180 */
4181 if (ia6 != NULL) {
4182 IFA_REMREF(&ia6->ia_ifa);
4183 }
4184 if ((ifp->if_flags & IFF_POINTOPOINT) == 0) {
4185 senderr(EHOSTUNREACH);
4186 }
4187 goto sendpkt;
4188 }
4189
4190 RT_LOCK_SPIN(rt);
4191 gw6 = *(SIN6(rt->rt_gateway));
4192
4193 /* If hint is now down, give up */
4194 if (!(rt->rt_flags & RTF_UP)) {
4195 RT_UNLOCK(rt);
4196 senderr(EHOSTUNREACH);
4197 }
4198
4199 /* If there's no gateway route, look it up */
4200 if ((gwrt = rt->rt_gwroute) == NULL) {
4201 RT_UNLOCK(rt);
4202 goto lookup;
4203 }
4204 /* Become a regular mutex */
4205 RT_CONVERT_LOCK(rt);
4206
4207 /*
4208 * Take gwrt's lock while holding route's lock;
4209 * this is okay since gwrt never points back
4210 * to rt, so no lock ordering issues.
4211 */
4212 RT_LOCK_SPIN(gwrt);
4213 if (!(gwrt->rt_flags & RTF_UP)) {
4214 rt->rt_gwroute = NULL;
4215 RT_UNLOCK(gwrt);
4216 RT_UNLOCK(rt);
4217 rtfree(gwrt);
4218 lookup:
4219 lck_mtx_lock(rnh_lock);
4220 gwrt = rtalloc1_scoped_locked(SA(&gw6), 1, 0,
4221 ifp->if_index);
4222
4223 RT_LOCK(rt);
4224 /*
4225 * Bail out if the route is down, no route
4226 * to gateway, circular route, or if the
4227 * gateway portion of "rt" has changed.
4228 */
4229 if (!(rt->rt_flags & RTF_UP) ||
4230 gwrt == NULL || gwrt == rt ||
4231 !equal(SA(&gw6), rt->rt_gateway)) {
4232 if (gwrt == rt) {
4233 RT_REMREF_LOCKED(gwrt);
4234 gwrt = NULL;
4235 }
4236 RT_UNLOCK(rt);
4237 if (gwrt != NULL) {
4238 rtfree_locked(gwrt);
4239 }
4240 lck_mtx_unlock(rnh_lock);
4241 senderr(EHOSTUNREACH);
4242 }
4243 VERIFY(gwrt != NULL);
4244 /*
4245 * Set gateway route; callee adds ref to gwrt;
4246 * gwrt has an extra ref from rtalloc1() for
4247 * this routine.
4248 */
4249 rt_set_gwroute(rt, rt_key(rt), gwrt);
4250 RT_UNLOCK(rt);
4251 lck_mtx_unlock(rnh_lock);
4252 /* Remember to release/free "rt" at the end */
4253 rtrele = rt;
4254 rt = gwrt;
4255 } else {
4256 RT_ADDREF_LOCKED(gwrt);
4257 RT_UNLOCK(gwrt);
4258 RT_UNLOCK(rt);
4259 /* Remember to release/free "rt" at the end */
4260 rtrele = rt;
4261 rt = gwrt;
4262 }
4263 VERIFY(rt == gwrt);
4264
4265 /*
4266 * This is an opportunity to revalidate the parent
4267 * route's gwroute, in case it now points to a dead
4268 * route entry. Parent route won't go away since the
4269 * clone (hint) holds a reference to it. rt == gwrt.
4270 */
4271 RT_LOCK_SPIN(hint);
4272 if ((hint->rt_flags & (RTF_WASCLONED | RTF_UP)) ==
4273 (RTF_WASCLONED | RTF_UP)) {
4274 struct rtentry *prt = hint->rt_parent;
4275 VERIFY(prt != NULL);
4276
4277 RT_CONVERT_LOCK(hint);
4278 RT_ADDREF(prt);
4279 RT_UNLOCK(hint);
4280 rt_revalidate_gwroute(prt, rt);
4281 RT_REMREF(prt);
4282 } else {
4283 RT_UNLOCK(hint);
4284 }
4285
4286 RT_LOCK_SPIN(rt);
4287 /* rt == gwrt; if it is now down, give up */
4288 if (!(rt->rt_flags & RTF_UP)) {
4289 RT_UNLOCK(rt);
4290 rtfree(rt);
4291 rt = NULL;
4292 /* "rtrele" == original "rt" */
4293 senderr(EHOSTUNREACH);
4294 }
4295 }
4296
4297 /* Become a regular mutex */
4298 RT_CONVERT_LOCK(rt);
4299 }
4300
4301 /*
4302 * Address resolution or Neighbor Unreachability Detection
4303 * for the next hop.
4304 * At this point, the destination of the packet must be a unicast
4305 * or an anycast address(i.e. not a multicast).
4306 */
4307
4308 /* Look up the neighbor cache for the nexthop */
4309 if (rt && (rt->rt_flags & RTF_LLINFO) != 0) {
4310 ln = rt->rt_llinfo;
4311 } else {
4312 struct sockaddr_in6 sin6;
4313 /*
4314 * Clear out Scope ID field in case it is set.
4315 */
4316 sin6 = *dst;
4317 if (in6_embedded_scope) {
4318 sin6.sin6_scope_id = 0;
4319 }
4320 /*
4321 * Since nd6_is_addr_neighbor() internally calls nd6_lookup(),
4322 * the condition below is not very efficient. But we believe
4323 * it is tolerable, because this should be a rare case.
4324 * Must drop rt_lock since nd6_is_addr_neighbor() calls
4325 * nd6_lookup() and acquires rnh_lock.
4326 */
4327 if (rt != NULL) {
4328 RT_UNLOCK(rt);
4329 }
4330 if (nd6_is_addr_neighbor(&sin6, ifp, 0)) {
4331 /* "rtrele" may have been used, so clean up "rt" now */
4332 if (rt != NULL) {
4333 /* Don't free "hint0" */
4334 if (rt == hint0) {
4335 RT_REMREF(rt);
4336 } else {
4337 rtfree(rt);
4338 }
4339 }
4340 /* Callee returns a locked route upon success */
4341 rt = nd6_lookup(&dst->sin6_addr, 1, ifp, 0);
4342 if (rt != NULL) {
4343 RT_LOCK_ASSERT_HELD(rt);
4344 ln = rt->rt_llinfo;
4345 }
4346 } else if (rt != NULL) {
4347 RT_LOCK(rt);
4348 }
4349 }
4350
4351 if (!ln || !rt) {
4352 if (rt != NULL) {
4353 RT_UNLOCK(rt);
4354 }
4355 ndi = ND_IFINFO(ifp);
4356 VERIFY(ndi != NULL && ndi->initialized);
4357 lck_mtx_lock(&ndi->lock);
4358 if ((ifp->if_flags & IFF_POINTOPOINT) == 0 &&
4359 !(ndi->flags & ND6_IFF_PERFORMNUD)) {
4360 lck_mtx_unlock(&ndi->lock);
4361 log(LOG_DEBUG,
4362 "nd6_output: can't allocate llinfo for %s "
4363 "(ln=0x%llx, rt=0x%llx)\n",
4364 ip6_sprintf(&dst->sin6_addr),
4365 (uint64_t)VM_KERNEL_ADDRPERM(ln),
4366 (uint64_t)VM_KERNEL_ADDRPERM(rt));
4367 senderr(EIO); /* XXX: good error? */
4368 }
4369 lck_mtx_unlock(&ndi->lock);
4370
4371 goto sendpkt; /* send anyway */
4372 }
4373
4374 net_update_uptime();
4375 timenow = net_uptime();
4376
4377 /* We don't have to do link-layer address resolution on a p2p link. */
4378 if ((ifp->if_flags & IFF_POINTOPOINT) != 0 &&
4379 ln->ln_state < ND6_LLINFO_REACHABLE) {
4380 ND6_CACHE_STATE_TRANSITION(ln, ND6_LLINFO_STALE);
4381 ln_setexpire(ln, timenow + nd6_gctimer);
4382 }
4383
4384 /*
4385 * The first time we send a packet to a neighbor whose entry is
4386 * STALE, we have to change the state to DELAY and a sets a timer to
4387 * expire in DELAY_FIRST_PROBE_TIME seconds to ensure do
4388 * neighbor unreachability detection on expiration.
4389 * (RFC 4861 7.3.3)
4390 */
4391 if (ln->ln_state == ND6_LLINFO_STALE) {
4392 ln->ln_asked = 0;
4393 ND6_CACHE_STATE_TRANSITION(ln, ND6_LLINFO_DELAY);
4394 ln_setexpire(ln, timenow + nd6_delay);
4395 /* N.B.: we will re-arm the timer below. */
4396 _CASSERT(ND6_LLINFO_DELAY > ND6_LLINFO_INCOMPLETE);
4397 }
4398
4399 /*
4400 * If the neighbor cache entry has a state other than INCOMPLETE
4401 * (i.e. its link-layer address is already resolved), just
4402 * send the packet.
4403 */
4404 if (ln->ln_state > ND6_LLINFO_INCOMPLETE) {
4405 RT_UNLOCK(rt);
4406 /*
4407 * Move this entry to the head of the queue so that it is
4408 * less likely for this entry to be a target of forced
4409 * garbage collection (see nd6_rtrequest()). Do this only
4410 * if the entry is non-permanent (as permanent ones will
4411 * never be purged), and if the number of active entries
4412 * is at least half of the threshold.
4413 */
4414 if (ln->ln_state == ND6_LLINFO_DELAY ||
4415 (ln->ln_expire != 0 && ip6_neighborgcthresh > 0 &&
4416 nd6_inuse >= (ip6_neighborgcthresh >> 1))) {
4417 lck_mtx_lock(rnh_lock);
4418 if (ln->ln_state == ND6_LLINFO_DELAY) {
4419 nd6_sched_timeout(NULL, NULL);
4420 }
4421 if (ln->ln_expire != 0 && ip6_neighborgcthresh > 0 &&
4422 nd6_inuse >= (ip6_neighborgcthresh >> 1)) {
4423 RT_LOCK_SPIN(rt);
4424 if (ln->ln_flags & ND6_LNF_IN_USE) {
4425 LN_DEQUEUE(ln);
4426 LN_INSERTHEAD(ln);
4427 }
4428 RT_UNLOCK(rt);
4429 }
4430 lck_mtx_unlock(rnh_lock);
4431 }
4432 goto sendpkt;
4433 }
4434
4435 /*
4436 * If this is a prefix proxy route, record the inbound interface
4437 * so that it can be excluded from the list of interfaces eligible
4438 * for forwarding the proxied NS in nd6_prproxy_ns_output().
4439 */
4440 if (rt->rt_flags & RTF_PROXY) {
4441 ln->ln_exclifp = ((origifp == ifp) ? NULL : origifp);
4442 }
4443
4444 /*
4445 * There is a neighbor cache entry, but no ethernet address
4446 * response yet. Replace the held mbuf (if any) with this
4447 * latest one.
4448 *
4449 * This code conforms to the rate-limiting rule described in Section
4450 * 7.2.2 of RFC 4861, because the timer is set correctly after sending
4451 * an NS below.
4452 */
4453 if (ln->ln_state == ND6_LLINFO_NOSTATE) {
4454 ND6_CACHE_STATE_TRANSITION(ln, ND6_LLINFO_INCOMPLETE);
4455 }
4456 if (ln->ln_hold) {
4457 m_freem_list(ln->ln_hold);
4458 }
4459 ln->ln_hold = m0;
4460 if (!ND6_LLINFO_PERMANENT(ln) && ln->ln_asked == 0) {
4461 ln->ln_asked++;
4462 ndi = ND_IFINFO(ifp);
4463 VERIFY(ndi != NULL && ndi->initialized);
4464 lck_mtx_lock(&ndi->lock);
4465 ln_setexpire(ln, timenow + ndi->retrans / 1000);
4466 lck_mtx_unlock(&ndi->lock);
4467 RT_UNLOCK(rt);
4468 /* We still have a reference on rt (for ln) */
4469 if (ip6_forwarding) {
4470 nd6_prproxy_ns_output(ifp, origifp, NULL,
4471 &dst->sin6_addr, ln);
4472 } else {
4473 nd6_ns_output(ifp, NULL, &dst->sin6_addr, ln, NULL);
4474 }
4475 lck_mtx_lock(rnh_lock);
4476 nd6_sched_timeout(NULL, NULL);
4477 lck_mtx_unlock(rnh_lock);
4478 } else {
4479 RT_UNLOCK(rt);
4480 }
4481 /*
4482 * Move this entry to the head of the queue so that it is
4483 * less likely for this entry to be a target of forced
4484 * garbage collection (see nd6_rtrequest()). Do this only
4485 * if the entry is non-permanent (as permanent ones will
4486 * never be purged), and if the number of active entries
4487 * is at least half of the threshold.
4488 */
4489 if (ln->ln_expire != 0 && ip6_neighborgcthresh > 0 &&
4490 nd6_inuse >= (ip6_neighborgcthresh >> 1)) {
4491 lck_mtx_lock(rnh_lock);
4492 RT_LOCK_SPIN(rt);
4493 if (ln->ln_flags & ND6_LNF_IN_USE) {
4494 LN_DEQUEUE(ln);
4495 LN_INSERTHEAD(ln);
4496 }
4497 /* Clean up "rt" now while we can */
4498 if (rt == hint0) {
4499 RT_REMREF_LOCKED(rt);
4500 RT_UNLOCK(rt);
4501 } else {
4502 RT_UNLOCK(rt);
4503 rtfree_locked(rt);
4504 }
4505 rt = NULL; /* "rt" has been taken care of */
4506 lck_mtx_unlock(rnh_lock);
4507 }
4508 error = 0;
4509 goto release;
4510
4511 sendpkt:
4512 if (rt != NULL) {
4513 RT_LOCK_ASSERT_NOTHELD(rt);
4514 }
4515
4516 /* discard the packet if IPv6 operation is disabled on the interface */
4517 if (ifp->if_eflags & IFEF_IPV6_DISABLED) {
4518 error = ENETDOWN; /* better error? */
4519 goto bad;
4520 }
4521
4522 if (ifp->if_flags & IFF_LOOPBACK) {
4523 /* forwarding rules require the original scope_id */
4524 m0->m_pkthdr.rcvif = origifp;
4525 error = dlil_output(origifp, PF_INET6, m0, (caddr_t)rt,
4526 SA(dst), 0, adv);
4527 goto release;
4528 } else {
4529 /* Do not allow loopback address to wind up on a wire */
4530 struct ip6_hdr *ip6 = mtod(m0, struct ip6_hdr *);
4531
4532 if ((IN6_IS_ADDR_LOOPBACK(&ip6->ip6_src) ||
4533 IN6_IS_ADDR_LOOPBACK(&ip6->ip6_dst))) {
4534 ip6stat.ip6s_badscope++;
4535 error = EADDRNOTAVAIL;
4536 goto bad;
4537 }
4538 }
4539
4540 if (rt != NULL) {
4541 RT_LOCK_SPIN(rt);
4542 /* Mark use timestamp */
4543 if (rt->rt_llinfo != NULL) {
4544 nd6_llreach_use(rt->rt_llinfo);
4545 }
4546 RT_UNLOCK(rt);
4547 }
4548
4549 struct mbuf *mcur = m0;
4550 uint32_t pktcnt = 0;
4551
4552 while (mcur) {
4553 if (hint != NULL && nstat_collect) {
4554 int scnt;
4555
4556 if ((mcur->m_pkthdr.csum_flags & CSUM_TSO_IPV6) &&
4557 (mcur->m_pkthdr.tso_segsz > 0)) {
4558 scnt = mcur->m_pkthdr.len / mcur->m_pkthdr.tso_segsz;
4559 } else {
4560 scnt = 1;
4561 }
4562
4563 nstat_route_tx(hint, scnt, mcur->m_pkthdr.len, 0);
4564 }
4565 pktcnt++;
4566
4567 mcur->m_pkthdr.rcvif = NULL;
4568 mcur = mcur->m_nextpkt;
4569 }
4570 if (pktcnt > ip6_maxchainsent) {
4571 ip6_maxchainsent = pktcnt;
4572 }
4573 error = dlil_output(ifp, PF_INET6, m0, (caddr_t)rt, SA(dst), 0, adv);
4574 goto release;
4575
4576 bad:
4577 if (m0 != NULL) {
4578 m_freem_list(m0);
4579 }
4580
4581 release:
4582 /* Clean up "rt" unless it's already been done */
4583 if (rt != NULL) {
4584 RT_LOCK_SPIN(rt);
4585 if (rt == hint0) {
4586 RT_REMREF_LOCKED(rt);
4587 RT_UNLOCK(rt);
4588 } else {
4589 RT_UNLOCK(rt);
4590 rtfree(rt);
4591 }
4592 }
4593 /* And now clean up "rtrele" if there is any */
4594 if (rtrele != NULL) {
4595 RT_LOCK_SPIN(rtrele);
4596 if (rtrele == hint0) {
4597 RT_REMREF_LOCKED(rtrele);
4598 RT_UNLOCK(rtrele);
4599 } else {
4600 RT_UNLOCK(rtrele);
4601 rtfree(rtrele);
4602 }
4603 }
4604 return error;
4605 }
4606 #undef senderr
4607
4608 int
nd6_need_cache(struct ifnet * ifp)4609 nd6_need_cache(struct ifnet *ifp)
4610 {
4611 /*
4612 * XXX: we currently do not make neighbor cache on any interface
4613 * other than ARCnet, Ethernet, FDDI and GIF.
4614 *
4615 * RFC2893 says:
4616 * - unidirectional tunnels needs no ND
4617 */
4618 switch (ifp->if_type) {
4619 case IFT_ARCNET:
4620 case IFT_ETHER:
4621 case IFT_FDDI:
4622 case IFT_IEEE1394:
4623 case IFT_L2VLAN:
4624 case IFT_IEEE8023ADLAG:
4625 #if IFT_IEEE80211
4626 case IFT_IEEE80211:
4627 #endif
4628 case IFT_GIF: /* XXX need more cases? */
4629 case IFT_PPP:
4630 #if IFT_TUNNEL
4631 case IFT_TUNNEL:
4632 #endif
4633 case IFT_BRIDGE:
4634 case IFT_CELLULAR:
4635 return 1;
4636 default:
4637 return 0;
4638 }
4639 }
4640
4641 int
nd6_storelladdr(struct ifnet * ifp,struct rtentry * rt,struct mbuf * m,struct sockaddr * dst,u_char * desten)4642 nd6_storelladdr(struct ifnet *ifp, struct rtentry *rt, struct mbuf *m,
4643 struct sockaddr *dst, u_char *desten)
4644 {
4645 int i;
4646 struct sockaddr_dl *sdl;
4647
4648 if (m->m_flags & M_MCAST) {
4649 switch (ifp->if_type) {
4650 case IFT_ETHER:
4651 case IFT_FDDI:
4652 case IFT_L2VLAN:
4653 case IFT_IEEE8023ADLAG:
4654 #if IFT_IEEE80211
4655 case IFT_IEEE80211:
4656 #endif
4657 case IFT_BRIDGE:
4658 ETHER_MAP_IPV6_MULTICAST(&SIN6(dst)->sin6_addr, desten);
4659 return 1;
4660 case IFT_IEEE1394:
4661 for (i = 0; i < ifp->if_addrlen; i++) {
4662 desten[i] = ~0;
4663 }
4664 return 1;
4665 case IFT_ARCNET:
4666 *desten = 0;
4667 return 1;
4668 default:
4669 return 0; /* caller will free mbuf */
4670 }
4671 }
4672
4673 if (rt == NULL) {
4674 /* this could happen, if we could not allocate memory */
4675 return 0; /* caller will free mbuf */
4676 }
4677 RT_LOCK(rt);
4678 if (rt->rt_gateway->sa_family != AF_LINK) {
4679 printf("nd6_storelladdr: something odd happens\n");
4680 RT_UNLOCK(rt);
4681 return 0; /* caller will free mbuf */
4682 }
4683 sdl = SDL(rt->rt_gateway);
4684 if (sdl->sdl_alen == 0) {
4685 /* this should be impossible, but we bark here for debugging */
4686 printf("nd6_storelladdr: sdl_alen == 0\n");
4687 RT_UNLOCK(rt);
4688 return 0; /* caller will free mbuf */
4689 }
4690
4691 bcopy(LLADDR(sdl), desten, sdl->sdl_alen);
4692 RT_UNLOCK(rt);
4693 return 1;
4694 }
4695
4696 /*
4697 * This is the ND pre-output routine; care must be taken to ensure that
4698 * the "hint" route never gets freed via rtfree(), since the caller may
4699 * have stored it inside a struct route with a reference held for that
4700 * placeholder.
4701 */
4702 errno_t
nd6_lookup_ipv6(ifnet_t ifp,const struct sockaddr_in6 * ip6_dest,struct sockaddr_dl * ll_dest,size_t ll_dest_len,route_t hint,mbuf_t packet)4703 nd6_lookup_ipv6(ifnet_t ifp, const struct sockaddr_in6 *ip6_dest,
4704 struct sockaddr_dl *ll_dest, size_t ll_dest_len, route_t hint,
4705 mbuf_t packet)
4706 {
4707 route_t route = hint;
4708 errno_t result = 0;
4709 struct sockaddr_dl *sdl = NULL;
4710 size_t copy_len;
4711
4712 if (ifp == NULL || ip6_dest == NULL) {
4713 return EINVAL;
4714 }
4715
4716 if (ip6_dest->sin6_family != AF_INET6) {
4717 return EAFNOSUPPORT;
4718 }
4719
4720 if ((ifp->if_flags & (IFF_UP | IFF_RUNNING)) != (IFF_UP | IFF_RUNNING)) {
4721 return ENETDOWN;
4722 }
4723
4724 if (hint != NULL) {
4725 /*
4726 * Callee holds a reference on the route and returns
4727 * with the route entry locked, upon success.
4728 */
4729 result = route_to_gwroute((const struct sockaddr *)ip6_dest,
4730 hint, &route);
4731 if (result != 0) {
4732 return result;
4733 }
4734 if (route != NULL) {
4735 RT_LOCK_ASSERT_HELD(route);
4736 }
4737 }
4738
4739 if ((packet != NULL && (packet->m_flags & M_MCAST) != 0) ||
4740 ((ifp->if_flags & IFF_MULTICAST) &&
4741 IN6_IS_ADDR_MULTICAST(&ip6_dest->sin6_addr))) {
4742 if (route != NULL) {
4743 RT_UNLOCK(route);
4744 }
4745 result = dlil_resolve_multi(ifp,
4746 (const struct sockaddr *)ip6_dest,
4747 SA(ll_dest), ll_dest_len);
4748 if (route != NULL) {
4749 RT_LOCK(route);
4750 }
4751 goto release;
4752 } else if (route == NULL) {
4753 /*
4754 * rdar://24596652
4755 * For unicast, lookup existing ND6 entries but
4756 * do not trigger a resolution
4757 */
4758 lck_mtx_lock(rnh_lock);
4759 route = rt_lookup(TRUE,
4760 __DECONST(struct sockaddr *, ip6_dest), NULL,
4761 rt_tables[AF_INET6], ifp->if_index);
4762 lck_mtx_unlock(rnh_lock);
4763
4764 if (route != NULL) {
4765 RT_LOCK(route);
4766 }
4767 }
4768
4769 if (route == NULL) {
4770 /*
4771 * This could happen, if we could not allocate memory or
4772 * if route_to_gwroute() didn't return a route.
4773 */
4774 result = ENOBUFS;
4775 goto release;
4776 }
4777
4778 if (route->rt_gateway->sa_family != AF_LINK) {
4779 nd6log0(error, "%s: route %s on %s%d gateway address not AF_LINK\n",
4780 __func__, ip6_sprintf(&ip6_dest->sin6_addr),
4781 route->rt_ifp->if_name, route->rt_ifp->if_unit);
4782 result = EADDRNOTAVAIL;
4783 goto release;
4784 }
4785
4786 sdl = SDL(route->rt_gateway);
4787 if (sdl->sdl_alen == 0) {
4788 /* this should be impossible, but we bark here for debugging */
4789 nd6log(error, "%s: route %s on %s%d sdl_alen == 0\n", __func__,
4790 ip6_sprintf(&ip6_dest->sin6_addr), route->rt_ifp->if_name,
4791 route->rt_ifp->if_unit);
4792 result = EHOSTUNREACH;
4793 goto release;
4794 }
4795
4796 copy_len = sdl->sdl_len <= ll_dest_len ? sdl->sdl_len : ll_dest_len;
4797 bcopy(sdl, ll_dest, copy_len);
4798
4799 release:
4800 if (route != NULL) {
4801 if (route == hint) {
4802 RT_REMREF_LOCKED(route);
4803 RT_UNLOCK(route);
4804 } else {
4805 RT_UNLOCK(route);
4806 rtfree(route);
4807 }
4808 }
4809 return result;
4810 }
4811
4812 #if (DEVELOPMENT || DEBUG)
4813
4814 static int sysctl_nd6_lookup_ipv6 SYSCTL_HANDLER_ARGS;
4815 SYSCTL_PROC(_net_inet6_icmp6, OID_AUTO, nd6_lookup_ipv6,
4816 CTLTYPE_STRUCT | CTLFLAG_RW | CTLFLAG_LOCKED, 0, 0,
4817 sysctl_nd6_lookup_ipv6, "S", "");
4818
4819 int
4820 sysctl_nd6_lookup_ipv6 SYSCTL_HANDLER_ARGS
4821 {
4822 #pragma unused(oidp, arg1, arg2)
4823 int error = 0;
4824 struct nd6_lookup_ipv6_args nd6_lookup_ipv6_args;
4825 ifnet_t ifp = NULL;
4826
4827 /*
4828 * Only root can lookup MAC addresses
4829 */
4830 error = proc_suser(current_proc());
4831 if (error != 0) {
4832 nd6log0(error, "%s: proc_suser() error %d\n",
4833 __func__, error);
4834 goto done;
4835 }
4836 if (req->oldptr == USER_ADDR_NULL) {
4837 req->oldidx = sizeof(struct nd6_lookup_ipv6_args);
4838 }
4839 if (req->newptr == USER_ADDR_NULL) {
4840 goto done;
4841 }
4842 if (req->oldlen != sizeof(struct nd6_lookup_ipv6_args) ||
4843 req->newlen != sizeof(struct nd6_lookup_ipv6_args)) {
4844 error = EINVAL;
4845 nd6log0(error, "%s: bad req, error %d\n",
4846 __func__, error);
4847 goto done;
4848 }
4849 error = SYSCTL_IN(req, &nd6_lookup_ipv6_args,
4850 sizeof(struct nd6_lookup_ipv6_args));
4851 if (error != 0) {
4852 nd6log0(error, "%s: SYSCTL_IN() error %d\n",
4853 __func__, error);
4854 goto done;
4855 }
4856
4857 if (nd6_lookup_ipv6_args.ll_dest_len > sizeof(nd6_lookup_ipv6_args.ll_dest_)) {
4858 error = EINVAL;
4859 nd6log0(error, "%s: bad ll_dest_len, error %d\n",
4860 __func__, error);
4861 goto done;
4862 }
4863
4864 /* Make sure to terminate the string */
4865 nd6_lookup_ipv6_args.ifname[IFNAMSIZ - 1] = 0;
4866
4867 error = ifnet_find_by_name(nd6_lookup_ipv6_args.ifname, &ifp);
4868 if (error != 0) {
4869 nd6log0(error, "%s: ifnet_find_by_name() error %d\n",
4870 __func__, error);
4871 goto done;
4872 }
4873
4874 error = nd6_lookup_ipv6(ifp, &nd6_lookup_ipv6_args.ip6_dest,
4875 &nd6_lookup_ipv6_args.ll_dest_._sdl,
4876 nd6_lookup_ipv6_args.ll_dest_len, NULL, NULL);
4877 if (error != 0) {
4878 nd6log0(error, "%s: nd6_lookup_ipv6() error %d\n",
4879 __func__, error);
4880 goto done;
4881 }
4882
4883 error = SYSCTL_OUT(req, &nd6_lookup_ipv6_args,
4884 sizeof(struct nd6_lookup_ipv6_args));
4885 if (error != 0) {
4886 nd6log0(error, "%s: SYSCTL_OUT() error %d\n",
4887 __func__, error);
4888 goto done;
4889 }
4890 done:
4891 return error;
4892 }
4893
4894 #endif /* (DEVELOPEMENT || DEBUG) */
4895
4896 int
nd6_setifinfo(struct ifnet * ifp,u_int32_t before,u_int32_t after)4897 nd6_setifinfo(struct ifnet *ifp, u_int32_t before, u_int32_t after)
4898 {
4899 uint32_t b, a;
4900 int err = 0;
4901
4902 /*
4903 * Handle ND6_IFF_IFDISABLED
4904 */
4905 if ((before & ND6_IFF_IFDISABLED) ||
4906 (after & ND6_IFF_IFDISABLED)) {
4907 b = (before & ND6_IFF_IFDISABLED);
4908 a = (after & ND6_IFF_IFDISABLED);
4909
4910 if (b != a && (err = nd6_if_disable(ifp,
4911 ((int32_t)(a - b) > 0))) != 0) {
4912 goto done;
4913 }
4914 }
4915
4916 /*
4917 * Handle ND6_IFF_PROXY_PREFIXES
4918 */
4919 if ((before & ND6_IFF_PROXY_PREFIXES) ||
4920 (after & ND6_IFF_PROXY_PREFIXES)) {
4921 b = (before & ND6_IFF_PROXY_PREFIXES);
4922 a = (after & ND6_IFF_PROXY_PREFIXES);
4923
4924 if (b != a && (err = nd6_if_prproxy(ifp,
4925 ((int32_t)(a - b) > 0))) != 0) {
4926 goto done;
4927 }
4928 }
4929 done:
4930 return err;
4931 }
4932
4933 /*
4934 * Enable/disable IPv6 on an interface, called as part of
4935 * setting/clearing ND6_IFF_IFDISABLED, or during DAD failure.
4936 */
4937 int
nd6_if_disable(struct ifnet * ifp,boolean_t enable)4938 nd6_if_disable(struct ifnet *ifp, boolean_t enable)
4939 {
4940 if (enable) {
4941 if_set_eflags(ifp, IFEF_IPV6_DISABLED);
4942 } else {
4943 if_clear_eflags(ifp, IFEF_IPV6_DISABLED);
4944 }
4945
4946 return 0;
4947 }
4948
4949 static int
4950 nd6_sysctl_drlist SYSCTL_HANDLER_ARGS
4951 {
4952 #pragma unused(oidp, arg1, arg2)
4953 char pbuf[MAX_IPv6_STR_LEN];
4954 struct nd_defrouter *dr;
4955 int error = 0;
4956
4957 if (req->newptr != USER_ADDR_NULL) {
4958 return EPERM;
4959 }
4960
4961 /* XXX Handle mapped defrouter entries */
4962 lck_mtx_lock(nd6_mutex);
4963 if (proc_is64bit(req->p)) {
4964 struct in6_defrouter_64 d;
4965
4966 bzero(&d, sizeof(d));
4967 d.rtaddr.sin6_family = AF_INET6;
4968 d.rtaddr.sin6_len = sizeof(d.rtaddr);
4969
4970 TAILQ_FOREACH(dr, &nd_defrouter_list, dr_entry) {
4971 d.rtaddr.sin6_addr = dr->rtaddr;
4972 if (in6_recoverscope(&d.rtaddr,
4973 &dr->rtaddr, dr->ifp) != 0) {
4974 log(LOG_ERR, "scope error in default router "
4975 "list (%s)\n", inet_ntop(AF_INET6,
4976 &dr->rtaddr, pbuf, sizeof(pbuf)));
4977 }
4978 d.flags = dr->flags;
4979 d.stateflags = dr->stateflags;
4980 d.rtlifetime = (u_short)dr->rtlifetime;
4981 d.expire = (int)nddr_getexpire(dr);
4982 d.if_index = dr->ifp->if_index;
4983 error = SYSCTL_OUT(req, &d, sizeof(d));
4984 if (error != 0) {
4985 break;
4986 }
4987 }
4988 } else {
4989 struct in6_defrouter_32 d;
4990
4991 bzero(&d, sizeof(d));
4992 d.rtaddr.sin6_family = AF_INET6;
4993 d.rtaddr.sin6_len = sizeof(d.rtaddr);
4994
4995 TAILQ_FOREACH(dr, &nd_defrouter_list, dr_entry) {
4996 d.rtaddr.sin6_addr = dr->rtaddr;
4997 if (in6_recoverscope(&d.rtaddr,
4998 &dr->rtaddr, dr->ifp) != 0) {
4999 log(LOG_ERR, "scope error in default router "
5000 "list (%s)\n", inet_ntop(AF_INET6,
5001 &dr->rtaddr, pbuf, sizeof(pbuf)));
5002 }
5003 d.flags = dr->flags;
5004 d.stateflags = dr->stateflags;
5005 d.rtlifetime = (u_short)dr->rtlifetime;
5006 d.expire = (int)nddr_getexpire(dr);
5007 d.if_index = dr->ifp->if_index;
5008 error = SYSCTL_OUT(req, &d, sizeof(d));
5009 if (error != 0) {
5010 break;
5011 }
5012 }
5013 }
5014 lck_mtx_unlock(nd6_mutex);
5015 return error;
5016 }
5017
5018 static int
5019 nd6_sysctl_prlist SYSCTL_HANDLER_ARGS
5020 {
5021 #pragma unused(oidp, arg1, arg2)
5022 char pbuf[MAX_IPv6_STR_LEN];
5023 struct nd_pfxrouter *pfr;
5024 struct sockaddr_in6 s6;
5025 struct nd_prefix *pr;
5026 int error = 0;
5027
5028 if (req->newptr != USER_ADDR_NULL) {
5029 return EPERM;
5030 }
5031
5032 bzero(&s6, sizeof(s6));
5033 s6.sin6_family = AF_INET6;
5034 s6.sin6_len = sizeof(s6);
5035
5036 /* XXX Handle mapped defrouter entries */
5037 lck_mtx_lock(nd6_mutex);
5038 if (proc_is64bit(req->p)) {
5039 struct in6_prefix_64 p;
5040
5041 bzero(&p, sizeof(p));
5042 p.origin = PR_ORIG_RA;
5043
5044 LIST_FOREACH(pr, &nd_prefix, ndpr_entry) {
5045 NDPR_LOCK(pr);
5046 p.prefix = pr->ndpr_prefix;
5047 if (in6_recoverscope(&p.prefix,
5048 &pr->ndpr_prefix.sin6_addr, pr->ndpr_ifp) != 0) {
5049 log(LOG_ERR, "scope error in "
5050 "prefix list (%s)\n", inet_ntop(AF_INET6,
5051 &p.prefix.sin6_addr, pbuf, sizeof(pbuf)));
5052 }
5053 p.raflags = pr->ndpr_raf;
5054 p.prefixlen = pr->ndpr_plen;
5055 p.vltime = pr->ndpr_vltime;
5056 p.pltime = pr->ndpr_pltime;
5057 p.if_index = pr->ndpr_ifp->if_index;
5058 p.expire = (u_long)ndpr_getexpire(pr);
5059 p.refcnt = pr->ndpr_addrcnt;
5060 p.flags = pr->ndpr_stateflags;
5061 p.advrtrs = 0;
5062 LIST_FOREACH(pfr, &pr->ndpr_advrtrs, pfr_entry)
5063 p.advrtrs++;
5064 error = SYSCTL_OUT(req, &p, sizeof(p));
5065 if (error != 0) {
5066 NDPR_UNLOCK(pr);
5067 break;
5068 }
5069 LIST_FOREACH(pfr, &pr->ndpr_advrtrs, pfr_entry) {
5070 s6.sin6_addr = pfr->router->rtaddr;
5071 if (in6_recoverscope(&s6, &pfr->router->rtaddr,
5072 pfr->router->ifp) != 0) {
5073 log(LOG_ERR,
5074 "scope error in prefix list (%s)\n",
5075 inet_ntop(AF_INET6, &s6.sin6_addr,
5076 pbuf, sizeof(pbuf)));
5077 }
5078 error = SYSCTL_OUT(req, &s6, sizeof(s6));
5079 if (error != 0) {
5080 break;
5081 }
5082 }
5083 NDPR_UNLOCK(pr);
5084 if (error != 0) {
5085 break;
5086 }
5087 }
5088 } else {
5089 struct in6_prefix_32 p;
5090
5091 bzero(&p, sizeof(p));
5092 p.origin = PR_ORIG_RA;
5093
5094 LIST_FOREACH(pr, &nd_prefix, ndpr_entry) {
5095 NDPR_LOCK(pr);
5096 p.prefix = pr->ndpr_prefix;
5097 if (in6_recoverscope(&p.prefix,
5098 &pr->ndpr_prefix.sin6_addr, pr->ndpr_ifp) != 0) {
5099 log(LOG_ERR,
5100 "scope error in prefix list (%s)\n",
5101 inet_ntop(AF_INET6, &p.prefix.sin6_addr,
5102 pbuf, sizeof(pbuf)));
5103 }
5104 p.raflags = pr->ndpr_raf;
5105 p.prefixlen = pr->ndpr_plen;
5106 p.vltime = pr->ndpr_vltime;
5107 p.pltime = pr->ndpr_pltime;
5108 p.if_index = pr->ndpr_ifp->if_index;
5109 p.expire = (u_int32_t)ndpr_getexpire(pr);
5110 p.refcnt = pr->ndpr_addrcnt;
5111 p.flags = pr->ndpr_stateflags;
5112 p.advrtrs = 0;
5113 LIST_FOREACH(pfr, &pr->ndpr_advrtrs, pfr_entry)
5114 p.advrtrs++;
5115 error = SYSCTL_OUT(req, &p, sizeof(p));
5116 if (error != 0) {
5117 NDPR_UNLOCK(pr);
5118 break;
5119 }
5120 LIST_FOREACH(pfr, &pr->ndpr_advrtrs, pfr_entry) {
5121 s6.sin6_addr = pfr->router->rtaddr;
5122 if (in6_recoverscope(&s6, &pfr->router->rtaddr,
5123 pfr->router->ifp) != 0) {
5124 log(LOG_ERR,
5125 "scope error in prefix list (%s)\n",
5126 inet_ntop(AF_INET6, &s6.sin6_addr,
5127 pbuf, sizeof(pbuf)));
5128 }
5129 error = SYSCTL_OUT(req, &s6, sizeof(s6));
5130 if (error != 0) {
5131 break;
5132 }
5133 }
5134 NDPR_UNLOCK(pr);
5135 if (error != 0) {
5136 break;
5137 }
5138 }
5139 }
5140 lck_mtx_unlock(nd6_mutex);
5141
5142 return error;
5143 }
5144
5145 void
in6_ifaddr_set_dadprogress(struct in6_ifaddr * ia)5146 in6_ifaddr_set_dadprogress(struct in6_ifaddr *ia)
5147 {
5148 struct ifnet* ifp = ia->ia_ifp;
5149 uint32_t flags = IN6_IFF_TENTATIVE;
5150 uint32_t optdad = nd6_optimistic_dad;
5151 struct nd_ifinfo *ndi = NULL;
5152
5153 ndi = ND_IFINFO(ifp);
5154 VERIFY((NULL != ndi) && (TRUE == ndi->initialized));
5155 if (!(ndi->flags & ND6_IFF_DAD)) {
5156 return;
5157 }
5158
5159 if (optdad) {
5160 if (ifp->if_ipv6_router_mode == IPV6_ROUTER_MODE_EXCLUSIVE) {
5161 optdad = 0;
5162 } else {
5163 lck_mtx_lock(&ndi->lock);
5164 if ((ndi->flags & ND6_IFF_REPLICATED) != 0) {
5165 optdad = 0;
5166 }
5167 lck_mtx_unlock(&ndi->lock);
5168 }
5169 }
5170
5171 if (optdad) {
5172 if ((optdad & ND6_OPTIMISTIC_DAD_LINKLOCAL) &&
5173 IN6_IS_ADDR_LINKLOCAL(&ia->ia_addr.sin6_addr)) {
5174 flags = IN6_IFF_OPTIMISTIC;
5175 } else if ((optdad & ND6_OPTIMISTIC_DAD_AUTOCONF) &&
5176 (ia->ia6_flags & IN6_IFF_AUTOCONF)) {
5177 if (ia->ia6_flags & IN6_IFF_TEMPORARY) {
5178 if (optdad & ND6_OPTIMISTIC_DAD_TEMPORARY) {
5179 flags = IN6_IFF_OPTIMISTIC;
5180 }
5181 } else if (ia->ia6_flags & IN6_IFF_SECURED) {
5182 if (optdad & ND6_OPTIMISTIC_DAD_SECURED) {
5183 flags = IN6_IFF_OPTIMISTIC;
5184 }
5185 } else {
5186 /*
5187 * Keeping the behavior for temp and CGA
5188 * SLAAC addresses to have a knob for optimistic
5189 * DAD.
5190 * Other than that if ND6_OPTIMISTIC_DAD_AUTOCONF
5191 * is set, we should default to optimistic
5192 * DAD.
5193 * For now this means SLAAC addresses with interface
5194 * identifier derived from modified EUI-64 bit
5195 * identifiers.
5196 */
5197 flags = IN6_IFF_OPTIMISTIC;
5198 }
5199 } else if ((optdad & ND6_OPTIMISTIC_DAD_DYNAMIC) &&
5200 (ia->ia6_flags & IN6_IFF_DYNAMIC)) {
5201 if (ia->ia6_flags & IN6_IFF_TEMPORARY) {
5202 if (optdad & ND6_OPTIMISTIC_DAD_TEMPORARY) {
5203 flags = IN6_IFF_OPTIMISTIC;
5204 }
5205 } else {
5206 flags = IN6_IFF_OPTIMISTIC;
5207 }
5208 } else if ((optdad & ND6_OPTIMISTIC_DAD_MANUAL) &&
5209 (ia->ia6_flags & IN6_IFF_OPTIMISTIC)) {
5210 /*
5211 * rdar://17483438
5212 * Bypass tentative for address assignments
5213 * not covered above (e.g. manual) upon request
5214 */
5215 if (!IN6_IS_ADDR_LINKLOCAL(&ia->ia_addr.sin6_addr) &&
5216 !(ia->ia6_flags & IN6_IFF_AUTOCONF) &&
5217 !(ia->ia6_flags & IN6_IFF_DYNAMIC)) {
5218 flags = IN6_IFF_OPTIMISTIC;
5219 }
5220 }
5221 }
5222
5223 ia->ia6_flags &= ~(IN6_IFF_DUPLICATED | IN6_IFF_DADPROGRESS);
5224 ia->ia6_flags |= flags;
5225
5226 nd6log2(debug, "%s - %s ifp %s ia6_flags 0x%x\n",
5227 __func__,
5228 ip6_sprintf(&ia->ia_addr.sin6_addr),
5229 if_name(ia->ia_ifp),
5230 ia->ia6_flags);
5231 }
5232