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