2 * Copyright (c) 2000-2015 Apple Inc. All rights reserved.
4 * @APPLE_OSREFERENCE_LICENSE_HEADER_START@
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.
15 * Please obtain a copy of the License at
16 * http://www.opensource.apple.com/apsl/ and read it before using this file.
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.
26 * @APPLE_OSREFERENCE_LICENSE_HEADER_END@
29 * Copyright (c) 1980, 1986, 1991, 1993
30 * The Regents of the University of California. All rights reserved.
32 * Redistribution and use in source and binary forms, with or without
33 * modification, are permitted provided that the following conditions
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.
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
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 $
64 #include <sys/param.h>
65 #include <sys/sysctl.h>
66 #include <sys/systm.h>
67 #include <sys/malloc.h>
69 #include <sys/socket.h>
70 #include <sys/domain.h>
71 #include <sys/syslog.h>
72 #include <sys/queue.h>
73 #include <sys/mcache.h>
74 #include <sys/protosw.h>
75 #include <sys/kernel.h>
76 #include <kern/locks.h>
77 #include <kern/zalloc.h>
81 #include <net/route.h>
82 #include <net/ntstat.h>
84 #include <netinet/in.h>
85 #include <netinet/in_var.h>
86 #include <netinet/ip_var.h>
87 #include <netinet/ip6.h>
90 #include <netinet6/ip6_var.h>
91 #include <netinet6/in6_var.h>
92 #include <netinet6/nd6.h>
95 #include <net/if_dl.h>
97 #include <libkern/OSAtomic.h>
98 #include <libkern/OSDebug.h>
100 #include <pexpert/pexpert.h>
103 #include <sys/kauth.h>
107 * Synchronization notes:
109 * Routing entries fall under two locking domains: the global routing table
110 * lock (rnh_lock) and the per-entry lock (rt_lock); the latter is a mutex that
111 * resides (statically defined) in the rtentry structure.
113 * The locking domains for routing are defined as follows:
115 * The global routing lock is used to serialize all accesses to the radix
116 * trees defined by rt_tables[], as well as the tree of masks. This includes
117 * lookups, insertions and removals of nodes to/from the respective tree.
118 * It is also used to protect certain fields in the route entry that aren't
119 * often modified and/or require global serialization (more details below.)
121 * The per-route entry lock is used to serialize accesses to several routing
122 * entry fields (more details below.) Acquiring and releasing this lock is
123 * done via RT_LOCK() and RT_UNLOCK() routines.
125 * In cases where both rnh_lock and rt_lock must be held, the former must be
126 * acquired first in order to maintain lock ordering. It is not a requirement
127 * that rnh_lock be acquired first before rt_lock, but in case both must be
128 * acquired in succession, the correct lock ordering must be followed.
130 * The fields of the rtentry structure are protected in the following way:
134 * - Routing table lock (rnh_lock).
136 * rt_parent, rt_mask, rt_llinfo_free, rt_tree_genid
138 * - Set once during creation and never changes; no locks to read.
140 * rt_flags, rt_genmask, rt_llinfo, rt_rmx, rt_refcnt, rt_gwroute
142 * - Routing entry lock (rt_lock) for read/write access.
144 * - Some values of rt_flags are either set once at creation time,
145 * or aren't currently used, and thus checking against them can
146 * be done without rt_lock: RTF_GATEWAY, RTF_HOST, RTF_DYNAMIC,
147 * RTF_DONE, RTF_XRESOLVE, RTF_STATIC, RTF_BLACKHOLE, RTF_ANNOUNCE,
148 * RTF_USETRAILERS, RTF_WASCLONED, RTF_PINNED, RTF_LOCAL,
149 * RTF_BROADCAST, RTF_MULTICAST, RTF_IFSCOPE, RTF_IFREF.
151 * rt_key, rt_gateway, rt_ifp, rt_ifa
153 * - Always written/modified with both rnh_lock and rt_lock held.
155 * - May be read freely with rnh_lock held, else must hold rt_lock
156 * for read access; holding both locks for read is also okay.
158 * - In the event rnh_lock is not acquired, or is not possible to be
159 * acquired across the operation, setting RTF_CONDEMNED on a route
160 * entry will prevent its rt_key, rt_gateway, rt_ifp and rt_ifa
161 * from being modified. This is typically done on a route that
162 * has been chosen for a removal (from the tree) prior to dropping
163 * the rt_lock, so that those values will remain the same until
164 * the route is freed.
166 * When rnh_lock is held rt_setgate(), rt_setif(), and rtsetifa() are
167 * single-threaded, thus exclusive. This flag will also prevent the
168 * route from being looked up via rt_lookup().
172 * - Assumes that 32-bit writes are atomic; no locks.
176 * - Currently unused; no locks.
178 * Operations on a route entry can be described as follows:
180 * CREATE an entry with reference count set to 0 as part of RTM_ADD/RESOLVE.
182 * INSERTION of an entry into the radix tree holds the rnh_lock, checks
183 * for duplicates and then adds the entry. rtrequest returns the entry
184 * after bumping up the reference count to 1 (for the caller).
186 * LOOKUP of an entry holds the rnh_lock and bumps up the reference count
187 * before returning; it is valid to also bump up the reference count using
188 * RT_ADDREF after the lookup has returned an entry.
190 * REMOVAL of an entry from the radix tree holds the rnh_lock, removes the
191 * entry but does not decrement the reference count. Removal happens when
192 * the route is explicitly deleted (RTM_DELETE) or when it is in the cached
193 * state and it expires. The route is said to be "down" when it is no
194 * longer present in the tree. Freeing the entry will happen on the last
195 * reference release of such a "down" route.
197 * RT_ADDREF/RT_REMREF operates on the routing entry which increments/
198 * decrements the reference count, rt_refcnt, atomically on the rtentry.
199 * rt_refcnt is modified only using this routine. The general rule is to
200 * do RT_ADDREF in the function that is passing the entry as an argument,
201 * in order to prevent the entry from being freed by the callee.
204 #define equal(a1, a2) (bcmp((caddr_t)(a1), (caddr_t)(a2), (a1)->sa_len) == 0)
206 extern void kdp_set_gateway_mac(void *gatewaymac
);
208 __private_extern__
struct rtstat rtstat
= { 0, 0, 0, 0, 0 };
209 struct radix_node_head
*rt_tables
[AF_MAX
+1];
211 decl_lck_mtx_data(, rnh_lock_data
); /* global routing tables mutex */
212 lck_mtx_t
*rnh_lock
= &rnh_lock_data
;
213 static lck_attr_t
*rnh_lock_attr
;
214 static lck_grp_t
*rnh_lock_grp
;
215 static lck_grp_attr_t
*rnh_lock_grp_attr
;
217 /* Lock group and attribute for routing entry locks */
218 static lck_attr_t
*rte_mtx_attr
;
219 static lck_grp_t
*rte_mtx_grp
;
220 static lck_grp_attr_t
*rte_mtx_grp_attr
;
222 int rttrash
= 0; /* routes not in table but not freed */
224 unsigned int rte_debug
;
226 /* Possible flags for rte_debug */
227 #define RTD_DEBUG 0x1 /* enable or disable rtentry debug facility */
228 #define RTD_TRACE 0x2 /* trace alloc, free, refcnt and lock */
229 #define RTD_NO_FREE 0x4 /* don't free (good to catch corruptions) */
231 #define RTE_NAME "rtentry" /* name for zone and rt_lock */
233 static struct zone
*rte_zone
; /* special zone for rtentry */
234 #define RTE_ZONE_MAX 65536 /* maximum elements in zone */
235 #define RTE_ZONE_NAME RTE_NAME /* name of rtentry zone */
237 #define RTD_INUSE 0xFEEDFACE /* entry is in use */
238 #define RTD_FREED 0xDEADBEEF /* entry is freed */
240 #define MAX_SCOPE_ADDR_STR_LEN (MAX_IPv6_STR_LEN + 6)
243 __private_extern__
unsigned int ctrace_stack_size
= CTRACE_STACK_SIZE
;
244 __private_extern__
unsigned int ctrace_hist_size
= CTRACE_HIST_SIZE
;
247 * Debug variant of rtentry structure.
250 struct rtentry rtd_entry
; /* rtentry */
251 struct rtentry rtd_entry_saved
; /* saved rtentry */
252 uint32_t rtd_inuse
; /* in use pattern */
253 uint16_t rtd_refhold_cnt
; /* # of rtref */
254 uint16_t rtd_refrele_cnt
; /* # of rtunref */
255 uint32_t rtd_lock_cnt
; /* # of locks */
256 uint32_t rtd_unlock_cnt
; /* # of unlocks */
258 * Alloc and free callers.
263 * Circular lists of rtref and rtunref callers.
265 ctrace_t rtd_refhold
[CTRACE_HIST_SIZE
];
266 ctrace_t rtd_refrele
[CTRACE_HIST_SIZE
];
268 * Circular lists of locks and unlocks.
270 ctrace_t rtd_lock
[CTRACE_HIST_SIZE
];
271 ctrace_t rtd_unlock
[CTRACE_HIST_SIZE
];
275 TAILQ_ENTRY(rtentry_dbg
) rtd_trash_link
;
278 /* List of trash route entries protected by rnh_lock */
279 static TAILQ_HEAD(, rtentry_dbg
) rttrash_head
;
281 static void rte_lock_init(struct rtentry
*);
282 static void rte_lock_destroy(struct rtentry
*);
283 static inline struct rtentry
*rte_alloc_debug(void);
284 static inline void rte_free_debug(struct rtentry
*);
285 static inline void rte_lock_debug(struct rtentry_dbg
*);
286 static inline void rte_unlock_debug(struct rtentry_dbg
*);
287 static void rt_maskedcopy(const struct sockaddr
*,
288 struct sockaddr
*, const struct sockaddr
*);
289 static void rtable_init(void **);
290 static inline void rtref_audit(struct rtentry_dbg
*);
291 static inline void rtunref_audit(struct rtentry_dbg
*);
292 static struct rtentry
*rtalloc1_common_locked(struct sockaddr
*, int, uint32_t,
294 static int rtrequest_common_locked(int, struct sockaddr
*,
295 struct sockaddr
*, struct sockaddr
*, int, struct rtentry
**,
297 static struct rtentry
*rtalloc1_locked(struct sockaddr
*, int, uint32_t);
298 static void rtalloc_ign_common_locked(struct route
*, uint32_t, unsigned int);
299 static inline void sin6_set_ifscope(struct sockaddr
*, unsigned int);
300 static inline void sin6_set_embedded_ifscope(struct sockaddr
*, unsigned int);
301 static inline unsigned int sin6_get_embedded_ifscope(struct sockaddr
*);
302 static struct sockaddr
*ma_copy(int, struct sockaddr
*,
303 struct sockaddr_storage
*, unsigned int);
304 static struct sockaddr
*sa_trim(struct sockaddr
*, int);
305 static struct radix_node
*node_lookup(struct sockaddr
*, struct sockaddr
*,
307 static struct radix_node
*node_lookup_default(int);
308 static struct rtentry
*rt_lookup_common(boolean_t
, boolean_t
, struct sockaddr
*,
309 struct sockaddr
*, struct radix_node_head
*, unsigned int);
310 static int rn_match_ifscope(struct radix_node
*, void *);
311 static struct ifaddr
*ifa_ifwithroute_common_locked(int,
312 const struct sockaddr
*, const struct sockaddr
*, unsigned int);
313 static struct rtentry
*rte_alloc(void);
314 static void rte_free(struct rtentry
*);
315 static void rtfree_common(struct rtentry
*, boolean_t
);
316 static void rte_if_ref(struct ifnet
*, int);
317 static void rt_set_idleref(struct rtentry
*);
318 static void rt_clear_idleref(struct rtentry
*);
319 static void rt_str4(struct rtentry
*, char *, uint32_t, char *, uint32_t);
321 static void rt_str6(struct rtentry
*, char *, uint32_t, char *, uint32_t);
324 uint32_t route_genid_inet
= 0;
326 uint32_t route_genid_inet6
= 0;
329 #define ASSERT_SINIFSCOPE(sa) { \
330 if ((sa)->sa_family != AF_INET || \
331 (sa)->sa_len < sizeof (struct sockaddr_in)) \
332 panic("%s: bad sockaddr_in %p\n", __func__, sa); \
335 #define ASSERT_SIN6IFSCOPE(sa) { \
336 if ((sa)->sa_family != AF_INET6 || \
337 (sa)->sa_len < sizeof (struct sockaddr_in6)) \
338 panic("%s: bad sockaddr_in6 %p\n", __func__, sa); \
342 * Argument to leaf-matching routine; at present it is scoped routing
343 * specific but can be expanded in future to include other search filters.
345 struct matchleaf_arg
{
346 unsigned int ifscope
; /* interface scope */
350 * For looking up the non-scoped default route (sockaddr instead
351 * of sockaddr_in for convenience).
353 static struct sockaddr sin_def
= {
354 sizeof (struct sockaddr_in
), AF_INET
, { 0, }
357 static struct sockaddr_in6 sin6_def
= {
358 sizeof (struct sockaddr_in6
), AF_INET6
, 0, 0, IN6ADDR_ANY_INIT
, 0
362 * Interface index (scope) of the primary interface; determined at
363 * the time when the default, non-scoped route gets added, changed
364 * or deleted. Protected by rnh_lock.
366 static unsigned int primary_ifscope
= IFSCOPE_NONE
;
367 static unsigned int primary6_ifscope
= IFSCOPE_NONE
;
369 #define INET_DEFAULT(sa) \
370 ((sa)->sa_family == AF_INET && SIN(sa)->sin_addr.s_addr == 0)
372 #define INET6_DEFAULT(sa) \
373 ((sa)->sa_family == AF_INET6 && \
374 IN6_IS_ADDR_UNSPECIFIED(&SIN6(sa)->sin6_addr))
376 #define SA_DEFAULT(sa) (INET_DEFAULT(sa) || INET6_DEFAULT(sa))
377 #define RT(r) ((struct rtentry *)r)
378 #define RN(r) ((struct radix_node *)r)
379 #define RT_HOST(r) (RT(r)->rt_flags & RTF_HOST)
381 SYSCTL_DECL(_net_route
);
383 unsigned int rt_verbose
; /* verbosity level (0 to disable) */
384 SYSCTL_UINT(_net_route
, OID_AUTO
, verbose
, CTLFLAG_RW
| CTLFLAG_LOCKED
,
388 rtable_init(void **table
)
392 domain_proto_mtx_lock_assert_held();
394 TAILQ_FOREACH(dom
, &domains
, dom_entry
) {
395 if (dom
->dom_rtattach
!= NULL
)
396 dom
->dom_rtattach(&table
[dom
->dom_family
],
402 * Called by route_dinit().
410 _CASSERT(offsetof(struct route
, ro_rt
) ==
411 offsetof(struct route_in6
, ro_rt
));
412 _CASSERT(offsetof(struct route
, ro_srcia
) ==
413 offsetof(struct route_in6
, ro_srcia
));
414 _CASSERT(offsetof(struct route
, ro_flags
) ==
415 offsetof(struct route_in6
, ro_flags
));
416 _CASSERT(offsetof(struct route
, ro_dst
) ==
417 offsetof(struct route_in6
, ro_dst
));
420 PE_parse_boot_argn("rte_debug", &rte_debug
, sizeof (rte_debug
));
422 rte_debug
|= RTD_DEBUG
;
424 rnh_lock_grp_attr
= lck_grp_attr_alloc_init();
425 rnh_lock_grp
= lck_grp_alloc_init("route", rnh_lock_grp_attr
);
426 rnh_lock_attr
= lck_attr_alloc_init();
427 lck_mtx_init(rnh_lock
, rnh_lock_grp
, rnh_lock_attr
);
429 rte_mtx_grp_attr
= lck_grp_attr_alloc_init();
430 rte_mtx_grp
= lck_grp_alloc_init(RTE_NAME
, rte_mtx_grp_attr
);
431 rte_mtx_attr
= lck_attr_alloc_init();
433 lck_mtx_lock(rnh_lock
);
434 rn_init(); /* initialize all zeroes, all ones, mask table */
435 lck_mtx_unlock(rnh_lock
);
436 rtable_init((void **)rt_tables
);
438 if (rte_debug
& RTD_DEBUG
)
439 size
= sizeof (struct rtentry_dbg
);
441 size
= sizeof (struct rtentry
);
443 rte_zone
= zinit(size
, RTE_ZONE_MAX
* size
, 0, RTE_ZONE_NAME
);
444 if (rte_zone
== NULL
) {
445 panic("%s: failed allocating rte_zone", __func__
);
448 zone_change(rte_zone
, Z_EXPAND
, TRUE
);
449 zone_change(rte_zone
, Z_CALLERACCT
, FALSE
);
450 zone_change(rte_zone
, Z_NOENCRYPT
, TRUE
);
452 TAILQ_INIT(&rttrash_head
);
456 * Given a route, determine whether or not it is the non-scoped default
457 * route; dst typically comes from rt_key(rt) but may be coming from
458 * a separate place when rt is in the process of being created.
461 rt_primary_default(struct rtentry
*rt
, struct sockaddr
*dst
)
463 return (SA_DEFAULT(dst
) && !(rt
->rt_flags
& RTF_IFSCOPE
));
467 * Set the ifscope of the primary interface; caller holds rnh_lock.
470 set_primary_ifscope(int af
, unsigned int ifscope
)
473 primary_ifscope
= ifscope
;
475 primary6_ifscope
= ifscope
;
479 * Return the ifscope of the primary interface; caller holds rnh_lock.
482 get_primary_ifscope(int af
)
484 return (af
== AF_INET
? primary_ifscope
: primary6_ifscope
);
488 * Set the scope ID of a given a sockaddr_in.
491 sin_set_ifscope(struct sockaddr
*sa
, unsigned int ifscope
)
493 /* Caller must pass in sockaddr_in */
494 ASSERT_SINIFSCOPE(sa
);
496 SINIFSCOPE(sa
)->sin_scope_id
= ifscope
;
500 * Set the scope ID of given a sockaddr_in6.
503 sin6_set_ifscope(struct sockaddr
*sa
, unsigned int ifscope
)
505 /* Caller must pass in sockaddr_in6 */
506 ASSERT_SIN6IFSCOPE(sa
);
508 SIN6IFSCOPE(sa
)->sin6_scope_id
= ifscope
;
512 * Given a sockaddr_in, return the scope ID to the caller.
515 sin_get_ifscope(struct sockaddr
*sa
)
517 /* Caller must pass in sockaddr_in */
518 ASSERT_SINIFSCOPE(sa
);
520 return (SINIFSCOPE(sa
)->sin_scope_id
);
524 * Given a sockaddr_in6, return the scope ID to the caller.
527 sin6_get_ifscope(struct sockaddr
*sa
)
529 /* Caller must pass in sockaddr_in6 */
530 ASSERT_SIN6IFSCOPE(sa
);
532 return (SIN6IFSCOPE(sa
)->sin6_scope_id
);
536 sin6_set_embedded_ifscope(struct sockaddr
*sa
, unsigned int ifscope
)
538 /* Caller must pass in sockaddr_in6 */
539 ASSERT_SIN6IFSCOPE(sa
);
540 VERIFY(IN6_IS_SCOPE_EMBED(&(SIN6(sa
)->sin6_addr
)));
542 SIN6(sa
)->sin6_addr
.s6_addr16
[1] = htons(ifscope
);
545 static inline unsigned int
546 sin6_get_embedded_ifscope(struct sockaddr
*sa
)
548 /* Caller must pass in sockaddr_in6 */
549 ASSERT_SIN6IFSCOPE(sa
);
551 return (ntohs(SIN6(sa
)->sin6_addr
.s6_addr16
[1]));
555 * Copy a sockaddr_{in,in6} src to a dst storage and set scope ID into dst.
557 * To clear the scope ID, pass is a NULL pifscope. To set the scope ID, pass
558 * in a non-NULL pifscope with non-zero ifscope. Otherwise if pifscope is
559 * non-NULL and ifscope is IFSCOPE_NONE, the existing scope ID is left intact.
560 * In any case, the effective scope ID value is returned to the caller via
561 * pifscope, if it is non-NULL.
564 sa_copy(struct sockaddr
*src
, struct sockaddr_storage
*dst
,
565 unsigned int *pifscope
)
567 int af
= src
->sa_family
;
568 unsigned int ifscope
= (pifscope
!= NULL
) ? *pifscope
: IFSCOPE_NONE
;
570 VERIFY(af
== AF_INET
|| af
== AF_INET6
);
572 bzero(dst
, sizeof (*dst
));
575 bcopy(src
, dst
, sizeof (struct sockaddr_in
));
576 if (pifscope
== NULL
|| ifscope
!= IFSCOPE_NONE
)
577 sin_set_ifscope(SA(dst
), ifscope
);
579 bcopy(src
, dst
, sizeof (struct sockaddr_in6
));
580 if (pifscope
!= NULL
&&
581 IN6_IS_SCOPE_EMBED(&SIN6(dst
)->sin6_addr
)) {
582 unsigned int eifscope
;
584 * If the address contains the embedded scope ID,
585 * use that as the value for sin6_scope_id as long
586 * the caller doesn't insist on clearing it (by
587 * passing NULL) or setting it.
589 eifscope
= sin6_get_embedded_ifscope(SA(dst
));
590 if (eifscope
!= IFSCOPE_NONE
&& ifscope
== IFSCOPE_NONE
)
592 if (ifscope
!= IFSCOPE_NONE
) {
593 /* Set ifscope from pifscope or eifscope */
594 sin6_set_ifscope(SA(dst
), ifscope
);
596 /* If sin6_scope_id has a value, use that one */
597 ifscope
= sin6_get_ifscope(SA(dst
));
600 * If sin6_scope_id is set but the address doesn't
601 * contain the equivalent embedded value, set it.
603 if (ifscope
!= IFSCOPE_NONE
&& eifscope
!= ifscope
)
604 sin6_set_embedded_ifscope(SA(dst
), ifscope
);
605 } else if (pifscope
== NULL
|| ifscope
!= IFSCOPE_NONE
) {
606 sin6_set_ifscope(SA(dst
), ifscope
);
610 if (pifscope
!= NULL
) {
611 *pifscope
= (af
== AF_INET
) ? sin_get_ifscope(SA(dst
)) :
612 sin6_get_ifscope(SA(dst
));
619 * Copy a mask from src to a dst storage and set scope ID into dst.
621 static struct sockaddr
*
622 ma_copy(int af
, struct sockaddr
*src
, struct sockaddr_storage
*dst
,
623 unsigned int ifscope
)
625 VERIFY(af
== AF_INET
|| af
== AF_INET6
);
627 bzero(dst
, sizeof (*dst
));
628 rt_maskedcopy(src
, SA(dst
), src
);
631 * The length of the mask sockaddr would need to be adjusted
632 * to cover the additional {sin,sin6}_ifscope field; when ifscope
633 * is IFSCOPE_NONE, we'd end up clearing the scope ID field on
634 * the destination mask in addition to extending the length
635 * of the sockaddr, as a side effect. This is okay, as any
636 * trailing zeroes would be skipped by rn_addmask prior to
637 * inserting or looking up the mask in the mask tree.
640 SINIFSCOPE(dst
)->sin_scope_id
= ifscope
;
641 SINIFSCOPE(dst
)->sin_len
=
642 offsetof(struct sockaddr_inifscope
, sin_scope_id
) +
643 sizeof (SINIFSCOPE(dst
)->sin_scope_id
);
645 SIN6IFSCOPE(dst
)->sin6_scope_id
= ifscope
;
646 SIN6IFSCOPE(dst
)->sin6_len
=
647 offsetof(struct sockaddr_in6
, sin6_scope_id
) +
648 sizeof (SIN6IFSCOPE(dst
)->sin6_scope_id
);
655 * Trim trailing zeroes on a sockaddr and update its length.
657 static struct sockaddr
*
658 sa_trim(struct sockaddr
*sa
, int skip
)
660 caddr_t cp
, base
= (caddr_t
)sa
+ skip
;
662 if (sa
->sa_len
<= skip
)
665 for (cp
= base
+ (sa
->sa_len
- skip
); cp
> base
&& cp
[-1] == 0; )
668 sa
->sa_len
= (cp
- base
) + skip
;
669 if (sa
->sa_len
< skip
) {
670 /* Must not happen, and if so, panic */
671 panic("%s: broken logic (sa_len %d < skip %d )", __func__
,
674 } else if (sa
->sa_len
== skip
) {
675 /* If we end up with all zeroes, then there's no mask */
683 * Called by rtm_msg{1,2} routines to "scrub" socket address structures of
684 * kernel private information, so that clients of the routing socket will
685 * not be confused by the presence of the information, or the side effect of
686 * the increased length due to that. The source sockaddr is not modified;
687 * instead, the scrubbing happens on the destination sockaddr storage that
688 * is passed in by the caller.
691 * - removing embedded scope identifiers from network mask and destination
692 * IPv4 and IPv6 socket addresses
693 * - optionally removing global scope interface hardware addresses from
694 * link-layer interface addresses when the MAC framework check fails.
697 rtm_scrub(int type
, int idx
, struct sockaddr
*hint
, struct sockaddr
*sa
,
698 void *buf
, uint32_t buflen
, kauth_cred_t
*credp
)
700 struct sockaddr_storage
*ss
= (struct sockaddr_storage
*)buf
;
701 struct sockaddr
*ret
= sa
;
703 VERIFY(buf
!= NULL
&& buflen
>= sizeof (*ss
));
709 * If this is for an AF_INET/AF_INET6 destination address,
710 * call sa_copy() to clear the scope ID field.
712 if (sa
->sa_family
== AF_INET
&&
713 SINIFSCOPE(sa
)->sin_scope_id
!= IFSCOPE_NONE
) {
714 ret
= sa_copy(sa
, ss
, NULL
);
715 } else if (sa
->sa_family
== AF_INET6
&&
716 SIN6IFSCOPE(sa
)->sin6_scope_id
!= IFSCOPE_NONE
) {
717 ret
= sa_copy(sa
, ss
, NULL
);
724 * If this is for a mask, we can't tell whether or not there
725 * is an valid scope ID value, as the span of bytes between
726 * sa_len and the beginning of the mask (offset of sin_addr in
727 * the case of AF_INET, or sin6_addr for AF_INET6) may be
728 * filled with all-ones by rn_addmask(), and hence we cannot
729 * rely on sa_family. Because of this, we use the sa_family
730 * of the hint sockaddr (RTAX_{DST,IFA}) as indicator as to
731 * whether or not the mask is to be treated as one for AF_INET
732 * or AF_INET6. Clearing the scope ID field involves setting
733 * it to IFSCOPE_NONE followed by calling sa_trim() to trim
734 * trailing zeroes from the storage sockaddr, which reverses
735 * what was done earlier by ma_copy() on the source sockaddr.
738 ((af
= hint
->sa_family
) != AF_INET
&& af
!= AF_INET6
))
739 break; /* nothing to do */
741 skip
= (af
== AF_INET
) ?
742 offsetof(struct sockaddr_in
, sin_addr
) :
743 offsetof(struct sockaddr_in6
, sin6_addr
);
745 if (sa
->sa_len
> skip
&& sa
->sa_len
<= sizeof (*ss
)) {
746 bcopy(sa
, ss
, sa
->sa_len
);
748 * Don't use {sin,sin6}_set_ifscope() as sa_family
749 * and sa_len for the netmask might not be set to
750 * the corresponding expected values of the hint.
752 if (hint
->sa_family
== AF_INET
)
753 SINIFSCOPE(ss
)->sin_scope_id
= IFSCOPE_NONE
;
755 SIN6IFSCOPE(ss
)->sin6_scope_id
= IFSCOPE_NONE
;
756 ret
= sa_trim(SA(ss
), skip
);
759 * For AF_INET6 mask, set sa_len appropriately unless
760 * this is requested via systl_dumpentry(), in which
761 * case we return the raw value.
763 if (hint
->sa_family
== AF_INET6
&&
764 type
!= RTM_GET
&& type
!= RTM_GET2
)
765 SA(ret
)->sa_len
= sizeof (struct sockaddr_in6
);
770 if (sa
->sa_family
== AF_LINK
&& credp
) {
771 struct sockaddr_dl
*sdl
= SDL(buf
);
775 /* caller should handle worst case: SOCK_MAXADDRLEN */
776 VERIFY(buflen
>= sa
->sa_len
);
778 bcopy(sa
, sdl
, sa
->sa_len
);
779 bytes
= dlil_ifaddr_bytes(sdl
, &size
, credp
);
780 if (bytes
!= CONST_LLADDR(sdl
)) {
781 VERIFY(sdl
->sdl_alen
== size
);
782 bcopy(bytes
, LLADDR(sdl
), size
);
784 ret
= (struct sockaddr
*)sdl
;
796 * Callback leaf-matching routine for rn_matchaddr_args used
797 * for looking up an exact match for a scoped route entry.
800 rn_match_ifscope(struct radix_node
*rn
, void *arg
)
802 struct rtentry
*rt
= (struct rtentry
*)rn
;
803 struct matchleaf_arg
*ma
= arg
;
804 int af
= rt_key(rt
)->sa_family
;
806 if (!(rt
->rt_flags
& RTF_IFSCOPE
) || (af
!= AF_INET
&& af
!= AF_INET6
))
809 return (af
== AF_INET
?
810 (SINIFSCOPE(rt_key(rt
))->sin_scope_id
== ma
->ifscope
) :
811 (SIN6IFSCOPE(rt_key(rt
))->sin6_scope_id
== ma
->ifscope
));
815 * Atomically increment route generation counter
818 routegenid_update(void)
820 routegenid_inet_update();
822 routegenid_inet6_update();
827 routegenid_inet_update(void)
829 atomic_add_32(&route_genid_inet
, 1);
834 routegenid_inet6_update(void)
836 atomic_add_32(&route_genid_inet6
, 1);
841 * Packet routing routines.
844 rtalloc(struct route
*ro
)
850 rtalloc_scoped(struct route
*ro
, unsigned int ifscope
)
852 rtalloc_scoped_ign(ro
, 0, ifscope
);
856 rtalloc_ign_common_locked(struct route
*ro
, uint32_t ignore
,
857 unsigned int ifscope
)
861 if ((rt
= ro
->ro_rt
) != NULL
) {
863 if (rt
->rt_ifp
!= NULL
&& !ROUTE_UNUSABLE(ro
)) {
868 ROUTE_RELEASE_LOCKED(ro
); /* rnh_lock already held */
870 ro
->ro_rt
= rtalloc1_common_locked(&ro
->ro_dst
, 1, ignore
, ifscope
);
871 if (ro
->ro_rt
!= NULL
) {
872 RT_GENID_SYNC(ro
->ro_rt
);
873 RT_LOCK_ASSERT_NOTHELD(ro
->ro_rt
);
878 rtalloc_ign(struct route
*ro
, uint32_t ignore
)
880 lck_mtx_assert(rnh_lock
, LCK_MTX_ASSERT_NOTOWNED
);
881 lck_mtx_lock(rnh_lock
);
882 rtalloc_ign_common_locked(ro
, ignore
, IFSCOPE_NONE
);
883 lck_mtx_unlock(rnh_lock
);
887 rtalloc_scoped_ign(struct route
*ro
, uint32_t ignore
, unsigned int ifscope
)
889 lck_mtx_assert(rnh_lock
, LCK_MTX_ASSERT_NOTOWNED
);
890 lck_mtx_lock(rnh_lock
);
891 rtalloc_ign_common_locked(ro
, ignore
, ifscope
);
892 lck_mtx_unlock(rnh_lock
);
895 static struct rtentry
*
896 rtalloc1_locked(struct sockaddr
*dst
, int report
, uint32_t ignflags
)
898 return (rtalloc1_common_locked(dst
, report
, ignflags
, IFSCOPE_NONE
));
902 rtalloc1_scoped_locked(struct sockaddr
*dst
, int report
, uint32_t ignflags
,
903 unsigned int ifscope
)
905 return (rtalloc1_common_locked(dst
, report
, ignflags
, ifscope
));
909 * Look up the route that matches the address given
910 * Or, at least try.. Create a cloned route if needed.
912 static struct rtentry
*
913 rtalloc1_common_locked(struct sockaddr
*dst
, int report
, uint32_t ignflags
,
914 unsigned int ifscope
)
916 struct radix_node_head
*rnh
= rt_tables
[dst
->sa_family
];
917 struct rtentry
*rt
, *newrt
= NULL
;
918 struct rt_addrinfo info
;
920 int err
= 0, msgtype
= RTM_MISS
;
926 * Find the longest prefix or exact (in the scoped case) address match;
927 * callee adds a reference to entry and checks for root node as well
929 rt
= rt_lookup(FALSE
, dst
, NULL
, rnh
, ifscope
);
935 nflags
= rt
->rt_flags
& ~ignflags
;
937 if (report
&& (nflags
& (RTF_CLONING
| RTF_PRCLONING
))) {
939 * We are apparently adding (report = 0 in delete).
940 * If it requires that it be cloned, do so.
941 * (This implies it wasn't a HOST route.)
943 err
= rtrequest_locked(RTM_RESOLVE
, dst
, NULL
, NULL
, 0, &newrt
);
946 * If the cloning didn't succeed, maybe what we
947 * have from lookup above will do. Return that;
948 * no need to hold another reference since it's
956 * We cloned it; drop the original route found during lookup.
957 * The resulted cloned route (newrt) would now have an extra
958 * reference held during rtrequest.
963 * If the newly created cloned route is a direct host route
964 * then also check if it is to a router or not.
965 * If it is, then set the RTF_ROUTER flag on the host route
968 * XXX It is possible for the default route to be created post
969 * cloned route creation of router's IP.
970 * We can handle that corner case by special handing for RTM_ADD
973 if ((newrt
->rt_flags
& (RTF_HOST
| RTF_LLINFO
)) ==
974 (RTF_HOST
| RTF_LLINFO
)) {
975 struct rtentry
*defrt
= NULL
;
976 struct sockaddr_storage def_key
;
978 bzero(&def_key
, sizeof(def_key
));
979 def_key
.ss_len
= rt_key(newrt
)->sa_len
;
980 def_key
.ss_family
= rt_key(newrt
)->sa_family
;
982 defrt
= rtalloc1_scoped_locked((struct sockaddr
*)&def_key
,
983 0, 0, newrt
->rt_ifp
->if_index
);
986 if (equal(rt_key(newrt
), defrt
->rt_gateway
)) {
987 newrt
->rt_flags
|= RTF_ROUTER
;
989 rtfree_locked(defrt
);
993 if ((rt
= newrt
) && (rt
->rt_flags
& RTF_XRESOLVE
)) {
995 * If the new route specifies it be
996 * externally resolved, then go do that.
998 msgtype
= RTM_RESOLVE
;
1006 * Either we hit the root or couldn't find any match,
1007 * Which basically means "cant get there from here"
1009 rtstat
.rts_unreach
++;
1013 * If required, report the failure to the supervising
1015 * For a delete, this is not an error. (report == 0)
1017 bzero((caddr_t
)&info
, sizeof(info
));
1018 info
.rti_info
[RTAX_DST
] = dst
;
1019 rt_missmsg(msgtype
, &info
, 0, err
);
1026 rtalloc1(struct sockaddr
*dst
, int report
, uint32_t ignflags
)
1028 struct rtentry
*entry
;
1029 lck_mtx_assert(rnh_lock
, LCK_MTX_ASSERT_NOTOWNED
);
1030 lck_mtx_lock(rnh_lock
);
1031 entry
= rtalloc1_locked(dst
, report
, ignflags
);
1032 lck_mtx_unlock(rnh_lock
);
1037 rtalloc1_scoped(struct sockaddr
*dst
, int report
, uint32_t ignflags
,
1038 unsigned int ifscope
)
1040 struct rtentry
*entry
;
1041 lck_mtx_assert(rnh_lock
, LCK_MTX_ASSERT_NOTOWNED
);
1042 lck_mtx_lock(rnh_lock
);
1043 entry
= rtalloc1_scoped_locked(dst
, report
, ignflags
, ifscope
);
1044 lck_mtx_unlock(rnh_lock
);
1049 * Remove a reference count from an rtentry.
1050 * If the count gets low enough, take it out of the routing table
1053 rtfree_locked(struct rtentry
*rt
)
1055 rtfree_common(rt
, TRUE
);
1059 rtfree_common(struct rtentry
*rt
, boolean_t locked
)
1061 struct radix_node_head
*rnh
;
1063 lck_mtx_assert(rnh_lock
, locked
?
1064 LCK_MTX_ASSERT_OWNED
: LCK_MTX_ASSERT_NOTOWNED
);
1067 * Atomically decrement the reference count and if it reaches 0,
1068 * and there is a close function defined, call the close function.
1071 if (rtunref(rt
) > 0) {
1077 * To avoid violating lock ordering, we must drop rt_lock before
1078 * trying to acquire the global rnh_lock. If we are called with
1079 * rnh_lock held, then we already have exclusive access; otherwise
1080 * we do the lock dance.
1084 * Note that we check it again below after grabbing rnh_lock,
1085 * since it is possible that another thread doing a lookup wins
1086 * the race, grabs the rnh_lock first, and bumps up reference
1087 * count in which case the route should be left alone as it is
1088 * still in use. It's also possible that another thread frees
1089 * the route after we drop rt_lock; to prevent the route from
1090 * being freed, we hold an extra reference.
1092 RT_ADDREF_LOCKED(rt
);
1094 lck_mtx_lock(rnh_lock
);
1096 if (rtunref(rt
) > 0) {
1097 /* We've lost the race, so abort */
1104 * We may be blocked on other lock(s) as part of freeing
1105 * the entry below, so convert from spin to full mutex.
1107 RT_CONVERT_LOCK(rt
);
1109 lck_mtx_assert(rnh_lock
, LCK_MTX_ASSERT_OWNED
);
1111 /* Negative refcnt must never happen */
1112 if (rt
->rt_refcnt
!= 0) {
1113 panic("rt %p invalid refcnt %d", rt
, rt
->rt_refcnt
);
1116 /* Idle refcnt must have been dropped during rtunref() */
1117 VERIFY(!(rt
->rt_flags
& RTF_IFREF
));
1120 * find the tree for that address family
1121 * Note: in the case of igmp packets, there might not be an rnh
1123 rnh
= rt_tables
[rt_key(rt
)->sa_family
];
1126 * On last reference give the "close method" a chance to cleanup
1127 * private state. This also permits (for IPv4 and IPv6) a chance
1128 * to decide if the routing table entry should be purged immediately
1129 * or at a later time. When an immediate purge is to happen the
1130 * close routine typically issues RTM_DELETE which clears the RTF_UP
1131 * flag on the entry so that the code below reclaims the storage.
1133 if (rnh
!= NULL
&& rnh
->rnh_close
!= NULL
)
1134 rnh
->rnh_close((struct radix_node
*)rt
, rnh
);
1137 * If we are no longer "up" (and ref == 0) then we can free the
1138 * resources associated with the route.
1140 if (!(rt
->rt_flags
& RTF_UP
)) {
1141 struct rtentry
*rt_parent
;
1142 struct ifaddr
*rt_ifa
;
1144 if (rt
->rt_nodes
->rn_flags
& (RNF_ACTIVE
| RNF_ROOT
)) {
1145 panic("rt %p freed while in radix tree\n", rt
);
1149 * the rtentry must have been removed from the routing table
1150 * so it is represented in rttrash; remove that now.
1152 (void) OSDecrementAtomic(&rttrash
);
1153 if (rte_debug
& RTD_DEBUG
) {
1154 TAILQ_REMOVE(&rttrash_head
, (struct rtentry_dbg
*)rt
,
1159 * release references on items we hold them on..
1160 * e.g other routes and ifaddrs.
1162 if ((rt_parent
= rt
->rt_parent
) != NULL
)
1163 rt
->rt_parent
= NULL
;
1165 if ((rt_ifa
= rt
->rt_ifa
) != NULL
)
1169 * Now free any attached link-layer info.
1171 if (rt
->rt_llinfo
!= NULL
) {
1172 if (rt
->rt_llinfo_free
!= NULL
)
1173 (*rt
->rt_llinfo_free
)(rt
->rt_llinfo
);
1175 R_Free(rt
->rt_llinfo
);
1176 rt
->rt_llinfo
= NULL
;
1180 * Route is no longer in the tree and refcnt is 0;
1181 * we have exclusive access, so destroy it.
1185 if (rt_parent
!= NULL
)
1186 rtfree_locked(rt_parent
);
1192 * The key is separately alloc'd so free it (see rt_setgate()).
1193 * This also frees the gateway, as they are always malloc'd
1199 * Free any statistics that may have been allocated
1201 nstat_route_detach(rt
);
1204 * and the rtentry itself of course
1206 rte_lock_destroy(rt
);
1210 * The "close method" has been called, but the route is
1211 * still in the radix tree with zero refcnt, i.e. "up"
1212 * and in the cached state.
1218 lck_mtx_unlock(rnh_lock
);
1222 rtfree(struct rtentry
*rt
)
1224 rtfree_common(rt
, FALSE
);
1228 * Decrements the refcount but does not free the route when
1229 * the refcount reaches zero. Unless you have really good reason,
1230 * use rtfree not rtunref.
1233 rtunref(struct rtentry
*p
)
1235 RT_LOCK_ASSERT_HELD(p
);
1237 if (p
->rt_refcnt
== 0) {
1238 panic("%s(%p) bad refcnt\n", __func__
, p
);
1240 } else if (--p
->rt_refcnt
== 0) {
1242 * Release any idle reference count held on the interface;
1243 * if the route is eligible, still UP and the refcnt becomes
1244 * non-zero at some point in future before it is purged from
1245 * the routing table, rt_set_idleref() will undo this.
1247 rt_clear_idleref(p
);
1250 if (rte_debug
& RTD_DEBUG
)
1251 rtunref_audit((struct rtentry_dbg
*)p
);
1253 /* Return new value */
1254 return (p
->rt_refcnt
);
1258 rtunref_audit(struct rtentry_dbg
*rte
)
1262 if (rte
->rtd_inuse
!= RTD_INUSE
) {
1263 panic("rtunref: on freed rte=%p\n", rte
);
1266 idx
= atomic_add_16_ov(&rte
->rtd_refrele_cnt
, 1) % CTRACE_HIST_SIZE
;
1267 if (rte_debug
& RTD_TRACE
)
1268 ctrace_record(&rte
->rtd_refrele
[idx
]);
1272 * Add a reference count from an rtentry.
1275 rtref(struct rtentry
*p
)
1277 RT_LOCK_ASSERT_HELD(p
);
1279 if (++p
->rt_refcnt
== 0) {
1280 panic("%s(%p) bad refcnt\n", __func__
, p
);
1282 } else if (p
->rt_refcnt
== 1) {
1284 * Hold an idle reference count on the interface,
1285 * if the route is eligible for it.
1290 if (rte_debug
& RTD_DEBUG
)
1291 rtref_audit((struct rtentry_dbg
*)p
);
1295 rtref_audit(struct rtentry_dbg
*rte
)
1299 if (rte
->rtd_inuse
!= RTD_INUSE
) {
1300 panic("rtref_audit: on freed rte=%p\n", rte
);
1303 idx
= atomic_add_16_ov(&rte
->rtd_refhold_cnt
, 1) % CTRACE_HIST_SIZE
;
1304 if (rte_debug
& RTD_TRACE
)
1305 ctrace_record(&rte
->rtd_refhold
[idx
]);
1309 rtsetifa(struct rtentry
*rt
, struct ifaddr
*ifa
)
1311 lck_mtx_assert(rnh_lock
, LCK_MTX_ASSERT_OWNED
);
1313 RT_LOCK_ASSERT_HELD(rt
);
1315 if (rt
->rt_ifa
== ifa
)
1318 /* Become a regular mutex, just in case */
1319 RT_CONVERT_LOCK(rt
);
1321 /* Release the old ifa */
1323 IFA_REMREF(rt
->rt_ifa
);
1328 /* Take a reference to the ifa */
1330 IFA_ADDREF(rt
->rt_ifa
);
1334 * Force a routing table entry to the specified
1335 * destination to go through the given gateway.
1336 * Normally called as a result of a routing redirect
1337 * message from the network layer.
1340 rtredirect(struct ifnet
*ifp
, struct sockaddr
*dst
, struct sockaddr
*gateway
,
1341 struct sockaddr
*netmask
, int flags
, struct sockaddr
*src
,
1342 struct rtentry
**rtp
)
1344 struct rtentry
*rt
= NULL
;
1347 struct rt_addrinfo info
;
1348 struct ifaddr
*ifa
= NULL
;
1349 unsigned int ifscope
= (ifp
!= NULL
) ? ifp
->if_index
: IFSCOPE_NONE
;
1350 struct sockaddr_storage ss
;
1351 int af
= src
->sa_family
;
1353 lck_mtx_assert(rnh_lock
, LCK_MTX_ASSERT_NOTOWNED
);
1354 lck_mtx_lock(rnh_lock
);
1357 * Transform src into the internal routing table form for
1358 * comparison against rt_gateway below.
1361 if ((af
== AF_INET
&& ip_doscopedroute
) ||
1362 (af
== AF_INET6
&& ip6_doscopedroute
))
1364 if (af
== AF_INET
&& ip_doscopedroute
)
1366 src
= sa_copy(src
, &ss
, &ifscope
);
1369 * Verify the gateway is directly reachable; if scoped routing
1370 * is enabled, verify that it is reachable from the interface
1371 * where the ICMP redirect arrived on.
1373 if ((ifa
= ifa_ifwithnet_scoped(gateway
, ifscope
)) == NULL
) {
1374 error
= ENETUNREACH
;
1378 /* Lookup route to the destination (from the original IP header) */
1379 rt
= rtalloc1_scoped_locked(dst
, 0, RTF_CLONING
|RTF_PRCLONING
, ifscope
);
1384 * If the redirect isn't from our current router for this dst,
1385 * it's either old or wrong. If it redirects us to ourselves,
1386 * we have a routing loop, perhaps as a result of an interface
1387 * going down recently. Holding rnh_lock here prevents the
1388 * possibility of rt_ifa/ifa's ifa_addr from changing (e.g.
1389 * in_ifinit), so okay to access ifa_addr without locking.
1391 if (!(flags
& RTF_DONE
) && rt
!= NULL
&&
1392 (!equal(src
, rt
->rt_gateway
) || !equal(rt
->rt_ifa
->ifa_addr
,
1397 if ((ifa
= ifa_ifwithaddr(gateway
))) {
1400 error
= EHOSTUNREACH
;
1416 * Create a new entry if we just got back a wildcard entry
1417 * or the the lookup failed. This is necessary for hosts
1418 * which use routing redirects generated by smart gateways
1419 * to dynamically build the routing tables.
1421 if ((rt
== NULL
) || (rt_mask(rt
) != NULL
&& rt_mask(rt
)->sa_len
< 2))
1424 * Don't listen to the redirect if it's
1425 * for a route to an interface.
1427 RT_LOCK_ASSERT_HELD(rt
);
1428 if (rt
->rt_flags
& RTF_GATEWAY
) {
1429 if (((rt
->rt_flags
& RTF_HOST
) == 0) && (flags
& RTF_HOST
)) {
1431 * Changing from route to net => route to host.
1432 * Create new route, rather than smashing route
1433 * to net; similar to cloned routes, the newly
1434 * created host route is scoped as well.
1439 flags
|= RTF_GATEWAY
| RTF_DYNAMIC
;
1440 error
= rtrequest_scoped_locked(RTM_ADD
, dst
,
1441 gateway
, netmask
, flags
, NULL
, ifscope
);
1442 stat
= &rtstat
.rts_dynamic
;
1445 * Smash the current notion of the gateway to
1446 * this destination. Should check about netmask!!!
1448 rt
->rt_flags
|= RTF_MODIFIED
;
1449 flags
|= RTF_MODIFIED
;
1450 stat
= &rtstat
.rts_newgateway
;
1452 * add the key and gateway (in one malloc'd chunk).
1454 error
= rt_setgate(rt
, rt_key(rt
), gateway
);
1459 error
= EHOSTUNREACH
;
1463 RT_LOCK_ASSERT_NOTHELD(rt
);
1471 rtstat
.rts_badredirect
++;
1477 routegenid_inet_update();
1479 else if (af
== AF_INET6
)
1480 routegenid_inet6_update();
1483 lck_mtx_unlock(rnh_lock
);
1484 bzero((caddr_t
)&info
, sizeof(info
));
1485 info
.rti_info
[RTAX_DST
] = dst
;
1486 info
.rti_info
[RTAX_GATEWAY
] = gateway
;
1487 info
.rti_info
[RTAX_NETMASK
] = netmask
;
1488 info
.rti_info
[RTAX_AUTHOR
] = src
;
1489 rt_missmsg(RTM_REDIRECT
, &info
, flags
, error
);
1493 * Routing table ioctl interface.
1496 rtioctl(unsigned long req
, caddr_t data
, struct proc
*p
)
1498 #pragma unused(p, req, data)
1505 const struct sockaddr
*dst
,
1506 const struct sockaddr
*gateway
)
1510 lck_mtx_lock(rnh_lock
);
1511 ifa
= ifa_ifwithroute_locked(flags
, dst
, gateway
);
1512 lck_mtx_unlock(rnh_lock
);
1518 ifa_ifwithroute_locked(int flags
, const struct sockaddr
*dst
,
1519 const struct sockaddr
*gateway
)
1521 return (ifa_ifwithroute_common_locked((flags
& ~RTF_IFSCOPE
), dst
,
1522 gateway
, IFSCOPE_NONE
));
1526 ifa_ifwithroute_scoped_locked(int flags
, const struct sockaddr
*dst
,
1527 const struct sockaddr
*gateway
, unsigned int ifscope
)
1529 if (ifscope
!= IFSCOPE_NONE
)
1530 flags
|= RTF_IFSCOPE
;
1532 flags
&= ~RTF_IFSCOPE
;
1534 return (ifa_ifwithroute_common_locked(flags
, dst
, gateway
, ifscope
));
1537 static struct ifaddr
*
1538 ifa_ifwithroute_common_locked(int flags
, const struct sockaddr
*dst
,
1539 const struct sockaddr
*gw
, unsigned int ifscope
)
1541 struct ifaddr
*ifa
= NULL
;
1542 struct rtentry
*rt
= NULL
;
1543 struct sockaddr_storage dst_ss
, gw_ss
;
1545 lck_mtx_assert(rnh_lock
, LCK_MTX_ASSERT_OWNED
);
1548 * Just in case the sockaddr passed in by the caller
1549 * contains a scope ID, make sure to clear it since
1550 * interface addresses aren't scoped.
1554 ((dst
->sa_family
== AF_INET
&& ip_doscopedroute
) ||
1555 (dst
->sa_family
== AF_INET6
&& ip6_doscopedroute
)))
1557 if (dst
!= NULL
&& dst
->sa_family
== AF_INET
&& ip_doscopedroute
)
1559 dst
= sa_copy(SA((uintptr_t)dst
), &dst_ss
, NULL
);
1563 ((gw
->sa_family
== AF_INET
&& ip_doscopedroute
) ||
1564 (gw
->sa_family
== AF_INET6
&& ip6_doscopedroute
)))
1566 if (gw
!= NULL
&& gw
->sa_family
== AF_INET
&& ip_doscopedroute
)
1568 gw
= sa_copy(SA((uintptr_t)gw
), &gw_ss
, NULL
);
1570 if (!(flags
& RTF_GATEWAY
)) {
1572 * If we are adding a route to an interface,
1573 * and the interface is a pt to pt link
1574 * we should search for the destination
1575 * as our clue to the interface. Otherwise
1576 * we can use the local address.
1578 if (flags
& RTF_HOST
) {
1579 ifa
= ifa_ifwithdstaddr(dst
);
1582 ifa
= ifa_ifwithaddr_scoped(gw
, ifscope
);
1585 * If we are adding a route to a remote net
1586 * or host, the gateway may still be on the
1587 * other end of a pt to pt link.
1589 ifa
= ifa_ifwithdstaddr(gw
);
1592 ifa
= ifa_ifwithnet_scoped(gw
, ifscope
);
1594 /* Workaround to avoid gcc warning regarding const variable */
1595 rt
= rtalloc1_scoped_locked((struct sockaddr
*)(size_t)dst
,
1601 /* Become a regular mutex */
1602 RT_CONVERT_LOCK(rt
);
1605 RT_REMREF_LOCKED(rt
);
1611 * Holding rnh_lock here prevents the possibility of ifa from
1612 * changing (e.g. in_ifinit), so it is safe to access its
1613 * ifa_addr (here and down below) without locking.
1615 if (ifa
!= NULL
&& ifa
->ifa_addr
->sa_family
!= dst
->sa_family
) {
1616 struct ifaddr
*newifa
;
1617 /* Callee adds reference to newifa upon success */
1618 newifa
= ifaof_ifpforaddr(dst
, ifa
->ifa_ifp
);
1619 if (newifa
!= NULL
) {
1625 * If we are adding a gateway, it is quite possible that the
1626 * routing table has a static entry in place for the gateway,
1627 * that may not agree with info garnered from the interfaces.
1628 * The routing table should carry more precedence than the
1629 * interfaces in this matter. Must be careful not to stomp
1630 * on new entries from rtinit, hence (ifa->ifa_addr != gw).
1633 !equal(ifa
->ifa_addr
, (struct sockaddr
*)(size_t)gw
)) &&
1634 (rt
= rtalloc1_scoped_locked((struct sockaddr
*)(size_t)gw
,
1635 0, 0, ifscope
)) != NULL
) {
1641 /* Become a regular mutex */
1642 RT_CONVERT_LOCK(rt
);
1645 RT_REMREF_LOCKED(rt
);
1649 * If an interface scope was specified, the interface index of
1650 * the found ifaddr must be equivalent to that of the scope;
1651 * otherwise there is no match.
1653 if ((flags
& RTF_IFSCOPE
) &&
1654 ifa
!= NULL
&& ifa
->ifa_ifp
->if_index
!= ifscope
) {
1662 static int rt_fixdelete(struct radix_node
*, void *);
1663 static int rt_fixchange(struct radix_node
*, void *);
1666 struct rtentry
*rt0
;
1667 struct radix_node_head
*rnh
;
1671 rtrequest_locked(int req
, struct sockaddr
*dst
, struct sockaddr
*gateway
,
1672 struct sockaddr
*netmask
, int flags
, struct rtentry
**ret_nrt
)
1674 return (rtrequest_common_locked(req
, dst
, gateway
, netmask
,
1675 (flags
& ~RTF_IFSCOPE
), ret_nrt
, IFSCOPE_NONE
));
1679 rtrequest_scoped_locked(int req
, struct sockaddr
*dst
,
1680 struct sockaddr
*gateway
, struct sockaddr
*netmask
, int flags
,
1681 struct rtentry
**ret_nrt
, unsigned int ifscope
)
1683 if (ifscope
!= IFSCOPE_NONE
)
1684 flags
|= RTF_IFSCOPE
;
1686 flags
&= ~RTF_IFSCOPE
;
1688 return (rtrequest_common_locked(req
, dst
, gateway
, netmask
,
1689 flags
, ret_nrt
, ifscope
));
1693 * Do appropriate manipulations of a routing tree given all the bits of
1696 * Storing the scope ID in the radix key is an internal job that should be
1697 * left to routines in this module. Callers should specify the scope value
1698 * to the "scoped" variants of route routines instead of manipulating the
1699 * key itself. This is typically done when creating a scoped route, e.g.
1700 * rtrequest(RTM_ADD). Once such a route is created and marked with the
1701 * RTF_IFSCOPE flag, callers can simply use its rt_key(rt) to clone it
1702 * (RTM_RESOLVE) or to remove it (RTM_DELETE). An exception to this is
1703 * during certain routing socket operations where the search key might be
1704 * derived from the routing message itself, in which case the caller must
1705 * specify the destination address and scope value for RTM_ADD/RTM_DELETE.
1708 rtrequest_common_locked(int req
, struct sockaddr
*dst0
,
1709 struct sockaddr
*gateway
, struct sockaddr
*netmask
, int flags
,
1710 struct rtentry
**ret_nrt
, unsigned int ifscope
)
1714 struct radix_node
*rn
;
1715 struct radix_node_head
*rnh
;
1716 struct ifaddr
*ifa
= NULL
;
1717 struct sockaddr
*ndst
, *dst
= dst0
;
1718 struct sockaddr_storage ss
, mask
;
1719 struct timeval caltime
;
1720 int af
= dst
->sa_family
;
1721 void (*ifa_rtrequest
)(int, struct rtentry
*, struct sockaddr
*);
1723 #define senderr(x) { error = x; goto bad; }
1725 lck_mtx_assert(rnh_lock
, LCK_MTX_ASSERT_OWNED
);
1727 * Find the correct routing tree to use for this Address Family
1729 if ((rnh
= rt_tables
[af
]) == NULL
)
1732 * If we are adding a host route then we don't want to put
1733 * a netmask in the tree
1735 if (flags
& RTF_HOST
)
1739 * If Scoped Routing is enabled, use a local copy of the destination
1740 * address to store the scope ID into. This logic is repeated below
1741 * in the RTM_RESOLVE handler since the caller does not normally
1742 * specify such a flag during a resolve, as well as for the handling
1743 * of IPv4 link-local address; instead, it passes in the route used for
1744 * cloning for which the scope info is derived from. Note also that
1745 * in the case of RTM_DELETE, the address passed in by the caller
1746 * might already contain the scope ID info when it is the key itself,
1747 * thus making RTF_IFSCOPE unnecessary; one instance where it is
1748 * explicitly set is inside route_output() as part of handling a
1749 * routing socket request.
1752 if (req
!= RTM_RESOLVE
&&
1753 ((af
== AF_INET
&& ip_doscopedroute
) ||
1754 (af
== AF_INET6
&& ip6_doscopedroute
))) {
1756 if (req
!= RTM_RESOLVE
&& af
== AF_INET
&& ip_doscopedroute
) {
1758 /* Transform dst into the internal routing table form */
1759 dst
= sa_copy(dst
, &ss
, &ifscope
);
1761 /* Transform netmask into the internal routing table form */
1762 if (netmask
!= NULL
)
1763 netmask
= ma_copy(af
, netmask
, &mask
, ifscope
);
1765 if (ifscope
!= IFSCOPE_NONE
)
1766 flags
|= RTF_IFSCOPE
;
1768 if ((flags
& RTF_IFSCOPE
) && (af
!= AF_INET
&& af
!= AF_INET6
))
1772 if ((af
== AF_INET
&& !ip_doscopedroute
) ||
1773 (af
== AF_INET6
&& !ip6_doscopedroute
))
1775 if (af
== AF_INET
&& !ip_doscopedroute
)
1777 ifscope
= IFSCOPE_NONE
;
1780 if (ifscope
== IFSCOPE_NONE
)
1781 flags
&= ~RTF_IFSCOPE
;
1785 struct rtentry
*gwrt
= NULL
;
1787 * Remove the item from the tree and return it.
1788 * Complain if it is not there and do no more processing.
1790 if ((rn
= rnh
->rnh_deladdr(dst
, netmask
, rnh
)) == NULL
)
1792 if (rn
->rn_flags
& (RNF_ACTIVE
| RNF_ROOT
)) {
1793 panic("rtrequest delete");
1796 rt
= (struct rtentry
*)rn
;
1799 rt
->rt_flags
&= ~RTF_UP
;
1801 * Release any idle reference count held on the interface
1802 * as this route is no longer externally visible.
1804 rt_clear_idleref(rt
);
1806 * Take an extra reference to handle the deletion of a route
1807 * entry whose reference count is already 0; e.g. an expiring
1808 * cloned route entry or an entry that was added to the table
1809 * with 0 reference. If the caller is interested in this route,
1810 * we will return it with the reference intact. Otherwise we
1811 * will decrement the reference via rtfree_locked() and then
1812 * possibly deallocate it.
1814 RT_ADDREF_LOCKED(rt
);
1817 * For consistency, in case the caller didn't set the flag.
1819 rt
->rt_flags
|= RTF_CONDEMNED
;
1822 * Clear RTF_ROUTER if it's set.
1824 if (rt
->rt_flags
& RTF_ROUTER
) {
1825 VERIFY(rt
->rt_flags
& RTF_HOST
);
1826 rt
->rt_flags
&= ~RTF_ROUTER
;
1830 * Now search what's left of the subtree for any cloned
1831 * routes which might have been formed from this node.
1833 if ((rt
->rt_flags
& (RTF_CLONING
| RTF_PRCLONING
)) &&
1836 rnh
->rnh_walktree_from(rnh
, dst
, rt_mask(rt
),
1842 * Remove any external references we may have.
1844 if ((gwrt
= rt
->rt_gwroute
) != NULL
)
1845 rt
->rt_gwroute
= NULL
;
1848 * give the protocol a chance to keep things in sync.
1850 if ((ifa
= rt
->rt_ifa
) != NULL
) {
1852 ifa_rtrequest
= ifa
->ifa_rtrequest
;
1854 if (ifa_rtrequest
!= NULL
)
1855 ifa_rtrequest(RTM_DELETE
, rt
, NULL
);
1856 /* keep reference on rt_ifa */
1861 * one more rtentry floating around that is not
1862 * linked to the routing table.
1864 (void) OSIncrementAtomic(&rttrash
);
1865 if (rte_debug
& RTD_DEBUG
) {
1866 TAILQ_INSERT_TAIL(&rttrash_head
,
1867 (struct rtentry_dbg
*)rt
, rtd_trash_link
);
1871 * If this is the (non-scoped) default route, clear
1872 * the interface index used for the primary ifscope.
1874 if (rt_primary_default(rt
, rt_key(rt
))) {
1875 set_primary_ifscope(rt_key(rt
)->sa_family
,
1882 * This might result in another rtentry being freed if
1883 * we held its last reference. Do this after the rtentry
1884 * lock is dropped above, as it could lead to the same
1885 * lock being acquired if gwrt is a clone of rt.
1888 rtfree_locked(gwrt
);
1891 * If the caller wants it, then it can have it,
1892 * but it's up to it to free the rtentry as we won't be
1895 if (ret_nrt
!= NULL
) {
1896 /* Return the route to caller with reference intact */
1899 /* Dereference or deallocate the route */
1903 routegenid_inet_update();
1905 else if (af
== AF_INET6
)
1906 routegenid_inet6_update();
1911 if (ret_nrt
== NULL
|| (rt
= *ret_nrt
) == NULL
)
1914 * According to the UNIX conformance tests, we need to return
1915 * ENETUNREACH when the parent route is RTF_REJECT.
1916 * However, there isn't any point in cloning RTF_REJECT
1917 * routes, so we immediately return an error.
1919 if (rt
->rt_flags
& RTF_REJECT
) {
1920 if (rt
->rt_flags
& RTF_HOST
) {
1921 senderr(EHOSTUNREACH
);
1923 senderr(ENETUNREACH
);
1927 * If cloning, we have the parent route given by the caller
1928 * and will use its rt_gateway, rt_rmx as part of the cloning
1929 * process below. Since rnh_lock is held at this point, the
1930 * parent's rt_ifa and rt_gateway will not change, and its
1931 * relevant rt_flags will not change as well. The only thing
1932 * that could change are the metrics, and thus we hold the
1933 * parent route's rt_lock later on during the actual copying
1938 flags
= rt
->rt_flags
&
1939 ~(RTF_CLONING
| RTF_PRCLONING
| RTF_STATIC
);
1940 flags
|= RTF_WASCLONED
;
1941 gateway
= rt
->rt_gateway
;
1942 if ((netmask
= rt
->rt_genmask
) == NULL
)
1946 if ((af
!= AF_INET
&& af
!= AF_INET6
) ||
1947 (af
== AF_INET
&& !ip_doscopedroute
) ||
1948 (af
== AF_INET6
&& !ip6_doscopedroute
))
1950 if (af
!= AF_INET
|| !ip_doscopedroute
)
1955 * When scoped routing is enabled, cloned entries are
1956 * always scoped according to the interface portion of
1957 * the parent route. The exception to this are IPv4
1958 * link local addresses, or those routes that are cloned
1959 * from a RTF_PROXY route. For the latter, the clone
1960 * gets to keep the RTF_PROXY flag.
1962 if ((af
== AF_INET
&&
1963 IN_LINKLOCAL(ntohl(SIN(dst
)->sin_addr
.s_addr
))) ||
1964 (rt
->rt_flags
& RTF_PROXY
)) {
1965 ifscope
= IFSCOPE_NONE
;
1966 flags
&= ~RTF_IFSCOPE
;
1968 * These types of cloned routes aren't currently
1969 * eligible for idle interface reference counting.
1971 flags
|= RTF_NOIFREF
;
1973 if (flags
& RTF_IFSCOPE
) {
1974 ifscope
= (af
== AF_INET
) ?
1975 sin_get_ifscope(rt_key(rt
)) :
1976 sin6_get_ifscope(rt_key(rt
));
1978 ifscope
= rt
->rt_ifp
->if_index
;
1979 flags
|= RTF_IFSCOPE
;
1981 VERIFY(ifscope
!= IFSCOPE_NONE
);
1985 * Transform dst into the internal routing table form,
1986 * clearing out the scope ID field if ifscope isn't set.
1988 dst
= sa_copy(dst
, &ss
, (ifscope
== IFSCOPE_NONE
) ?
1991 /* Transform netmask into the internal routing table form */
1992 if (netmask
!= NULL
)
1993 netmask
= ma_copy(af
, netmask
, &mask
, ifscope
);
1998 if ((flags
& RTF_GATEWAY
) && !gateway
) {
1999 panic("rtrequest: RTF_GATEWAY but no gateway");
2002 if (flags
& RTF_IFSCOPE
) {
2003 ifa
= ifa_ifwithroute_scoped_locked(flags
, dst0
,
2006 ifa
= ifa_ifwithroute_locked(flags
, dst0
, gateway
);
2009 senderr(ENETUNREACH
);
2011 if ((rt
= rte_alloc()) == NULL
)
2013 Bzero(rt
, sizeof(*rt
));
2015 getmicrotime(&caltime
);
2016 rt
->base_calendartime
= caltime
.tv_sec
;
2017 rt
->base_uptime
= net_uptime();
2019 rt
->rt_flags
= RTF_UP
| flags
;
2022 * Point the generation ID to the tree's.
2026 rt
->rt_tree_genid
= &route_genid_inet
;
2030 rt
->rt_tree_genid
= &route_genid_inet6
;
2038 * Add the gateway. Possibly re-malloc-ing the storage for it
2039 * also add the rt_gwroute if possible.
2041 if ((error
= rt_setgate(rt
, dst
, gateway
)) != 0) {
2044 nstat_route_detach(rt
);
2045 rte_lock_destroy(rt
);
2051 * point to the (possibly newly malloc'd) dest address.
2056 * make sure it contains the value we want (masked if needed).
2059 rt_maskedcopy(dst
, ndst
, netmask
);
2061 Bcopy(dst
, ndst
, dst
->sa_len
);
2064 * Note that we now have a reference to the ifa.
2065 * This moved from below so that rnh->rnh_addaddr() can
2066 * examine the ifa and ifa->ifa_ifp if it so desires.
2069 rt
->rt_ifp
= rt
->rt_ifa
->ifa_ifp
;
2071 /* XXX mtu manipulation will be done in rnh_addaddr -- itojun */
2073 rn
= rnh
->rnh_addaddr((caddr_t
)ndst
, (caddr_t
)netmask
,
2076 struct rtentry
*rt2
;
2078 * Uh-oh, we already have one of these in the tree.
2079 * We do a special hack: if the route that's already
2080 * there was generated by the protocol-cloning
2081 * mechanism, then we just blow it away and retry
2082 * the insertion of the new one.
2084 if (flags
& RTF_IFSCOPE
) {
2085 rt2
= rtalloc1_scoped_locked(dst0
, 0,
2086 RTF_CLONING
| RTF_PRCLONING
, ifscope
);
2088 rt2
= rtalloc1_locked(dst
, 0,
2089 RTF_CLONING
| RTF_PRCLONING
);
2091 if (rt2
&& rt2
->rt_parent
) {
2093 * rnh_lock is held here, so rt_key and
2094 * rt_gateway of rt2 will not change.
2096 (void) rtrequest_locked(RTM_DELETE
, rt_key(rt2
),
2097 rt2
->rt_gateway
, rt_mask(rt2
),
2100 rn
= rnh
->rnh_addaddr((caddr_t
)ndst
,
2101 (caddr_t
)netmask
, rnh
, rt
->rt_nodes
);
2103 /* undo the extra ref we got */
2109 * If it still failed to go into the tree,
2110 * then un-make it (this should be a function)
2113 /* Clear gateway route */
2114 rt_set_gwroute(rt
, rt_key(rt
), NULL
);
2116 IFA_REMREF(rt
->rt_ifa
);
2121 nstat_route_detach(rt
);
2122 rte_lock_destroy(rt
);
2127 rt
->rt_parent
= NULL
;
2130 * If we got here from RESOLVE, then we are cloning so clone
2131 * the rest, and note that we are a clone (and increment the
2132 * parent's references). rnh_lock is still held, which prevents
2133 * a lookup from returning the newly-created route. Hence
2134 * holding and releasing the parent's rt_lock while still
2135 * holding the route's rt_lock is safe since the new route
2136 * is not yet externally visible.
2138 if (req
== RTM_RESOLVE
) {
2139 RT_LOCK_SPIN(*ret_nrt
);
2140 VERIFY((*ret_nrt
)->rt_expire
== 0 ||
2141 (*ret_nrt
)->rt_rmx
.rmx_expire
!= 0);
2142 VERIFY((*ret_nrt
)->rt_expire
!= 0 ||
2143 (*ret_nrt
)->rt_rmx
.rmx_expire
== 0);
2144 rt
->rt_rmx
= (*ret_nrt
)->rt_rmx
;
2145 rt_setexpire(rt
, (*ret_nrt
)->rt_expire
);
2146 if ((*ret_nrt
)->rt_flags
&
2147 (RTF_CLONING
| RTF_PRCLONING
)) {
2148 rt
->rt_parent
= (*ret_nrt
);
2149 RT_ADDREF_LOCKED(*ret_nrt
);
2151 RT_UNLOCK(*ret_nrt
);
2155 * if this protocol has something to add to this then
2156 * allow it to do that as well.
2159 ifa_rtrequest
= ifa
->ifa_rtrequest
;
2161 if (ifa_rtrequest
!= NULL
)
2162 ifa_rtrequest(req
, rt
, SA(ret_nrt
? *ret_nrt
: NULL
));
2167 * If this is the (non-scoped) default route, record
2168 * the interface index used for the primary ifscope.
2170 if (rt_primary_default(rt
, rt_key(rt
))) {
2171 set_primary_ifscope(rt_key(rt
)->sa_family
,
2172 rt
->rt_ifp
->if_index
);
2176 * actually return a resultant rtentry and
2177 * give the caller a single reference.
2181 RT_ADDREF_LOCKED(rt
);
2185 routegenid_inet_update();
2187 else if (af
== AF_INET6
)
2188 routegenid_inet6_update();
2194 * We repeat the same procedures from rt_setgate() here
2195 * because they weren't completed when we called it earlier,
2196 * since the node was embryonic.
2198 if ((rt
->rt_flags
& RTF_GATEWAY
) && rt
->rt_gwroute
!= NULL
)
2199 rt_set_gwroute(rt
, rt_key(rt
), rt
->rt_gwroute
);
2201 if (req
== RTM_ADD
&&
2202 !(rt
->rt_flags
& RTF_HOST
) && rt_mask(rt
) != NULL
) {
2203 struct rtfc_arg arg
;
2207 rnh
->rnh_walktree_from(rnh
, rt_key(rt
), rt_mask(rt
),
2208 rt_fixchange
, &arg
);
2213 nstat_route_new_entry(rt
);
2224 rtrequest(int req
, struct sockaddr
*dst
, struct sockaddr
*gateway
,
2225 struct sockaddr
*netmask
, int flags
, struct rtentry
**ret_nrt
)
2228 lck_mtx_assert(rnh_lock
, LCK_MTX_ASSERT_NOTOWNED
);
2229 lck_mtx_lock(rnh_lock
);
2230 error
= rtrequest_locked(req
, dst
, gateway
, netmask
, flags
, ret_nrt
);
2231 lck_mtx_unlock(rnh_lock
);
2236 rtrequest_scoped(int req
, struct sockaddr
*dst
, struct sockaddr
*gateway
,
2237 struct sockaddr
*netmask
, int flags
, struct rtentry
**ret_nrt
,
2238 unsigned int ifscope
)
2241 lck_mtx_assert(rnh_lock
, LCK_MTX_ASSERT_NOTOWNED
);
2242 lck_mtx_lock(rnh_lock
);
2243 error
= rtrequest_scoped_locked(req
, dst
, gateway
, netmask
, flags
,
2245 lck_mtx_unlock(rnh_lock
);
2250 * Called from rtrequest(RTM_DELETE, ...) to fix up the route's ``family''
2251 * (i.e., the routes related to it by the operation of cloning). This
2252 * routine is iterated over all potential former-child-routes by way of
2253 * rnh->rnh_walktree_from() above, and those that actually are children of
2254 * the late parent (passed in as VP here) are themselves deleted.
2257 rt_fixdelete(struct radix_node
*rn
, void *vp
)
2259 struct rtentry
*rt
= (struct rtentry
*)rn
;
2260 struct rtentry
*rt0
= vp
;
2262 lck_mtx_assert(rnh_lock
, LCK_MTX_ASSERT_OWNED
);
2265 if (rt
->rt_parent
== rt0
&&
2266 !(rt
->rt_flags
& (RTF_CLONING
| RTF_PRCLONING
))) {
2268 * Safe to drop rt_lock and use rt_key, since holding
2269 * rnh_lock here prevents another thread from calling
2270 * rt_setgate() on this route.
2273 return (rtrequest_locked(RTM_DELETE
, rt_key(rt
), NULL
,
2274 rt_mask(rt
), rt
->rt_flags
, NULL
));
2281 * This routine is called from rt_setgate() to do the analogous thing for
2282 * adds and changes. There is the added complication in this case of a
2283 * middle insert; i.e., insertion of a new network route between an older
2284 * network route and (cloned) host routes. For this reason, a simple check
2285 * of rt->rt_parent is insufficient; each candidate route must be tested
2286 * against the (mask, value) of the new route (passed as before in vp)
2287 * to see if the new route matches it.
2289 * XXX - it may be possible to do fixdelete() for changes and reserve this
2290 * routine just for adds. I'm not sure why I thought it was necessary to do
2294 rt_fixchange(struct radix_node
*rn
, void *vp
)
2296 struct rtentry
*rt
= (struct rtentry
*)rn
;
2297 struct rtfc_arg
*ap
= vp
;
2298 struct rtentry
*rt0
= ap
->rt0
;
2299 struct radix_node_head
*rnh
= ap
->rnh
;
2300 u_char
*xk1
, *xm1
, *xk2
, *xmp
;
2303 lck_mtx_assert(rnh_lock
, LCK_MTX_ASSERT_OWNED
);
2307 if (!rt
->rt_parent
||
2308 (rt
->rt_flags
& (RTF_CLONING
| RTF_PRCLONING
))) {
2313 if (rt
->rt_parent
== rt0
)
2317 * There probably is a function somewhere which does this...
2318 * if not, there should be.
2320 len
= imin(rt_key(rt0
)->sa_len
, rt_key(rt
)->sa_len
);
2322 xk1
= (u_char
*)rt_key(rt0
);
2323 xm1
= (u_char
*)rt_mask(rt0
);
2324 xk2
= (u_char
*)rt_key(rt
);
2327 * Avoid applying a less specific route; do this only if the parent
2328 * route (rt->rt_parent) is a network route, since otherwise its mask
2329 * will be NULL if it is a cloning host route.
2331 if ((xmp
= (u_char
*)rt_mask(rt
->rt_parent
)) != NULL
) {
2332 int mlen
= rt_mask(rt
->rt_parent
)->sa_len
;
2333 if (mlen
> rt_mask(rt0
)->sa_len
) {
2338 for (i
= rnh
->rnh_treetop
->rn_offset
; i
< mlen
; i
++) {
2339 if ((xmp
[i
] & ~(xmp
[i
] ^ xm1
[i
])) != xmp
[i
]) {
2346 for (i
= rnh
->rnh_treetop
->rn_offset
; i
< len
; i
++) {
2347 if ((xk2
[i
] & xm1
[i
]) != xk1
[i
]) {
2354 * OK, this node is a clone, and matches the node currently being
2355 * changed/added under the node's mask. So, get rid of it.
2359 * Safe to drop rt_lock and use rt_key, since holding rnh_lock here
2360 * prevents another thread from calling rt_setgate() on this route.
2363 return (rtrequest_locked(RTM_DELETE
, rt_key(rt
), NULL
,
2364 rt_mask(rt
), rt
->rt_flags
, NULL
));
2368 * Round up sockaddr len to multiples of 32-bytes. This will reduce
2369 * or even eliminate the need to re-allocate the chunk of memory used
2370 * for rt_key and rt_gateway in the event the gateway portion changes.
2371 * Certain code paths (e.g. IPSec) are notorious for caching the address
2372 * of rt_gateway; this rounding-up would help ensure that the gateway
2373 * portion never gets deallocated (though it may change contents) and
2374 * thus greatly simplifies things.
2376 #define SA_SIZE(x) (-(-((uintptr_t)(x)) & -(32)))
2379 * Sets the gateway and/or gateway route portion of a route; may be
2380 * called on an existing route to modify the gateway portion. Both
2381 * rt_key and rt_gateway are allocated out of the same memory chunk.
2382 * Route entry lock must be held by caller; this routine will return
2383 * with the lock held.
2386 rt_setgate(struct rtentry
*rt
, struct sockaddr
*dst
, struct sockaddr
*gate
)
2388 int dlen
= SA_SIZE(dst
->sa_len
), glen
= SA_SIZE(gate
->sa_len
);
2389 struct radix_node_head
*rnh
= NULL
;
2390 boolean_t loop
= FALSE
;
2392 if (dst
->sa_family
!= AF_INET
&& dst
->sa_family
!= AF_INET6
) {
2396 rnh
= rt_tables
[dst
->sa_family
];
2397 lck_mtx_assert(rnh_lock
, LCK_MTX_ASSERT_OWNED
);
2398 RT_LOCK_ASSERT_HELD(rt
);
2401 * If this is for a route that is on its way of being removed,
2402 * or is temporarily frozen, reject the modification request.
2404 if (rt
->rt_flags
& RTF_CONDEMNED
) {
2408 /* Add an extra ref for ourselves */
2409 RT_ADDREF_LOCKED(rt
);
2411 if (rt
->rt_flags
& RTF_GATEWAY
) {
2412 if ((dst
->sa_len
== gate
->sa_len
) &&
2413 (dst
->sa_family
== AF_INET
|| dst
->sa_family
== AF_INET6
)) {
2414 struct sockaddr_storage dst_ss
, gate_ss
;
2416 (void) sa_copy(dst
, &dst_ss
, NULL
);
2417 (void) sa_copy(gate
, &gate_ss
, NULL
);
2419 loop
= equal(SA(&dst_ss
), SA(&gate_ss
));
2421 loop
= (dst
->sa_len
== gate
->sa_len
&&
2427 * A (cloning) network route with the destination equal to the gateway
2428 * will create an endless loop (see notes below), so disallow it.
2430 if (((rt
->rt_flags
& (RTF_HOST
|RTF_GATEWAY
|RTF_LLINFO
)) ==
2431 RTF_GATEWAY
) && loop
) {
2432 /* Release extra ref */
2433 RT_REMREF_LOCKED(rt
);
2434 return (EADDRNOTAVAIL
);
2438 * A host route with the destination equal to the gateway
2439 * will interfere with keeping LLINFO in the routing
2440 * table, so disallow it.
2442 if (((rt
->rt_flags
& (RTF_HOST
|RTF_GATEWAY
|RTF_LLINFO
)) ==
2443 (RTF_HOST
|RTF_GATEWAY
)) && loop
) {
2445 * The route might already exist if this is an RTM_CHANGE
2446 * or a routing redirect, so try to delete it.
2448 if (rt_key(rt
) != NULL
) {
2450 * Safe to drop rt_lock and use rt_key, rt_gateway,
2451 * since holding rnh_lock here prevents another thread
2452 * from calling rt_setgate() on this route.
2455 (void) rtrequest_locked(RTM_DELETE
, rt_key(rt
),
2456 rt
->rt_gateway
, rt_mask(rt
), rt
->rt_flags
, NULL
);
2459 /* Release extra ref */
2460 RT_REMREF_LOCKED(rt
);
2461 return (EADDRNOTAVAIL
);
2465 * The destination is not directly reachable. Get a route
2466 * to the next-hop gateway and store it in rt_gwroute.
2468 if (rt
->rt_flags
& RTF_GATEWAY
) {
2469 struct rtentry
*gwrt
;
2470 unsigned int ifscope
;
2472 if (dst
->sa_family
== AF_INET
)
2473 ifscope
= sin_get_ifscope(dst
);
2474 else if (dst
->sa_family
== AF_INET6
)
2475 ifscope
= sin6_get_ifscope(dst
);
2477 ifscope
= IFSCOPE_NONE
;
2481 * Don't ignore RTF_CLONING, since we prefer that rt_gwroute
2482 * points to a clone rather than a cloning route; see above
2483 * check for cloning loop avoidance (dst == gate).
2485 gwrt
= rtalloc1_scoped_locked(gate
, 1, RTF_PRCLONING
, ifscope
);
2487 RT_LOCK_ASSERT_NOTHELD(gwrt
);
2491 * Cloning loop avoidance:
2493 * In the presence of protocol-cloning and bad configuration,
2494 * it is possible to get stuck in bottomless mutual recursion
2495 * (rtrequest rt_setgate rtalloc1). We avoid this by not
2496 * allowing protocol-cloning to operate for gateways (which
2497 * is probably the correct choice anyway), and avoid the
2498 * resulting reference loops by disallowing any route to run
2499 * through itself as a gateway. This is obviously mandatory
2500 * when we get rt->rt_output(). It implies that a route to
2501 * the gateway must already be present in the system in order
2502 * for the gateway to be referred to by another route.
2505 RT_REMREF_LOCKED(gwrt
);
2506 /* Release extra ref */
2507 RT_REMREF_LOCKED(rt
);
2508 return (EADDRINUSE
); /* failure */
2512 * If scoped, the gateway route must use the same interface;
2513 * we're holding rnh_lock now, so rt_gateway and rt_ifp of gwrt
2514 * should not change and are freely accessible.
2516 if (ifscope
!= IFSCOPE_NONE
&& (rt
->rt_flags
& RTF_IFSCOPE
) &&
2517 gwrt
!= NULL
&& gwrt
->rt_ifp
!= NULL
&&
2518 gwrt
->rt_ifp
->if_index
!= ifscope
) {
2519 rtfree_locked(gwrt
); /* rt != gwrt, no deadlock */
2520 /* Release extra ref */
2521 RT_REMREF_LOCKED(rt
);
2522 return ((rt
->rt_flags
& RTF_HOST
) ?
2523 EHOSTUNREACH
: ENETUNREACH
);
2526 /* Check again since we dropped the lock above */
2527 if (rt
->rt_flags
& RTF_CONDEMNED
) {
2529 rtfree_locked(gwrt
);
2530 /* Release extra ref */
2531 RT_REMREF_LOCKED(rt
);
2535 /* Set gateway route; callee adds ref to gwrt if non-NULL */
2536 rt_set_gwroute(rt
, dst
, gwrt
);
2539 * In case the (non-scoped) default route gets modified via
2540 * an ICMP redirect, record the interface index used for the
2541 * primary ifscope. Also done in rt_setif() to take care
2542 * of the non-redirect cases.
2544 if (rt_primary_default(rt
, dst
) && rt
->rt_ifp
!= NULL
) {
2545 set_primary_ifscope(dst
->sa_family
,
2546 rt
->rt_ifp
->if_index
);
2550 * Tell the kernel debugger about the new default gateway
2551 * if the gateway route uses the primary interface, or
2552 * if we are in a transient state before the non-scoped
2553 * default gateway is installed (similar to how the system
2554 * was behaving in the past). In future, it would be good
2555 * to do all this only when KDP is enabled.
2557 if ((dst
->sa_family
== AF_INET
) &&
2558 gwrt
!= NULL
&& gwrt
->rt_gateway
->sa_family
== AF_LINK
&&
2559 (gwrt
->rt_ifp
->if_index
== get_primary_ifscope(AF_INET
) ||
2560 get_primary_ifscope(AF_INET
) == IFSCOPE_NONE
)) {
2561 kdp_set_gateway_mac(SDL((void *)gwrt
->rt_gateway
)->
2565 /* Release extra ref from rtalloc1() */
2571 * Prepare to store the gateway in rt_gateway. Both dst and gateway
2572 * are stored one after the other in the same malloc'd chunk. If we
2573 * have room, reuse the old buffer since rt_gateway already points
2574 * to the right place. Otherwise, malloc a new block and update
2575 * the 'dst' address and point rt_gateway to the right place.
2577 if (rt
->rt_gateway
== NULL
|| glen
> SA_SIZE(rt
->rt_gateway
->sa_len
)) {
2580 /* The underlying allocation is done with M_WAITOK set */
2581 R_Malloc(new, caddr_t
, dlen
+ glen
);
2583 /* Clear gateway route */
2584 rt_set_gwroute(rt
, dst
, NULL
);
2585 /* Release extra ref */
2586 RT_REMREF_LOCKED(rt
);
2591 * Copy from 'dst' and not rt_key(rt) because we can get
2592 * here to initialize a newly allocated route entry, in
2593 * which case rt_key(rt) is NULL (and so does rt_gateway).
2595 bzero(new, dlen
+ glen
);
2596 Bcopy(dst
, new, dst
->sa_len
);
2597 R_Free(rt_key(rt
)); /* free old block; NULL is okay */
2598 rt
->rt_nodes
->rn_key
= new;
2599 rt
->rt_gateway
= (struct sockaddr
*)(new + dlen
);
2603 * Copy the new gateway value into the memory chunk.
2605 Bcopy(gate
, rt
->rt_gateway
, gate
->sa_len
);
2608 * For consistency between rt_gateway and rt_key(gwrt).
2610 if ((rt
->rt_flags
& RTF_GATEWAY
) && rt
->rt_gwroute
!= NULL
&&
2611 (rt
->rt_gwroute
->rt_flags
& RTF_IFSCOPE
)) {
2612 if (rt
->rt_gateway
->sa_family
== AF_INET
&&
2613 rt_key(rt
->rt_gwroute
)->sa_family
== AF_INET
) {
2614 sin_set_ifscope(rt
->rt_gateway
,
2615 sin_get_ifscope(rt_key(rt
->rt_gwroute
)));
2616 } else if (rt
->rt_gateway
->sa_family
== AF_INET6
&&
2617 rt_key(rt
->rt_gwroute
)->sa_family
== AF_INET6
) {
2618 sin6_set_ifscope(rt
->rt_gateway
,
2619 sin6_get_ifscope(rt_key(rt
->rt_gwroute
)));
2624 * This isn't going to do anything useful for host routes, so
2625 * don't bother. Also make sure we have a reasonable mask
2626 * (we don't yet have one during adds).
2628 if (!(rt
->rt_flags
& RTF_HOST
) && rt_mask(rt
) != 0) {
2629 struct rtfc_arg arg
;
2633 rnh
->rnh_walktree_from(rnh
, rt_key(rt
), rt_mask(rt
),
2634 rt_fixchange
, &arg
);
2638 /* Release extra ref */
2639 RT_REMREF_LOCKED(rt
);
2646 rt_set_gwroute(struct rtentry
*rt
, struct sockaddr
*dst
, struct rtentry
*gwrt
)
2648 boolean_t gwrt_isrouter
;
2650 lck_mtx_assert(rnh_lock
, LCK_MTX_ASSERT_OWNED
);
2651 RT_LOCK_ASSERT_HELD(rt
);
2654 RT_ADDREF(gwrt
); /* for this routine */
2657 * Get rid of existing gateway route; if rt_gwroute is already
2658 * set to gwrt, this is slightly redundant (though safe since
2659 * we held an extra ref above) but makes the code simpler.
2661 if (rt
->rt_gwroute
!= NULL
) {
2662 struct rtentry
*ogwrt
= rt
->rt_gwroute
;
2664 VERIFY(rt
!= ogwrt
); /* sanity check */
2665 rt
->rt_gwroute
= NULL
;
2667 rtfree_locked(ogwrt
);
2669 VERIFY(rt
->rt_gwroute
== NULL
);
2673 * And associate the new gateway route.
2675 if ((rt
->rt_gwroute
= gwrt
) != NULL
) {
2676 RT_ADDREF(gwrt
); /* for rt */
2678 if (rt
->rt_flags
& RTF_WASCLONED
) {
2679 /* rt_parent might be NULL if rt is embryonic */
2680 gwrt_isrouter
= (rt
->rt_parent
!= NULL
&&
2681 SA_DEFAULT(rt_key(rt
->rt_parent
)) &&
2682 !RT_HOST(rt
->rt_parent
));
2684 gwrt_isrouter
= (SA_DEFAULT(dst
) && !RT_HOST(rt
));
2687 /* If gwrt points to a default router, mark it accordingly */
2688 if (gwrt_isrouter
&& RT_HOST(gwrt
) &&
2689 !(gwrt
->rt_flags
& RTF_ROUTER
)) {
2691 gwrt
->rt_flags
|= RTF_ROUTER
;
2695 RT_REMREF(gwrt
); /* for this routine */
2700 rt_maskedcopy(const struct sockaddr
*src
, struct sockaddr
*dst
,
2701 const struct sockaddr
*netmask
)
2703 const char *netmaskp
= &netmask
->sa_data
[0];
2704 const char *srcp
= &src
->sa_data
[0];
2705 char *dstp
= &dst
->sa_data
[0];
2706 const char *maskend
= (char *)dst
2707 + MIN(netmask
->sa_len
, src
->sa_len
);
2708 const char *srcend
= (char *)dst
+ src
->sa_len
;
2710 dst
->sa_len
= src
->sa_len
;
2711 dst
->sa_family
= src
->sa_family
;
2713 while (dstp
< maskend
)
2714 *dstp
++ = *srcp
++ & *netmaskp
++;
2716 memset(dstp
, 0, (size_t)(srcend
- dstp
));
2720 * Lookup an AF_INET/AF_INET6 scoped or non-scoped route depending on the
2721 * ifscope value passed in by the caller (IFSCOPE_NONE implies non-scoped).
2723 static struct radix_node
*
2724 node_lookup(struct sockaddr
*dst
, struct sockaddr
*netmask
,
2725 unsigned int ifscope
)
2727 struct radix_node_head
*rnh
;
2728 struct radix_node
*rn
;
2729 struct sockaddr_storage ss
, mask
;
2730 int af
= dst
->sa_family
;
2731 struct matchleaf_arg ma
= { ifscope
};
2732 rn_matchf_t
*f
= rn_match_ifscope
;
2735 if (af
!= AF_INET
&& af
!= AF_INET6
)
2738 rnh
= rt_tables
[af
];
2741 * Transform dst into the internal routing table form,
2742 * clearing out the scope ID field if ifscope isn't set.
2744 dst
= sa_copy(dst
, &ss
, (ifscope
== IFSCOPE_NONE
) ? NULL
: &ifscope
);
2746 /* Transform netmask into the internal routing table form */
2747 if (netmask
!= NULL
)
2748 netmask
= ma_copy(af
, netmask
, &mask
, ifscope
);
2750 if (ifscope
== IFSCOPE_NONE
)
2753 rn
= rnh
->rnh_lookup_args(dst
, netmask
, rnh
, f
, w
);
2754 if (rn
!= NULL
&& (rn
->rn_flags
& RNF_ROOT
))
2761 * Lookup the AF_INET/AF_INET6 non-scoped default route.
2763 static struct radix_node
*
2764 node_lookup_default(int af
)
2766 struct radix_node_head
*rnh
;
2768 VERIFY(af
== AF_INET
|| af
== AF_INET6
);
2769 rnh
= rt_tables
[af
];
2771 return (af
== AF_INET
? rnh
->rnh_lookup(&sin_def
, NULL
, rnh
) :
2772 rnh
->rnh_lookup(&sin6_def
, NULL
, rnh
));
2776 rt_ifa_is_dst(struct sockaddr
*dst
, struct ifaddr
*ifa
)
2778 boolean_t result
= FALSE
;
2780 if (ifa
== NULL
|| ifa
->ifa_addr
== NULL
)
2785 if (dst
->sa_family
== ifa
->ifa_addr
->sa_family
&&
2786 ((dst
->sa_family
== AF_INET
&&
2787 SIN(dst
)->sin_addr
.s_addr
==
2788 SIN(ifa
->ifa_addr
)->sin_addr
.s_addr
) ||
2789 (dst
->sa_family
== AF_INET6
&&
2790 SA6_ARE_ADDR_EQUAL(SIN6(dst
), SIN6(ifa
->ifa_addr
)))))
2799 * Common routine to lookup/match a route. It invokes the lookup/matchaddr
2800 * callback which could be address family-specific. The main difference
2801 * between the two (at least for AF_INET/AF_INET6) is that a lookup does
2802 * not alter the expiring state of a route, whereas a match would unexpire
2803 * or revalidate the route.
2805 * The optional scope or interface index property of a route allows for a
2806 * per-interface route instance. This permits multiple route entries having
2807 * the same destination (but not necessarily the same gateway) to exist in
2808 * the routing table; each of these entries is specific to the corresponding
2809 * interface. This is made possible by storing the scope ID value into the
2810 * radix key, thus making each route entry unique. These scoped entries
2811 * exist along with the regular, non-scoped entries in the same radix tree
2812 * for a given address family (AF_INET/AF_INET6); the scope logically
2813 * partitions it into multiple per-interface sub-trees.
2815 * When a scoped route lookup is performed, the routing table is searched for
2816 * the best match that would result in a route using the same interface as the
2817 * one associated with the scope (the exception to this are routes that point
2818 * to the loopback interface). The search rule follows the longest matching
2819 * prefix with the additional interface constraint.
2821 static struct rtentry
*
2822 rt_lookup_common(boolean_t lookup_only
, boolean_t coarse
, struct sockaddr
*dst
,
2823 struct sockaddr
*netmask
, struct radix_node_head
*rnh
, unsigned int ifscope
)
2825 struct radix_node
*rn0
, *rn
;
2827 int af
= dst
->sa_family
;
2828 struct sockaddr_storage dst_ss
, mask_ss
;
2829 char s_dst
[MAX_IPv6_STR_LEN
], s_netmask
[MAX_IPv6_STR_LEN
];
2830 char dbuf
[MAX_SCOPE_ADDR_STR_LEN
], gbuf
[MAX_IPv6_STR_LEN
];
2832 VERIFY(!coarse
|| ifscope
== IFSCOPE_NONE
);
2834 lck_mtx_assert(rnh_lock
, LCK_MTX_ASSERT_OWNED
);
2837 * While we have rnh_lock held, see if we need to schedule the timer.
2839 if (nd6_sched_timeout_want
)
2840 nd6_sched_timeout(NULL
, NULL
);
2847 * Non-scoped route lookup.
2850 if ((af
!= AF_INET
&& af
!= AF_INET6
) ||
2851 (af
== AF_INET
&& !ip_doscopedroute
) ||
2852 (af
== AF_INET6
&& !ip6_doscopedroute
)) {
2854 if (af
!= AF_INET
|| !ip_doscopedroute
) {
2856 rn
= rnh
->rnh_matchaddr(dst
, rnh
);
2859 * Don't return a root node; also, rnh_matchaddr callback
2860 * would have done the necessary work to clear RTPRF_OURS
2861 * for certain protocol families.
2863 if (rn
!= NULL
&& (rn
->rn_flags
& RNF_ROOT
))
2866 RT_LOCK_SPIN(RT(rn
));
2867 if (!(RT(rn
)->rt_flags
& RTF_CONDEMNED
)) {
2868 RT_ADDREF_LOCKED(RT(rn
));
2878 /* Transform dst/netmask into the internal routing table form */
2879 dst
= sa_copy(dst
, &dst_ss
, &ifscope
);
2880 if (netmask
!= NULL
)
2881 netmask
= ma_copy(af
, netmask
, &mask_ss
, ifscope
);
2882 dontcare
= (ifscope
== IFSCOPE_NONE
);
2886 (void) inet_ntop(af
, &SIN(dst
)->sin_addr
.s_addr
,
2887 s_dst
, sizeof (s_dst
));
2889 (void) inet_ntop(af
, &SIN6(dst
)->sin6_addr
,
2890 s_dst
, sizeof (s_dst
));
2892 if (netmask
!= NULL
&& af
== AF_INET
)
2893 (void) inet_ntop(af
, &SIN(netmask
)->sin_addr
.s_addr
,
2894 s_netmask
, sizeof (s_netmask
));
2895 if (netmask
!= NULL
&& af
== AF_INET6
)
2896 (void) inet_ntop(af
, &SIN6(netmask
)->sin6_addr
,
2897 s_netmask
, sizeof (s_netmask
));
2900 printf("%s (%d, %d, %s, %s, %u)\n",
2901 __func__
, lookup_only
, coarse
, s_dst
, s_netmask
, ifscope
);
2905 * Scoped route lookup:
2907 * We first perform a non-scoped lookup for the original result.
2908 * Afterwards, depending on whether or not the caller has specified
2909 * a scope, we perform a more specific scoped search and fallback
2910 * to this original result upon failure.
2912 rn0
= rn
= node_lookup(dst
, netmask
, IFSCOPE_NONE
);
2915 * If the caller did not specify a scope, use the primary scope
2916 * derived from the system's non-scoped default route. If, for
2917 * any reason, there is no primary interface, ifscope will be
2918 * set to IFSCOPE_NONE; if the above lookup resulted in a route,
2919 * we'll do a more-specific search below, scoped to the interface
2923 ifscope
= get_primary_ifscope(af
);
2926 * Keep the original result if either of the following is true:
2928 * 1) The interface portion of the route has the same interface
2929 * index as the scope value and it is marked with RTF_IFSCOPE.
2930 * 2) The route uses the loopback interface, in which case the
2931 * destination (host/net) is local/loopback.
2933 * Otherwise, do a more specified search using the scope;
2934 * we're holding rnh_lock now, so rt_ifp should not change.
2937 struct rtentry
*rt
= RT(rn
);
2940 rt_str(rt
, dbuf
, sizeof (dbuf
), gbuf
, sizeof (gbuf
));
2941 printf("%s unscoped search %p to %s->%s->%s ifa_ifp %s\n",
2944 (rt
->rt_ifp
!= NULL
) ? rt
->rt_ifp
->if_xname
: "",
2945 (rt
->rt_ifa
->ifa_ifp
!= NULL
) ?
2946 rt
->rt_ifa
->ifa_ifp
->if_xname
: "");
2948 if (!(rt
->rt_ifp
->if_flags
& IFF_LOOPBACK
)) {
2949 if (rt
->rt_ifp
->if_index
!= ifscope
) {
2951 * Wrong interface; keep the original result
2952 * only if the caller did not specify a scope,
2953 * and do a more specific scoped search using
2954 * the scope of the found route. Otherwise,
2955 * start again from scratch.
2957 * For loopback scope we keep the unscoped
2958 * route for local addresses
2962 ifscope
= rt
->rt_ifp
->if_index
;
2963 else if (ifscope
!= lo_ifp
->if_index
||
2964 rt_ifa_is_dst(dst
, rt
->rt_ifa
) == FALSE
)
2966 } else if (!(rt
->rt_flags
& RTF_IFSCOPE
)) {
2968 * Right interface, except that this route
2969 * isn't marked with RTF_IFSCOPE. Do a more
2970 * specific scoped search. Keep the original
2971 * result and return it it in case the scoped
2980 * Scoped search. Find the most specific entry having the same
2981 * interface scope as the one requested. The following will result
2982 * in searching for the longest prefix scoped match.
2985 rn
= node_lookup(dst
, netmask
, ifscope
);
2987 if (rt_verbose
&& rn
!= NULL
) {
2988 struct rtentry
*rt
= RT(rn
);
2990 rt_str(rt
, dbuf
, sizeof (dbuf
), gbuf
, sizeof (gbuf
));
2991 printf("%s scoped search %p to %s->%s->%s ifa %s\n",
2994 (rt
->rt_ifp
!= NULL
) ? rt
->rt_ifp
->if_xname
: "",
2995 (rt
->rt_ifa
->ifa_ifp
!= NULL
) ?
2996 rt
->rt_ifa
->ifa_ifp
->if_xname
: "");
3000 * Use the original result if either of the following is true:
3002 * 1) The scoped search did not yield any result.
3003 * 2) The caller insists on performing a coarse-grained lookup.
3004 * 3) The result from the scoped search is a scoped default route,
3005 * and the original (non-scoped) result is not a default route,
3006 * i.e. the original result is a more specific host/net route.
3007 * 4) The scoped search yielded a net route but the original
3008 * result is a host route, i.e. the original result is treated
3009 * as a more specific route.
3011 if (rn
== NULL
|| coarse
|| (rn0
!= NULL
&&
3012 ((SA_DEFAULT(rt_key(RT(rn
))) && !SA_DEFAULT(rt_key(RT(rn0
)))) ||
3013 (!RT_HOST(rn
) && RT_HOST(rn0
)))))
3017 * If we still don't have a route, use the non-scoped default
3018 * route as long as the interface portion satistifes the scope.
3020 if (rn
== NULL
&& (rn
= node_lookup_default(af
)) != NULL
&&
3021 RT(rn
)->rt_ifp
->if_index
!= ifscope
) {
3027 * Manually clear RTPRF_OURS using rt_validate() and
3028 * bump up the reference count after, and not before;
3029 * we only get here for AF_INET/AF_INET6. node_lookup()
3030 * has done the check against RNF_ROOT, so we can be sure
3031 * that we're not returning a root node here.
3033 RT_LOCK_SPIN(RT(rn
));
3034 if (rt_validate(RT(rn
))) {
3035 RT_ADDREF_LOCKED(RT(rn
));
3045 printf("%s %u return NULL\n", __func__
, ifscope
);
3047 struct rtentry
*rt
= RT(rn
);
3049 rt_str(rt
, dbuf
, sizeof (dbuf
), gbuf
, sizeof (gbuf
));
3051 printf("%s %u return %p to %s->%s->%s ifa_ifp %s\n",
3052 __func__
, ifscope
, rt
,
3054 (rt
->rt_ifp
!= NULL
) ? rt
->rt_ifp
->if_xname
: "",
3055 (rt
->rt_ifa
->ifa_ifp
!= NULL
) ?
3056 rt
->rt_ifa
->ifa_ifp
->if_xname
: "");
3064 rt_lookup(boolean_t lookup_only
, struct sockaddr
*dst
, struct sockaddr
*netmask
,
3065 struct radix_node_head
*rnh
, unsigned int ifscope
)
3067 return (rt_lookup_common(lookup_only
, FALSE
, dst
, netmask
,
3072 rt_lookup_coarse(boolean_t lookup_only
, struct sockaddr
*dst
,
3073 struct sockaddr
*netmask
, struct radix_node_head
*rnh
)
3075 return (rt_lookup_common(lookup_only
, TRUE
, dst
, netmask
,
3076 rnh
, IFSCOPE_NONE
));
3080 rt_validate(struct rtentry
*rt
)
3082 RT_LOCK_ASSERT_HELD(rt
);
3084 if ((rt
->rt_flags
& (RTF_UP
| RTF_CONDEMNED
)) == RTF_UP
) {
3085 int af
= rt_key(rt
)->sa_family
;
3088 (void) in_validate(RN(rt
));
3089 else if (af
== AF_INET6
)
3090 (void) in6_validate(RN(rt
));
3095 return (rt
!= NULL
);
3099 * Set up a routing table entry, normally
3103 rtinit(struct ifaddr
*ifa
, int cmd
, int flags
)
3107 lck_mtx_assert(rnh_lock
, LCK_MTX_ASSERT_NOTOWNED
);
3109 lck_mtx_lock(rnh_lock
);
3110 error
= rtinit_locked(ifa
, cmd
, flags
);
3111 lck_mtx_unlock(rnh_lock
);
3117 rtinit_locked(struct ifaddr
*ifa
, int cmd
, int flags
)
3119 struct radix_node_head
*rnh
;
3120 uint8_t nbuf
[128]; /* long enough for IPv6 */
3121 char dbuf
[MAX_IPv6_STR_LEN
], gbuf
[MAX_IPv6_STR_LEN
];
3122 char abuf
[MAX_IPv6_STR_LEN
];
3123 struct rtentry
*rt
= NULL
;
3124 struct sockaddr
*dst
;
3125 struct sockaddr
*netmask
;
3129 * Holding rnh_lock here prevents the possibility of ifa from
3130 * changing (e.g. in_ifinit), so it is safe to access its
3131 * ifa_{dst}addr (here and down below) without locking.
3133 lck_mtx_assert(rnh_lock
, LCK_MTX_ASSERT_OWNED
);
3135 if (flags
& RTF_HOST
) {
3136 dst
= ifa
->ifa_dstaddr
;
3139 dst
= ifa
->ifa_addr
;
3140 netmask
= ifa
->ifa_netmask
;
3143 if (dst
->sa_len
== 0) {
3144 log(LOG_ERR
, "%s: %s failed, invalid dst sa_len %d\n",
3145 __func__
, rtm2str(cmd
), dst
->sa_len
);
3149 if (netmask
!= NULL
&& netmask
->sa_len
> sizeof (nbuf
)) {
3150 log(LOG_ERR
, "%s: %s failed, mask sa_len %d too large\n",
3151 __func__
, rtm2str(cmd
), dst
->sa_len
);
3156 if (dst
->sa_family
== AF_INET
) {
3157 (void) inet_ntop(AF_INET
, &SIN(dst
)->sin_addr
.s_addr
,
3158 abuf
, sizeof (abuf
));
3161 else if (dst
->sa_family
== AF_INET6
) {
3162 (void) inet_ntop(AF_INET6
, &SIN6(dst
)->sin6_addr
,
3163 abuf
, sizeof (abuf
));
3167 if ((rnh
= rt_tables
[dst
->sa_family
]) == NULL
) {
3173 * If it's a delete, check that if it exists, it's on the correct
3174 * interface or we might scrub a route to another ifa which would
3175 * be confusing at best and possibly worse.
3177 if (cmd
== RTM_DELETE
) {
3179 * It's a delete, so it should already exist..
3180 * If it's a net, mask off the host bits
3181 * (Assuming we have a mask)
3183 if (netmask
!= NULL
) {
3184 rt_maskedcopy(dst
, SA(nbuf
), netmask
);
3188 * Get an rtentry that is in the routing tree and contains
3189 * the correct info. Note that we perform a coarse-grained
3190 * lookup here, in case there is a scoped variant of the
3191 * subnet/prefix route which we should ignore, as we never
3192 * add a scoped subnet/prefix route as part of adding an
3193 * interface address.
3195 rt
= rt_lookup_coarse(TRUE
, dst
, NULL
, rnh
);
3197 rt_str(rt
, dbuf
, sizeof (dbuf
), gbuf
, sizeof (gbuf
));
3199 * Ok so we found the rtentry. it has an extra reference
3200 * for us at this stage. we won't need that so
3204 if (rt
->rt_ifa
!= ifa
) {
3206 * If the interface address in the rtentry
3207 * doesn't match the interface we are using,
3208 * then we don't want to delete it, so return
3209 * an error. This seems to be the only point
3210 * of this whole RTM_DELETE clause.
3213 log(LOG_DEBUG
, "%s: not removing "
3214 "route to %s->%s->%s, flags %b, "
3215 "ifaddr %s, rt_ifa 0x%llx != "
3216 "ifa 0x%llx\n", __func__
, dbuf
,
3217 gbuf
, ((rt
->rt_ifp
!= NULL
) ?
3218 rt
->rt_ifp
->if_xname
: ""),
3219 rt
->rt_flags
, RTF_BITS
, abuf
,
3220 (uint64_t)VM_KERNEL_ADDRPERM(
3222 (uint64_t)VM_KERNEL_ADDRPERM(ifa
));
3224 RT_REMREF_LOCKED(rt
);
3227 error
= ((flags
& RTF_HOST
) ?
3228 EHOSTUNREACH
: ENETUNREACH
);
3230 } else if (rt
->rt_flags
& RTF_STATIC
) {
3232 * Don't remove the subnet/prefix route if
3233 * this was manually added from above.
3236 log(LOG_DEBUG
, "%s: not removing "
3237 "static route to %s->%s->%s, "
3238 "flags %b, ifaddr %s\n", __func__
,
3239 dbuf
, gbuf
, ((rt
->rt_ifp
!= NULL
) ?
3240 rt
->rt_ifp
->if_xname
: ""),
3241 rt
->rt_flags
, RTF_BITS
, abuf
);
3243 RT_REMREF_LOCKED(rt
);
3250 log(LOG_DEBUG
, "%s: removing route to "
3251 "%s->%s->%s, flags %b, ifaddr %s\n",
3252 __func__
, dbuf
, gbuf
,
3253 ((rt
->rt_ifp
!= NULL
) ?
3254 rt
->rt_ifp
->if_xname
: ""),
3255 rt
->rt_flags
, RTF_BITS
, abuf
);
3257 RT_REMREF_LOCKED(rt
);
3263 * Do the actual request
3265 if ((error
= rtrequest_locked(cmd
, dst
, ifa
->ifa_addr
, netmask
,
3266 flags
| ifa
->ifa_flags
, &rt
)) != 0)
3271 rt_str(rt
, dbuf
, sizeof (dbuf
), gbuf
, sizeof (gbuf
));
3276 * If we are deleting, and we found an entry, then it's
3277 * been removed from the tree. Notify any listening
3278 * routing agents of the change and throw it away.
3281 rt_newaddrmsg(cmd
, ifa
, error
, rt
);
3284 log(LOG_DEBUG
, "%s: removed route to %s->%s->%s, "
3285 "flags %b, ifaddr %s\n", __func__
, dbuf
, gbuf
,
3286 ((rt
->rt_ifp
!= NULL
) ? rt
->rt_ifp
->if_xname
: ""),
3287 rt
->rt_flags
, RTF_BITS
, abuf
);
3294 * We are adding, and we have a returned routing entry.
3295 * We need to sanity check the result. If it came back
3296 * with an unexpected interface, then it must have already
3297 * existed or something.
3300 if (rt
->rt_ifa
!= ifa
) {
3301 void (*ifa_rtrequest
)
3302 (int, struct rtentry
*, struct sockaddr
*);
3304 if (!(rt
->rt_ifa
->ifa_ifp
->if_flags
&
3305 (IFF_POINTOPOINT
|IFF_LOOPBACK
))) {
3306 log(LOG_ERR
, "%s: %s route to %s->%s->%s, "
3307 "flags %b, ifaddr %s, rt_ifa 0x%llx != "
3308 "ifa 0x%llx\n", __func__
, rtm2str(cmd
),
3309 dbuf
, gbuf
, ((rt
->rt_ifp
!= NULL
) ?
3310 rt
->rt_ifp
->if_xname
: ""), rt
->rt_flags
,
3312 (uint64_t)VM_KERNEL_ADDRPERM(rt
->rt_ifa
),
3313 (uint64_t)VM_KERNEL_ADDRPERM(ifa
));
3317 log(LOG_DEBUG
, "%s: %s route to %s->%s->%s, "
3318 "flags %b, ifaddr %s, rt_ifa was 0x%llx "
3319 "now 0x%llx\n", __func__
, rtm2str(cmd
),
3320 dbuf
, gbuf
, ((rt
->rt_ifp
!= NULL
) ?
3321 rt
->rt_ifp
->if_xname
: ""), rt
->rt_flags
,
3323 (uint64_t)VM_KERNEL_ADDRPERM(rt
->rt_ifa
),
3324 (uint64_t)VM_KERNEL_ADDRPERM(ifa
));
3328 * Ask that the protocol in question
3329 * remove anything it has associated with
3330 * this route and ifaddr.
3332 ifa_rtrequest
= rt
->rt_ifa
->ifa_rtrequest
;
3333 if (ifa_rtrequest
!= NULL
)
3334 ifa_rtrequest(RTM_DELETE
, rt
, NULL
);
3336 * Set the route's ifa.
3340 if (rt
->rt_ifp
!= ifa
->ifa_ifp
) {
3342 * Purge any link-layer info caching.
3344 if (rt
->rt_llinfo_purge
!= NULL
)
3345 rt
->rt_llinfo_purge(rt
);
3347 * Adjust route ref count for the interfaces.
3349 if (rt
->rt_if_ref_fn
!= NULL
) {
3350 rt
->rt_if_ref_fn(ifa
->ifa_ifp
, 1);
3351 rt
->rt_if_ref_fn(rt
->rt_ifp
, -1);
3356 * And substitute in references to the ifaddr
3359 rt
->rt_ifp
= ifa
->ifa_ifp
;
3361 * If rmx_mtu is not locked, update it
3362 * to the MTU used by the new interface.
3364 if (!(rt
->rt_rmx
.rmx_locks
& RTV_MTU
))
3365 rt
->rt_rmx
.rmx_mtu
= rt
->rt_ifp
->if_mtu
;
3368 * Now ask the protocol to check if it needs
3369 * any special processing in its new form.
3371 ifa_rtrequest
= ifa
->ifa_rtrequest
;
3372 if (ifa_rtrequest
!= NULL
)
3373 ifa_rtrequest(RTM_ADD
, rt
, NULL
);
3376 log(LOG_DEBUG
, "%s: added route to %s->%s->%s, "
3377 "flags %b, ifaddr %s\n", __func__
, dbuf
,
3378 gbuf
, ((rt
->rt_ifp
!= NULL
) ?
3379 rt
->rt_ifp
->if_xname
: ""), rt
->rt_flags
,
3384 * notify any listenning routing agents of the change
3386 rt_newaddrmsg(cmd
, ifa
, error
, rt
);
3388 * We just wanted to add it; we don't actually need a
3389 * reference. This will result in a route that's added
3390 * to the routing table without a reference count. The
3391 * RTM_DELETE code will do the necessary step to adjust
3392 * the reference count at deletion time.
3394 RT_REMREF_LOCKED(rt
);
3407 rt_set_idleref(struct rtentry
*rt
)
3409 RT_LOCK_ASSERT_HELD(rt
);
3412 * We currently keep idle refcnt only on unicast cloned routes
3413 * that aren't marked with RTF_NOIFREF.
3415 if (rt
->rt_parent
!= NULL
&& !(rt
->rt_flags
&
3416 (RTF_NOIFREF
|RTF_BROADCAST
| RTF_MULTICAST
)) &&
3417 (rt
->rt_flags
& (RTF_UP
|RTF_WASCLONED
|RTF_IFREF
)) ==
3418 (RTF_UP
|RTF_WASCLONED
)) {
3419 rt_clear_idleref(rt
); /* drop existing refcnt if any */
3420 rt
->rt_if_ref_fn
= rte_if_ref
;
3421 /* Become a regular mutex, just in case */
3422 RT_CONVERT_LOCK(rt
);
3423 rt
->rt_if_ref_fn(rt
->rt_ifp
, 1);
3424 rt
->rt_flags
|= RTF_IFREF
;
3429 rt_clear_idleref(struct rtentry
*rt
)
3431 RT_LOCK_ASSERT_HELD(rt
);
3433 if (rt
->rt_if_ref_fn
!= NULL
) {
3434 VERIFY((rt
->rt_flags
& (RTF_NOIFREF
| RTF_IFREF
)) == RTF_IFREF
);
3435 /* Become a regular mutex, just in case */
3436 RT_CONVERT_LOCK(rt
);
3437 rt
->rt_if_ref_fn(rt
->rt_ifp
, -1);
3438 rt
->rt_flags
&= ~RTF_IFREF
;
3439 rt
->rt_if_ref_fn
= NULL
;
3444 rt_set_proxy(struct rtentry
*rt
, boolean_t set
)
3446 lck_mtx_lock(rnh_lock
);
3449 * Search for any cloned routes which might have
3450 * been formed from this node, and delete them.
3452 if (rt
->rt_flags
& (RTF_CLONING
| RTF_PRCLONING
)) {
3453 struct radix_node_head
*rnh
= rt_tables
[rt_key(rt
)->sa_family
];
3456 rt
->rt_flags
|= RTF_PROXY
;
3458 rt
->rt_flags
&= ~RTF_PROXY
;
3461 if (rnh
!= NULL
&& rt_mask(rt
)) {
3462 rnh
->rnh_walktree_from(rnh
, rt_key(rt
), rt_mask(rt
),
3468 lck_mtx_unlock(rnh_lock
);
3472 rte_lock_init(struct rtentry
*rt
)
3474 lck_mtx_init(&rt
->rt_lock
, rte_mtx_grp
, rte_mtx_attr
);
3478 rte_lock_destroy(struct rtentry
*rt
)
3480 RT_LOCK_ASSERT_NOTHELD(rt
);
3481 lck_mtx_destroy(&rt
->rt_lock
, rte_mtx_grp
);
3485 rt_lock(struct rtentry
*rt
, boolean_t spin
)
3487 RT_LOCK_ASSERT_NOTHELD(rt
);
3489 lck_mtx_lock_spin(&rt
->rt_lock
);
3491 lck_mtx_lock(&rt
->rt_lock
);
3492 if (rte_debug
& RTD_DEBUG
)
3493 rte_lock_debug((struct rtentry_dbg
*)rt
);
3497 rt_unlock(struct rtentry
*rt
)
3499 if (rte_debug
& RTD_DEBUG
)
3500 rte_unlock_debug((struct rtentry_dbg
*)rt
);
3501 lck_mtx_unlock(&rt
->rt_lock
);
3506 rte_lock_debug(struct rtentry_dbg
*rte
)
3510 RT_LOCK_ASSERT_HELD((struct rtentry
*)rte
);
3511 idx
= atomic_add_32_ov(&rte
->rtd_lock_cnt
, 1) % CTRACE_HIST_SIZE
;
3512 if (rte_debug
& RTD_TRACE
)
3513 ctrace_record(&rte
->rtd_lock
[idx
]);
3517 rte_unlock_debug(struct rtentry_dbg
*rte
)
3521 RT_LOCK_ASSERT_HELD((struct rtentry
*)rte
);
3522 idx
= atomic_add_32_ov(&rte
->rtd_unlock_cnt
, 1) % CTRACE_HIST_SIZE
;
3523 if (rte_debug
& RTD_TRACE
)
3524 ctrace_record(&rte
->rtd_unlock
[idx
]);
3527 static struct rtentry
*
3530 if (rte_debug
& RTD_DEBUG
)
3531 return (rte_alloc_debug());
3533 return ((struct rtentry
*)zalloc(rte_zone
));
3537 rte_free(struct rtentry
*p
)
3539 if (rte_debug
& RTD_DEBUG
) {
3544 if (p
->rt_refcnt
!= 0) {
3545 panic("rte_free: rte=%p refcnt=%d non-zero\n", p
, p
->rt_refcnt
);
3553 rte_if_ref(struct ifnet
*ifp
, int cnt
)
3555 struct kev_msg ev_msg
;
3556 struct net_event_data ev_data
;
3559 /* Force cnt to 1 increment/decrement */
3560 if (cnt
< -1 || cnt
> 1) {
3561 panic("%s: invalid count argument (%d)", __func__
, cnt
);
3564 old
= atomic_add_32_ov(&ifp
->if_route_refcnt
, cnt
);
3565 if (cnt
< 0 && old
== 0) {
3566 panic("%s: ifp=%p negative route refcnt!", __func__
, ifp
);
3570 * The following is done without first holding the ifnet lock,
3571 * for performance reasons. The relevant ifnet fields, with
3572 * the exception of the if_idle_flags, are never changed
3573 * during the lifetime of the ifnet. The if_idle_flags
3574 * may possibly be modified, so in the event that the value
3575 * is stale because IFRF_IDLE_NOTIFY was cleared, we'd end up
3576 * sending the event anyway. This is harmless as it is just
3577 * a notification to the monitoring agent in user space, and
3578 * it is expected to check via SIOCGIFGETRTREFCNT again anyway.
3580 if ((ifp
->if_idle_flags
& IFRF_IDLE_NOTIFY
) && cnt
< 0 && old
== 1) {
3581 bzero(&ev_msg
, sizeof (ev_msg
));
3582 bzero(&ev_data
, sizeof (ev_data
));
3584 ev_msg
.vendor_code
= KEV_VENDOR_APPLE
;
3585 ev_msg
.kev_class
= KEV_NETWORK_CLASS
;
3586 ev_msg
.kev_subclass
= KEV_DL_SUBCLASS
;
3587 ev_msg
.event_code
= KEV_DL_IF_IDLE_ROUTE_REFCNT
;
3589 strlcpy(&ev_data
.if_name
[0], ifp
->if_name
, IFNAMSIZ
);
3591 ev_data
.if_family
= ifp
->if_family
;
3592 ev_data
.if_unit
= ifp
->if_unit
;
3593 ev_msg
.dv
[0].data_length
= sizeof (struct net_event_data
);
3594 ev_msg
.dv
[0].data_ptr
= &ev_data
;
3596 kev_post_msg(&ev_msg
);
3600 static inline struct rtentry
*
3601 rte_alloc_debug(void)
3603 struct rtentry_dbg
*rte
;
3605 rte
= ((struct rtentry_dbg
*)zalloc(rte_zone
));
3607 bzero(rte
, sizeof (*rte
));
3608 if (rte_debug
& RTD_TRACE
)
3609 ctrace_record(&rte
->rtd_alloc
);
3610 rte
->rtd_inuse
= RTD_INUSE
;
3612 return ((struct rtentry
*)rte
);
3616 rte_free_debug(struct rtentry
*p
)
3618 struct rtentry_dbg
*rte
= (struct rtentry_dbg
*)p
;
3620 if (p
->rt_refcnt
!= 0) {
3621 panic("rte_free: rte=%p refcnt=%d\n", p
, p
->rt_refcnt
);
3624 if (rte
->rtd_inuse
== RTD_FREED
) {
3625 panic("rte_free: double free rte=%p\n", rte
);
3627 } else if (rte
->rtd_inuse
!= RTD_INUSE
) {
3628 panic("rte_free: corrupted rte=%p\n", rte
);
3631 bcopy((caddr_t
)p
, (caddr_t
)&rte
->rtd_entry_saved
, sizeof (*p
));
3632 /* Preserve rt_lock to help catch use-after-free cases */
3633 bzero((caddr_t
)p
, offsetof(struct rtentry
, rt_lock
));
3635 rte
->rtd_inuse
= RTD_FREED
;
3637 if (rte_debug
& RTD_TRACE
)
3638 ctrace_record(&rte
->rtd_free
);
3640 if (!(rte_debug
& RTD_NO_FREE
))
3645 ctrace_record(ctrace_t
*tr
)
3647 tr
->th
= current_thread();
3648 bzero(tr
->pc
, sizeof (tr
->pc
));
3649 (void) OSBacktrace(tr
->pc
, CTRACE_STACK_SIZE
);
3653 route_copyout(struct route
*dst
, const struct route
*src
, size_t length
)
3655 /* Copy everything (rt, srcif, flags, dst) from src */
3656 bcopy(src
, dst
, length
);
3658 /* Hold one reference for the local copy of struct route */
3659 if (dst
->ro_rt
!= NULL
)
3660 RT_ADDREF(dst
->ro_rt
);
3662 /* Hold one reference for the local copy of struct ifaddr */
3663 if (dst
->ro_srcia
!= NULL
)
3664 IFA_ADDREF(dst
->ro_srcia
);
3668 route_copyin(struct route
*src
, struct route
*dst
, size_t length
)
3670 /* No cached route at the destination? */
3671 if (dst
->ro_rt
== NULL
) {
3673 * Ditch the address in the cached copy (dst) since
3674 * we're about to take everything there is in src.
3676 if (dst
->ro_srcia
!= NULL
)
3677 IFA_REMREF(dst
->ro_srcia
);
3679 * Copy everything (rt, srcia, flags, dst) from src; the
3680 * references to rt and/or srcia were held at the time
3681 * of storage and are kept intact.
3683 bcopy(src
, dst
, length
);
3684 } else if (src
->ro_rt
!= NULL
) {
3686 * If the same, update srcia and flags, and ditch the route
3687 * in the local copy. Else ditch the one that is currently
3688 * cached, and cache the new route.
3690 if (dst
->ro_rt
== src
->ro_rt
) {
3691 dst
->ro_flags
= src
->ro_flags
;
3692 if (dst
->ro_srcia
!= src
->ro_srcia
) {
3693 if (dst
->ro_srcia
!= NULL
)
3694 IFA_REMREF(dst
->ro_srcia
);
3695 dst
->ro_srcia
= src
->ro_srcia
;
3696 } else if (src
->ro_srcia
!= NULL
) {
3697 IFA_REMREF(src
->ro_srcia
);
3702 if (dst
->ro_srcia
!= NULL
)
3703 IFA_REMREF(dst
->ro_srcia
);
3704 bcopy(src
, dst
, length
);
3706 } else if (src
->ro_srcia
!= NULL
) {
3708 * Ditch src address in the local copy (src) since we're
3709 * not caching the route entry anyway (ro_rt is NULL).
3711 IFA_REMREF(src
->ro_srcia
);
3714 /* This function consumes the references on src */
3716 src
->ro_srcia
= NULL
;
3720 * route_to_gwroute will find the gateway route for a given route.
3722 * If the route is down, look the route up again.
3723 * If the route goes through a gateway, get the route to the gateway.
3724 * If the gateway route is down, look it up again.
3725 * If the route is set to reject, verify it hasn't expired.
3727 * If the returned route is non-NULL, the caller is responsible for
3728 * releasing the reference and unlocking the route.
3730 #define senderr(e) { error = (e); goto bad; }
3732 route_to_gwroute(const struct sockaddr
*net_dest
, struct rtentry
*hint0
,
3733 struct rtentry
**out_route
)
3736 struct rtentry
*rt
= hint0
, *hint
= hint0
;
3738 unsigned int ifindex
;
3747 * Next hop determination. Because we may involve the gateway route
3748 * in addition to the original route, locking is rather complicated.
3749 * The general concept is that regardless of whether the route points
3750 * to the original route or to the gateway route, this routine takes
3751 * an extra reference on such a route. This extra reference will be
3752 * released at the end.
3754 * Care must be taken to ensure that the "hint0" route never gets freed
3755 * via rtfree(), since the caller may have stored it inside a struct
3756 * route with a reference held for that placeholder.
3759 ifindex
= rt
->rt_ifp
->if_index
;
3760 RT_ADDREF_LOCKED(rt
);
3761 if (!(rt
->rt_flags
& RTF_UP
)) {
3762 RT_REMREF_LOCKED(rt
);
3764 /* route is down, find a new one */
3765 hint
= rt
= rtalloc1_scoped((struct sockaddr
*)
3766 (size_t)net_dest
, 1, 0, ifindex
);
3769 ifindex
= rt
->rt_ifp
->if_index
;
3771 senderr(EHOSTUNREACH
);
3776 * We have a reference to "rt" by now; it will either
3777 * be released or freed at the end of this routine.
3779 RT_LOCK_ASSERT_HELD(rt
);
3780 if ((gwroute
= (rt
->rt_flags
& RTF_GATEWAY
))) {
3781 struct rtentry
*gwrt
= rt
->rt_gwroute
;
3782 struct sockaddr_storage ss
;
3783 struct sockaddr
*gw
= (struct sockaddr
*)&ss
;
3786 RT_ADDREF_LOCKED(hint
);
3788 /* If there's no gateway rt, look it up */
3790 bcopy(rt
->rt_gateway
, gw
, MIN(sizeof (ss
),
3791 rt
->rt_gateway
->sa_len
));
3795 /* Become a regular mutex */
3796 RT_CONVERT_LOCK(rt
);
3799 * Take gwrt's lock while holding route's lock;
3800 * this is okay since gwrt never points back
3801 * to "rt", so no lock ordering issues.
3804 if (!(gwrt
->rt_flags
& RTF_UP
)) {
3805 rt
->rt_gwroute
= NULL
;
3807 bcopy(rt
->rt_gateway
, gw
, MIN(sizeof (ss
),
3808 rt
->rt_gateway
->sa_len
));
3812 lck_mtx_lock(rnh_lock
);
3813 gwrt
= rtalloc1_scoped_locked(gw
, 1, 0, ifindex
);
3817 * Bail out if the route is down, no route
3818 * to gateway, circular route, or if the
3819 * gateway portion of "rt" has changed.
3821 if (!(rt
->rt_flags
& RTF_UP
) || gwrt
== NULL
||
3822 gwrt
== rt
|| !equal(gw
, rt
->rt_gateway
)) {
3824 RT_REMREF_LOCKED(gwrt
);
3828 RT_REMREF_LOCKED(hint
);
3832 rtfree_locked(gwrt
);
3833 lck_mtx_unlock(rnh_lock
);
3834 senderr(EHOSTUNREACH
);
3836 VERIFY(gwrt
!= NULL
);
3838 * Set gateway route; callee adds ref to gwrt;
3839 * gwrt has an extra ref from rtalloc1() for
3842 rt_set_gwroute(rt
, rt_key(rt
), gwrt
);
3844 RT_REMREF_LOCKED(rt
); /* hint still holds a refcnt */
3846 lck_mtx_unlock(rnh_lock
);
3849 RT_ADDREF_LOCKED(gwrt
);
3852 RT_REMREF_LOCKED(rt
); /* hint still holds a refcnt */
3856 VERIFY(rt
== gwrt
&& rt
!= hint
);
3859 * This is an opportunity to revalidate the parent route's
3860 * rt_gwroute, in case it now points to a dead route entry.
3861 * Parent route won't go away since the clone (hint) holds
3862 * a reference to it. rt == gwrt.
3865 if ((hint
->rt_flags
& (RTF_WASCLONED
| RTF_UP
)) ==
3866 (RTF_WASCLONED
| RTF_UP
)) {
3867 struct rtentry
*prt
= hint
->rt_parent
;
3868 VERIFY(prt
!= NULL
);
3870 RT_CONVERT_LOCK(hint
);
3873 rt_revalidate_gwroute(prt
, rt
);
3879 /* Clean up "hint" now; see notes above regarding hint0 */
3886 /* rt == gwrt; if it is now down, give up */
3888 if (!(rt
->rt_flags
& RTF_UP
)) {
3890 senderr(EHOSTUNREACH
);
3894 if (rt
->rt_flags
& RTF_REJECT
) {
3895 VERIFY(rt
->rt_expire
== 0 || rt
->rt_rmx
.rmx_expire
!= 0);
3896 VERIFY(rt
->rt_expire
!= 0 || rt
->rt_rmx
.rmx_expire
== 0);
3897 timenow
= net_uptime();
3898 if (rt
->rt_expire
== 0 || timenow
< rt
->rt_expire
) {
3900 senderr(!gwroute
? EHOSTDOWN
: EHOSTUNREACH
);
3904 /* Become a regular mutex */
3905 RT_CONVERT_LOCK(rt
);
3907 /* Caller is responsible for cleaning up "rt" */
3912 /* Clean up route (either it is "rt" or "gwrt") */
3916 RT_REMREF_LOCKED(rt
);
3928 rt_revalidate_gwroute(struct rtentry
*rt
, struct rtentry
*gwrt
)
3930 VERIFY(gwrt
!= NULL
);
3933 if ((rt
->rt_flags
& (RTF_GATEWAY
| RTF_UP
)) == (RTF_GATEWAY
| RTF_UP
) &&
3934 rt
->rt_ifp
== gwrt
->rt_ifp
&& rt
->rt_gateway
->sa_family
==
3935 rt_key(gwrt
)->sa_family
&& (rt
->rt_gwroute
== NULL
||
3936 !(rt
->rt_gwroute
->rt_flags
& RTF_UP
))) {
3938 VERIFY(rt
->rt_flags
& (RTF_CLONING
| RTF_PRCLONING
));
3940 if (rt
->rt_gateway
->sa_family
== AF_INET
||
3941 rt
->rt_gateway
->sa_family
== AF_INET6
) {
3942 struct sockaddr_storage key_ss
, gw_ss
;
3944 * We need to compare rt_key and rt_gateway; create
3945 * local copies to get rid of any ifscope association.
3947 (void) sa_copy(rt_key(gwrt
), &key_ss
, NULL
);
3948 (void) sa_copy(rt
->rt_gateway
, &gw_ss
, NULL
);
3950 isequal
= equal(SA(&key_ss
), SA(&gw_ss
));
3952 isequal
= equal(rt_key(gwrt
), rt
->rt_gateway
);
3955 /* If they are the same, update gwrt */
3958 lck_mtx_lock(rnh_lock
);
3960 rt_set_gwroute(rt
, rt_key(rt
), gwrt
);
3962 lck_mtx_unlock(rnh_lock
);
3972 rt_str4(struct rtentry
*rt
, char *ds
, uint32_t dslen
, char *gs
, uint32_t gslen
)
3974 VERIFY(rt_key(rt
)->sa_family
== AF_INET
);
3977 (void) inet_ntop(AF_INET
,
3978 &SIN(rt_key(rt
))->sin_addr
.s_addr
, ds
, dslen
);
3979 if (dslen
>= MAX_SCOPE_ADDR_STR_LEN
&&
3980 SINIFSCOPE(rt_key(rt
))->sin_scope_id
!= IFSCOPE_NONE
) {
3983 snprintf(scpstr
, sizeof(scpstr
), "@%u",
3984 SINIFSCOPE(rt_key(rt
))->sin_scope_id
);
3986 strlcat(ds
, scpstr
, dslen
);
3991 if (rt
->rt_flags
& RTF_GATEWAY
) {
3992 (void) inet_ntop(AF_INET
,
3993 &SIN(rt
->rt_gateway
)->sin_addr
.s_addr
, gs
, gslen
);
3994 } else if (rt
->rt_ifp
!= NULL
) {
3995 snprintf(gs
, gslen
, "link#%u", rt
->rt_ifp
->if_unit
);
3997 snprintf(gs
, gslen
, "%s", "link");
4004 rt_str6(struct rtentry
*rt
, char *ds
, uint32_t dslen
, char *gs
, uint32_t gslen
)
4006 VERIFY(rt_key(rt
)->sa_family
== AF_INET6
);
4009 (void) inet_ntop(AF_INET6
,
4010 &SIN6(rt_key(rt
))->sin6_addr
, ds
, dslen
);
4011 if (dslen
>= MAX_SCOPE_ADDR_STR_LEN
&&
4012 SIN6IFSCOPE(rt_key(rt
))->sin6_scope_id
!= IFSCOPE_NONE
) {
4015 snprintf(scpstr
, sizeof(scpstr
), "@%u",
4016 SIN6IFSCOPE(rt_key(rt
))->sin6_scope_id
);
4018 strlcat(ds
, scpstr
, dslen
);
4023 if (rt
->rt_flags
& RTF_GATEWAY
) {
4024 (void) inet_ntop(AF_INET6
,
4025 &SIN6(rt
->rt_gateway
)->sin6_addr
, gs
, gslen
);
4026 } else if (rt
->rt_ifp
!= NULL
) {
4027 snprintf(gs
, gslen
, "link#%u", rt
->rt_ifp
->if_unit
);
4029 snprintf(gs
, gslen
, "%s", "link");
4037 rt_str(struct rtentry
*rt
, char *ds
, uint32_t dslen
, char *gs
, uint32_t gslen
)
4039 switch (rt_key(rt
)->sa_family
) {
4041 rt_str4(rt
, ds
, dslen
, gs
, gslen
);
4045 rt_str6(rt
, ds
, dslen
, gs
, gslen
);