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