]> git.saurik.com Git - apple/xnu.git/blob - bsd/net/route.c
xnu-7195.60.75.tar.gz
[apple/xnu.git] / bsd / net / route.c
1 /*
2 * Copyright (c) 2000-2020 Apple Inc. All rights reserved.
3 *
4 * @APPLE_OSREFERENCE_LICENSE_HEADER_START@
5 *
6 * This file contains Original Code and/or Modifications of Original Code
7 * as defined in and that are subject to the Apple Public Source License
8 * Version 2.0 (the 'License'). You may not use this file except in
9 * compliance with the License. The rights granted to you under the License
10 * may not be used to create, or enable the creation or redistribution of,
11 * unlawful or unlicensed copies of an Apple operating system, or to
12 * circumvent, violate, or enable the circumvention or violation of, any
13 * terms of an Apple operating system software license agreement.
14 *
15 * Please obtain a copy of the License at
16 * http://www.opensource.apple.com/apsl/ and read it before using this file.
17 *
18 * The Original Code and all software distributed under the License are
19 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
20 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
21 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
22 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
23 * Please see the License for the specific language governing rights and
24 * limitations under the License.
25 *
26 * @APPLE_OSREFERENCE_LICENSE_HEADER_END@
27 */
28 /*
29 * Copyright (c) 1980, 1986, 1991, 1993
30 * The Regents of the University of California. All rights reserved.
31 *
32 * Redistribution and use in source and binary forms, with or without
33 * modification, are permitted provided that the following conditions
34 * are met:
35 * 1. Redistributions of source code must retain the above copyright
36 * notice, this list of conditions and the following disclaimer.
37 * 2. Redistributions in binary form must reproduce the above copyright
38 * notice, this list of conditions and the following disclaimer in the
39 * documentation and/or other materials provided with the distribution.
40 * 3. All advertising materials mentioning features or use of this software
41 * must display the following acknowledgement:
42 * This product includes software developed by the University of
43 * California, Berkeley and its contributors.
44 * 4. Neither the name of the University nor the names of its contributors
45 * may be used to endorse or promote products derived from this software
46 * without specific prior written permission.
47 *
48 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
49 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
50 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
51 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
52 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
53 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
54 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
55 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
56 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
57 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
58 * SUCH DAMAGE.
59 *
60 * @(#)route.c 8.2 (Berkeley) 11/15/93
61 * $FreeBSD: src/sys/net/route.c,v 1.59.2.3 2001/07/29 19:18:02 ume Exp $
62 */
63
64 #include <sys/param.h>
65 #include <sys/sysctl.h>
66 #include <sys/systm.h>
67 #include <sys/malloc.h>
68 #include <sys/mbuf.h>
69 #include <sys/socket.h>
70 #include <sys/domain.h>
71 #include <sys/stat.h>
72 #include <sys/ubc.h>
73 #include <sys/vnode.h>
74 #include <sys/syslog.h>
75 #include <sys/queue.h>
76 #include <sys/mcache.h>
77 #include <sys/priv.h>
78 #include <sys/protosw.h>
79 #include <sys/sdt.h>
80 #include <sys/kernel.h>
81 #include <kern/locks.h>
82 #include <kern/zalloc.h>
83
84 #include <net/dlil.h>
85 #include <net/if.h>
86 #include <net/route.h>
87 #include <net/ntstat.h>
88 #include <net/nwk_wq.h>
89 #if NECP
90 #include <net/necp.h>
91 #endif /* NECP */
92
93 #include <netinet/in.h>
94 #include <netinet/in_var.h>
95 #include <netinet/ip_var.h>
96 #include <netinet/ip.h>
97 #include <netinet/ip6.h>
98 #include <netinet/in_arp.h>
99
100 #include <netinet6/ip6_var.h>
101 #include <netinet6/in6_var.h>
102 #include <netinet6/nd6.h>
103
104 #include <net/if_dl.h>
105
106 #include <libkern/OSAtomic.h>
107 #include <libkern/OSDebug.h>
108
109 #include <pexpert/pexpert.h>
110
111 #if CONFIG_MACF
112 #include <sys/kauth.h>
113 #endif
114
115 /*
116 * Synchronization notes:
117 *
118 * Routing entries fall under two locking domains: the global routing table
119 * lock (rnh_lock) and the per-entry lock (rt_lock); the latter is a mutex that
120 * resides (statically defined) in the rtentry structure.
121 *
122 * The locking domains for routing are defined as follows:
123 *
124 * The global routing lock is used to serialize all accesses to the radix
125 * trees defined by rt_tables[], as well as the tree of masks. This includes
126 * lookups, insertions and removals of nodes to/from the respective tree.
127 * It is also used to protect certain fields in the route entry that aren't
128 * often modified and/or require global serialization (more details below.)
129 *
130 * The per-route entry lock is used to serialize accesses to several routing
131 * entry fields (more details below.) Acquiring and releasing this lock is
132 * done via RT_LOCK() and RT_UNLOCK() routines.
133 *
134 * In cases where both rnh_lock and rt_lock must be held, the former must be
135 * acquired first in order to maintain lock ordering. It is not a requirement
136 * that rnh_lock be acquired first before rt_lock, but in case both must be
137 * acquired in succession, the correct lock ordering must be followed.
138 *
139 * The fields of the rtentry structure are protected in the following way:
140 *
141 * rt_nodes[]
142 *
143 * - Routing table lock (rnh_lock).
144 *
145 * rt_parent, rt_mask, rt_llinfo_free, rt_tree_genid
146 *
147 * - Set once during creation and never changes; no locks to read.
148 *
149 * rt_flags, rt_genmask, rt_llinfo, rt_rmx, rt_refcnt, rt_gwroute
150 *
151 * - Routing entry lock (rt_lock) for read/write access.
152 *
153 * - Some values of rt_flags are either set once at creation time,
154 * or aren't currently used, and thus checking against them can
155 * be done without rt_lock: RTF_GATEWAY, RTF_HOST, RTF_DYNAMIC,
156 * RTF_DONE, RTF_XRESOLVE, RTF_STATIC, RTF_BLACKHOLE, RTF_ANNOUNCE,
157 * RTF_USETRAILERS, RTF_WASCLONED, RTF_PINNED, RTF_LOCAL,
158 * RTF_BROADCAST, RTF_MULTICAST, RTF_IFSCOPE, RTF_IFREF.
159 *
160 * rt_key, rt_gateway, rt_ifp, rt_ifa
161 *
162 * - Always written/modified with both rnh_lock and rt_lock held.
163 *
164 * - May be read freely with rnh_lock held, else must hold rt_lock
165 * for read access; holding both locks for read is also okay.
166 *
167 * - In the event rnh_lock is not acquired, or is not possible to be
168 * acquired across the operation, setting RTF_CONDEMNED on a route
169 * entry will prevent its rt_key, rt_gateway, rt_ifp and rt_ifa
170 * from being modified. This is typically done on a route that
171 * has been chosen for a removal (from the tree) prior to dropping
172 * the rt_lock, so that those values will remain the same until
173 * the route is freed.
174 *
175 * When rnh_lock is held rt_setgate(), rt_setif(), and rtsetifa() are
176 * single-threaded, thus exclusive. This flag will also prevent the
177 * route from being looked up via rt_lookup().
178 *
179 * rt_genid
180 *
181 * - Assumes that 32-bit writes are atomic; no locks.
182 *
183 * rt_dlt, rt_output
184 *
185 * - Currently unused; no locks.
186 *
187 * Operations on a route entry can be described as follows:
188 *
189 * CREATE an entry with reference count set to 0 as part of RTM_ADD/RESOLVE.
190 *
191 * INSERTION of an entry into the radix tree holds the rnh_lock, checks
192 * for duplicates and then adds the entry. rtrequest returns the entry
193 * after bumping up the reference count to 1 (for the caller).
194 *
195 * LOOKUP of an entry holds the rnh_lock and bumps up the reference count
196 * before returning; it is valid to also bump up the reference count using
197 * RT_ADDREF after the lookup has returned an entry.
198 *
199 * REMOVAL of an entry from the radix tree holds the rnh_lock, removes the
200 * entry but does not decrement the reference count. Removal happens when
201 * the route is explicitly deleted (RTM_DELETE) or when it is in the cached
202 * state and it expires. The route is said to be "down" when it is no
203 * longer present in the tree. Freeing the entry will happen on the last
204 * reference release of such a "down" route.
205 *
206 * RT_ADDREF/RT_REMREF operates on the routing entry which increments/
207 * decrements the reference count, rt_refcnt, atomically on the rtentry.
208 * rt_refcnt is modified only using this routine. The general rule is to
209 * do RT_ADDREF in the function that is passing the entry as an argument,
210 * in order to prevent the entry from being freed by the callee.
211 */
212
213 #define equal(a1, a2) (bcmp((caddr_t)(a1), (caddr_t)(a2), (a1)->sa_len) == 0)
214
215 extern void kdp_set_gateway_mac(void *gatewaymac);
216
217 __private_extern__ struct rtstat rtstat = {
218 .rts_badredirect = 0,
219 .rts_dynamic = 0,
220 .rts_newgateway = 0,
221 .rts_unreach = 0,
222 .rts_wildcard = 0,
223 .rts_badrtgwroute = 0
224 };
225 struct radix_node_head *rt_tables[AF_MAX + 1];
226
227 decl_lck_mtx_data(, rnh_lock_data); /* global routing tables mutex */
228 lck_mtx_t *rnh_lock = &rnh_lock_data;
229 static lck_attr_t *rnh_lock_attr;
230 static lck_grp_t *rnh_lock_grp;
231 static lck_grp_attr_t *rnh_lock_grp_attr;
232
233 /* Lock group and attribute for routing entry locks */
234 static lck_attr_t *rte_mtx_attr;
235 static lck_grp_t *rte_mtx_grp;
236 static lck_grp_attr_t *rte_mtx_grp_attr;
237
238 int rttrash = 0; /* routes not in table but not freed */
239
240 boolean_t trigger_v6_defrtr_select = FALSE;
241 unsigned int rte_debug = 0;
242
243 /* Possible flags for rte_debug */
244 #define RTD_DEBUG 0x1 /* enable or disable rtentry debug facility */
245 #define RTD_TRACE 0x2 /* trace alloc, free, refcnt and lock */
246 #define RTD_NO_FREE 0x4 /* don't free (good to catch corruptions) */
247
248 #define RTE_NAME "rtentry" /* name for zone and rt_lock */
249
250 static struct zone *rte_zone; /* special zone for rtentry */
251 #define RTE_ZONE_MAX 65536 /* maximum elements in zone */
252 #define RTE_ZONE_NAME RTE_NAME /* name of rtentry zone */
253
254 #define RTD_INUSE 0xFEEDFACE /* entry is in use */
255 #define RTD_FREED 0xDEADBEEF /* entry is freed */
256
257 #define MAX_SCOPE_ADDR_STR_LEN (MAX_IPv6_STR_LEN + 6)
258
259 /* For gdb */
260 __private_extern__ unsigned int ctrace_stack_size = CTRACE_STACK_SIZE;
261 __private_extern__ unsigned int ctrace_hist_size = CTRACE_HIST_SIZE;
262
263 /*
264 * Debug variant of rtentry structure.
265 */
266 struct rtentry_dbg {
267 struct rtentry rtd_entry; /* rtentry */
268 struct rtentry rtd_entry_saved; /* saved rtentry */
269 uint32_t rtd_inuse; /* in use pattern */
270 uint16_t rtd_refhold_cnt; /* # of rtref */
271 uint16_t rtd_refrele_cnt; /* # of rtunref */
272 uint32_t rtd_lock_cnt; /* # of locks */
273 uint32_t rtd_unlock_cnt; /* # of unlocks */
274 /*
275 * Alloc and free callers.
276 */
277 ctrace_t rtd_alloc;
278 ctrace_t rtd_free;
279 /*
280 * Circular lists of rtref and rtunref callers.
281 */
282 ctrace_t rtd_refhold[CTRACE_HIST_SIZE];
283 ctrace_t rtd_refrele[CTRACE_HIST_SIZE];
284 /*
285 * Circular lists of locks and unlocks.
286 */
287 ctrace_t rtd_lock[CTRACE_HIST_SIZE];
288 ctrace_t rtd_unlock[CTRACE_HIST_SIZE];
289 /*
290 * Trash list linkage
291 */
292 TAILQ_ENTRY(rtentry_dbg) rtd_trash_link;
293 };
294
295 /* List of trash route entries protected by rnh_lock */
296 static TAILQ_HEAD(, rtentry_dbg) rttrash_head;
297
298 static void rte_lock_init(struct rtentry *);
299 static void rte_lock_destroy(struct rtentry *);
300 static inline struct rtentry *rte_alloc_debug(void);
301 static inline void rte_free_debug(struct rtentry *);
302 static inline void rte_lock_debug(struct rtentry_dbg *);
303 static inline void rte_unlock_debug(struct rtentry_dbg *);
304 static void rt_maskedcopy(const struct sockaddr *,
305 struct sockaddr *, const struct sockaddr *);
306 static void rtable_init(void **);
307 static inline void rtref_audit(struct rtentry_dbg *);
308 static inline void rtunref_audit(struct rtentry_dbg *);
309 static struct rtentry *rtalloc1_common_locked(struct sockaddr *, int, uint32_t,
310 unsigned int);
311 static int rtrequest_common_locked(int, struct sockaddr *,
312 struct sockaddr *, struct sockaddr *, int, struct rtentry **,
313 unsigned int);
314 static struct rtentry *rtalloc1_locked(struct sockaddr *, int, uint32_t);
315 static void rtalloc_ign_common_locked(struct route *, uint32_t, unsigned int);
316 static inline void sin6_set_ifscope(struct sockaddr *, unsigned int);
317 static inline void sin6_set_embedded_ifscope(struct sockaddr *, unsigned int);
318 static inline unsigned int sin6_get_embedded_ifscope(struct sockaddr *);
319 static struct sockaddr *ma_copy(int, struct sockaddr *,
320 struct sockaddr_storage *, unsigned int);
321 static struct sockaddr *sa_trim(struct sockaddr *, int);
322 static struct radix_node *node_lookup(struct sockaddr *, struct sockaddr *,
323 unsigned int);
324 static struct radix_node *node_lookup_default(int);
325 static struct rtentry *rt_lookup_common(boolean_t, boolean_t, struct sockaddr *,
326 struct sockaddr *, struct radix_node_head *, unsigned int);
327 static int rn_match_ifscope(struct radix_node *, void *);
328 static struct ifaddr *ifa_ifwithroute_common_locked(int,
329 const struct sockaddr *, const struct sockaddr *, unsigned int);
330 static struct rtentry *rte_alloc(void);
331 static void rte_free(struct rtentry *);
332 static void rtfree_common(struct rtentry *, boolean_t);
333 static void rte_if_ref(struct ifnet *, int);
334 static void rt_set_idleref(struct rtentry *);
335 static void rt_clear_idleref(struct rtentry *);
336 static void route_event_callback(void *);
337 static void rt_str4(struct rtentry *, char *, uint32_t, char *, uint32_t);
338 static void rt_str6(struct rtentry *, char *, uint32_t, char *, uint32_t);
339 static boolean_t route_ignore_protocol_cloning_for_dst(struct rtentry *, struct sockaddr *);
340
341 uint32_t route_genid_inet = 0;
342 uint32_t route_genid_inet6 = 0;
343
344 #define ASSERT_SINIFSCOPE(sa) { \
345 if ((sa)->sa_family != AF_INET || \
346 (sa)->sa_len < sizeof (struct sockaddr_in)) \
347 panic("%s: bad sockaddr_in %p\n", __func__, sa); \
348 }
349
350 #define ASSERT_SIN6IFSCOPE(sa) { \
351 if ((sa)->sa_family != AF_INET6 || \
352 (sa)->sa_len < sizeof (struct sockaddr_in6)) \
353 panic("%s: bad sockaddr_in6 %p\n", __func__, sa); \
354 }
355
356 /*
357 * Argument to leaf-matching routine; at present it is scoped routing
358 * specific but can be expanded in future to include other search filters.
359 */
360 struct matchleaf_arg {
361 unsigned int ifscope; /* interface scope */
362 };
363
364 /*
365 * For looking up the non-scoped default route (sockaddr instead
366 * of sockaddr_in for convenience).
367 */
368 static struct sockaddr sin_def = {
369 .sa_len = sizeof(struct sockaddr_in),
370 .sa_family = AF_INET,
371 .sa_data = { 0, }
372 };
373
374 static struct sockaddr_in6 sin6_def = {
375 .sin6_len = sizeof(struct sockaddr_in6),
376 .sin6_family = AF_INET6,
377 .sin6_port = 0,
378 .sin6_flowinfo = 0,
379 .sin6_addr = IN6ADDR_ANY_INIT,
380 .sin6_scope_id = 0
381 };
382
383 /*
384 * Interface index (scope) of the primary interface; determined at
385 * the time when the default, non-scoped route gets added, changed
386 * or deleted. Protected by rnh_lock.
387 */
388 static unsigned int primary_ifscope = IFSCOPE_NONE;
389 static unsigned int primary6_ifscope = IFSCOPE_NONE;
390
391 #define INET_DEFAULT(sa) \
392 ((sa)->sa_family == AF_INET && SIN(sa)->sin_addr.s_addr == 0)
393
394 #define INET6_DEFAULT(sa) \
395 ((sa)->sa_family == AF_INET6 && \
396 IN6_IS_ADDR_UNSPECIFIED(&SIN6(sa)->sin6_addr))
397
398 #define SA_DEFAULT(sa) (INET_DEFAULT(sa) || INET6_DEFAULT(sa))
399 #define RT(r) ((struct rtentry *)r)
400 #define RN(r) ((struct radix_node *)r)
401 #define RT_HOST(r) (RT(r)->rt_flags & RTF_HOST)
402
403 unsigned int rt_verbose = 0;
404 #if (DEVELOPMENT || DEBUG)
405 SYSCTL_DECL(_net_route);
406 SYSCTL_UINT(_net_route, OID_AUTO, verbose, CTLFLAG_RW | CTLFLAG_LOCKED,
407 &rt_verbose, 0, "");
408 #endif /* (DEVELOPMENT || DEBUG) */
409
410 static void
411 rtable_init(void **table)
412 {
413 struct domain *dom;
414
415 domain_proto_mtx_lock_assert_held();
416
417 TAILQ_FOREACH(dom, &domains, dom_entry) {
418 if (dom->dom_rtattach != NULL) {
419 dom->dom_rtattach(&table[dom->dom_family],
420 dom->dom_rtoffset);
421 }
422 }
423 }
424
425 /*
426 * Called by route_dinit().
427 */
428 void
429 route_init(void)
430 {
431 int size;
432
433 _CASSERT(offsetof(struct route, ro_rt) ==
434 offsetof(struct route_in6, ro_rt));
435 _CASSERT(offsetof(struct route, ro_lle) ==
436 offsetof(struct route_in6, ro_lle));
437 _CASSERT(offsetof(struct route, ro_srcia) ==
438 offsetof(struct route_in6, ro_srcia));
439 _CASSERT(offsetof(struct route, ro_flags) ==
440 offsetof(struct route_in6, ro_flags));
441 _CASSERT(offsetof(struct route, ro_dst) ==
442 offsetof(struct route_in6, ro_dst));
443
444 PE_parse_boot_argn("rte_debug", &rte_debug, sizeof(rte_debug));
445 if (rte_debug != 0) {
446 rte_debug |= RTD_DEBUG;
447 }
448
449 rnh_lock_grp_attr = lck_grp_attr_alloc_init();
450 rnh_lock_grp = lck_grp_alloc_init("route", rnh_lock_grp_attr);
451 rnh_lock_attr = lck_attr_alloc_init();
452 lck_mtx_init(rnh_lock, rnh_lock_grp, rnh_lock_attr);
453
454 rte_mtx_grp_attr = lck_grp_attr_alloc_init();
455 rte_mtx_grp = lck_grp_alloc_init(RTE_NAME, rte_mtx_grp_attr);
456 rte_mtx_attr = lck_attr_alloc_init();
457
458 lck_mtx_lock(rnh_lock);
459 rn_init(); /* initialize all zeroes, all ones, mask table */
460 lck_mtx_unlock(rnh_lock);
461 rtable_init((void **)rt_tables);
462
463 if (rte_debug & RTD_DEBUG) {
464 size = sizeof(struct rtentry_dbg);
465 } else {
466 size = sizeof(struct rtentry);
467 }
468
469 rte_zone = zone_create(RTE_ZONE_NAME, size, ZC_NOENCRYPT);
470
471 TAILQ_INIT(&rttrash_head);
472 }
473
474 /*
475 * Given a route, determine whether or not it is the non-scoped default
476 * route; dst typically comes from rt_key(rt) but may be coming from
477 * a separate place when rt is in the process of being created.
478 */
479 boolean_t
480 rt_primary_default(struct rtentry *rt, struct sockaddr *dst)
481 {
482 return SA_DEFAULT(dst) && !(rt->rt_flags & RTF_IFSCOPE);
483 }
484
485 /*
486 * Set the ifscope of the primary interface; caller holds rnh_lock.
487 */
488 void
489 set_primary_ifscope(int af, unsigned int ifscope)
490 {
491 if (af == AF_INET) {
492 primary_ifscope = ifscope;
493 } else {
494 primary6_ifscope = ifscope;
495 }
496 }
497
498 /*
499 * Return the ifscope of the primary interface; caller holds rnh_lock.
500 */
501 unsigned int
502 get_primary_ifscope(int af)
503 {
504 return af == AF_INET ? primary_ifscope : primary6_ifscope;
505 }
506
507 /*
508 * Set the scope ID of a given a sockaddr_in.
509 */
510 void
511 sin_set_ifscope(struct sockaddr *sa, unsigned int ifscope)
512 {
513 /* Caller must pass in sockaddr_in */
514 ASSERT_SINIFSCOPE(sa);
515
516 SINIFSCOPE(sa)->sin_scope_id = ifscope;
517 }
518
519 /*
520 * Set the scope ID of given a sockaddr_in6.
521 */
522 static inline void
523 sin6_set_ifscope(struct sockaddr *sa, unsigned int ifscope)
524 {
525 /* Caller must pass in sockaddr_in6 */
526 ASSERT_SIN6IFSCOPE(sa);
527
528 SIN6IFSCOPE(sa)->sin6_scope_id = ifscope;
529 }
530
531 /*
532 * Given a sockaddr_in, return the scope ID to the caller.
533 */
534 unsigned int
535 sin_get_ifscope(struct sockaddr *sa)
536 {
537 /* Caller must pass in sockaddr_in */
538 ASSERT_SINIFSCOPE(sa);
539
540 return SINIFSCOPE(sa)->sin_scope_id;
541 }
542
543 /*
544 * Given a sockaddr_in6, return the scope ID to the caller.
545 */
546 unsigned int
547 sin6_get_ifscope(struct sockaddr *sa)
548 {
549 /* Caller must pass in sockaddr_in6 */
550 ASSERT_SIN6IFSCOPE(sa);
551
552 return SIN6IFSCOPE(sa)->sin6_scope_id;
553 }
554
555 static inline void
556 sin6_set_embedded_ifscope(struct sockaddr *sa, unsigned int ifscope)
557 {
558 /* Caller must pass in sockaddr_in6 */
559 ASSERT_SIN6IFSCOPE(sa);
560 VERIFY(IN6_IS_SCOPE_EMBED(&(SIN6(sa)->sin6_addr)));
561
562 SIN6(sa)->sin6_addr.s6_addr16[1] = htons(ifscope);
563 }
564
565 static inline unsigned int
566 sin6_get_embedded_ifscope(struct sockaddr *sa)
567 {
568 /* Caller must pass in sockaddr_in6 */
569 ASSERT_SIN6IFSCOPE(sa);
570
571 return ntohs(SIN6(sa)->sin6_addr.s6_addr16[1]);
572 }
573
574 /*
575 * Copy a sockaddr_{in,in6} src to a dst storage and set scope ID into dst.
576 *
577 * To clear the scope ID, pass is a NULL pifscope. To set the scope ID, pass
578 * in a non-NULL pifscope with non-zero ifscope. Otherwise if pifscope is
579 * non-NULL and ifscope is IFSCOPE_NONE, the existing scope ID is left intact.
580 * In any case, the effective scope ID value is returned to the caller via
581 * pifscope, if it is non-NULL.
582 */
583 struct sockaddr *
584 sa_copy(struct sockaddr *src, struct sockaddr_storage *dst,
585 unsigned int *pifscope)
586 {
587 int af = src->sa_family;
588 unsigned int ifscope = (pifscope != NULL) ? *pifscope : IFSCOPE_NONE;
589
590 VERIFY(af == AF_INET || af == AF_INET6);
591
592 bzero(dst, sizeof(*dst));
593
594 if (af == AF_INET) {
595 bcopy(src, dst, sizeof(struct sockaddr_in));
596 dst->ss_len = sizeof(struct sockaddr_in);
597 if (pifscope == NULL || ifscope != IFSCOPE_NONE) {
598 sin_set_ifscope(SA(dst), ifscope);
599 }
600 } else {
601 bcopy(src, dst, sizeof(struct sockaddr_in6));
602 dst->ss_len = sizeof(struct sockaddr_in6);
603 if (pifscope != NULL &&
604 IN6_IS_SCOPE_EMBED(&SIN6(dst)->sin6_addr)) {
605 unsigned int eifscope;
606 /*
607 * If the address contains the embedded scope ID,
608 * use that as the value for sin6_scope_id as long
609 * the caller doesn't insist on clearing it (by
610 * passing NULL) or setting it.
611 */
612 eifscope = sin6_get_embedded_ifscope(SA(dst));
613 if (eifscope != IFSCOPE_NONE && ifscope == IFSCOPE_NONE) {
614 ifscope = eifscope;
615 }
616 if (ifscope != IFSCOPE_NONE) {
617 /* Set ifscope from pifscope or eifscope */
618 sin6_set_ifscope(SA(dst), ifscope);
619 } else {
620 /* If sin6_scope_id has a value, use that one */
621 ifscope = sin6_get_ifscope(SA(dst));
622 }
623 /*
624 * If sin6_scope_id is set but the address doesn't
625 * contain the equivalent embedded value, set it.
626 */
627 if (ifscope != IFSCOPE_NONE && eifscope != ifscope) {
628 sin6_set_embedded_ifscope(SA(dst), ifscope);
629 }
630 } else if (pifscope == NULL || ifscope != IFSCOPE_NONE) {
631 sin6_set_ifscope(SA(dst), ifscope);
632 }
633 }
634
635 if (pifscope != NULL) {
636 *pifscope = (af == AF_INET) ? sin_get_ifscope(SA(dst)) :
637 sin6_get_ifscope(SA(dst));
638 }
639
640 return SA(dst);
641 }
642
643 /*
644 * Copy a mask from src to a dst storage and set scope ID into dst.
645 */
646 static struct sockaddr *
647 ma_copy(int af, struct sockaddr *src, struct sockaddr_storage *dst,
648 unsigned int ifscope)
649 {
650 VERIFY(af == AF_INET || af == AF_INET6);
651
652 bzero(dst, sizeof(*dst));
653 rt_maskedcopy(src, SA(dst), src);
654
655 /*
656 * The length of the mask sockaddr would need to be adjusted
657 * to cover the additional {sin,sin6}_ifscope field; when ifscope
658 * is IFSCOPE_NONE, we'd end up clearing the scope ID field on
659 * the destination mask in addition to extending the length
660 * of the sockaddr, as a side effect. This is okay, as any
661 * trailing zeroes would be skipped by rn_addmask prior to
662 * inserting or looking up the mask in the mask tree.
663 */
664 if (af == AF_INET) {
665 SINIFSCOPE(dst)->sin_scope_id = ifscope;
666 SINIFSCOPE(dst)->sin_len =
667 offsetof(struct sockaddr_inifscope, sin_scope_id) +
668 sizeof(SINIFSCOPE(dst)->sin_scope_id);
669 } else {
670 SIN6IFSCOPE(dst)->sin6_scope_id = ifscope;
671 SIN6IFSCOPE(dst)->sin6_len =
672 offsetof(struct sockaddr_in6, sin6_scope_id) +
673 sizeof(SIN6IFSCOPE(dst)->sin6_scope_id);
674 }
675
676 return SA(dst);
677 }
678
679 /*
680 * Trim trailing zeroes on a sockaddr and update its length.
681 */
682 static struct sockaddr *
683 sa_trim(struct sockaddr *sa, int skip)
684 {
685 caddr_t cp, base = (caddr_t)sa + skip;
686
687 if (sa->sa_len <= skip) {
688 return sa;
689 }
690
691 for (cp = base + (sa->sa_len - skip); cp > base && cp[-1] == 0;) {
692 cp--;
693 }
694
695 sa->sa_len = (cp - base) + skip;
696 if (sa->sa_len < skip) {
697 /* Must not happen, and if so, panic */
698 panic("%s: broken logic (sa_len %d < skip %d )", __func__,
699 sa->sa_len, skip);
700 /* NOTREACHED */
701 } else if (sa->sa_len == skip) {
702 /* If we end up with all zeroes, then there's no mask */
703 sa->sa_len = 0;
704 }
705
706 return sa;
707 }
708
709 /*
710 * Called by rtm_msg{1,2} routines to "scrub" socket address structures of
711 * kernel private information, so that clients of the routing socket will
712 * not be confused by the presence of the information, or the side effect of
713 * the increased length due to that. The source sockaddr is not modified;
714 * instead, the scrubbing happens on the destination sockaddr storage that
715 * is passed in by the caller.
716 *
717 * Scrubbing entails:
718 * - removing embedded scope identifiers from network mask and destination
719 * IPv4 and IPv6 socket addresses
720 * - optionally removing global scope interface hardware addresses from
721 * link-layer interface addresses when the MAC framework check fails.
722 */
723 struct sockaddr *
724 rtm_scrub(int type, int idx, struct sockaddr *hint, struct sockaddr *sa,
725 void *buf, uint32_t buflen, kauth_cred_t *credp)
726 {
727 struct sockaddr_storage *ss = (struct sockaddr_storage *)buf;
728 struct sockaddr *ret = sa;
729
730 VERIFY(buf != NULL && buflen >= sizeof(*ss));
731 bzero(buf, buflen);
732
733 switch (idx) {
734 case RTAX_DST:
735 /*
736 * If this is for an AF_INET/AF_INET6 destination address,
737 * call sa_copy() to clear the scope ID field.
738 */
739 if (sa->sa_family == AF_INET &&
740 SINIFSCOPE(sa)->sin_scope_id != IFSCOPE_NONE) {
741 ret = sa_copy(sa, ss, NULL);
742 } else if (sa->sa_family == AF_INET6 &&
743 SIN6IFSCOPE(sa)->sin6_scope_id != IFSCOPE_NONE) {
744 ret = sa_copy(sa, ss, NULL);
745 }
746 break;
747
748 case RTAX_NETMASK: {
749 int skip, af;
750 /*
751 * If this is for a mask, we can't tell whether or not there
752 * is an valid scope ID value, as the span of bytes between
753 * sa_len and the beginning of the mask (offset of sin_addr in
754 * the case of AF_INET, or sin6_addr for AF_INET6) may be
755 * filled with all-ones by rn_addmask(), and hence we cannot
756 * rely on sa_family. Because of this, we use the sa_family
757 * of the hint sockaddr (RTAX_{DST,IFA}) as indicator as to
758 * whether or not the mask is to be treated as one for AF_INET
759 * or AF_INET6. Clearing the scope ID field involves setting
760 * it to IFSCOPE_NONE followed by calling sa_trim() to trim
761 * trailing zeroes from the storage sockaddr, which reverses
762 * what was done earlier by ma_copy() on the source sockaddr.
763 */
764 if (hint == NULL ||
765 ((af = hint->sa_family) != AF_INET && af != AF_INET6)) {
766 break; /* nothing to do */
767 }
768 skip = (af == AF_INET) ?
769 offsetof(struct sockaddr_in, sin_addr) :
770 offsetof(struct sockaddr_in6, sin6_addr);
771
772 if (sa->sa_len > skip && sa->sa_len <= sizeof(*ss)) {
773 bcopy(sa, ss, sa->sa_len);
774 /*
775 * Don't use {sin,sin6}_set_ifscope() as sa_family
776 * and sa_len for the netmask might not be set to
777 * the corresponding expected values of the hint.
778 */
779 if (hint->sa_family == AF_INET) {
780 SINIFSCOPE(ss)->sin_scope_id = IFSCOPE_NONE;
781 } else {
782 SIN6IFSCOPE(ss)->sin6_scope_id = IFSCOPE_NONE;
783 }
784 ret = sa_trim(SA(ss), skip);
785
786 /*
787 * For AF_INET6 mask, set sa_len appropriately unless
788 * this is requested via systl_dumpentry(), in which
789 * case we return the raw value.
790 */
791 if (hint->sa_family == AF_INET6 &&
792 type != RTM_GET && type != RTM_GET2) {
793 SA(ret)->sa_len = sizeof(struct sockaddr_in6);
794 }
795 }
796 break;
797 }
798 case RTAX_GATEWAY: {
799 /*
800 * Break if the gateway is not AF_LINK type (indirect routes)
801 *
802 * Else, if is, check if it is resolved. If not yet resolved
803 * simply break else scrub the link layer address.
804 */
805 if ((sa->sa_family != AF_LINK) || (SDL(sa)->sdl_alen == 0)) {
806 break;
807 }
808 OS_FALLTHROUGH;
809 }
810
811 case RTAX_IFP: {
812 if (sa->sa_family == AF_LINK && credp) {
813 struct sockaddr_dl *sdl = SDL(buf);
814 const void *bytes;
815 size_t size;
816
817 /* caller should handle worst case: SOCK_MAXADDRLEN */
818 VERIFY(buflen >= sa->sa_len);
819
820 bcopy(sa, sdl, sa->sa_len);
821 bytes = dlil_ifaddr_bytes(sdl, &size, credp);
822 if (bytes != CONST_LLADDR(sdl)) {
823 VERIFY(sdl->sdl_alen == size);
824 bcopy(bytes, LLADDR(sdl), size);
825 }
826 ret = (struct sockaddr *)sdl;
827 }
828 break;
829 }
830 default:
831 break;
832 }
833
834 return ret;
835 }
836
837 /*
838 * Callback leaf-matching routine for rn_matchaddr_args used
839 * for looking up an exact match for a scoped route entry.
840 */
841 static int
842 rn_match_ifscope(struct radix_node *rn, void *arg)
843 {
844 struct rtentry *rt = (struct rtentry *)rn;
845 struct matchleaf_arg *ma = arg;
846 int af = rt_key(rt)->sa_family;
847
848 if (!(rt->rt_flags & RTF_IFSCOPE) || (af != AF_INET && af != AF_INET6)) {
849 return 0;
850 }
851
852 return af == AF_INET ?
853 (SINIFSCOPE(rt_key(rt))->sin_scope_id == ma->ifscope) :
854 (SIN6IFSCOPE(rt_key(rt))->sin6_scope_id == ma->ifscope);
855 }
856
857 /*
858 * Atomically increment route generation counter
859 */
860 void
861 routegenid_update(void)
862 {
863 routegenid_inet_update();
864 routegenid_inet6_update();
865 }
866
867 void
868 routegenid_inet_update(void)
869 {
870 atomic_add_32(&route_genid_inet, 1);
871 }
872
873 void
874 routegenid_inet6_update(void)
875 {
876 atomic_add_32(&route_genid_inet6, 1);
877 }
878
879 /*
880 * Packet routing routines.
881 */
882 void
883 rtalloc(struct route *ro)
884 {
885 rtalloc_ign(ro, 0);
886 }
887
888 void
889 rtalloc_scoped(struct route *ro, unsigned int ifscope)
890 {
891 rtalloc_scoped_ign(ro, 0, ifscope);
892 }
893
894 static void
895 rtalloc_ign_common_locked(struct route *ro, uint32_t ignore,
896 unsigned int ifscope)
897 {
898 struct rtentry *rt;
899
900 if ((rt = ro->ro_rt) != NULL) {
901 RT_LOCK_SPIN(rt);
902 if (rt->rt_ifp != NULL && !ROUTE_UNUSABLE(ro)) {
903 RT_UNLOCK(rt);
904 return;
905 }
906 RT_UNLOCK(rt);
907 ROUTE_RELEASE_LOCKED(ro); /* rnh_lock already held */
908 }
909 ro->ro_rt = rtalloc1_common_locked(&ro->ro_dst, 1, ignore, ifscope);
910 if (ro->ro_rt != NULL) {
911 RT_GENID_SYNC(ro->ro_rt);
912 RT_LOCK_ASSERT_NOTHELD(ro->ro_rt);
913 }
914 }
915
916 void
917 rtalloc_ign(struct route *ro, uint32_t ignore)
918 {
919 LCK_MTX_ASSERT(rnh_lock, LCK_MTX_ASSERT_NOTOWNED);
920 lck_mtx_lock(rnh_lock);
921 rtalloc_ign_common_locked(ro, ignore, IFSCOPE_NONE);
922 lck_mtx_unlock(rnh_lock);
923 }
924
925 void
926 rtalloc_scoped_ign(struct route *ro, uint32_t ignore, unsigned int ifscope)
927 {
928 LCK_MTX_ASSERT(rnh_lock, LCK_MTX_ASSERT_NOTOWNED);
929 lck_mtx_lock(rnh_lock);
930 rtalloc_ign_common_locked(ro, ignore, ifscope);
931 lck_mtx_unlock(rnh_lock);
932 }
933
934 static struct rtentry *
935 rtalloc1_locked(struct sockaddr *dst, int report, uint32_t ignflags)
936 {
937 return rtalloc1_common_locked(dst, report, ignflags, IFSCOPE_NONE);
938 }
939
940 struct rtentry *
941 rtalloc1_scoped_locked(struct sockaddr *dst, int report, uint32_t ignflags,
942 unsigned int ifscope)
943 {
944 return rtalloc1_common_locked(dst, report, ignflags, ifscope);
945 }
946
947 static boolean_t
948 route_ignore_protocol_cloning_for_dst(struct rtentry *rt, struct sockaddr *dst)
949 {
950 /*
951 * For now keep protocol cloning for any type of IPv4
952 * destination.
953 */
954 if (dst->sa_family != AF_INET6) {
955 return FALSE;
956 }
957
958 /*
959 * Limit protocol route creation of IPv6 ULA destinations
960 * from default route,
961 * Just to be safe, even though it doesn't affect routability,
962 * still allow protocol cloned routes if we happen to hit
963 * default route over companion link for ULA destination.
964 */
965 if (!IFNET_IS_COMPANION_LINK(rt->rt_ifp) &&
966 (rt->rt_flags & RTF_GATEWAY) &&
967 (rt->rt_flags & RTF_PRCLONING) &&
968 SA_DEFAULT(rt_key(rt)) &&
969 IN6_IS_ADDR_UNIQUE_LOCAL(&SIN6(dst)->sin6_addr)) {
970 return TRUE;
971 }
972 return FALSE;
973 }
974
975 struct rtentry *
976 rtalloc1_common_locked(struct sockaddr *dst, int report, uint32_t ignflags,
977 unsigned int ifscope)
978 {
979 struct radix_node_head *rnh = rt_tables[dst->sa_family];
980 struct rtentry *rt, *newrt = NULL;
981 struct rt_addrinfo info;
982 uint32_t nflags;
983 int err = 0, msgtype = RTM_MISS;
984
985 if (rnh == NULL) {
986 goto unreachable;
987 }
988
989 /*
990 * Find the longest prefix or exact (in the scoped case) address match;
991 * callee adds a reference to entry and checks for root node as well
992 */
993 rt = rt_lookup(FALSE, dst, NULL, rnh, ifscope);
994 if (rt == NULL) {
995 goto unreachable;
996 }
997
998 /*
999 * Explicitly ignore protocol cloning for certain destinations.
1000 * Some checks below are kind of redundant, as for now, RTF_PRCLONING
1001 * is only set on indirect (RTF_GATEWAY) routes.
1002 * Also, we do this only when the route lookup above, resulted in default
1003 * route.
1004 * This is done to ensure, the resulting indirect host route doesn't
1005 * interfere when routing table gets configured with a indirect subnet
1006 * route/direct subnet route that is more specific than the current
1007 * parent route of the resulting protocol cloned route.
1008 *
1009 * At the crux of it all, it is a problem that we maintain host cache
1010 * in the routing table. We should revisit this for a generic solution.
1011 */
1012 if (route_ignore_protocol_cloning_for_dst(rt, dst)) {
1013 ignflags |= RTF_PRCLONING;
1014 }
1015
1016 RT_LOCK_SPIN(rt);
1017 newrt = rt;
1018 nflags = rt->rt_flags & ~ignflags;
1019 RT_UNLOCK(rt);
1020
1021 if (report && (nflags & (RTF_CLONING | RTF_PRCLONING))) {
1022 /*
1023 * We are apparently adding (report = 0 in delete).
1024 * If it requires that it be cloned, do so.
1025 * (This implies it wasn't a HOST route.)
1026 */
1027 err = rtrequest_locked(RTM_RESOLVE, dst, NULL, NULL, 0, &newrt);
1028 if (err) {
1029 /*
1030 * If the cloning didn't succeed, maybe what we
1031 * have from lookup above will do. Return that;
1032 * no need to hold another reference since it's
1033 * already done.
1034 */
1035 newrt = rt;
1036 goto miss;
1037 }
1038
1039 /*
1040 * We cloned it; drop the original route found during lookup.
1041 * The resulted cloned route (newrt) would now have an extra
1042 * reference held during rtrequest.
1043 */
1044 rtfree_locked(rt);
1045
1046 /*
1047 * If the newly created cloned route is a direct host route
1048 * then also check if it is to a router or not.
1049 * If it is, then set the RTF_ROUTER flag on the host route
1050 * for the gateway.
1051 *
1052 * XXX It is possible for the default route to be created post
1053 * cloned route creation of router's IP.
1054 * We can handle that corner case by special handing for RTM_ADD
1055 * of default route.
1056 */
1057 if ((newrt->rt_flags & (RTF_HOST | RTF_LLINFO)) ==
1058 (RTF_HOST | RTF_LLINFO)) {
1059 struct rtentry *defrt = NULL;
1060 struct sockaddr_storage def_key;
1061
1062 bzero(&def_key, sizeof(def_key));
1063 def_key.ss_len = rt_key(newrt)->sa_len;
1064 def_key.ss_family = rt_key(newrt)->sa_family;
1065
1066 defrt = rtalloc1_scoped_locked((struct sockaddr *)&def_key,
1067 0, 0, newrt->rt_ifp->if_index);
1068
1069 if (defrt) {
1070 if (equal(rt_key(newrt), defrt->rt_gateway)) {
1071 newrt->rt_flags |= RTF_ROUTER;
1072 }
1073 rtfree_locked(defrt);
1074 }
1075 }
1076
1077 if ((rt = newrt) && (rt->rt_flags & RTF_XRESOLVE)) {
1078 /*
1079 * If the new route specifies it be
1080 * externally resolved, then go do that.
1081 */
1082 msgtype = RTM_RESOLVE;
1083 goto miss;
1084 }
1085 }
1086 goto done;
1087
1088 unreachable:
1089 /*
1090 * Either we hit the root or couldn't find any match,
1091 * Which basically means "cant get there from here"
1092 */
1093 rtstat.rts_unreach++;
1094
1095 miss:
1096 if (report) {
1097 /*
1098 * If required, report the failure to the supervising
1099 * Authorities.
1100 * For a delete, this is not an error. (report == 0)
1101 */
1102 bzero((caddr_t)&info, sizeof(info));
1103 info.rti_info[RTAX_DST] = dst;
1104 rt_missmsg(msgtype, &info, 0, err);
1105 }
1106 done:
1107 return newrt;
1108 }
1109
1110 struct rtentry *
1111 rtalloc1(struct sockaddr *dst, int report, uint32_t ignflags)
1112 {
1113 struct rtentry *entry;
1114 LCK_MTX_ASSERT(rnh_lock, LCK_MTX_ASSERT_NOTOWNED);
1115 lck_mtx_lock(rnh_lock);
1116 entry = rtalloc1_locked(dst, report, ignflags);
1117 lck_mtx_unlock(rnh_lock);
1118 return entry;
1119 }
1120
1121 struct rtentry *
1122 rtalloc1_scoped(struct sockaddr *dst, int report, uint32_t ignflags,
1123 unsigned int ifscope)
1124 {
1125 struct rtentry *entry;
1126 LCK_MTX_ASSERT(rnh_lock, LCK_MTX_ASSERT_NOTOWNED);
1127 lck_mtx_lock(rnh_lock);
1128 entry = rtalloc1_scoped_locked(dst, report, ignflags, ifscope);
1129 lck_mtx_unlock(rnh_lock);
1130 return entry;
1131 }
1132
1133 /*
1134 * Remove a reference count from an rtentry.
1135 * If the count gets low enough, take it out of the routing table
1136 */
1137 void
1138 rtfree_locked(struct rtentry *rt)
1139 {
1140 rtfree_common(rt, TRUE);
1141 }
1142
1143 static void
1144 rtfree_common(struct rtentry *rt, boolean_t locked)
1145 {
1146 struct radix_node_head *rnh;
1147
1148 LCK_MTX_ASSERT(rnh_lock, locked ?
1149 LCK_MTX_ASSERT_OWNED : LCK_MTX_ASSERT_NOTOWNED);
1150
1151 /*
1152 * Atomically decrement the reference count and if it reaches 0,
1153 * and there is a close function defined, call the close function.
1154 */
1155 RT_LOCK_SPIN(rt);
1156 if (rtunref(rt) > 0) {
1157 RT_UNLOCK(rt);
1158 return;
1159 }
1160
1161 /*
1162 * To avoid violating lock ordering, we must drop rt_lock before
1163 * trying to acquire the global rnh_lock. If we are called with
1164 * rnh_lock held, then we already have exclusive access; otherwise
1165 * we do the lock dance.
1166 */
1167 if (!locked) {
1168 /*
1169 * Note that we check it again below after grabbing rnh_lock,
1170 * since it is possible that another thread doing a lookup wins
1171 * the race, grabs the rnh_lock first, and bumps up reference
1172 * count in which case the route should be left alone as it is
1173 * still in use. It's also possible that another thread frees
1174 * the route after we drop rt_lock; to prevent the route from
1175 * being freed, we hold an extra reference.
1176 */
1177 RT_ADDREF_LOCKED(rt);
1178 RT_UNLOCK(rt);
1179 lck_mtx_lock(rnh_lock);
1180 RT_LOCK_SPIN(rt);
1181 if (rtunref(rt) > 0) {
1182 /* We've lost the race, so abort */
1183 RT_UNLOCK(rt);
1184 goto done;
1185 }
1186 }
1187
1188 /*
1189 * We may be blocked on other lock(s) as part of freeing
1190 * the entry below, so convert from spin to full mutex.
1191 */
1192 RT_CONVERT_LOCK(rt);
1193
1194 LCK_MTX_ASSERT(rnh_lock, LCK_MTX_ASSERT_OWNED);
1195
1196 /* Negative refcnt must never happen */
1197 if (rt->rt_refcnt != 0) {
1198 panic("rt %p invalid refcnt %d", rt, rt->rt_refcnt);
1199 /* NOTREACHED */
1200 }
1201 /* Idle refcnt must have been dropped during rtunref() */
1202 VERIFY(!(rt->rt_flags & RTF_IFREF));
1203
1204 /*
1205 * find the tree for that address family
1206 * Note: in the case of igmp packets, there might not be an rnh
1207 */
1208 rnh = rt_tables[rt_key(rt)->sa_family];
1209
1210 /*
1211 * On last reference give the "close method" a chance to cleanup
1212 * private state. This also permits (for IPv4 and IPv6) a chance
1213 * to decide if the routing table entry should be purged immediately
1214 * or at a later time. When an immediate purge is to happen the
1215 * close routine typically issues RTM_DELETE which clears the RTF_UP
1216 * flag on the entry so that the code below reclaims the storage.
1217 */
1218 if (rnh != NULL && rnh->rnh_close != NULL) {
1219 rnh->rnh_close((struct radix_node *)rt, rnh);
1220 }
1221
1222 /*
1223 * If we are no longer "up" (and ref == 0) then we can free the
1224 * resources associated with the route.
1225 */
1226 if (!(rt->rt_flags & RTF_UP)) {
1227 struct rtentry *rt_parent;
1228 struct ifaddr *rt_ifa;
1229
1230 rt->rt_flags |= RTF_DEAD;
1231 if (rt->rt_nodes->rn_flags & (RNF_ACTIVE | RNF_ROOT)) {
1232 panic("rt %p freed while in radix tree\n", rt);
1233 /* NOTREACHED */
1234 }
1235 /*
1236 * the rtentry must have been removed from the routing table
1237 * so it is represented in rttrash; remove that now.
1238 */
1239 (void) OSDecrementAtomic(&rttrash);
1240 if (rte_debug & RTD_DEBUG) {
1241 TAILQ_REMOVE(&rttrash_head, (struct rtentry_dbg *)rt,
1242 rtd_trash_link);
1243 }
1244
1245 /*
1246 * release references on items we hold them on..
1247 * e.g other routes and ifaddrs.
1248 */
1249 if ((rt_parent = rt->rt_parent) != NULL) {
1250 rt->rt_parent = NULL;
1251 }
1252
1253 if ((rt_ifa = rt->rt_ifa) != NULL) {
1254 rt->rt_ifa = NULL;
1255 }
1256
1257 /*
1258 * Now free any attached link-layer info.
1259 */
1260 if (rt->rt_llinfo != NULL) {
1261 if (rt->rt_llinfo_free != NULL) {
1262 (*rt->rt_llinfo_free)(rt->rt_llinfo);
1263 } else {
1264 R_Free(rt->rt_llinfo);
1265 }
1266 rt->rt_llinfo = NULL;
1267 }
1268
1269 /* Destroy eventhandler lists context */
1270 eventhandler_lists_ctxt_destroy(&rt->rt_evhdlr_ctxt);
1271
1272 /*
1273 * Route is no longer in the tree and refcnt is 0;
1274 * we have exclusive access, so destroy it.
1275 */
1276 RT_UNLOCK(rt);
1277 rte_lock_destroy(rt);
1278
1279 if (rt_parent != NULL) {
1280 rtfree_locked(rt_parent);
1281 }
1282
1283 if (rt_ifa != NULL) {
1284 IFA_REMREF(rt_ifa);
1285 }
1286
1287 /*
1288 * The key is separately alloc'd so free it (see rt_setgate()).
1289 * This also frees the gateway, as they are always malloc'd
1290 * together.
1291 */
1292 R_Free(rt_key(rt));
1293
1294 /*
1295 * Free any statistics that may have been allocated
1296 */
1297 nstat_route_detach(rt);
1298
1299 /*
1300 * and the rtentry itself of course
1301 */
1302 rte_free(rt);
1303 } else {
1304 /*
1305 * The "close method" has been called, but the route is
1306 * still in the radix tree with zero refcnt, i.e. "up"
1307 * and in the cached state.
1308 */
1309 RT_UNLOCK(rt);
1310 }
1311 done:
1312 if (!locked) {
1313 lck_mtx_unlock(rnh_lock);
1314 }
1315 }
1316
1317 void
1318 rtfree(struct rtentry *rt)
1319 {
1320 rtfree_common(rt, FALSE);
1321 }
1322
1323 /*
1324 * Decrements the refcount but does not free the route when
1325 * the refcount reaches zero. Unless you have really good reason,
1326 * use rtfree not rtunref.
1327 */
1328 int
1329 rtunref(struct rtentry *p)
1330 {
1331 RT_LOCK_ASSERT_HELD(p);
1332
1333 if (p->rt_refcnt == 0) {
1334 panic("%s(%p) bad refcnt\n", __func__, p);
1335 /* NOTREACHED */
1336 } else if (--p->rt_refcnt == 0) {
1337 /*
1338 * Release any idle reference count held on the interface;
1339 * if the route is eligible, still UP and the refcnt becomes
1340 * non-zero at some point in future before it is purged from
1341 * the routing table, rt_set_idleref() will undo this.
1342 */
1343 rt_clear_idleref(p);
1344 }
1345
1346 if (rte_debug & RTD_DEBUG) {
1347 rtunref_audit((struct rtentry_dbg *)p);
1348 }
1349
1350 /* Return new value */
1351 return p->rt_refcnt;
1352 }
1353
1354 static inline void
1355 rtunref_audit(struct rtentry_dbg *rte)
1356 {
1357 uint16_t idx;
1358
1359 if (rte->rtd_inuse != RTD_INUSE) {
1360 panic("rtunref: on freed rte=%p\n", rte);
1361 /* NOTREACHED */
1362 }
1363 idx = atomic_add_16_ov(&rte->rtd_refrele_cnt, 1) % CTRACE_HIST_SIZE;
1364 if (rte_debug & RTD_TRACE) {
1365 ctrace_record(&rte->rtd_refrele[idx]);
1366 }
1367 }
1368
1369 /*
1370 * Add a reference count from an rtentry.
1371 */
1372 void
1373 rtref(struct rtentry *p)
1374 {
1375 RT_LOCK_ASSERT_HELD(p);
1376
1377 VERIFY((p->rt_flags & RTF_DEAD) == 0);
1378 if (++p->rt_refcnt == 0) {
1379 panic("%s(%p) bad refcnt\n", __func__, p);
1380 /* NOTREACHED */
1381 } else if (p->rt_refcnt == 1) {
1382 /*
1383 * Hold an idle reference count on the interface,
1384 * if the route is eligible for it.
1385 */
1386 rt_set_idleref(p);
1387 }
1388
1389 if (rte_debug & RTD_DEBUG) {
1390 rtref_audit((struct rtentry_dbg *)p);
1391 }
1392 }
1393
1394 static inline void
1395 rtref_audit(struct rtentry_dbg *rte)
1396 {
1397 uint16_t idx;
1398
1399 if (rte->rtd_inuse != RTD_INUSE) {
1400 panic("rtref_audit: on freed rte=%p\n", rte);
1401 /* NOTREACHED */
1402 }
1403 idx = atomic_add_16_ov(&rte->rtd_refhold_cnt, 1) % CTRACE_HIST_SIZE;
1404 if (rte_debug & RTD_TRACE) {
1405 ctrace_record(&rte->rtd_refhold[idx]);
1406 }
1407 }
1408
1409 void
1410 rtsetifa(struct rtentry *rt, struct ifaddr *ifa)
1411 {
1412 LCK_MTX_ASSERT(rnh_lock, LCK_MTX_ASSERT_OWNED);
1413
1414 RT_LOCK_ASSERT_HELD(rt);
1415
1416 if (rt->rt_ifa == ifa) {
1417 return;
1418 }
1419
1420 /* Become a regular mutex, just in case */
1421 RT_CONVERT_LOCK(rt);
1422
1423 /* Release the old ifa */
1424 if (rt->rt_ifa) {
1425 IFA_REMREF(rt->rt_ifa);
1426 }
1427
1428 /* Set rt_ifa */
1429 rt->rt_ifa = ifa;
1430
1431 /* Take a reference to the ifa */
1432 if (rt->rt_ifa) {
1433 IFA_ADDREF(rt->rt_ifa);
1434 }
1435 }
1436
1437 /*
1438 * Force a routing table entry to the specified
1439 * destination to go through the given gateway.
1440 * Normally called as a result of a routing redirect
1441 * message from the network layer.
1442 */
1443 void
1444 rtredirect(struct ifnet *ifp, struct sockaddr *dst, struct sockaddr *gateway,
1445 struct sockaddr *netmask, int flags, struct sockaddr *src,
1446 struct rtentry **rtp)
1447 {
1448 struct rtentry *rt = NULL;
1449 int error = 0;
1450 short *stat = 0;
1451 struct rt_addrinfo info;
1452 struct ifaddr *ifa = NULL;
1453 unsigned int ifscope = (ifp != NULL) ? ifp->if_index : IFSCOPE_NONE;
1454 struct sockaddr_storage ss;
1455 int af = src->sa_family;
1456
1457 LCK_MTX_ASSERT(rnh_lock, LCK_MTX_ASSERT_NOTOWNED);
1458 lck_mtx_lock(rnh_lock);
1459
1460 /*
1461 * Transform src into the internal routing table form for
1462 * comparison against rt_gateway below.
1463 */
1464 if ((af == AF_INET) || (af == AF_INET6)) {
1465 src = sa_copy(src, &ss, &ifscope);
1466 }
1467
1468 /*
1469 * Verify the gateway is directly reachable; if scoped routing
1470 * is enabled, verify that it is reachable from the interface
1471 * where the ICMP redirect arrived on.
1472 */
1473 if ((ifa = ifa_ifwithnet_scoped(gateway, ifscope)) == NULL) {
1474 error = ENETUNREACH;
1475 goto out;
1476 }
1477
1478 /* Lookup route to the destination (from the original IP header) */
1479 rt = rtalloc1_scoped_locked(dst, 0, RTF_CLONING | RTF_PRCLONING, ifscope);
1480 if (rt != NULL) {
1481 RT_LOCK(rt);
1482 }
1483
1484 /*
1485 * If the redirect isn't from our current router for this dst,
1486 * it's either old or wrong. If it redirects us to ourselves,
1487 * we have a routing loop, perhaps as a result of an interface
1488 * going down recently. Holding rnh_lock here prevents the
1489 * possibility of rt_ifa/ifa's ifa_addr from changing (e.g.
1490 * in_ifinit), so okay to access ifa_addr without locking.
1491 */
1492 if (!(flags & RTF_DONE) && rt != NULL &&
1493 (!equal(src, rt->rt_gateway) || !equal(rt->rt_ifa->ifa_addr,
1494 ifa->ifa_addr))) {
1495 error = EINVAL;
1496 } else {
1497 IFA_REMREF(ifa);
1498 if ((ifa = ifa_ifwithaddr(gateway))) {
1499 IFA_REMREF(ifa);
1500 ifa = NULL;
1501 error = EHOSTUNREACH;
1502 }
1503 }
1504
1505 if (ifa) {
1506 IFA_REMREF(ifa);
1507 ifa = NULL;
1508 }
1509
1510 if (error) {
1511 if (rt != NULL) {
1512 RT_UNLOCK(rt);
1513 }
1514 goto done;
1515 }
1516
1517 /*
1518 * Create a new entry if we just got back a wildcard entry
1519 * or the the lookup failed. This is necessary for hosts
1520 * which use routing redirects generated by smart gateways
1521 * to dynamically build the routing tables.
1522 */
1523 if ((rt == NULL) || (rt_mask(rt) != NULL && rt_mask(rt)->sa_len < 2)) {
1524 goto create;
1525 }
1526 /*
1527 * Don't listen to the redirect if it's
1528 * for a route to an interface.
1529 */
1530 RT_LOCK_ASSERT_HELD(rt);
1531 if (rt->rt_flags & RTF_GATEWAY) {
1532 if (((rt->rt_flags & RTF_HOST) == 0) && (flags & RTF_HOST)) {
1533 /*
1534 * Changing from route to net => route to host.
1535 * Create new route, rather than smashing route
1536 * to net; similar to cloned routes, the newly
1537 * created host route is scoped as well.
1538 */
1539 create:
1540 if (rt != NULL) {
1541 RT_UNLOCK(rt);
1542 }
1543 flags |= RTF_GATEWAY | RTF_DYNAMIC;
1544 error = rtrequest_scoped_locked(RTM_ADD, dst,
1545 gateway, netmask, flags, NULL, ifscope);
1546 stat = &rtstat.rts_dynamic;
1547 } else {
1548 /*
1549 * Smash the current notion of the gateway to
1550 * this destination. Should check about netmask!!!
1551 */
1552 rt->rt_flags |= RTF_MODIFIED;
1553 flags |= RTF_MODIFIED;
1554 stat = &rtstat.rts_newgateway;
1555 /*
1556 * add the key and gateway (in one malloc'd chunk).
1557 */
1558 error = rt_setgate(rt, rt_key(rt), gateway);
1559 RT_UNLOCK(rt);
1560 }
1561 } else {
1562 RT_UNLOCK(rt);
1563 error = EHOSTUNREACH;
1564 }
1565 done:
1566 if (rt != NULL) {
1567 RT_LOCK_ASSERT_NOTHELD(rt);
1568 if (!error) {
1569 /* Enqueue event to refresh flow route entries */
1570 route_event_enqueue_nwk_wq_entry(rt, NULL, ROUTE_ENTRY_REFRESH, NULL, FALSE);
1571 if (rtp) {
1572 *rtp = rt;
1573 } else {
1574 rtfree_locked(rt);
1575 }
1576 } else {
1577 rtfree_locked(rt);
1578 }
1579 }
1580 out:
1581 if (error) {
1582 rtstat.rts_badredirect++;
1583 } else {
1584 if (stat != NULL) {
1585 (*stat)++;
1586 }
1587
1588 if (af == AF_INET) {
1589 routegenid_inet_update();
1590 } else if (af == AF_INET6) {
1591 routegenid_inet6_update();
1592 }
1593 }
1594 lck_mtx_unlock(rnh_lock);
1595 bzero((caddr_t)&info, sizeof(info));
1596 info.rti_info[RTAX_DST] = dst;
1597 info.rti_info[RTAX_GATEWAY] = gateway;
1598 info.rti_info[RTAX_NETMASK] = netmask;
1599 info.rti_info[RTAX_AUTHOR] = src;
1600 rt_missmsg(RTM_REDIRECT, &info, flags, error);
1601 }
1602
1603 /*
1604 * Routing table ioctl interface.
1605 */
1606 int
1607 rtioctl(unsigned long req, caddr_t data, struct proc *p)
1608 {
1609 #pragma unused(p, req, data)
1610 return ENXIO;
1611 }
1612
1613 struct ifaddr *
1614 ifa_ifwithroute(
1615 int flags,
1616 const struct sockaddr *dst,
1617 const struct sockaddr *gateway)
1618 {
1619 struct ifaddr *ifa;
1620
1621 lck_mtx_lock(rnh_lock);
1622 ifa = ifa_ifwithroute_locked(flags, dst, gateway);
1623 lck_mtx_unlock(rnh_lock);
1624
1625 return ifa;
1626 }
1627
1628 struct ifaddr *
1629 ifa_ifwithroute_locked(int flags, const struct sockaddr *dst,
1630 const struct sockaddr *gateway)
1631 {
1632 return ifa_ifwithroute_common_locked((flags & ~RTF_IFSCOPE), dst,
1633 gateway, IFSCOPE_NONE);
1634 }
1635
1636 struct ifaddr *
1637 ifa_ifwithroute_scoped_locked(int flags, const struct sockaddr *dst,
1638 const struct sockaddr *gateway, unsigned int ifscope)
1639 {
1640 if (ifscope != IFSCOPE_NONE) {
1641 flags |= RTF_IFSCOPE;
1642 } else {
1643 flags &= ~RTF_IFSCOPE;
1644 }
1645
1646 return ifa_ifwithroute_common_locked(flags, dst, gateway, ifscope);
1647 }
1648
1649 static struct ifaddr *
1650 ifa_ifwithroute_common_locked(int flags, const struct sockaddr *dst,
1651 const struct sockaddr *gw, unsigned int ifscope)
1652 {
1653 struct ifaddr *ifa = NULL;
1654 struct rtentry *rt = NULL;
1655 struct sockaddr_storage dst_ss, gw_ss;
1656
1657 LCK_MTX_ASSERT(rnh_lock, LCK_MTX_ASSERT_OWNED);
1658
1659 /*
1660 * Just in case the sockaddr passed in by the caller
1661 * contains a scope ID, make sure to clear it since
1662 * interface addresses aren't scoped.
1663 */
1664 if (dst != NULL &&
1665 ((dst->sa_family == AF_INET) ||
1666 (dst->sa_family == AF_INET6))) {
1667 dst = sa_copy(SA((uintptr_t)dst), &dst_ss, NULL);
1668 }
1669
1670 if (gw != NULL &&
1671 ((gw->sa_family == AF_INET) ||
1672 (gw->sa_family == AF_INET6))) {
1673 gw = sa_copy(SA((uintptr_t)gw), &gw_ss, NULL);
1674 }
1675
1676 if (!(flags & RTF_GATEWAY)) {
1677 /*
1678 * If we are adding a route to an interface,
1679 * and the interface is a pt to pt link
1680 * we should search for the destination
1681 * as our clue to the interface. Otherwise
1682 * we can use the local address.
1683 */
1684 if (flags & RTF_HOST) {
1685 ifa = ifa_ifwithdstaddr(dst);
1686 }
1687 if (ifa == NULL) {
1688 ifa = ifa_ifwithaddr_scoped(gw, ifscope);
1689 }
1690 } else {
1691 /*
1692 * If we are adding a route to a remote net
1693 * or host, the gateway may still be on the
1694 * other end of a pt to pt link.
1695 */
1696 ifa = ifa_ifwithdstaddr(gw);
1697 }
1698 if (ifa == NULL) {
1699 ifa = ifa_ifwithnet_scoped(gw, ifscope);
1700 }
1701 if (ifa == NULL) {
1702 /* Workaround to avoid gcc warning regarding const variable */
1703 rt = rtalloc1_scoped_locked((struct sockaddr *)(size_t)dst,
1704 0, 0, ifscope);
1705 if (rt != NULL) {
1706 RT_LOCK_SPIN(rt);
1707 ifa = rt->rt_ifa;
1708 if (ifa != NULL) {
1709 /* Become a regular mutex */
1710 RT_CONVERT_LOCK(rt);
1711 IFA_ADDREF(ifa);
1712 }
1713 RT_REMREF_LOCKED(rt);
1714 RT_UNLOCK(rt);
1715 rt = NULL;
1716 }
1717 }
1718 /*
1719 * Holding rnh_lock here prevents the possibility of ifa from
1720 * changing (e.g. in_ifinit), so it is safe to access its
1721 * ifa_addr (here and down below) without locking.
1722 */
1723 if (ifa != NULL && ifa->ifa_addr->sa_family != dst->sa_family) {
1724 struct ifaddr *newifa;
1725 /* Callee adds reference to newifa upon success */
1726 newifa = ifaof_ifpforaddr(dst, ifa->ifa_ifp);
1727 if (newifa != NULL) {
1728 IFA_REMREF(ifa);
1729 ifa = newifa;
1730 }
1731 }
1732 /*
1733 * If we are adding a gateway, it is quite possible that the
1734 * routing table has a static entry in place for the gateway,
1735 * that may not agree with info garnered from the interfaces.
1736 * The routing table should carry more precedence than the
1737 * interfaces in this matter. Must be careful not to stomp
1738 * on new entries from rtinit, hence (ifa->ifa_addr != gw).
1739 */
1740 if ((ifa == NULL ||
1741 !equal(ifa->ifa_addr, (struct sockaddr *)(size_t)gw)) &&
1742 (rt = rtalloc1_scoped_locked((struct sockaddr *)(size_t)gw,
1743 0, 0, ifscope)) != NULL) {
1744 if (ifa != NULL) {
1745 IFA_REMREF(ifa);
1746 }
1747 RT_LOCK_SPIN(rt);
1748 ifa = rt->rt_ifa;
1749 if (ifa != NULL) {
1750 /* Become a regular mutex */
1751 RT_CONVERT_LOCK(rt);
1752 IFA_ADDREF(ifa);
1753 }
1754 RT_REMREF_LOCKED(rt);
1755 RT_UNLOCK(rt);
1756 }
1757 /*
1758 * If an interface scope was specified, the interface index of
1759 * the found ifaddr must be equivalent to that of the scope;
1760 * otherwise there is no match.
1761 */
1762 if ((flags & RTF_IFSCOPE) &&
1763 ifa != NULL && ifa->ifa_ifp->if_index != ifscope) {
1764 IFA_REMREF(ifa);
1765 ifa = NULL;
1766 }
1767
1768 /*
1769 * ifa's address family must match destination's address family
1770 * after all is said and done.
1771 */
1772 if (ifa != NULL &&
1773 ifa->ifa_addr->sa_family != dst->sa_family) {
1774 IFA_REMREF(ifa);
1775 ifa = NULL;
1776 }
1777
1778 return ifa;
1779 }
1780
1781 static int rt_fixdelete(struct radix_node *, void *);
1782 static int rt_fixchange(struct radix_node *, void *);
1783
1784 struct rtfc_arg {
1785 struct rtentry *rt0;
1786 struct radix_node_head *rnh;
1787 };
1788
1789 int
1790 rtrequest_locked(int req, struct sockaddr *dst, struct sockaddr *gateway,
1791 struct sockaddr *netmask, int flags, struct rtentry **ret_nrt)
1792 {
1793 return rtrequest_common_locked(req, dst, gateway, netmask,
1794 (flags & ~RTF_IFSCOPE), ret_nrt, IFSCOPE_NONE);
1795 }
1796
1797 int
1798 rtrequest_scoped_locked(int req, struct sockaddr *dst,
1799 struct sockaddr *gateway, struct sockaddr *netmask, int flags,
1800 struct rtentry **ret_nrt, unsigned int ifscope)
1801 {
1802 if (ifscope != IFSCOPE_NONE) {
1803 flags |= RTF_IFSCOPE;
1804 } else {
1805 flags &= ~RTF_IFSCOPE;
1806 }
1807
1808 return rtrequest_common_locked(req, dst, gateway, netmask,
1809 flags, ret_nrt, ifscope);
1810 }
1811
1812 /*
1813 * Do appropriate manipulations of a routing tree given all the bits of
1814 * info needed.
1815 *
1816 * Storing the scope ID in the radix key is an internal job that should be
1817 * left to routines in this module. Callers should specify the scope value
1818 * to the "scoped" variants of route routines instead of manipulating the
1819 * key itself. This is typically done when creating a scoped route, e.g.
1820 * rtrequest(RTM_ADD). Once such a route is created and marked with the
1821 * RTF_IFSCOPE flag, callers can simply use its rt_key(rt) to clone it
1822 * (RTM_RESOLVE) or to remove it (RTM_DELETE). An exception to this is
1823 * during certain routing socket operations where the search key might be
1824 * derived from the routing message itself, in which case the caller must
1825 * specify the destination address and scope value for RTM_ADD/RTM_DELETE.
1826 */
1827 static int
1828 rtrequest_common_locked(int req, struct sockaddr *dst0,
1829 struct sockaddr *gateway, struct sockaddr *netmask, int flags,
1830 struct rtentry **ret_nrt, unsigned int ifscope)
1831 {
1832 int error = 0;
1833 struct rtentry *rt;
1834 struct radix_node *rn;
1835 struct radix_node_head *rnh;
1836 struct ifaddr *ifa = NULL;
1837 struct sockaddr *ndst, *dst = dst0;
1838 struct sockaddr_storage ss, mask;
1839 struct timeval caltime;
1840 int af = dst->sa_family;
1841 void (*ifa_rtrequest)(int, struct rtentry *, struct sockaddr *);
1842
1843 #define senderr(x) { error = x; goto bad; }
1844
1845 DTRACE_ROUTE6(rtrequest, int, req, struct sockaddr *, dst0,
1846 struct sockaddr *, gateway, struct sockaddr *, netmask,
1847 int, flags, unsigned int, ifscope);
1848
1849 LCK_MTX_ASSERT(rnh_lock, LCK_MTX_ASSERT_OWNED);
1850 /*
1851 * Find the correct routing tree to use for this Address Family
1852 */
1853 if ((rnh = rt_tables[af]) == NULL) {
1854 senderr(ESRCH);
1855 }
1856 /*
1857 * If we are adding a host route then we don't want to put
1858 * a netmask in the tree
1859 */
1860 if (flags & RTF_HOST) {
1861 netmask = NULL;
1862 }
1863
1864 /*
1865 * If Scoped Routing is enabled, use a local copy of the destination
1866 * address to store the scope ID into. This logic is repeated below
1867 * in the RTM_RESOLVE handler since the caller does not normally
1868 * specify such a flag during a resolve, as well as for the handling
1869 * of IPv4 link-local address; instead, it passes in the route used for
1870 * cloning for which the scope info is derived from. Note also that
1871 * in the case of RTM_DELETE, the address passed in by the caller
1872 * might already contain the scope ID info when it is the key itself,
1873 * thus making RTF_IFSCOPE unnecessary; one instance where it is
1874 * explicitly set is inside route_output() as part of handling a
1875 * routing socket request.
1876 */
1877 if (req != RTM_RESOLVE && ((af == AF_INET) || (af == AF_INET6))) {
1878 /* Transform dst into the internal routing table form */
1879 dst = sa_copy(dst, &ss, &ifscope);
1880
1881 /* Transform netmask into the internal routing table form */
1882 if (netmask != NULL) {
1883 netmask = ma_copy(af, netmask, &mask, ifscope);
1884 }
1885
1886 if (ifscope != IFSCOPE_NONE) {
1887 flags |= RTF_IFSCOPE;
1888 }
1889 } else if ((flags & RTF_IFSCOPE) &&
1890 (af != AF_INET && af != AF_INET6)) {
1891 senderr(EINVAL);
1892 }
1893
1894 if (ifscope == IFSCOPE_NONE) {
1895 flags &= ~RTF_IFSCOPE;
1896 }
1897
1898 switch (req) {
1899 case RTM_DELETE: {
1900 struct rtentry *gwrt = NULL;
1901 boolean_t was_router = FALSE;
1902 uint32_t old_rt_refcnt = 0;
1903 /*
1904 * Remove the item from the tree and return it.
1905 * Complain if it is not there and do no more processing.
1906 */
1907 if ((rn = rnh->rnh_deladdr(dst, netmask, rnh)) == NULL) {
1908 senderr(ESRCH);
1909 }
1910 if (rn->rn_flags & (RNF_ACTIVE | RNF_ROOT)) {
1911 panic("rtrequest delete");
1912 /* NOTREACHED */
1913 }
1914 rt = (struct rtentry *)rn;
1915
1916 RT_LOCK(rt);
1917 old_rt_refcnt = rt->rt_refcnt;
1918 rt->rt_flags &= ~RTF_UP;
1919 /*
1920 * Release any idle reference count held on the interface
1921 * as this route is no longer externally visible.
1922 */
1923 rt_clear_idleref(rt);
1924 /*
1925 * Take an extra reference to handle the deletion of a route
1926 * entry whose reference count is already 0; e.g. an expiring
1927 * cloned route entry or an entry that was added to the table
1928 * with 0 reference. If the caller is interested in this route,
1929 * we will return it with the reference intact. Otherwise we
1930 * will decrement the reference via rtfree_locked() and then
1931 * possibly deallocate it.
1932 */
1933 RT_ADDREF_LOCKED(rt);
1934
1935 /*
1936 * For consistency, in case the caller didn't set the flag.
1937 */
1938 rt->rt_flags |= RTF_CONDEMNED;
1939
1940 /*
1941 * Clear RTF_ROUTER if it's set.
1942 */
1943 if (rt->rt_flags & RTF_ROUTER) {
1944 was_router = TRUE;
1945 VERIFY(rt->rt_flags & RTF_HOST);
1946 rt->rt_flags &= ~RTF_ROUTER;
1947 }
1948
1949 /*
1950 * Enqueue work item to invoke callback for this route entry
1951 *
1952 * If the old count is 0, it implies that last reference is being
1953 * removed and there's no one listening for this route event.
1954 */
1955 if (old_rt_refcnt != 0) {
1956 route_event_enqueue_nwk_wq_entry(rt, NULL,
1957 ROUTE_ENTRY_DELETED, NULL, TRUE);
1958 }
1959
1960 /*
1961 * Now search what's left of the subtree for any cloned
1962 * routes which might have been formed from this node.
1963 */
1964 if ((rt->rt_flags & (RTF_CLONING | RTF_PRCLONING)) &&
1965 rt_mask(rt)) {
1966 RT_UNLOCK(rt);
1967 rnh->rnh_walktree_from(rnh, dst, rt_mask(rt),
1968 rt_fixdelete, rt);
1969 RT_LOCK(rt);
1970 }
1971
1972 if (was_router) {
1973 struct route_event rt_ev;
1974 route_event_init(&rt_ev, rt, NULL, ROUTE_LLENTRY_DELETED);
1975 RT_UNLOCK(rt);
1976 (void) rnh->rnh_walktree(rnh,
1977 route_event_walktree, (void *)&rt_ev);
1978 RT_LOCK(rt);
1979 }
1980
1981 /*
1982 * Remove any external references we may have.
1983 */
1984 if ((gwrt = rt->rt_gwroute) != NULL) {
1985 rt->rt_gwroute = NULL;
1986 }
1987
1988 /*
1989 * give the protocol a chance to keep things in sync.
1990 */
1991 if ((ifa = rt->rt_ifa) != NULL) {
1992 IFA_LOCK_SPIN(ifa);
1993 ifa_rtrequest = ifa->ifa_rtrequest;
1994 IFA_UNLOCK(ifa);
1995 if (ifa_rtrequest != NULL) {
1996 ifa_rtrequest(RTM_DELETE, rt, NULL);
1997 }
1998 /* keep reference on rt_ifa */
1999 ifa = NULL;
2000 }
2001
2002 /*
2003 * one more rtentry floating around that is not
2004 * linked to the routing table.
2005 */
2006 (void) OSIncrementAtomic(&rttrash);
2007 if (rte_debug & RTD_DEBUG) {
2008 TAILQ_INSERT_TAIL(&rttrash_head,
2009 (struct rtentry_dbg *)rt, rtd_trash_link);
2010 }
2011
2012 /*
2013 * If this is the (non-scoped) default route, clear
2014 * the interface index used for the primary ifscope.
2015 */
2016 if (rt_primary_default(rt, rt_key(rt))) {
2017 set_primary_ifscope(rt_key(rt)->sa_family,
2018 IFSCOPE_NONE);
2019 if ((rt->rt_flags & RTF_STATIC) &&
2020 rt_key(rt)->sa_family == PF_INET6) {
2021 trigger_v6_defrtr_select = TRUE;
2022 }
2023 }
2024
2025 #if NECP
2026 /*
2027 * If this is a change in a default route, update
2028 * necp client watchers to re-evaluate
2029 */
2030 if (SA_DEFAULT(rt_key(rt))) {
2031 if (rt->rt_ifp != NULL) {
2032 ifnet_touch_lastupdown(rt->rt_ifp);
2033 }
2034 necp_update_all_clients();
2035 }
2036 #endif /* NECP */
2037
2038 RT_UNLOCK(rt);
2039
2040 /*
2041 * This might result in another rtentry being freed if
2042 * we held its last reference. Do this after the rtentry
2043 * lock is dropped above, as it could lead to the same
2044 * lock being acquired if gwrt is a clone of rt.
2045 */
2046 if (gwrt != NULL) {
2047 rtfree_locked(gwrt);
2048 }
2049
2050 /*
2051 * If the caller wants it, then it can have it,
2052 * but it's up to it to free the rtentry as we won't be
2053 * doing it.
2054 */
2055 if (ret_nrt != NULL) {
2056 /* Return the route to caller with reference intact */
2057 *ret_nrt = rt;
2058 } else {
2059 /* Dereference or deallocate the route */
2060 rtfree_locked(rt);
2061 }
2062 if (af == AF_INET) {
2063 routegenid_inet_update();
2064 } else if (af == AF_INET6) {
2065 routegenid_inet6_update();
2066 }
2067 break;
2068 }
2069 case RTM_RESOLVE:
2070 if (ret_nrt == NULL || (rt = *ret_nrt) == NULL) {
2071 senderr(EINVAL);
2072 }
2073 /*
2074 * According to the UNIX conformance tests, we need to return
2075 * ENETUNREACH when the parent route is RTF_REJECT.
2076 * However, there isn't any point in cloning RTF_REJECT
2077 * routes, so we immediately return an error.
2078 */
2079 if (rt->rt_flags & RTF_REJECT) {
2080 if (rt->rt_flags & RTF_HOST) {
2081 senderr(EHOSTUNREACH);
2082 } else {
2083 senderr(ENETUNREACH);
2084 }
2085 }
2086 /*
2087 * If cloning, we have the parent route given by the caller
2088 * and will use its rt_gateway, rt_rmx as part of the cloning
2089 * process below. Since rnh_lock is held at this point, the
2090 * parent's rt_ifa and rt_gateway will not change, and its
2091 * relevant rt_flags will not change as well. The only thing
2092 * that could change are the metrics, and thus we hold the
2093 * parent route's rt_lock later on during the actual copying
2094 * of rt_rmx.
2095 */
2096 ifa = rt->rt_ifa;
2097 IFA_ADDREF(ifa);
2098 flags = rt->rt_flags &
2099 ~(RTF_CLONING | RTF_PRCLONING | RTF_STATIC);
2100 flags |= RTF_WASCLONED;
2101 gateway = rt->rt_gateway;
2102 if ((netmask = rt->rt_genmask) == NULL) {
2103 flags |= RTF_HOST;
2104 }
2105
2106 if (af != AF_INET && af != AF_INET6) {
2107 goto makeroute;
2108 }
2109
2110 /*
2111 * When scoped routing is enabled, cloned entries are
2112 * always scoped according to the interface portion of
2113 * the parent route. The exception to this are IPv4
2114 * link local addresses, or those routes that are cloned
2115 * from a RTF_PROXY route. For the latter, the clone
2116 * gets to keep the RTF_PROXY flag.
2117 */
2118 if ((af == AF_INET &&
2119 IN_LINKLOCAL(ntohl(SIN(dst)->sin_addr.s_addr))) ||
2120 (rt->rt_flags & RTF_PROXY)) {
2121 ifscope = IFSCOPE_NONE;
2122 flags &= ~RTF_IFSCOPE;
2123 /*
2124 * These types of cloned routes aren't currently
2125 * eligible for idle interface reference counting.
2126 */
2127 flags |= RTF_NOIFREF;
2128 } else {
2129 if (flags & RTF_IFSCOPE) {
2130 ifscope = (af == AF_INET) ?
2131 sin_get_ifscope(rt_key(rt)) :
2132 sin6_get_ifscope(rt_key(rt));
2133 } else {
2134 ifscope = rt->rt_ifp->if_index;
2135 flags |= RTF_IFSCOPE;
2136 }
2137 VERIFY(ifscope != IFSCOPE_NONE);
2138 }
2139
2140 /*
2141 * Transform dst into the internal routing table form,
2142 * clearing out the scope ID field if ifscope isn't set.
2143 */
2144 dst = sa_copy(dst, &ss, (ifscope == IFSCOPE_NONE) ?
2145 NULL : &ifscope);
2146
2147 /* Transform netmask into the internal routing table form */
2148 if (netmask != NULL) {
2149 netmask = ma_copy(af, netmask, &mask, ifscope);
2150 }
2151
2152 goto makeroute;
2153
2154 case RTM_ADD:
2155 if ((flags & RTF_GATEWAY) && !gateway) {
2156 panic("rtrequest: RTF_GATEWAY but no gateway");
2157 /* NOTREACHED */
2158 }
2159 if (flags & RTF_IFSCOPE) {
2160 ifa = ifa_ifwithroute_scoped_locked(flags, dst0,
2161 gateway, ifscope);
2162 } else {
2163 ifa = ifa_ifwithroute_locked(flags, dst0, gateway);
2164 }
2165 if (ifa == NULL) {
2166 senderr(ENETUNREACH);
2167 }
2168 makeroute:
2169 /*
2170 * We land up here for both RTM_RESOLVE and RTM_ADD
2171 * when we decide to create a route.
2172 */
2173 if ((rt = rte_alloc()) == NULL) {
2174 senderr(ENOBUFS);
2175 }
2176 Bzero(rt, sizeof(*rt));
2177 rte_lock_init(rt);
2178 eventhandler_lists_ctxt_init(&rt->rt_evhdlr_ctxt);
2179 getmicrotime(&caltime);
2180 rt->base_calendartime = caltime.tv_sec;
2181 rt->base_uptime = net_uptime();
2182 RT_LOCK(rt);
2183 rt->rt_flags = RTF_UP | flags;
2184
2185 /*
2186 * Point the generation ID to the tree's.
2187 */
2188 switch (af) {
2189 case AF_INET:
2190 rt->rt_tree_genid = &route_genid_inet;
2191 break;
2192 case AF_INET6:
2193 rt->rt_tree_genid = &route_genid_inet6;
2194 break;
2195 default:
2196 break;
2197 }
2198
2199 /*
2200 * Add the gateway. Possibly re-malloc-ing the storage for it
2201 * also add the rt_gwroute if possible.
2202 */
2203 if ((error = rt_setgate(rt, dst, gateway)) != 0) {
2204 int tmp = error;
2205 RT_UNLOCK(rt);
2206 nstat_route_detach(rt);
2207 rte_lock_destroy(rt);
2208 rte_free(rt);
2209 senderr(tmp);
2210 }
2211
2212 /*
2213 * point to the (possibly newly malloc'd) dest address.
2214 */
2215 ndst = rt_key(rt);
2216
2217 /*
2218 * make sure it contains the value we want (masked if needed).
2219 */
2220 if (netmask) {
2221 rt_maskedcopy(dst, ndst, netmask);
2222 } else {
2223 Bcopy(dst, ndst, dst->sa_len);
2224 }
2225
2226 /*
2227 * Note that we now have a reference to the ifa.
2228 * This moved from below so that rnh->rnh_addaddr() can
2229 * examine the ifa and ifa->ifa_ifp if it so desires.
2230 */
2231 rtsetifa(rt, ifa);
2232 rt->rt_ifp = rt->rt_ifa->ifa_ifp;
2233
2234 /* XXX mtu manipulation will be done in rnh_addaddr -- itojun */
2235
2236 rn = rnh->rnh_addaddr((caddr_t)ndst, (caddr_t)netmask,
2237 rnh, rt->rt_nodes);
2238 if (rn == 0) {
2239 struct rtentry *rt2;
2240 /*
2241 * Uh-oh, we already have one of these in the tree.
2242 * We do a special hack: if the route that's already
2243 * there was generated by the protocol-cloning
2244 * mechanism, then we just blow it away and retry
2245 * the insertion of the new one.
2246 */
2247 if (flags & RTF_IFSCOPE) {
2248 rt2 = rtalloc1_scoped_locked(dst0, 0,
2249 RTF_CLONING | RTF_PRCLONING, ifscope);
2250 } else {
2251 rt2 = rtalloc1_locked(dst, 0,
2252 RTF_CLONING | RTF_PRCLONING);
2253 }
2254 if (rt2 && rt2->rt_parent) {
2255 /*
2256 * rnh_lock is held here, so rt_key and
2257 * rt_gateway of rt2 will not change.
2258 */
2259 (void) rtrequest_locked(RTM_DELETE, rt_key(rt2),
2260 rt2->rt_gateway, rt_mask(rt2),
2261 rt2->rt_flags, 0);
2262 rtfree_locked(rt2);
2263 rn = rnh->rnh_addaddr((caddr_t)ndst,
2264 (caddr_t)netmask, rnh, rt->rt_nodes);
2265 } else if (rt2) {
2266 /* undo the extra ref we got */
2267 rtfree_locked(rt2);
2268 }
2269 }
2270
2271 /*
2272 * If it still failed to go into the tree,
2273 * then un-make it (this should be a function)
2274 */
2275 if (rn == NULL) {
2276 /* Clear gateway route */
2277 rt_set_gwroute(rt, rt_key(rt), NULL);
2278 if (rt->rt_ifa) {
2279 IFA_REMREF(rt->rt_ifa);
2280 rt->rt_ifa = NULL;
2281 }
2282 R_Free(rt_key(rt));
2283 RT_UNLOCK(rt);
2284 nstat_route_detach(rt);
2285 rte_lock_destroy(rt);
2286 rte_free(rt);
2287 senderr(EEXIST);
2288 }
2289
2290 rt->rt_parent = NULL;
2291
2292 /*
2293 * If we got here from RESOLVE, then we are cloning so clone
2294 * the rest, and note that we are a clone (and increment the
2295 * parent's references). rnh_lock is still held, which prevents
2296 * a lookup from returning the newly-created route. Hence
2297 * holding and releasing the parent's rt_lock while still
2298 * holding the route's rt_lock is safe since the new route
2299 * is not yet externally visible.
2300 */
2301 if (req == RTM_RESOLVE) {
2302 RT_LOCK_SPIN(*ret_nrt);
2303 VERIFY((*ret_nrt)->rt_expire == 0 ||
2304 (*ret_nrt)->rt_rmx.rmx_expire != 0);
2305 VERIFY((*ret_nrt)->rt_expire != 0 ||
2306 (*ret_nrt)->rt_rmx.rmx_expire == 0);
2307 rt->rt_rmx = (*ret_nrt)->rt_rmx;
2308 rt_setexpire(rt, (*ret_nrt)->rt_expire);
2309 if ((*ret_nrt)->rt_flags &
2310 (RTF_CLONING | RTF_PRCLONING)) {
2311 rt->rt_parent = (*ret_nrt);
2312 RT_ADDREF_LOCKED(*ret_nrt);
2313 }
2314 RT_UNLOCK(*ret_nrt);
2315 }
2316
2317 /*
2318 * if this protocol has something to add to this then
2319 * allow it to do that as well.
2320 */
2321 IFA_LOCK_SPIN(ifa);
2322 ifa_rtrequest = ifa->ifa_rtrequest;
2323 IFA_UNLOCK(ifa);
2324 if (ifa_rtrequest != NULL) {
2325 ifa_rtrequest(req, rt, SA(ret_nrt ? *ret_nrt : NULL));
2326 }
2327 IFA_REMREF(ifa);
2328 ifa = NULL;
2329
2330 /*
2331 * If this is the (non-scoped) default route, record
2332 * the interface index used for the primary ifscope.
2333 */
2334 if (rt_primary_default(rt, rt_key(rt))) {
2335 set_primary_ifscope(rt_key(rt)->sa_family,
2336 rt->rt_ifp->if_index);
2337 }
2338
2339 #if NECP
2340 /*
2341 * If this is a change in a default route, update
2342 * necp client watchers to re-evaluate
2343 */
2344 if (SA_DEFAULT(rt_key(rt))) {
2345 if (rt->rt_ifp != NULL) {
2346 ifnet_touch_lastupdown(rt->rt_ifp);
2347 }
2348 necp_update_all_clients();
2349 }
2350 #endif /* NECP */
2351
2352 /*
2353 * actually return a resultant rtentry and
2354 * give the caller a single reference.
2355 */
2356 if (ret_nrt) {
2357 *ret_nrt = rt;
2358 RT_ADDREF_LOCKED(rt);
2359 }
2360
2361 if (af == AF_INET) {
2362 routegenid_inet_update();
2363 } else if (af == AF_INET6) {
2364 routegenid_inet6_update();
2365 }
2366
2367 RT_GENID_SYNC(rt);
2368
2369 /*
2370 * We repeat the same procedures from rt_setgate() here
2371 * because they weren't completed when we called it earlier,
2372 * since the node was embryonic.
2373 */
2374 if ((rt->rt_flags & RTF_GATEWAY) && rt->rt_gwroute != NULL) {
2375 rt_set_gwroute(rt, rt_key(rt), rt->rt_gwroute);
2376 }
2377
2378 if (req == RTM_ADD &&
2379 !(rt->rt_flags & RTF_HOST) && rt_mask(rt) != NULL) {
2380 struct rtfc_arg arg;
2381 arg.rnh = rnh;
2382 arg.rt0 = rt;
2383 RT_UNLOCK(rt);
2384 rnh->rnh_walktree_from(rnh, rt_key(rt), rt_mask(rt),
2385 rt_fixchange, &arg);
2386 } else {
2387 RT_UNLOCK(rt);
2388 }
2389
2390 nstat_route_new_entry(rt);
2391 break;
2392 }
2393 bad:
2394 if (ifa) {
2395 IFA_REMREF(ifa);
2396 }
2397 return error;
2398 }
2399 #undef senderr
2400
2401 int
2402 rtrequest(int req, struct sockaddr *dst, struct sockaddr *gateway,
2403 struct sockaddr *netmask, int flags, struct rtentry **ret_nrt)
2404 {
2405 int error;
2406 LCK_MTX_ASSERT(rnh_lock, LCK_MTX_ASSERT_NOTOWNED);
2407 lck_mtx_lock(rnh_lock);
2408 error = rtrequest_locked(req, dst, gateway, netmask, flags, ret_nrt);
2409 lck_mtx_unlock(rnh_lock);
2410 return error;
2411 }
2412
2413 int
2414 rtrequest_scoped(int req, struct sockaddr *dst, struct sockaddr *gateway,
2415 struct sockaddr *netmask, int flags, struct rtentry **ret_nrt,
2416 unsigned int ifscope)
2417 {
2418 int error;
2419 LCK_MTX_ASSERT(rnh_lock, LCK_MTX_ASSERT_NOTOWNED);
2420 lck_mtx_lock(rnh_lock);
2421 error = rtrequest_scoped_locked(req, dst, gateway, netmask, flags,
2422 ret_nrt, ifscope);
2423 lck_mtx_unlock(rnh_lock);
2424 return error;
2425 }
2426
2427 /*
2428 * Called from rtrequest(RTM_DELETE, ...) to fix up the route's ``family''
2429 * (i.e., the routes related to it by the operation of cloning). This
2430 * routine is iterated over all potential former-child-routes by way of
2431 * rnh->rnh_walktree_from() above, and those that actually are children of
2432 * the late parent (passed in as VP here) are themselves deleted.
2433 */
2434 static int
2435 rt_fixdelete(struct radix_node *rn, void *vp)
2436 {
2437 struct rtentry *rt = (struct rtentry *)rn;
2438 struct rtentry *rt0 = vp;
2439
2440 LCK_MTX_ASSERT(rnh_lock, LCK_MTX_ASSERT_OWNED);
2441
2442 RT_LOCK(rt);
2443 if (rt->rt_parent == rt0 &&
2444 !(rt->rt_flags & (RTF_CLONING | RTF_PRCLONING))) {
2445 /*
2446 * Safe to drop rt_lock and use rt_key, since holding
2447 * rnh_lock here prevents another thread from calling
2448 * rt_setgate() on this route.
2449 */
2450 RT_UNLOCK(rt);
2451 return rtrequest_locked(RTM_DELETE, rt_key(rt), NULL,
2452 rt_mask(rt), rt->rt_flags, NULL);
2453 }
2454 RT_UNLOCK(rt);
2455 return 0;
2456 }
2457
2458 /*
2459 * This routine is called from rt_setgate() to do the analogous thing for
2460 * adds and changes. There is the added complication in this case of a
2461 * middle insert; i.e., insertion of a new network route between an older
2462 * network route and (cloned) host routes. For this reason, a simple check
2463 * of rt->rt_parent is insufficient; each candidate route must be tested
2464 * against the (mask, value) of the new route (passed as before in vp)
2465 * to see if the new route matches it.
2466 *
2467 * XXX - it may be possible to do fixdelete() for changes and reserve this
2468 * routine just for adds. I'm not sure why I thought it was necessary to do
2469 * changes this way.
2470 */
2471 static int
2472 rt_fixchange(struct radix_node *rn, void *vp)
2473 {
2474 struct rtentry *rt = (struct rtentry *)rn;
2475 struct rtfc_arg *ap = vp;
2476 struct rtentry *rt0 = ap->rt0;
2477 struct radix_node_head *rnh = ap->rnh;
2478 u_char *xk1, *xm1, *xk2, *xmp;
2479 int i, len;
2480
2481 LCK_MTX_ASSERT(rnh_lock, LCK_MTX_ASSERT_OWNED);
2482
2483 RT_LOCK(rt);
2484
2485 if (!rt->rt_parent ||
2486 (rt->rt_flags & (RTF_CLONING | RTF_PRCLONING))) {
2487 RT_UNLOCK(rt);
2488 return 0;
2489 }
2490
2491 if (rt->rt_parent == rt0) {
2492 goto delete_rt;
2493 }
2494
2495 /*
2496 * There probably is a function somewhere which does this...
2497 * if not, there should be.
2498 */
2499 len = imin(rt_key(rt0)->sa_len, rt_key(rt)->sa_len);
2500
2501 xk1 = (u_char *)rt_key(rt0);
2502 xm1 = (u_char *)rt_mask(rt0);
2503 xk2 = (u_char *)rt_key(rt);
2504
2505 /*
2506 * Avoid applying a less specific route; do this only if the parent
2507 * route (rt->rt_parent) is a network route, since otherwise its mask
2508 * will be NULL if it is a cloning host route.
2509 */
2510 if ((xmp = (u_char *)rt_mask(rt->rt_parent)) != NULL) {
2511 int mlen = rt_mask(rt->rt_parent)->sa_len;
2512 if (mlen > rt_mask(rt0)->sa_len) {
2513 RT_UNLOCK(rt);
2514 return 0;
2515 }
2516
2517 for (i = rnh->rnh_treetop->rn_offset; i < mlen; i++) {
2518 if ((xmp[i] & ~(xmp[i] ^ xm1[i])) != xmp[i]) {
2519 RT_UNLOCK(rt);
2520 return 0;
2521 }
2522 }
2523 }
2524
2525 for (i = rnh->rnh_treetop->rn_offset; i < len; i++) {
2526 if ((xk2[i] & xm1[i]) != xk1[i]) {
2527 RT_UNLOCK(rt);
2528 return 0;
2529 }
2530 }
2531
2532 /*
2533 * OK, this node is a clone, and matches the node currently being
2534 * changed/added under the node's mask. So, get rid of it.
2535 */
2536 delete_rt:
2537 /*
2538 * Safe to drop rt_lock and use rt_key, since holding rnh_lock here
2539 * prevents another thread from calling rt_setgate() on this route.
2540 */
2541 RT_UNLOCK(rt);
2542 return rtrequest_locked(RTM_DELETE, rt_key(rt), NULL,
2543 rt_mask(rt), rt->rt_flags, NULL);
2544 }
2545
2546 /*
2547 * Round up sockaddr len to multiples of 32-bytes. This will reduce
2548 * or even eliminate the need to re-allocate the chunk of memory used
2549 * for rt_key and rt_gateway in the event the gateway portion changes.
2550 * Certain code paths (e.g. IPsec) are notorious for caching the address
2551 * of rt_gateway; this rounding-up would help ensure that the gateway
2552 * portion never gets deallocated (though it may change contents) and
2553 * thus greatly simplifies things.
2554 */
2555 #define SA_SIZE(x) (-(-((uintptr_t)(x)) & -(32)))
2556
2557 /*
2558 * Sets the gateway and/or gateway route portion of a route; may be
2559 * called on an existing route to modify the gateway portion. Both
2560 * rt_key and rt_gateway are allocated out of the same memory chunk.
2561 * Route entry lock must be held by caller; this routine will return
2562 * with the lock held.
2563 */
2564 int
2565 rt_setgate(struct rtentry *rt, struct sockaddr *dst, struct sockaddr *gate)
2566 {
2567 int dlen = SA_SIZE(dst->sa_len), glen = SA_SIZE(gate->sa_len);
2568 struct radix_node_head *rnh = NULL;
2569 boolean_t loop = FALSE;
2570
2571 if (dst->sa_family != AF_INET && dst->sa_family != AF_INET6) {
2572 return EINVAL;
2573 }
2574
2575 rnh = rt_tables[dst->sa_family];
2576 LCK_MTX_ASSERT(rnh_lock, LCK_MTX_ASSERT_OWNED);
2577 RT_LOCK_ASSERT_HELD(rt);
2578
2579 /*
2580 * If this is for a route that is on its way of being removed,
2581 * or is temporarily frozen, reject the modification request.
2582 */
2583 if (rt->rt_flags & RTF_CONDEMNED) {
2584 return EBUSY;
2585 }
2586
2587 /* Add an extra ref for ourselves */
2588 RT_ADDREF_LOCKED(rt);
2589
2590 if (rt->rt_flags & RTF_GATEWAY) {
2591 if ((dst->sa_len == gate->sa_len) &&
2592 (dst->sa_family == AF_INET || dst->sa_family == AF_INET6)) {
2593 struct sockaddr_storage dst_ss, gate_ss;
2594
2595 (void) sa_copy(dst, &dst_ss, NULL);
2596 (void) sa_copy(gate, &gate_ss, NULL);
2597
2598 loop = equal(SA(&dst_ss), SA(&gate_ss));
2599 } else {
2600 loop = (dst->sa_len == gate->sa_len &&
2601 equal(dst, gate));
2602 }
2603 }
2604
2605 /*
2606 * A (cloning) network route with the destination equal to the gateway
2607 * will create an endless loop (see notes below), so disallow it.
2608 */
2609 if (((rt->rt_flags & (RTF_HOST | RTF_GATEWAY | RTF_LLINFO)) ==
2610 RTF_GATEWAY) && loop) {
2611 /* Release extra ref */
2612 RT_REMREF_LOCKED(rt);
2613 return EADDRNOTAVAIL;
2614 }
2615
2616 /*
2617 * A host route with the destination equal to the gateway
2618 * will interfere with keeping LLINFO in the routing
2619 * table, so disallow it.
2620 */
2621 if (((rt->rt_flags & (RTF_HOST | RTF_GATEWAY | RTF_LLINFO)) ==
2622 (RTF_HOST | RTF_GATEWAY)) && loop) {
2623 /*
2624 * The route might already exist if this is an RTM_CHANGE
2625 * or a routing redirect, so try to delete it.
2626 */
2627 if (rt_key(rt) != NULL) {
2628 /*
2629 * Safe to drop rt_lock and use rt_key, rt_gateway,
2630 * since holding rnh_lock here prevents another thread
2631 * from calling rt_setgate() on this route.
2632 */
2633 RT_UNLOCK(rt);
2634 (void) rtrequest_locked(RTM_DELETE, rt_key(rt),
2635 rt->rt_gateway, rt_mask(rt), rt->rt_flags, NULL);
2636 RT_LOCK(rt);
2637 }
2638 /* Release extra ref */
2639 RT_REMREF_LOCKED(rt);
2640 return EADDRNOTAVAIL;
2641 }
2642
2643 /*
2644 * The destination is not directly reachable. Get a route
2645 * to the next-hop gateway and store it in rt_gwroute.
2646 */
2647 if (rt->rt_flags & RTF_GATEWAY) {
2648 struct rtentry *gwrt;
2649 unsigned int ifscope;
2650
2651 if (dst->sa_family == AF_INET) {
2652 ifscope = sin_get_ifscope(dst);
2653 } else if (dst->sa_family == AF_INET6) {
2654 ifscope = sin6_get_ifscope(dst);
2655 } else {
2656 ifscope = IFSCOPE_NONE;
2657 }
2658
2659 RT_UNLOCK(rt);
2660 /*
2661 * Don't ignore RTF_CLONING, since we prefer that rt_gwroute
2662 * points to a clone rather than a cloning route; see above
2663 * check for cloning loop avoidance (dst == gate).
2664 */
2665 gwrt = rtalloc1_scoped_locked(gate, 1, RTF_PRCLONING, ifscope);
2666 if (gwrt != NULL) {
2667 RT_LOCK_ASSERT_NOTHELD(gwrt);
2668 }
2669 RT_LOCK(rt);
2670
2671 /*
2672 * Cloning loop avoidance:
2673 *
2674 * In the presence of protocol-cloning and bad configuration,
2675 * it is possible to get stuck in bottomless mutual recursion
2676 * (rtrequest rt_setgate rtalloc1). We avoid this by not
2677 * allowing protocol-cloning to operate for gateways (which
2678 * is probably the correct choice anyway), and avoid the
2679 * resulting reference loops by disallowing any route to run
2680 * through itself as a gateway. This is obviously mandatory
2681 * when we get rt->rt_output(). It implies that a route to
2682 * the gateway must already be present in the system in order
2683 * for the gateway to be referred to by another route.
2684 */
2685 if (gwrt == rt) {
2686 RT_REMREF_LOCKED(gwrt);
2687 /* Release extra ref */
2688 RT_REMREF_LOCKED(rt);
2689 return EADDRINUSE; /* failure */
2690 }
2691
2692 /*
2693 * If scoped, the gateway route must use the same interface;
2694 * we're holding rnh_lock now, so rt_gateway and rt_ifp of gwrt
2695 * should not change and are freely accessible.
2696 */
2697 if (ifscope != IFSCOPE_NONE && (rt->rt_flags & RTF_IFSCOPE) &&
2698 gwrt != NULL && gwrt->rt_ifp != NULL &&
2699 gwrt->rt_ifp->if_index != ifscope) {
2700 rtfree_locked(gwrt); /* rt != gwrt, no deadlock */
2701 /* Release extra ref */
2702 RT_REMREF_LOCKED(rt);
2703 return (rt->rt_flags & RTF_HOST) ?
2704 EHOSTUNREACH : ENETUNREACH;
2705 }
2706
2707 /* Check again since we dropped the lock above */
2708 if (rt->rt_flags & RTF_CONDEMNED) {
2709 if (gwrt != NULL) {
2710 rtfree_locked(gwrt);
2711 }
2712 /* Release extra ref */
2713 RT_REMREF_LOCKED(rt);
2714 return EBUSY;
2715 }
2716
2717 /* Set gateway route; callee adds ref to gwrt if non-NULL */
2718 rt_set_gwroute(rt, dst, gwrt);
2719
2720 /*
2721 * In case the (non-scoped) default route gets modified via
2722 * an ICMP redirect, record the interface index used for the
2723 * primary ifscope. Also done in rt_setif() to take care
2724 * of the non-redirect cases.
2725 */
2726 if (rt_primary_default(rt, dst) && rt->rt_ifp != NULL) {
2727 set_primary_ifscope(dst->sa_family,
2728 rt->rt_ifp->if_index);
2729 }
2730
2731 #if NECP
2732 /*
2733 * If this is a change in a default route, update
2734 * necp client watchers to re-evaluate
2735 */
2736 if (SA_DEFAULT(dst)) {
2737 necp_update_all_clients();
2738 }
2739 #endif /* NECP */
2740
2741 /*
2742 * Tell the kernel debugger about the new default gateway
2743 * if the gateway route uses the primary interface, or
2744 * if we are in a transient state before the non-scoped
2745 * default gateway is installed (similar to how the system
2746 * was behaving in the past). In future, it would be good
2747 * to do all this only when KDP is enabled.
2748 */
2749 if ((dst->sa_family == AF_INET) &&
2750 gwrt != NULL && gwrt->rt_gateway->sa_family == AF_LINK &&
2751 (gwrt->rt_ifp->if_index == get_primary_ifscope(AF_INET) ||
2752 get_primary_ifscope(AF_INET) == IFSCOPE_NONE)) {
2753 kdp_set_gateway_mac(SDL((void *)gwrt->rt_gateway)->
2754 sdl_data);
2755 }
2756
2757 /* Release extra ref from rtalloc1() */
2758 if (gwrt != NULL) {
2759 RT_REMREF(gwrt);
2760 }
2761 }
2762
2763 /*
2764 * Prepare to store the gateway in rt_gateway. Both dst and gateway
2765 * are stored one after the other in the same malloc'd chunk. If we
2766 * have room, reuse the old buffer since rt_gateway already points
2767 * to the right place. Otherwise, malloc a new block and update
2768 * the 'dst' address and point rt_gateway to the right place.
2769 */
2770 if (rt->rt_gateway == NULL || glen > SA_SIZE(rt->rt_gateway->sa_len)) {
2771 caddr_t new;
2772
2773 /* The underlying allocation is done with M_WAITOK set */
2774 R_Malloc(new, caddr_t, dlen + glen);
2775 if (new == NULL) {
2776 /* Clear gateway route */
2777 rt_set_gwroute(rt, dst, NULL);
2778 /* Release extra ref */
2779 RT_REMREF_LOCKED(rt);
2780 return ENOBUFS;
2781 }
2782
2783 /*
2784 * Copy from 'dst' and not rt_key(rt) because we can get
2785 * here to initialize a newly allocated route entry, in
2786 * which case rt_key(rt) is NULL (and so does rt_gateway).
2787 */
2788 bzero(new, dlen + glen);
2789 Bcopy(dst, new, dst->sa_len);
2790 R_Free(rt_key(rt)); /* free old block; NULL is okay */
2791 rt->rt_nodes->rn_key = new;
2792 rt->rt_gateway = (struct sockaddr *)(new + dlen);
2793 }
2794
2795 /*
2796 * Copy the new gateway value into the memory chunk.
2797 */
2798 Bcopy(gate, rt->rt_gateway, gate->sa_len);
2799
2800 /*
2801 * For consistency between rt_gateway and rt_key(gwrt).
2802 */
2803 if ((rt->rt_flags & RTF_GATEWAY) && rt->rt_gwroute != NULL &&
2804 (rt->rt_gwroute->rt_flags & RTF_IFSCOPE)) {
2805 if (rt->rt_gateway->sa_family == AF_INET &&
2806 rt_key(rt->rt_gwroute)->sa_family == AF_INET) {
2807 sin_set_ifscope(rt->rt_gateway,
2808 sin_get_ifscope(rt_key(rt->rt_gwroute)));
2809 } else if (rt->rt_gateway->sa_family == AF_INET6 &&
2810 rt_key(rt->rt_gwroute)->sa_family == AF_INET6) {
2811 sin6_set_ifscope(rt->rt_gateway,
2812 sin6_get_ifscope(rt_key(rt->rt_gwroute)));
2813 }
2814 }
2815
2816 /*
2817 * This isn't going to do anything useful for host routes, so
2818 * don't bother. Also make sure we have a reasonable mask
2819 * (we don't yet have one during adds).
2820 */
2821 if (!(rt->rt_flags & RTF_HOST) && rt_mask(rt) != 0) {
2822 struct rtfc_arg arg;
2823 arg.rnh = rnh;
2824 arg.rt0 = rt;
2825 RT_UNLOCK(rt);
2826 rnh->rnh_walktree_from(rnh, rt_key(rt), rt_mask(rt),
2827 rt_fixchange, &arg);
2828 RT_LOCK(rt);
2829 }
2830
2831 /* Release extra ref */
2832 RT_REMREF_LOCKED(rt);
2833 return 0;
2834 }
2835
2836 #undef SA_SIZE
2837
2838 void
2839 rt_set_gwroute(struct rtentry *rt, struct sockaddr *dst, struct rtentry *gwrt)
2840 {
2841 boolean_t gwrt_isrouter;
2842
2843 LCK_MTX_ASSERT(rnh_lock, LCK_MTX_ASSERT_OWNED);
2844 RT_LOCK_ASSERT_HELD(rt);
2845
2846 if (gwrt != NULL) {
2847 RT_ADDREF(gwrt); /* for this routine */
2848 }
2849 /*
2850 * Get rid of existing gateway route; if rt_gwroute is already
2851 * set to gwrt, this is slightly redundant (though safe since
2852 * we held an extra ref above) but makes the code simpler.
2853 */
2854 if (rt->rt_gwroute != NULL) {
2855 struct rtentry *ogwrt = rt->rt_gwroute;
2856
2857 VERIFY(rt != ogwrt); /* sanity check */
2858 rt->rt_gwroute = NULL;
2859 RT_UNLOCK(rt);
2860 rtfree_locked(ogwrt);
2861 RT_LOCK(rt);
2862 VERIFY(rt->rt_gwroute == NULL);
2863 }
2864
2865 /*
2866 * And associate the new gateway route.
2867 */
2868 if ((rt->rt_gwroute = gwrt) != NULL) {
2869 RT_ADDREF(gwrt); /* for rt */
2870
2871 if (rt->rt_flags & RTF_WASCLONED) {
2872 /* rt_parent might be NULL if rt is embryonic */
2873 gwrt_isrouter = (rt->rt_parent != NULL &&
2874 SA_DEFAULT(rt_key(rt->rt_parent)) &&
2875 !RT_HOST(rt->rt_parent));
2876 } else {
2877 gwrt_isrouter = (SA_DEFAULT(dst) && !RT_HOST(rt));
2878 }
2879
2880 /* If gwrt points to a default router, mark it accordingly */
2881 if (gwrt_isrouter && RT_HOST(gwrt) &&
2882 !(gwrt->rt_flags & RTF_ROUTER)) {
2883 RT_LOCK(gwrt);
2884 gwrt->rt_flags |= RTF_ROUTER;
2885 RT_UNLOCK(gwrt);
2886 }
2887
2888 RT_REMREF(gwrt); /* for this routine */
2889 }
2890 }
2891
2892 static void
2893 rt_maskedcopy(const struct sockaddr *src, struct sockaddr *dst,
2894 const struct sockaddr *netmask)
2895 {
2896 const char *netmaskp = &netmask->sa_data[0];
2897 const char *srcp = &src->sa_data[0];
2898 char *dstp = &dst->sa_data[0];
2899 const char *maskend = (char *)dst
2900 + MIN(netmask->sa_len, src->sa_len);
2901 const char *srcend = (char *)dst + src->sa_len;
2902
2903 dst->sa_len = src->sa_len;
2904 dst->sa_family = src->sa_family;
2905
2906 while (dstp < maskend) {
2907 *dstp++ = *srcp++ & *netmaskp++;
2908 }
2909 if (dstp < srcend) {
2910 memset(dstp, 0, (size_t)(srcend - dstp));
2911 }
2912 }
2913
2914 /*
2915 * Lookup an AF_INET/AF_INET6 scoped or non-scoped route depending on the
2916 * ifscope value passed in by the caller (IFSCOPE_NONE implies non-scoped).
2917 */
2918 static struct radix_node *
2919 node_lookup(struct sockaddr *dst, struct sockaddr *netmask,
2920 unsigned int ifscope)
2921 {
2922 struct radix_node_head *rnh;
2923 struct radix_node *rn;
2924 struct sockaddr_storage ss, mask;
2925 int af = dst->sa_family;
2926 struct matchleaf_arg ma = { .ifscope = ifscope };
2927 rn_matchf_t *f = rn_match_ifscope;
2928 void *w = &ma;
2929
2930 if (af != AF_INET && af != AF_INET6) {
2931 return NULL;
2932 }
2933
2934 rnh = rt_tables[af];
2935
2936 /*
2937 * Transform dst into the internal routing table form,
2938 * clearing out the scope ID field if ifscope isn't set.
2939 */
2940 dst = sa_copy(dst, &ss, (ifscope == IFSCOPE_NONE) ? NULL : &ifscope);
2941
2942 /* Transform netmask into the internal routing table form */
2943 if (netmask != NULL) {
2944 netmask = ma_copy(af, netmask, &mask, ifscope);
2945 }
2946
2947 if (ifscope == IFSCOPE_NONE) {
2948 f = w = NULL;
2949 }
2950
2951 rn = rnh->rnh_lookup_args(dst, netmask, rnh, f, w);
2952 if (rn != NULL && (rn->rn_flags & RNF_ROOT)) {
2953 rn = NULL;
2954 }
2955
2956 return rn;
2957 }
2958
2959 /*
2960 * Lookup the AF_INET/AF_INET6 non-scoped default route.
2961 */
2962 static struct radix_node *
2963 node_lookup_default(int af)
2964 {
2965 struct radix_node_head *rnh;
2966
2967 VERIFY(af == AF_INET || af == AF_INET6);
2968 rnh = rt_tables[af];
2969
2970 return af == AF_INET ? rnh->rnh_lookup(&sin_def, NULL, rnh) :
2971 rnh->rnh_lookup(&sin6_def, NULL, rnh);
2972 }
2973
2974 boolean_t
2975 rt_ifa_is_dst(struct sockaddr *dst, struct ifaddr *ifa)
2976 {
2977 boolean_t result = FALSE;
2978
2979 if (ifa == NULL || ifa->ifa_addr == NULL) {
2980 return result;
2981 }
2982
2983 IFA_LOCK_SPIN(ifa);
2984
2985 if (dst->sa_family == ifa->ifa_addr->sa_family &&
2986 ((dst->sa_family == AF_INET &&
2987 SIN(dst)->sin_addr.s_addr ==
2988 SIN(ifa->ifa_addr)->sin_addr.s_addr) ||
2989 (dst->sa_family == AF_INET6 &&
2990 SA6_ARE_ADDR_EQUAL(SIN6(dst), SIN6(ifa->ifa_addr))))) {
2991 result = TRUE;
2992 }
2993
2994 IFA_UNLOCK(ifa);
2995
2996 return result;
2997 }
2998
2999 /*
3000 * Common routine to lookup/match a route. It invokes the lookup/matchaddr
3001 * callback which could be address family-specific. The main difference
3002 * between the two (at least for AF_INET/AF_INET6) is that a lookup does
3003 * not alter the expiring state of a route, whereas a match would unexpire
3004 * or revalidate the route.
3005 *
3006 * The optional scope or interface index property of a route allows for a
3007 * per-interface route instance. This permits multiple route entries having
3008 * the same destination (but not necessarily the same gateway) to exist in
3009 * the routing table; each of these entries is specific to the corresponding
3010 * interface. This is made possible by storing the scope ID value into the
3011 * radix key, thus making each route entry unique. These scoped entries
3012 * exist along with the regular, non-scoped entries in the same radix tree
3013 * for a given address family (AF_INET/AF_INET6); the scope logically
3014 * partitions it into multiple per-interface sub-trees.
3015 *
3016 * When a scoped route lookup is performed, the routing table is searched for
3017 * the best match that would result in a route using the same interface as the
3018 * one associated with the scope (the exception to this are routes that point
3019 * to the loopback interface). The search rule follows the longest matching
3020 * prefix with the additional interface constraint.
3021 */
3022 static struct rtentry *
3023 rt_lookup_common(boolean_t lookup_only, boolean_t coarse, struct sockaddr *dst,
3024 struct sockaddr *netmask, struct radix_node_head *rnh, unsigned int ifscope)
3025 {
3026 struct radix_node *rn0, *rn = NULL;
3027 int af = dst->sa_family;
3028 struct sockaddr_storage dst_ss;
3029 struct sockaddr_storage mask_ss;
3030 boolean_t dontcare;
3031 #if (DEVELOPMENT || DEBUG)
3032 char dbuf[MAX_SCOPE_ADDR_STR_LEN], gbuf[MAX_IPv6_STR_LEN];
3033 char s_dst[MAX_IPv6_STR_LEN], s_netmask[MAX_IPv6_STR_LEN];
3034 #endif
3035 VERIFY(!coarse || ifscope == IFSCOPE_NONE);
3036
3037 LCK_MTX_ASSERT(rnh_lock, LCK_MTX_ASSERT_OWNED);
3038 /*
3039 * While we have rnh_lock held, see if we need to schedule the timer.
3040 */
3041 if (nd6_sched_timeout_want) {
3042 nd6_sched_timeout(NULL, NULL);
3043 }
3044
3045 if (!lookup_only) {
3046 netmask = NULL;
3047 }
3048
3049 /*
3050 * Non-scoped route lookup.
3051 */
3052 if (af != AF_INET && af != AF_INET6) {
3053 rn = rnh->rnh_matchaddr(dst, rnh);
3054
3055 /*
3056 * Don't return a root node; also, rnh_matchaddr callback
3057 * would have done the necessary work to clear RTPRF_OURS
3058 * for certain protocol families.
3059 */
3060 if (rn != NULL && (rn->rn_flags & RNF_ROOT)) {
3061 rn = NULL;
3062 }
3063 if (rn != NULL) {
3064 RT_LOCK_SPIN(RT(rn));
3065 if (!(RT(rn)->rt_flags & RTF_CONDEMNED)) {
3066 RT_ADDREF_LOCKED(RT(rn));
3067 RT_UNLOCK(RT(rn));
3068 } else {
3069 RT_UNLOCK(RT(rn));
3070 rn = NULL;
3071 }
3072 }
3073 return RT(rn);
3074 }
3075
3076 /* Transform dst/netmask into the internal routing table form */
3077 dst = sa_copy(dst, &dst_ss, &ifscope);
3078 if (netmask != NULL) {
3079 netmask = ma_copy(af, netmask, &mask_ss, ifscope);
3080 }
3081 dontcare = (ifscope == IFSCOPE_NONE);
3082
3083 #if (DEVELOPMENT || DEBUG)
3084 if (rt_verbose) {
3085 if (af == AF_INET) {
3086 (void) inet_ntop(af, &SIN(dst)->sin_addr.s_addr,
3087 s_dst, sizeof(s_dst));
3088 } else {
3089 (void) inet_ntop(af, &SIN6(dst)->sin6_addr,
3090 s_dst, sizeof(s_dst));
3091 }
3092
3093 if (netmask != NULL && af == AF_INET) {
3094 (void) inet_ntop(af, &SIN(netmask)->sin_addr.s_addr,
3095 s_netmask, sizeof(s_netmask));
3096 }
3097 if (netmask != NULL && af == AF_INET6) {
3098 (void) inet_ntop(af, &SIN6(netmask)->sin6_addr,
3099 s_netmask, sizeof(s_netmask));
3100 } else {
3101 *s_netmask = '\0';
3102 }
3103 printf("%s (%d, %d, %s, %s, %u)\n",
3104 __func__, lookup_only, coarse, s_dst, s_netmask, ifscope);
3105 }
3106 #endif
3107
3108 /*
3109 * Scoped route lookup:
3110 *
3111 * We first perform a non-scoped lookup for the original result.
3112 * Afterwards, depending on whether or not the caller has specified
3113 * a scope, we perform a more specific scoped search and fallback
3114 * to this original result upon failure.
3115 */
3116 rn0 = rn = node_lookup(dst, netmask, IFSCOPE_NONE);
3117
3118 /*
3119 * If the caller did not specify a scope, use the primary scope
3120 * derived from the system's non-scoped default route. If, for
3121 * any reason, there is no primary interface, ifscope will be
3122 * set to IFSCOPE_NONE; if the above lookup resulted in a route,
3123 * we'll do a more-specific search below, scoped to the interface
3124 * of that route.
3125 */
3126 if (dontcare) {
3127 ifscope = get_primary_ifscope(af);
3128 }
3129
3130 /*
3131 * Keep the original result if either of the following is true:
3132 *
3133 * 1) The interface portion of the route has the same interface
3134 * index as the scope value and it is marked with RTF_IFSCOPE.
3135 * 2) The route uses the loopback interface, in which case the
3136 * destination (host/net) is local/loopback.
3137 *
3138 * Otherwise, do a more specified search using the scope;
3139 * we're holding rnh_lock now, so rt_ifp should not change.
3140 */
3141 if (rn != NULL) {
3142 struct rtentry *rt = RT(rn);
3143 #if (DEVELOPMENT || DEBUG)
3144 if (rt_verbose) {
3145 rt_str(rt, dbuf, sizeof(dbuf), gbuf, sizeof(gbuf));
3146 printf("%s unscoped search %p to %s->%s->%s ifa_ifp %s\n",
3147 __func__, rt,
3148 dbuf, gbuf,
3149 (rt->rt_ifp != NULL) ? rt->rt_ifp->if_xname : "",
3150 (rt->rt_ifa->ifa_ifp != NULL) ?
3151 rt->rt_ifa->ifa_ifp->if_xname : "");
3152 }
3153 #endif
3154 if (!(rt->rt_ifp->if_flags & IFF_LOOPBACK) ||
3155 (rt->rt_flags & RTF_GATEWAY)) {
3156 if (rt->rt_ifp->if_index != ifscope) {
3157 /*
3158 * Wrong interface; keep the original result
3159 * only if the caller did not specify a scope,
3160 * and do a more specific scoped search using
3161 * the scope of the found route. Otherwise,
3162 * start again from scratch.
3163 *
3164 * For loopback scope we keep the unscoped
3165 * route for local addresses
3166 */
3167 rn = NULL;
3168 if (dontcare) {
3169 ifscope = rt->rt_ifp->if_index;
3170 } else if (ifscope != lo_ifp->if_index ||
3171 rt_ifa_is_dst(dst, rt->rt_ifa) == FALSE) {
3172 rn0 = NULL;
3173 }
3174 } else if (!(rt->rt_flags & RTF_IFSCOPE)) {
3175 /*
3176 * Right interface, except that this route
3177 * isn't marked with RTF_IFSCOPE. Do a more
3178 * specific scoped search. Keep the original
3179 * result and return it it in case the scoped
3180 * search fails.
3181 */
3182 rn = NULL;
3183 }
3184 }
3185 }
3186
3187 /*
3188 * Scoped search. Find the most specific entry having the same
3189 * interface scope as the one requested. The following will result
3190 * in searching for the longest prefix scoped match.
3191 */
3192 if (rn == NULL) {
3193 rn = node_lookup(dst, netmask, ifscope);
3194 #if (DEVELOPMENT || DEBUG)
3195 if (rt_verbose && rn != NULL) {
3196 struct rtentry *rt = RT(rn);
3197
3198 rt_str(rt, dbuf, sizeof(dbuf), gbuf, sizeof(gbuf));
3199 printf("%s scoped search %p to %s->%s->%s ifa %s\n",
3200 __func__, rt,
3201 dbuf, gbuf,
3202 (rt->rt_ifp != NULL) ? rt->rt_ifp->if_xname : "",
3203 (rt->rt_ifa->ifa_ifp != NULL) ?
3204 rt->rt_ifa->ifa_ifp->if_xname : "");
3205 }
3206 #endif
3207 }
3208 /*
3209 * Use the original result if either of the following is true:
3210 *
3211 * 1) The scoped search did not yield any result.
3212 * 2) The caller insists on performing a coarse-grained lookup.
3213 * 3) The result from the scoped search is a scoped default route,
3214 * and the original (non-scoped) result is not a default route,
3215 * i.e. the original result is a more specific host/net route.
3216 * 4) The scoped search yielded a net route but the original
3217 * result is a host route, i.e. the original result is treated
3218 * as a more specific route.
3219 */
3220 if (rn == NULL || coarse || (rn0 != NULL &&
3221 ((SA_DEFAULT(rt_key(RT(rn))) && !SA_DEFAULT(rt_key(RT(rn0)))) ||
3222 (!RT_HOST(rn) && RT_HOST(rn0))))) {
3223 rn = rn0;
3224 }
3225
3226 /*
3227 * If we still don't have a route, use the non-scoped default
3228 * route as long as the interface portion satistifes the scope.
3229 */
3230 if (rn == NULL && (rn = node_lookup_default(af)) != NULL &&
3231 RT(rn)->rt_ifp->if_index != ifscope) {
3232 rn = NULL;
3233 }
3234
3235 if (rn != NULL) {
3236 /*
3237 * Manually clear RTPRF_OURS using rt_validate() and
3238 * bump up the reference count after, and not before;
3239 * we only get here for AF_INET/AF_INET6. node_lookup()
3240 * has done the check against RNF_ROOT, so we can be sure
3241 * that we're not returning a root node here.
3242 */
3243 RT_LOCK_SPIN(RT(rn));
3244 if (rt_validate(RT(rn))) {
3245 RT_ADDREF_LOCKED(RT(rn));
3246 RT_UNLOCK(RT(rn));
3247 } else {
3248 RT_UNLOCK(RT(rn));
3249 rn = NULL;
3250 }
3251 }
3252 #if (DEVELOPMENT || DEBUG)
3253 if (rt_verbose) {
3254 if (rn == NULL) {
3255 printf("%s %u return NULL\n", __func__, ifscope);
3256 } else {
3257 struct rtentry *rt = RT(rn);
3258
3259 rt_str(rt, dbuf, sizeof(dbuf), gbuf, sizeof(gbuf));
3260
3261 printf("%s %u return %p to %s->%s->%s ifa_ifp %s\n",
3262 __func__, ifscope, rt,
3263 dbuf, gbuf,
3264 (rt->rt_ifp != NULL) ? rt->rt_ifp->if_xname : "",
3265 (rt->rt_ifa->ifa_ifp != NULL) ?
3266 rt->rt_ifa->ifa_ifp->if_xname : "");
3267 }
3268 }
3269 #endif
3270 return RT(rn);
3271 }
3272
3273 struct rtentry *
3274 rt_lookup(boolean_t lookup_only, struct sockaddr *dst, struct sockaddr *netmask,
3275 struct radix_node_head *rnh, unsigned int ifscope)
3276 {
3277 return rt_lookup_common(lookup_only, FALSE, dst, netmask,
3278 rnh, ifscope);
3279 }
3280
3281 struct rtentry *
3282 rt_lookup_coarse(boolean_t lookup_only, struct sockaddr *dst,
3283 struct sockaddr *netmask, struct radix_node_head *rnh)
3284 {
3285 return rt_lookup_common(lookup_only, TRUE, dst, netmask,
3286 rnh, IFSCOPE_NONE);
3287 }
3288
3289 boolean_t
3290 rt_validate(struct rtentry *rt)
3291 {
3292 RT_LOCK_ASSERT_HELD(rt);
3293
3294 if ((rt->rt_flags & (RTF_UP | RTF_CONDEMNED)) == RTF_UP) {
3295 int af = rt_key(rt)->sa_family;
3296
3297 if (af == AF_INET) {
3298 (void) in_validate(RN(rt));
3299 } else if (af == AF_INET6) {
3300 (void) in6_validate(RN(rt));
3301 }
3302 } else {
3303 rt = NULL;
3304 }
3305
3306 return rt != NULL;
3307 }
3308
3309 /*
3310 * Set up a routing table entry, normally
3311 * for an interface.
3312 */
3313 int
3314 rtinit(struct ifaddr *ifa, int cmd, int flags)
3315 {
3316 int error;
3317
3318 LCK_MTX_ASSERT(rnh_lock, LCK_MTX_ASSERT_NOTOWNED);
3319
3320 lck_mtx_lock(rnh_lock);
3321 error = rtinit_locked(ifa, cmd, flags);
3322 lck_mtx_unlock(rnh_lock);
3323
3324 return error;
3325 }
3326
3327 int
3328 rtinit_locked(struct ifaddr *ifa, int cmd, int flags)
3329 {
3330 struct radix_node_head *rnh;
3331 uint8_t nbuf[128]; /* long enough for IPv6 */
3332 #if (DEVELOPMENT || DEBUG)
3333 char dbuf[MAX_IPv6_STR_LEN], gbuf[MAX_IPv6_STR_LEN];
3334 char abuf[MAX_IPv6_STR_LEN];
3335 #endif
3336 struct rtentry *rt = NULL;
3337 struct sockaddr *dst;
3338 struct sockaddr *netmask;
3339 int error = 0;
3340
3341 /*
3342 * Holding rnh_lock here prevents the possibility of ifa from
3343 * changing (e.g. in_ifinit), so it is safe to access its
3344 * ifa_{dst}addr (here and down below) without locking.
3345 */
3346 LCK_MTX_ASSERT(rnh_lock, LCK_MTX_ASSERT_OWNED);
3347
3348 if (flags & RTF_HOST) {
3349 dst = ifa->ifa_dstaddr;
3350 netmask = NULL;
3351 } else {
3352 dst = ifa->ifa_addr;
3353 netmask = ifa->ifa_netmask;
3354 }
3355
3356 if (dst->sa_len == 0) {
3357 log(LOG_ERR, "%s: %s failed, invalid dst sa_len %d\n",
3358 __func__, rtm2str(cmd), dst->sa_len);
3359 error = EINVAL;
3360 goto done;
3361 }
3362 if (netmask != NULL && netmask->sa_len > sizeof(nbuf)) {
3363 log(LOG_ERR, "%s: %s failed, mask sa_len %d too large\n",
3364 __func__, rtm2str(cmd), dst->sa_len);
3365 error = EINVAL;
3366 goto done;
3367 }
3368
3369 #if (DEVELOPMENT || DEBUG)
3370 if (dst->sa_family == AF_INET) {
3371 (void) inet_ntop(AF_INET, &SIN(dst)->sin_addr.s_addr,
3372 abuf, sizeof(abuf));
3373 } else if (dst->sa_family == AF_INET6) {
3374 (void) inet_ntop(AF_INET6, &SIN6(dst)->sin6_addr,
3375 abuf, sizeof(abuf));
3376 }
3377 #endif /* (DEVELOPMENT || DEBUG) */
3378
3379 if ((rnh = rt_tables[dst->sa_family]) == NULL) {
3380 error = EINVAL;
3381 goto done;
3382 }
3383
3384 /*
3385 * If it's a delete, check that if it exists, it's on the correct
3386 * interface or we might scrub a route to another ifa which would
3387 * be confusing at best and possibly worse.
3388 */
3389 if (cmd == RTM_DELETE) {
3390 /*
3391 * It's a delete, so it should already exist..
3392 * If it's a net, mask off the host bits
3393 * (Assuming we have a mask)
3394 */
3395 if (netmask != NULL) {
3396 rt_maskedcopy(dst, SA(nbuf), netmask);
3397 dst = SA(nbuf);
3398 }
3399 /*
3400 * Get an rtentry that is in the routing tree and contains
3401 * the correct info. Note that we perform a coarse-grained
3402 * lookup here, in case there is a scoped variant of the
3403 * subnet/prefix route which we should ignore, as we never
3404 * add a scoped subnet/prefix route as part of adding an
3405 * interface address.
3406 */
3407 rt = rt_lookup_coarse(TRUE, dst, NULL, rnh);
3408 if (rt != NULL) {
3409 #if (DEVELOPMENT || DEBUG)
3410 rt_str(rt, dbuf, sizeof(dbuf), gbuf, sizeof(gbuf));
3411 #endif
3412 /*
3413 * Ok so we found the rtentry. it has an extra reference
3414 * for us at this stage. we won't need that so
3415 * lop that off now.
3416 */
3417 RT_LOCK(rt);
3418 if (rt->rt_ifa != ifa) {
3419 /*
3420 * If the interface address in the rtentry
3421 * doesn't match the interface we are using,
3422 * then we don't want to delete it, so return
3423 * an error. This seems to be the only point
3424 * of this whole RTM_DELETE clause.
3425 */
3426 #if (DEVELOPMENT || DEBUG)
3427 if (rt_verbose) {
3428 log(LOG_DEBUG, "%s: not removing "
3429 "route to %s->%s->%s, flags %b, "
3430 "ifaddr %s, rt_ifa 0x%llx != "
3431 "ifa 0x%llx\n", __func__, dbuf,
3432 gbuf, ((rt->rt_ifp != NULL) ?
3433 rt->rt_ifp->if_xname : ""),
3434 rt->rt_flags, RTF_BITS, abuf,
3435 (uint64_t)VM_KERNEL_ADDRPERM(
3436 rt->rt_ifa),
3437 (uint64_t)VM_KERNEL_ADDRPERM(ifa));
3438 }
3439 #endif /* (DEVELOPMENT || DEBUG) */
3440 RT_REMREF_LOCKED(rt);
3441 RT_UNLOCK(rt);
3442 rt = NULL;
3443 error = ((flags & RTF_HOST) ?
3444 EHOSTUNREACH : ENETUNREACH);
3445 goto done;
3446 } else if (rt->rt_flags & RTF_STATIC) {
3447 /*
3448 * Don't remove the subnet/prefix route if
3449 * this was manually added from above.
3450 */
3451 #if (DEVELOPMENT || DEBUG)
3452 if (rt_verbose) {
3453 log(LOG_DEBUG, "%s: not removing "
3454 "static route to %s->%s->%s, "
3455 "flags %b, ifaddr %s\n", __func__,
3456 dbuf, gbuf, ((rt->rt_ifp != NULL) ?
3457 rt->rt_ifp->if_xname : ""),
3458 rt->rt_flags, RTF_BITS, abuf);
3459 }
3460 #endif /* (DEVELOPMENT || DEBUG) */
3461 RT_REMREF_LOCKED(rt);
3462 RT_UNLOCK(rt);
3463 rt = NULL;
3464 error = EBUSY;
3465 goto done;
3466 }
3467 #if (DEVELOPMENT || DEBUG)
3468 if (rt_verbose) {
3469 log(LOG_DEBUG, "%s: removing route to "
3470 "%s->%s->%s, flags %b, ifaddr %s\n",
3471 __func__, dbuf, gbuf,
3472 ((rt->rt_ifp != NULL) ?
3473 rt->rt_ifp->if_xname : ""),
3474 rt->rt_flags, RTF_BITS, abuf);
3475 }
3476 #endif /* (DEVELOPMENT || DEBUG) */
3477 RT_REMREF_LOCKED(rt);
3478 RT_UNLOCK(rt);
3479 rt = NULL;
3480 }
3481 }
3482 /*
3483 * Do the actual request
3484 */
3485 if ((error = rtrequest_locked(cmd, dst, ifa->ifa_addr, netmask,
3486 flags | ifa->ifa_flags, &rt)) != 0) {
3487 goto done;
3488 }
3489
3490 VERIFY(rt != NULL);
3491 #if (DEVELOPMENT || DEBUG)
3492 rt_str(rt, dbuf, sizeof(dbuf), gbuf, sizeof(gbuf));
3493 #endif /* (DEVELOPMENT || DEBUG) */
3494 switch (cmd) {
3495 case RTM_DELETE:
3496 /*
3497 * If we are deleting, and we found an entry, then it's
3498 * been removed from the tree. Notify any listening
3499 * routing agents of the change and throw it away.
3500 */
3501 RT_LOCK(rt);
3502 rt_newaddrmsg(cmd, ifa, error, rt);
3503 RT_UNLOCK(rt);
3504 #if (DEVELOPMENT || DEBUG)
3505 if (rt_verbose) {
3506 log(LOG_DEBUG, "%s: removed route to %s->%s->%s, "
3507 "flags %b, ifaddr %s\n", __func__, dbuf, gbuf,
3508 ((rt->rt_ifp != NULL) ? rt->rt_ifp->if_xname : ""),
3509 rt->rt_flags, RTF_BITS, abuf);
3510 }
3511 #endif /* (DEVELOPMENT || DEBUG) */
3512 rtfree_locked(rt);
3513 break;
3514
3515 case RTM_ADD:
3516 /*
3517 * We are adding, and we have a returned routing entry.
3518 * We need to sanity check the result. If it came back
3519 * with an unexpected interface, then it must have already
3520 * existed or something.
3521 */
3522 RT_LOCK(rt);
3523 if (rt->rt_ifa != ifa) {
3524 void (*ifa_rtrequest)
3525 (int, struct rtentry *, struct sockaddr *);
3526 #if (DEVELOPMENT || DEBUG)
3527 if (rt_verbose) {
3528 if (!(rt->rt_ifa->ifa_ifp->if_flags &
3529 (IFF_POINTOPOINT | IFF_LOOPBACK))) {
3530 log(LOG_ERR, "%s: %s route to %s->%s->%s, "
3531 "flags %b, ifaddr %s, rt_ifa 0x%llx != "
3532 "ifa 0x%llx\n", __func__, rtm2str(cmd),
3533 dbuf, gbuf, ((rt->rt_ifp != NULL) ?
3534 rt->rt_ifp->if_xname : ""), rt->rt_flags,
3535 RTF_BITS, abuf,
3536 (uint64_t)VM_KERNEL_ADDRPERM(rt->rt_ifa),
3537 (uint64_t)VM_KERNEL_ADDRPERM(ifa));
3538 }
3539
3540 log(LOG_DEBUG, "%s: %s route to %s->%s->%s, "
3541 "flags %b, ifaddr %s, rt_ifa was 0x%llx "
3542 "now 0x%llx\n", __func__, rtm2str(cmd),
3543 dbuf, gbuf, ((rt->rt_ifp != NULL) ?
3544 rt->rt_ifp->if_xname : ""), rt->rt_flags,
3545 RTF_BITS, abuf,
3546 (uint64_t)VM_KERNEL_ADDRPERM(rt->rt_ifa),
3547 (uint64_t)VM_KERNEL_ADDRPERM(ifa));
3548 }
3549 #endif /* (DEVELOPMENT || DEBUG) */
3550
3551 /*
3552 * Ask that the protocol in question
3553 * remove anything it has associated with
3554 * this route and ifaddr.
3555 */
3556 ifa_rtrequest = rt->rt_ifa->ifa_rtrequest;
3557 if (ifa_rtrequest != NULL) {
3558 ifa_rtrequest(RTM_DELETE, rt, NULL);
3559 }
3560 /*
3561 * Set the route's ifa.
3562 */
3563 rtsetifa(rt, ifa);
3564
3565 if (rt->rt_ifp != ifa->ifa_ifp) {
3566 /*
3567 * Purge any link-layer info caching.
3568 */
3569 if (rt->rt_llinfo_purge != NULL) {
3570 rt->rt_llinfo_purge(rt);
3571 }
3572 /*
3573 * Adjust route ref count for the interfaces.
3574 */
3575 if (rt->rt_if_ref_fn != NULL) {
3576 rt->rt_if_ref_fn(ifa->ifa_ifp, 1);
3577 rt->rt_if_ref_fn(rt->rt_ifp, -1);
3578 }
3579 }
3580
3581 /*
3582 * And substitute in references to the ifaddr
3583 * we are adding.
3584 */
3585 rt->rt_ifp = ifa->ifa_ifp;
3586 /*
3587 * If rmx_mtu is not locked, update it
3588 * to the MTU used by the new interface.
3589 */
3590 if (!(rt->rt_rmx.rmx_locks & RTV_MTU)) {
3591 rt->rt_rmx.rmx_mtu = rt->rt_ifp->if_mtu;
3592 if (dst->sa_family == AF_INET &&
3593 INTF_ADJUST_MTU_FOR_CLAT46(rt->rt_ifp)) {
3594 rt->rt_rmx.rmx_mtu = IN6_LINKMTU(rt->rt_ifp);
3595 /* Further adjust the size for CLAT46 expansion */
3596 rt->rt_rmx.rmx_mtu -= CLAT46_HDR_EXPANSION_OVERHD;
3597 }
3598 }
3599
3600 /*
3601 * Now ask the protocol to check if it needs
3602 * any special processing in its new form.
3603 */
3604 ifa_rtrequest = ifa->ifa_rtrequest;
3605 if (ifa_rtrequest != NULL) {
3606 ifa_rtrequest(RTM_ADD, rt, NULL);
3607 }
3608 } else {
3609 #if (DEVELOPMENT || DEBUG)
3610 if (rt_verbose) {
3611 log(LOG_DEBUG, "%s: added route to %s->%s->%s, "
3612 "flags %b, ifaddr %s\n", __func__, dbuf,
3613 gbuf, ((rt->rt_ifp != NULL) ?
3614 rt->rt_ifp->if_xname : ""), rt->rt_flags,
3615 RTF_BITS, abuf);
3616 }
3617 #endif /* (DEVELOPMENT || DEBUG) */
3618 }
3619 /*
3620 * notify any listenning routing agents of the change
3621 */
3622 rt_newaddrmsg(cmd, ifa, error, rt);
3623 /*
3624 * We just wanted to add it; we don't actually need a
3625 * reference. This will result in a route that's added
3626 * to the routing table without a reference count. The
3627 * RTM_DELETE code will do the necessary step to adjust
3628 * the reference count at deletion time.
3629 */
3630 RT_REMREF_LOCKED(rt);
3631 RT_UNLOCK(rt);
3632 break;
3633
3634 default:
3635 VERIFY(0);
3636 /* NOTREACHED */
3637 }
3638 done:
3639 return error;
3640 }
3641
3642 static void
3643 rt_set_idleref(struct rtentry *rt)
3644 {
3645 RT_LOCK_ASSERT_HELD(rt);
3646
3647 /*
3648 * We currently keep idle refcnt only on unicast cloned routes
3649 * that aren't marked with RTF_NOIFREF.
3650 */
3651 if (rt->rt_parent != NULL && !(rt->rt_flags &
3652 (RTF_NOIFREF | RTF_BROADCAST | RTF_MULTICAST)) &&
3653 (rt->rt_flags & (RTF_UP | RTF_WASCLONED | RTF_IFREF)) ==
3654 (RTF_UP | RTF_WASCLONED)) {
3655 rt_clear_idleref(rt); /* drop existing refcnt if any */
3656 rt->rt_if_ref_fn = rte_if_ref;
3657 /* Become a regular mutex, just in case */
3658 RT_CONVERT_LOCK(rt);
3659 rt->rt_if_ref_fn(rt->rt_ifp, 1);
3660 rt->rt_flags |= RTF_IFREF;
3661 }
3662 }
3663
3664 void
3665 rt_clear_idleref(struct rtentry *rt)
3666 {
3667 RT_LOCK_ASSERT_HELD(rt);
3668
3669 if (rt->rt_if_ref_fn != NULL) {
3670 VERIFY((rt->rt_flags & (RTF_NOIFREF | RTF_IFREF)) == RTF_IFREF);
3671 /* Become a regular mutex, just in case */
3672 RT_CONVERT_LOCK(rt);
3673 rt->rt_if_ref_fn(rt->rt_ifp, -1);
3674 rt->rt_flags &= ~RTF_IFREF;
3675 rt->rt_if_ref_fn = NULL;
3676 }
3677 }
3678
3679 void
3680 rt_set_proxy(struct rtentry *rt, boolean_t set)
3681 {
3682 lck_mtx_lock(rnh_lock);
3683 RT_LOCK(rt);
3684 /*
3685 * Search for any cloned routes which might have
3686 * been formed from this node, and delete them.
3687 */
3688 if (rt->rt_flags & (RTF_CLONING | RTF_PRCLONING)) {
3689 struct radix_node_head *rnh = rt_tables[rt_key(rt)->sa_family];
3690
3691 if (set) {
3692 rt->rt_flags |= RTF_PROXY;
3693 } else {
3694 rt->rt_flags &= ~RTF_PROXY;
3695 }
3696
3697 RT_UNLOCK(rt);
3698 if (rnh != NULL && rt_mask(rt)) {
3699 rnh->rnh_walktree_from(rnh, rt_key(rt), rt_mask(rt),
3700 rt_fixdelete, rt);
3701 }
3702 } else {
3703 RT_UNLOCK(rt);
3704 }
3705 lck_mtx_unlock(rnh_lock);
3706 }
3707
3708 static void
3709 rte_lock_init(struct rtentry *rt)
3710 {
3711 lck_mtx_init(&rt->rt_lock, rte_mtx_grp, rte_mtx_attr);
3712 }
3713
3714 static void
3715 rte_lock_destroy(struct rtentry *rt)
3716 {
3717 RT_LOCK_ASSERT_NOTHELD(rt);
3718 lck_mtx_destroy(&rt->rt_lock, rte_mtx_grp);
3719 }
3720
3721 void
3722 rt_lock(struct rtentry *rt, boolean_t spin)
3723 {
3724 RT_LOCK_ASSERT_NOTHELD(rt);
3725 if (spin) {
3726 lck_mtx_lock_spin(&rt->rt_lock);
3727 } else {
3728 lck_mtx_lock(&rt->rt_lock);
3729 }
3730 if (rte_debug & RTD_DEBUG) {
3731 rte_lock_debug((struct rtentry_dbg *)rt);
3732 }
3733 }
3734
3735 void
3736 rt_unlock(struct rtentry *rt)
3737 {
3738 if (rte_debug & RTD_DEBUG) {
3739 rte_unlock_debug((struct rtentry_dbg *)rt);
3740 }
3741 lck_mtx_unlock(&rt->rt_lock);
3742 }
3743
3744 static inline void
3745 rte_lock_debug(struct rtentry_dbg *rte)
3746 {
3747 uint32_t idx;
3748
3749 RT_LOCK_ASSERT_HELD((struct rtentry *)rte);
3750 idx = atomic_add_32_ov(&rte->rtd_lock_cnt, 1) % CTRACE_HIST_SIZE;
3751 if (rte_debug & RTD_TRACE) {
3752 ctrace_record(&rte->rtd_lock[idx]);
3753 }
3754 }
3755
3756 static inline void
3757 rte_unlock_debug(struct rtentry_dbg *rte)
3758 {
3759 uint32_t idx;
3760
3761 RT_LOCK_ASSERT_HELD((struct rtentry *)rte);
3762 idx = atomic_add_32_ov(&rte->rtd_unlock_cnt, 1) % CTRACE_HIST_SIZE;
3763 if (rte_debug & RTD_TRACE) {
3764 ctrace_record(&rte->rtd_unlock[idx]);
3765 }
3766 }
3767
3768 static struct rtentry *
3769 rte_alloc(void)
3770 {
3771 if (rte_debug & RTD_DEBUG) {
3772 return rte_alloc_debug();
3773 }
3774
3775 return (struct rtentry *)zalloc(rte_zone);
3776 }
3777
3778 static void
3779 rte_free(struct rtentry *p)
3780 {
3781 if (rte_debug & RTD_DEBUG) {
3782 rte_free_debug(p);
3783 return;
3784 }
3785
3786 if (p->rt_refcnt != 0) {
3787 panic("rte_free: rte=%p refcnt=%d non-zero\n", p, p->rt_refcnt);
3788 /* NOTREACHED */
3789 }
3790
3791 zfree(rte_zone, p);
3792 }
3793
3794 static void
3795 rte_if_ref(struct ifnet *ifp, int cnt)
3796 {
3797 struct kev_msg ev_msg;
3798 struct net_event_data ev_data;
3799 uint32_t old;
3800
3801 /* Force cnt to 1 increment/decrement */
3802 if (cnt < -1 || cnt > 1) {
3803 panic("%s: invalid count argument (%d)", __func__, cnt);
3804 /* NOTREACHED */
3805 }
3806 old = atomic_add_32_ov(&ifp->if_route_refcnt, cnt);
3807 if (cnt < 0 && old == 0) {
3808 panic("%s: ifp=%p negative route refcnt!", __func__, ifp);
3809 /* NOTREACHED */
3810 }
3811 /*
3812 * The following is done without first holding the ifnet lock,
3813 * for performance reasons. The relevant ifnet fields, with
3814 * the exception of the if_idle_flags, are never changed
3815 * during the lifetime of the ifnet. The if_idle_flags
3816 * may possibly be modified, so in the event that the value
3817 * is stale because IFRF_IDLE_NOTIFY was cleared, we'd end up
3818 * sending the event anyway. This is harmless as it is just
3819 * a notification to the monitoring agent in user space, and
3820 * it is expected to check via SIOCGIFGETRTREFCNT again anyway.
3821 */
3822 if ((ifp->if_idle_flags & IFRF_IDLE_NOTIFY) && cnt < 0 && old == 1) {
3823 bzero(&ev_msg, sizeof(ev_msg));
3824 bzero(&ev_data, sizeof(ev_data));
3825
3826 ev_msg.vendor_code = KEV_VENDOR_APPLE;
3827 ev_msg.kev_class = KEV_NETWORK_CLASS;
3828 ev_msg.kev_subclass = KEV_DL_SUBCLASS;
3829 ev_msg.event_code = KEV_DL_IF_IDLE_ROUTE_REFCNT;
3830
3831 strlcpy(&ev_data.if_name[0], ifp->if_name, IFNAMSIZ);
3832
3833 ev_data.if_family = ifp->if_family;
3834 ev_data.if_unit = ifp->if_unit;
3835 ev_msg.dv[0].data_length = sizeof(struct net_event_data);
3836 ev_msg.dv[0].data_ptr = &ev_data;
3837
3838 dlil_post_complete_msg(NULL, &ev_msg);
3839 }
3840 }
3841
3842 static inline struct rtentry *
3843 rte_alloc_debug(void)
3844 {
3845 struct rtentry_dbg *rte;
3846
3847 rte = ((struct rtentry_dbg *)zalloc(rte_zone));
3848 if (rte != NULL) {
3849 bzero(rte, sizeof(*rte));
3850 if (rte_debug & RTD_TRACE) {
3851 ctrace_record(&rte->rtd_alloc);
3852 }
3853 rte->rtd_inuse = RTD_INUSE;
3854 }
3855 return (struct rtentry *)rte;
3856 }
3857
3858 static inline void
3859 rte_free_debug(struct rtentry *p)
3860 {
3861 struct rtentry_dbg *rte = (struct rtentry_dbg *)p;
3862
3863 if (p->rt_refcnt != 0) {
3864 panic("rte_free: rte=%p refcnt=%d\n", p, p->rt_refcnt);
3865 /* NOTREACHED */
3866 }
3867 if (rte->rtd_inuse == RTD_FREED) {
3868 panic("rte_free: double free rte=%p\n", rte);
3869 /* NOTREACHED */
3870 } else if (rte->rtd_inuse != RTD_INUSE) {
3871 panic("rte_free: corrupted rte=%p\n", rte);
3872 /* NOTREACHED */
3873 }
3874 bcopy((caddr_t)p, (caddr_t)&rte->rtd_entry_saved, sizeof(*p));
3875 /* Preserve rt_lock to help catch use-after-free cases */
3876 bzero((caddr_t)p, offsetof(struct rtentry, rt_lock));
3877
3878 rte->rtd_inuse = RTD_FREED;
3879
3880 if (rte_debug & RTD_TRACE) {
3881 ctrace_record(&rte->rtd_free);
3882 }
3883
3884 if (!(rte_debug & RTD_NO_FREE)) {
3885 zfree(rte_zone, p);
3886 }
3887 }
3888
3889 void
3890 ctrace_record(ctrace_t *tr)
3891 {
3892 tr->th = current_thread();
3893 bzero(tr->pc, sizeof(tr->pc));
3894 (void) OSBacktrace(tr->pc, CTRACE_STACK_SIZE);
3895 }
3896
3897 void
3898 route_copyout(struct route *dst, const struct route *src, size_t length)
3899 {
3900 /* Copy everything (rt, srcif, flags, dst) from src */
3901 bcopy(src, dst, length);
3902
3903 /* Hold one reference for the local copy of struct route */
3904 if (dst->ro_rt != NULL) {
3905 RT_ADDREF(dst->ro_rt);
3906 }
3907
3908 /* Hold one reference for the local copy of struct lle */
3909 if (dst->ro_lle != NULL) {
3910 LLE_ADDREF(dst->ro_lle);
3911 }
3912
3913 /* Hold one reference for the local copy of struct ifaddr */
3914 if (dst->ro_srcia != NULL) {
3915 IFA_ADDREF(dst->ro_srcia);
3916 }
3917 }
3918
3919 void
3920 route_copyin(struct route *src, struct route *dst, size_t length)
3921 {
3922 /*
3923 * No cached route at the destination?
3924 * If none, then remove old references if present
3925 * and copy entire src route.
3926 */
3927 if (dst->ro_rt == NULL) {
3928 /*
3929 * Ditch the cached link layer reference (dst)
3930 * since we're about to take everything there is in src
3931 */
3932 if (dst->ro_lle != NULL) {
3933 LLE_REMREF(dst->ro_lle);
3934 }
3935 /*
3936 * Ditch the address in the cached copy (dst) since
3937 * we're about to take everything there is in src.
3938 */
3939 if (dst->ro_srcia != NULL) {
3940 IFA_REMREF(dst->ro_srcia);
3941 }
3942 /*
3943 * Copy everything (rt, ro_lle, srcia, flags, dst) from src; the
3944 * references to rt and/or srcia were held at the time
3945 * of storage and are kept intact.
3946 */
3947 bcopy(src, dst, length);
3948 goto done;
3949 }
3950
3951 /*
3952 * We know dst->ro_rt is not NULL here.
3953 * If the src->ro_rt is the same, update ro_lle, srcia and flags
3954 * and ditch the route in the local copy.
3955 */
3956 if (dst->ro_rt == src->ro_rt) {
3957 dst->ro_flags = src->ro_flags;
3958
3959 if (dst->ro_lle != src->ro_lle) {
3960 if (dst->ro_lle != NULL) {
3961 LLE_REMREF(dst->ro_lle);
3962 }
3963 dst->ro_lle = src->ro_lle;
3964 } else if (src->ro_lle != NULL) {
3965 LLE_REMREF(src->ro_lle);
3966 }
3967
3968 if (dst->ro_srcia != src->ro_srcia) {
3969 if (dst->ro_srcia != NULL) {
3970 IFA_REMREF(dst->ro_srcia);
3971 }
3972 dst->ro_srcia = src->ro_srcia;
3973 } else if (src->ro_srcia != NULL) {
3974 IFA_REMREF(src->ro_srcia);
3975 }
3976 rtfree(src->ro_rt);
3977 goto done;
3978 }
3979
3980 /*
3981 * If they are dst's ro_rt is not equal to src's,
3982 * and src'd rt is not NULL, then remove old references
3983 * if present and copy entire src route.
3984 */
3985 if (src->ro_rt != NULL) {
3986 rtfree(dst->ro_rt);
3987
3988 if (dst->ro_lle != NULL) {
3989 LLE_REMREF(dst->ro_lle);
3990 }
3991 if (dst->ro_srcia != NULL) {
3992 IFA_REMREF(dst->ro_srcia);
3993 }
3994 bcopy(src, dst, length);
3995 goto done;
3996 }
3997
3998 /*
3999 * Here, dst's cached route is not NULL but source's is.
4000 * Just get rid of all the other cached reference in src.
4001 */
4002 if (src->ro_srcia != NULL) {
4003 /*
4004 * Ditch src address in the local copy (src) since we're
4005 * not caching the route entry anyway (ro_rt is NULL).
4006 */
4007 IFA_REMREF(src->ro_srcia);
4008 }
4009 if (src->ro_lle != NULL) {
4010 /*
4011 * Ditch cache lle in the local copy (src) since we're
4012 * not caching the route anyway (ro_rt is NULL).
4013 */
4014 LLE_REMREF(src->ro_lle);
4015 }
4016 done:
4017 /* This function consumes the references on src */
4018 src->ro_lle = NULL;
4019 src->ro_rt = NULL;
4020 src->ro_srcia = NULL;
4021 }
4022
4023 /*
4024 * route_to_gwroute will find the gateway route for a given route.
4025 *
4026 * If the route is down, look the route up again.
4027 * If the route goes through a gateway, get the route to the gateway.
4028 * If the gateway route is down, look it up again.
4029 * If the route is set to reject, verify it hasn't expired.
4030 *
4031 * If the returned route is non-NULL, the caller is responsible for
4032 * releasing the reference and unlocking the route.
4033 */
4034 #define senderr(e) { error = (e); goto bad; }
4035 errno_t
4036 route_to_gwroute(const struct sockaddr *net_dest, struct rtentry *hint0,
4037 struct rtentry **out_route)
4038 {
4039 uint64_t timenow;
4040 struct rtentry *rt = hint0, *hint = hint0;
4041 errno_t error = 0;
4042 unsigned int ifindex;
4043 boolean_t gwroute;
4044
4045 *out_route = NULL;
4046
4047 if (rt == NULL) {
4048 return 0;
4049 }
4050
4051 /*
4052 * Next hop determination. Because we may involve the gateway route
4053 * in addition to the original route, locking is rather complicated.
4054 * The general concept is that regardless of whether the route points
4055 * to the original route or to the gateway route, this routine takes
4056 * an extra reference on such a route. This extra reference will be
4057 * released at the end.
4058 *
4059 * Care must be taken to ensure that the "hint0" route never gets freed
4060 * via rtfree(), since the caller may have stored it inside a struct
4061 * route with a reference held for that placeholder.
4062 */
4063 RT_LOCK_SPIN(rt);
4064 ifindex = rt->rt_ifp->if_index;
4065 RT_ADDREF_LOCKED(rt);
4066 if (!(rt->rt_flags & RTF_UP)) {
4067 RT_REMREF_LOCKED(rt);
4068 RT_UNLOCK(rt);
4069 /* route is down, find a new one */
4070 hint = rt = rtalloc1_scoped((struct sockaddr *)
4071 (size_t)net_dest, 1, 0, ifindex);
4072 if (hint != NULL) {
4073 RT_LOCK_SPIN(rt);
4074 ifindex = rt->rt_ifp->if_index;
4075 } else {
4076 senderr(EHOSTUNREACH);
4077 }
4078 }
4079
4080 /*
4081 * We have a reference to "rt" by now; it will either
4082 * be released or freed at the end of this routine.
4083 */
4084 RT_LOCK_ASSERT_HELD(rt);
4085 if ((gwroute = (rt->rt_flags & RTF_GATEWAY))) {
4086 struct rtentry *gwrt = rt->rt_gwroute;
4087 struct sockaddr_storage ss;
4088 struct sockaddr *gw = (struct sockaddr *)&ss;
4089
4090 VERIFY(rt == hint);
4091 RT_ADDREF_LOCKED(hint);
4092
4093 /* If there's no gateway rt, look it up */
4094 if (gwrt == NULL) {
4095 bcopy(rt->rt_gateway, gw, MIN(sizeof(ss),
4096 rt->rt_gateway->sa_len));
4097 gw->sa_len = MIN(sizeof(ss), rt->rt_gateway->sa_len);
4098 RT_UNLOCK(rt);
4099 goto lookup;
4100 }
4101 /* Become a regular mutex */
4102 RT_CONVERT_LOCK(rt);
4103
4104 /*
4105 * Take gwrt's lock while holding route's lock;
4106 * this is okay since gwrt never points back
4107 * to "rt", so no lock ordering issues.
4108 */
4109 RT_LOCK_SPIN(gwrt);
4110 if (!(gwrt->rt_flags & RTF_UP)) {
4111 rt->rt_gwroute = NULL;
4112 RT_UNLOCK(gwrt);
4113 bcopy(rt->rt_gateway, gw, MIN(sizeof(ss),
4114 rt->rt_gateway->sa_len));
4115 gw->sa_len = MIN(sizeof(ss), rt->rt_gateway->sa_len);
4116 RT_UNLOCK(rt);
4117 rtfree(gwrt);
4118 lookup:
4119 lck_mtx_lock(rnh_lock);
4120 gwrt = rtalloc1_scoped_locked(gw, 1, 0, ifindex);
4121
4122 RT_LOCK(rt);
4123 /*
4124 * Bail out if the route is down, no route
4125 * to gateway, circular route, or if the
4126 * gateway portion of "rt" has changed.
4127 */
4128 if (!(rt->rt_flags & RTF_UP) || gwrt == NULL ||
4129 gwrt == rt || !equal(gw, rt->rt_gateway)) {
4130 if (gwrt == rt) {
4131 RT_REMREF_LOCKED(gwrt);
4132 gwrt = NULL;
4133 }
4134 VERIFY(rt == hint);
4135 RT_REMREF_LOCKED(hint);
4136 hint = NULL;
4137 RT_UNLOCK(rt);
4138 if (gwrt != NULL) {
4139 rtfree_locked(gwrt);
4140 }
4141 lck_mtx_unlock(rnh_lock);
4142 senderr(EHOSTUNREACH);
4143 }
4144 VERIFY(gwrt != NULL);
4145 /*
4146 * Set gateway route; callee adds ref to gwrt;
4147 * gwrt has an extra ref from rtalloc1() for
4148 * this routine.
4149 */
4150 rt_set_gwroute(rt, rt_key(rt), gwrt);
4151 VERIFY(rt == hint);
4152 RT_REMREF_LOCKED(rt); /* hint still holds a refcnt */
4153 RT_UNLOCK(rt);
4154 lck_mtx_unlock(rnh_lock);
4155 rt = gwrt;
4156 } else {
4157 RT_ADDREF_LOCKED(gwrt);
4158 RT_UNLOCK(gwrt);
4159 VERIFY(rt == hint);
4160 RT_REMREF_LOCKED(rt); /* hint still holds a refcnt */
4161 RT_UNLOCK(rt);
4162 rt = gwrt;
4163 }
4164 VERIFY(rt == gwrt && rt != hint);
4165
4166 /*
4167 * This is an opportunity to revalidate the parent route's
4168 * rt_gwroute, in case it now points to a dead route entry.
4169 * Parent route won't go away since the clone (hint) holds
4170 * a reference to it. rt == gwrt.
4171 */
4172 RT_LOCK_SPIN(hint);
4173 if ((hint->rt_flags & (RTF_WASCLONED | RTF_UP)) ==
4174 (RTF_WASCLONED | RTF_UP)) {
4175 struct rtentry *prt = hint->rt_parent;
4176 VERIFY(prt != NULL);
4177
4178 RT_CONVERT_LOCK(hint);
4179 RT_ADDREF(prt);
4180 RT_UNLOCK(hint);
4181 rt_revalidate_gwroute(prt, rt);
4182 RT_REMREF(prt);
4183 } else {
4184 RT_UNLOCK(hint);
4185 }
4186
4187 /* Clean up "hint" now; see notes above regarding hint0 */
4188 if (hint == hint0) {
4189 RT_REMREF(hint);
4190 } else {
4191 rtfree(hint);
4192 }
4193 hint = NULL;
4194
4195 /* rt == gwrt; if it is now down, give up */
4196 RT_LOCK_SPIN(rt);
4197 if (!(rt->rt_flags & RTF_UP)) {
4198 RT_UNLOCK(rt);
4199 senderr(EHOSTUNREACH);
4200 }
4201 }
4202
4203 if (rt->rt_flags & RTF_REJECT) {
4204 VERIFY(rt->rt_expire == 0 || rt->rt_rmx.rmx_expire != 0);
4205 VERIFY(rt->rt_expire != 0 || rt->rt_rmx.rmx_expire == 0);
4206 timenow = net_uptime();
4207 if (rt->rt_expire == 0 || timenow < rt->rt_expire) {
4208 RT_UNLOCK(rt);
4209 senderr(!gwroute ? EHOSTDOWN : EHOSTUNREACH);
4210 }
4211 }
4212
4213 /* Become a regular mutex */
4214 RT_CONVERT_LOCK(rt);
4215
4216 /* Caller is responsible for cleaning up "rt" */
4217 *out_route = rt;
4218 return 0;
4219
4220 bad:
4221 /* Clean up route (either it is "rt" or "gwrt") */
4222 if (rt != NULL) {
4223 RT_LOCK_SPIN(rt);
4224 if (rt == hint0) {
4225 RT_REMREF_LOCKED(rt);
4226 RT_UNLOCK(rt);
4227 } else {
4228 RT_UNLOCK(rt);
4229 rtfree(rt);
4230 }
4231 }
4232 return error;
4233 }
4234 #undef senderr
4235
4236 void
4237 rt_revalidate_gwroute(struct rtentry *rt, struct rtentry *gwrt)
4238 {
4239 VERIFY(gwrt != NULL);
4240
4241 RT_LOCK_SPIN(rt);
4242 if ((rt->rt_flags & (RTF_GATEWAY | RTF_UP)) == (RTF_GATEWAY | RTF_UP) &&
4243 rt->rt_ifp == gwrt->rt_ifp && rt->rt_gateway->sa_family ==
4244 rt_key(gwrt)->sa_family && (rt->rt_gwroute == NULL ||
4245 !(rt->rt_gwroute->rt_flags & RTF_UP))) {
4246 boolean_t isequal;
4247 VERIFY(rt->rt_flags & (RTF_CLONING | RTF_PRCLONING));
4248
4249 if (rt->rt_gateway->sa_family == AF_INET ||
4250 rt->rt_gateway->sa_family == AF_INET6) {
4251 struct sockaddr_storage key_ss, gw_ss;
4252 /*
4253 * We need to compare rt_key and rt_gateway; create
4254 * local copies to get rid of any ifscope association.
4255 */
4256 (void) sa_copy(rt_key(gwrt), &key_ss, NULL);
4257 (void) sa_copy(rt->rt_gateway, &gw_ss, NULL);
4258
4259 isequal = equal(SA(&key_ss), SA(&gw_ss));
4260 } else {
4261 isequal = equal(rt_key(gwrt), rt->rt_gateway);
4262 }
4263
4264 /* If they are the same, update gwrt */
4265 if (isequal) {
4266 RT_UNLOCK(rt);
4267 lck_mtx_lock(rnh_lock);
4268 RT_LOCK(rt);
4269 rt_set_gwroute(rt, rt_key(rt), gwrt);
4270 RT_UNLOCK(rt);
4271 lck_mtx_unlock(rnh_lock);
4272 } else {
4273 RT_UNLOCK(rt);
4274 }
4275 } else {
4276 RT_UNLOCK(rt);
4277 }
4278 }
4279
4280 static void
4281 rt_str4(struct rtentry *rt, char *ds, uint32_t dslen, char *gs, uint32_t gslen)
4282 {
4283 VERIFY(rt_key(rt)->sa_family == AF_INET);
4284
4285 if (ds != NULL) {
4286 (void) inet_ntop(AF_INET,
4287 &SIN(rt_key(rt))->sin_addr.s_addr, ds, dslen);
4288 if (dslen >= MAX_SCOPE_ADDR_STR_LEN &&
4289 SINIFSCOPE(rt_key(rt))->sin_scope_id != IFSCOPE_NONE) {
4290 char scpstr[16];
4291
4292 snprintf(scpstr, sizeof(scpstr), "@%u",
4293 SINIFSCOPE(rt_key(rt))->sin_scope_id);
4294
4295 strlcat(ds, scpstr, dslen);
4296 }
4297 }
4298
4299 if (gs != NULL) {
4300 if (rt->rt_flags & RTF_GATEWAY) {
4301 (void) inet_ntop(AF_INET,
4302 &SIN(rt->rt_gateway)->sin_addr.s_addr, gs, gslen);
4303 } else if (rt->rt_ifp != NULL) {
4304 snprintf(gs, gslen, "link#%u", rt->rt_ifp->if_unit);
4305 } else {
4306 snprintf(gs, gslen, "%s", "link");
4307 }
4308 }
4309 }
4310
4311 static void
4312 rt_str6(struct rtentry *rt, char *ds, uint32_t dslen, char *gs, uint32_t gslen)
4313 {
4314 VERIFY(rt_key(rt)->sa_family == AF_INET6);
4315
4316 if (ds != NULL) {
4317 (void) inet_ntop(AF_INET6,
4318 &SIN6(rt_key(rt))->sin6_addr, ds, dslen);
4319 if (dslen >= MAX_SCOPE_ADDR_STR_LEN &&
4320 SIN6IFSCOPE(rt_key(rt))->sin6_scope_id != IFSCOPE_NONE) {
4321 char scpstr[16];
4322
4323 snprintf(scpstr, sizeof(scpstr), "@%u",
4324 SIN6IFSCOPE(rt_key(rt))->sin6_scope_id);
4325
4326 strlcat(ds, scpstr, dslen);
4327 }
4328 }
4329
4330 if (gs != NULL) {
4331 if (rt->rt_flags & RTF_GATEWAY) {
4332 (void) inet_ntop(AF_INET6,
4333 &SIN6(rt->rt_gateway)->sin6_addr, gs, gslen);
4334 } else if (rt->rt_ifp != NULL) {
4335 snprintf(gs, gslen, "link#%u", rt->rt_ifp->if_unit);
4336 } else {
4337 snprintf(gs, gslen, "%s", "link");
4338 }
4339 }
4340 }
4341
4342 void
4343 rt_str(struct rtentry *rt, char *ds, uint32_t dslen, char *gs, uint32_t gslen)
4344 {
4345 switch (rt_key(rt)->sa_family) {
4346 case AF_INET:
4347 rt_str4(rt, ds, dslen, gs, gslen);
4348 break;
4349 case AF_INET6:
4350 rt_str6(rt, ds, dslen, gs, gslen);
4351 break;
4352 default:
4353 if (ds != NULL) {
4354 bzero(ds, dslen);
4355 }
4356 if (gs != NULL) {
4357 bzero(gs, gslen);
4358 }
4359 break;
4360 }
4361 }
4362
4363 void
4364 route_event_init(struct route_event *p_route_ev, struct rtentry *rt,
4365 struct rtentry *gwrt, int route_ev_code)
4366 {
4367 VERIFY(p_route_ev != NULL);
4368 bzero(p_route_ev, sizeof(*p_route_ev));
4369
4370 p_route_ev->rt = rt;
4371 p_route_ev->gwrt = gwrt;
4372 p_route_ev->route_event_code = route_ev_code;
4373 }
4374
4375 static void
4376 route_event_callback(void *arg)
4377 {
4378 struct route_event *p_rt_ev = (struct route_event *)arg;
4379 struct rtentry *rt = p_rt_ev->rt;
4380 eventhandler_tag evtag = p_rt_ev->evtag;
4381 int route_ev_code = p_rt_ev->route_event_code;
4382
4383 if (route_ev_code == ROUTE_EVHDLR_DEREGISTER) {
4384 VERIFY(evtag != NULL);
4385 EVENTHANDLER_DEREGISTER(&rt->rt_evhdlr_ctxt, route_event,
4386 evtag);
4387 rtfree(rt);
4388 return;
4389 }
4390
4391 EVENTHANDLER_INVOKE(&rt->rt_evhdlr_ctxt, route_event, rt_key(rt),
4392 route_ev_code, (struct sockaddr *)&p_rt_ev->rt_addr,
4393 rt->rt_flags);
4394
4395 /* The code enqueuing the route event held a reference */
4396 rtfree(rt);
4397 /* XXX No reference is taken on gwrt */
4398 }
4399
4400 int
4401 route_event_walktree(struct radix_node *rn, void *arg)
4402 {
4403 struct route_event *p_route_ev = (struct route_event *)arg;
4404 struct rtentry *rt = (struct rtentry *)rn;
4405 struct rtentry *gwrt = p_route_ev->rt;
4406
4407 LCK_MTX_ASSERT(rnh_lock, LCK_MTX_ASSERT_OWNED);
4408
4409 RT_LOCK(rt);
4410
4411 /* Return if the entry is pending cleanup */
4412 if (rt->rt_flags & RTPRF_OURS) {
4413 RT_UNLOCK(rt);
4414 return 0;
4415 }
4416
4417 /* Return if it is not an indirect route */
4418 if (!(rt->rt_flags & RTF_GATEWAY)) {
4419 RT_UNLOCK(rt);
4420 return 0;
4421 }
4422
4423 if (rt->rt_gwroute != gwrt) {
4424 RT_UNLOCK(rt);
4425 return 0;
4426 }
4427
4428 route_event_enqueue_nwk_wq_entry(rt, gwrt, p_route_ev->route_event_code,
4429 NULL, TRUE);
4430 RT_UNLOCK(rt);
4431
4432 return 0;
4433 }
4434
4435 struct route_event_nwk_wq_entry {
4436 struct nwk_wq_entry nwk_wqe;
4437 struct route_event rt_ev_arg;
4438 };
4439
4440 void
4441 route_event_enqueue_nwk_wq_entry(struct rtentry *rt, struct rtentry *gwrt,
4442 uint32_t route_event_code, eventhandler_tag evtag, boolean_t rt_locked)
4443 {
4444 struct route_event_nwk_wq_entry *p_rt_ev = NULL;
4445 struct sockaddr *p_gw_saddr = NULL;
4446
4447 MALLOC(p_rt_ev, struct route_event_nwk_wq_entry *,
4448 sizeof(struct route_event_nwk_wq_entry),
4449 M_NWKWQ, M_WAITOK | M_ZERO);
4450
4451 /*
4452 * If the intent is to de-register, don't take
4453 * reference, route event registration already takes
4454 * a reference on route.
4455 */
4456 if (route_event_code != ROUTE_EVHDLR_DEREGISTER) {
4457 /* The reference is released by route_event_callback */
4458 if (rt_locked) {
4459 RT_ADDREF_LOCKED(rt);
4460 } else {
4461 RT_ADDREF(rt);
4462 }
4463 }
4464
4465 p_rt_ev->rt_ev_arg.rt = rt;
4466 p_rt_ev->rt_ev_arg.gwrt = gwrt;
4467 p_rt_ev->rt_ev_arg.evtag = evtag;
4468
4469 if (gwrt != NULL) {
4470 p_gw_saddr = gwrt->rt_gateway;
4471 } else {
4472 p_gw_saddr = rt->rt_gateway;
4473 }
4474
4475 VERIFY(p_gw_saddr->sa_len <= sizeof(p_rt_ev->rt_ev_arg.rt_addr));
4476 bcopy(p_gw_saddr, &(p_rt_ev->rt_ev_arg.rt_addr), p_gw_saddr->sa_len);
4477
4478 p_rt_ev->rt_ev_arg.route_event_code = route_event_code;
4479 p_rt_ev->nwk_wqe.func = route_event_callback;
4480 p_rt_ev->nwk_wqe.is_arg_managed = TRUE;
4481 p_rt_ev->nwk_wqe.arg = &p_rt_ev->rt_ev_arg;
4482 nwk_wq_enqueue((struct nwk_wq_entry*)p_rt_ev);
4483 }
4484
4485 const char *
4486 route_event2str(int route_event)
4487 {
4488 const char *route_event_str = "ROUTE_EVENT_UNKNOWN";
4489 switch (route_event) {
4490 case ROUTE_STATUS_UPDATE:
4491 route_event_str = "ROUTE_STATUS_UPDATE";
4492 break;
4493 case ROUTE_ENTRY_REFRESH:
4494 route_event_str = "ROUTE_ENTRY_REFRESH";
4495 break;
4496 case ROUTE_ENTRY_DELETED:
4497 route_event_str = "ROUTE_ENTRY_DELETED";
4498 break;
4499 case ROUTE_LLENTRY_RESOLVED:
4500 route_event_str = "ROUTE_LLENTRY_RESOLVED";
4501 break;
4502 case ROUTE_LLENTRY_UNREACH:
4503 route_event_str = "ROUTE_LLENTRY_UNREACH";
4504 break;
4505 case ROUTE_LLENTRY_CHANGED:
4506 route_event_str = "ROUTE_LLENTRY_CHANGED";
4507 break;
4508 case ROUTE_LLENTRY_STALE:
4509 route_event_str = "ROUTE_LLENTRY_STALE";
4510 break;
4511 case ROUTE_LLENTRY_TIMEDOUT:
4512 route_event_str = "ROUTE_LLENTRY_TIMEDOUT";
4513 break;
4514 case ROUTE_LLENTRY_DELETED:
4515 route_event_str = "ROUTE_LLENTRY_DELETED";
4516 break;
4517 case ROUTE_LLENTRY_EXPIRED:
4518 route_event_str = "ROUTE_LLENTRY_EXPIRED";
4519 break;
4520 case ROUTE_LLENTRY_PROBED:
4521 route_event_str = "ROUTE_LLENTRY_PROBED";
4522 break;
4523 case ROUTE_EVHDLR_DEREGISTER:
4524 route_event_str = "ROUTE_EVHDLR_DEREGISTER";
4525 break;
4526 default:
4527 /* Init'd to ROUTE_EVENT_UNKNOWN */
4528 break;
4529 }
4530 return route_event_str;
4531 }
4532
4533 int
4534 route_op_entitlement_check(struct socket *so,
4535 kauth_cred_t cred,
4536 int route_op_type,
4537 boolean_t allow_root)
4538 {
4539 if (so != NULL) {
4540 if (route_op_type == ROUTE_OP_READ) {
4541 /*
4542 * If needed we can later extend this for more
4543 * granular entitlements and return a bit set of
4544 * allowed accesses.
4545 */
4546 if (soopt_cred_check(so, PRIV_NET_RESTRICTED_ROUTE_NC_READ,
4547 allow_root, false) == 0) {
4548 return 0;
4549 } else {
4550 return -1;
4551 }
4552 }
4553 } else if (cred != NULL) {
4554 uid_t uid = kauth_cred_getuid(cred);
4555
4556 /* uid is 0 for root */
4557 if (uid != 0 || !allow_root) {
4558 if (route_op_type == ROUTE_OP_READ) {
4559 if (priv_check_cred(cred,
4560 PRIV_NET_RESTRICTED_ROUTE_NC_READ, 0) == 0) {
4561 return 0;
4562 } else {
4563 return -1;
4564 }
4565 }
4566 }
4567 }
4568 return -1;
4569 }