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