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