1 /*
2 * Copyright (c) 2000-2022 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 atomic_add_32(&route_genid_inet, 1);
862 }
863
864 void
routegenid_inet6_update(void)865 routegenid_inet6_update(void)
866 {
867 atomic_add_32(&route_genid_inet6, 1);
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 = atomic_add_16_ov(&rte->rtd_refrele_cnt, 1) % 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 = atomic_add_16_ov(&rte->rtd_refhold_cnt, 1) % 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 ifa = ifa_ifwithdstaddr(gw);
1717 }
1718 if (ifa == NULL) {
1719 ifa = ifa_ifwithnet_scoped(gw, ifscope);
1720 }
1721 if (ifa == NULL) {
1722 /* Workaround to avoid gcc warning regarding const variable */
1723 rt = rtalloc1_scoped_locked((struct sockaddr *)(size_t)dst,
1724 0, 0, ifscope);
1725 if (rt != NULL) {
1726 RT_LOCK_SPIN(rt);
1727 ifa = rt->rt_ifa;
1728 if (ifa != NULL) {
1729 /* Become a regular mutex */
1730 RT_CONVERT_LOCK(rt);
1731 IFA_ADDREF(ifa);
1732 }
1733 RT_REMREF_LOCKED(rt);
1734 RT_UNLOCK(rt);
1735 rt = NULL;
1736 }
1737 }
1738 /*
1739 * Holding rnh_lock here prevents the possibility of ifa from
1740 * changing (e.g. in_ifinit), so it is safe to access its
1741 * ifa_addr (here and down below) without locking.
1742 */
1743 if (ifa != NULL && ifa->ifa_addr->sa_family != dst->sa_family) {
1744 struct ifaddr *newifa;
1745 /* Callee adds reference to newifa upon success */
1746 newifa = ifaof_ifpforaddr(dst, ifa->ifa_ifp);
1747 if (newifa != NULL) {
1748 IFA_REMREF(ifa);
1749 ifa = newifa;
1750 }
1751 }
1752 /*
1753 * If we are adding a gateway, it is quite possible that the
1754 * routing table has a static entry in place for the gateway,
1755 * that may not agree with info garnered from the interfaces.
1756 * The routing table should carry more precedence than the
1757 * interfaces in this matter. Must be careful not to stomp
1758 * on new entries from rtinit, hence (ifa->ifa_addr != gw).
1759 */
1760 if ((ifa == NULL || (gw != NULL &&
1761 !sa_equal(ifa->ifa_addr, (struct sockaddr *)(size_t)gw))) &&
1762 (rt = rtalloc1_scoped_locked((struct sockaddr *)(size_t)gw,
1763 0, 0, ifscope)) != NULL) {
1764 if (ifa != NULL) {
1765 IFA_REMREF(ifa);
1766 }
1767 RT_LOCK_SPIN(rt);
1768 ifa = rt->rt_ifa;
1769 if (ifa != NULL) {
1770 /* Become a regular mutex */
1771 RT_CONVERT_LOCK(rt);
1772 IFA_ADDREF(ifa);
1773 }
1774 RT_REMREF_LOCKED(rt);
1775 RT_UNLOCK(rt);
1776 }
1777 /*
1778 * If an interface scope was specified, the interface index of
1779 * the found ifaddr must be equivalent to that of the scope;
1780 * otherwise there is no match.
1781 */
1782 if ((flags & RTF_IFSCOPE) &&
1783 ifa != NULL && ifa->ifa_ifp->if_index != ifscope) {
1784 IFA_REMREF(ifa);
1785 ifa = NULL;
1786 }
1787
1788 /*
1789 * ifa's address family must match destination's address family
1790 * after all is said and done.
1791 */
1792 if (ifa != NULL &&
1793 ifa->ifa_addr->sa_family != dst->sa_family) {
1794 IFA_REMREF(ifa);
1795 ifa = NULL;
1796 }
1797
1798 return ifa;
1799 }
1800
1801 static int rt_fixdelete(struct radix_node *, void *);
1802 static int rt_fixchange(struct radix_node *, void *);
1803
1804 struct rtfc_arg {
1805 struct rtentry *rt0;
1806 struct radix_node_head *rnh;
1807 };
1808
1809 int
rtrequest_locked(int req,struct sockaddr * dst,struct sockaddr * gateway,struct sockaddr * netmask,int flags,struct rtentry ** ret_nrt)1810 rtrequest_locked(int req, struct sockaddr *dst, struct sockaddr *gateway,
1811 struct sockaddr *netmask, int flags, struct rtentry **ret_nrt)
1812 {
1813 return rtrequest_common_locked(req, dst, gateway, netmask,
1814 (flags & ~RTF_IFSCOPE), ret_nrt, IFSCOPE_NONE);
1815 }
1816
1817 int
rtrequest_scoped_locked(int req,struct sockaddr * dst,struct sockaddr * gateway,struct sockaddr * netmask,int flags,struct rtentry ** ret_nrt,unsigned int ifscope)1818 rtrequest_scoped_locked(int req, struct sockaddr *dst,
1819 struct sockaddr *gateway, struct sockaddr *netmask, int flags,
1820 struct rtentry **ret_nrt, unsigned int ifscope)
1821 {
1822 if (ifscope != IFSCOPE_NONE) {
1823 flags |= RTF_IFSCOPE;
1824 } else {
1825 flags &= ~RTF_IFSCOPE;
1826 }
1827
1828 return rtrequest_common_locked(req, dst, gateway, netmask,
1829 flags, ret_nrt, ifscope);
1830 }
1831
1832 /*
1833 * Do appropriate manipulations of a routing tree given all the bits of
1834 * info needed.
1835 *
1836 * Storing the scope ID in the radix key is an internal job that should be
1837 * left to routines in this module. Callers should specify the scope value
1838 * to the "scoped" variants of route routines instead of manipulating the
1839 * key itself. This is typically done when creating a scoped route, e.g.
1840 * rtrequest(RTM_ADD). Once such a route is created and marked with the
1841 * RTF_IFSCOPE flag, callers can simply use its rt_key(rt) to clone it
1842 * (RTM_RESOLVE) or to remove it (RTM_DELETE). An exception to this is
1843 * during certain routing socket operations where the search key might be
1844 * derived from the routing message itself, in which case the caller must
1845 * specify the destination address and scope value for RTM_ADD/RTM_DELETE.
1846 */
1847 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)1848 rtrequest_common_locked(int req, struct sockaddr *dst0,
1849 struct sockaddr *gateway, struct sockaddr *netmask, int flags,
1850 struct rtentry **ret_nrt, unsigned int ifscope)
1851 {
1852 int error = 0;
1853 struct rtentry *rt;
1854 struct radix_node *rn;
1855 struct radix_node_head *rnh;
1856 struct ifaddr *ifa = NULL;
1857 struct sockaddr *ndst, *dst = dst0;
1858 struct sockaddr_storage ss, mask;
1859 struct timeval caltime;
1860 int af = dst->sa_family;
1861 void (*ifa_rtrequest)(int, struct rtentry *, struct sockaddr *);
1862
1863 #define senderr(x) { error = x; goto bad; }
1864
1865 DTRACE_ROUTE6(rtrequest, int, req, struct sockaddr *, dst0,
1866 struct sockaddr *, gateway, struct sockaddr *, netmask,
1867 int, flags, unsigned int, ifscope);
1868
1869 LCK_MTX_ASSERT(rnh_lock, LCK_MTX_ASSERT_OWNED);
1870
1871 #if !(DEVELOPMENT || DEBUG)
1872 /*
1873 * Setting the global internet flag external is only for testing
1874 */
1875 flags &= ~RTF_GLOBAL;
1876 #endif /* !(DEVELOPMENT || DEBUG) */
1877
1878 /*
1879 * Find the correct routing tree to use for this Address Family
1880 */
1881 if ((rnh = rt_tables[af]) == NULL) {
1882 senderr(ESRCH);
1883 }
1884 /*
1885 * If we are adding a host route then we don't want to put
1886 * a netmask in the tree
1887 */
1888 if (flags & RTF_HOST) {
1889 netmask = NULL;
1890 }
1891
1892 /*
1893 * If Scoped Routing is enabled, use a local copy of the destination
1894 * address to store the scope ID into. This logic is repeated below
1895 * in the RTM_RESOLVE handler since the caller does not normally
1896 * specify such a flag during a resolve, as well as for the handling
1897 * of IPv4 link-local address; instead, it passes in the route used for
1898 * cloning for which the scope info is derived from. Note also that
1899 * in the case of RTM_DELETE, the address passed in by the caller
1900 * might already contain the scope ID info when it is the key itself,
1901 * thus making RTF_IFSCOPE unnecessary; one instance where it is
1902 * explicitly set is inside route_output() as part of handling a
1903 * routing socket request.
1904 */
1905 if (req != RTM_RESOLVE && ((af == AF_INET) || (af == AF_INET6))) {
1906 /* Transform dst into the internal routing table form */
1907 dst = sa_copy(dst, &ss, &ifscope);
1908
1909 /* Transform netmask into the internal routing table form */
1910 if (netmask != NULL) {
1911 netmask = ma_copy(af, netmask, &mask, ifscope);
1912 }
1913
1914 if (ifscope != IFSCOPE_NONE) {
1915 flags |= RTF_IFSCOPE;
1916 }
1917 } else if ((flags & RTF_IFSCOPE) &&
1918 (af != AF_INET && af != AF_INET6)) {
1919 senderr(EINVAL);
1920 }
1921
1922 if (ifscope == IFSCOPE_NONE) {
1923 flags &= ~RTF_IFSCOPE;
1924 }
1925
1926 if (!in6_embedded_scope) {
1927 if (af == AF_INET6 &&
1928 IN6_IS_SCOPE_EMBED(&SIN6(dst)->sin6_addr) &&
1929 SIN6(dst)->sin6_scope_id == IFSCOPE_NONE) {
1930 SIN6(dst)->sin6_scope_id = ifscope;
1931 if (in6_embedded_scope_debug) {
1932 VERIFY(SIN6(dst)->sin6_scope_id != IFSCOPE_NONE);
1933 }
1934 }
1935
1936 if (af == AF_INET6 &&
1937 IN6_IS_SCOPE_EMBED(&SIN6(dst)->sin6_addr) &&
1938 ifscope == IFSCOPE_NONE) {
1939 ifscope = SIN6(dst)->sin6_scope_id;
1940 flags |= RTF_IFSCOPE;
1941 if (in6_embedded_scope_debug) {
1942 VERIFY(ifscope!= IFSCOPE_NONE);
1943 }
1944 }
1945 }
1946
1947 switch (req) {
1948 case RTM_DELETE: {
1949 struct rtentry *gwrt = NULL;
1950 boolean_t was_router = FALSE;
1951 uint32_t old_rt_refcnt = 0;
1952 /*
1953 * Remove the item from the tree and return it.
1954 * Complain if it is not there and do no more processing.
1955 */
1956 if ((rn = rnh->rnh_deladdr(dst, netmask, rnh)) == NULL) {
1957 senderr(ESRCH);
1958 }
1959 if (rn->rn_flags & (RNF_ACTIVE | RNF_ROOT)) {
1960 panic("rtrequest delete");
1961 /* NOTREACHED */
1962 }
1963 rt = (struct rtentry *)rn;
1964
1965 RT_LOCK(rt);
1966 old_rt_refcnt = rt->rt_refcnt;
1967 rt->rt_flags &= ~RTF_UP;
1968 /*
1969 * Release any idle reference count held on the interface
1970 * as this route is no longer externally visible.
1971 */
1972 rt_clear_idleref(rt);
1973 /*
1974 * Take an extra reference to handle the deletion of a route
1975 * entry whose reference count is already 0; e.g. an expiring
1976 * cloned route entry or an entry that was added to the table
1977 * with 0 reference. If the caller is interested in this route,
1978 * we will return it with the reference intact. Otherwise we
1979 * will decrement the reference via rtfree_locked() and then
1980 * possibly deallocate it.
1981 */
1982 RT_ADDREF_LOCKED(rt);
1983
1984 /*
1985 * For consistency, in case the caller didn't set the flag.
1986 */
1987 rt->rt_flags |= RTF_CONDEMNED;
1988
1989 /*
1990 * Clear RTF_ROUTER if it's set.
1991 */
1992 if (rt->rt_flags & RTF_ROUTER) {
1993 was_router = TRUE;
1994 VERIFY(rt->rt_flags & RTF_HOST);
1995 rt->rt_flags &= ~RTF_ROUTER;
1996 }
1997
1998 /*
1999 * Enqueue work item to invoke callback for this route entry
2000 *
2001 * If the old count is 0, it implies that last reference is being
2002 * removed and there's no one listening for this route event.
2003 */
2004 if (old_rt_refcnt != 0) {
2005 route_event_enqueue_nwk_wq_entry(rt, NULL,
2006 ROUTE_ENTRY_DELETED, NULL, TRUE);
2007 }
2008
2009 /*
2010 * Now search what's left of the subtree for any cloned
2011 * routes which might have been formed from this node.
2012 */
2013 if ((rt->rt_flags & (RTF_CLONING | RTF_PRCLONING)) &&
2014 rt_mask(rt)) {
2015 RT_UNLOCK(rt);
2016 rnh->rnh_walktree_from(rnh, dst, rt_mask(rt),
2017 rt_fixdelete, rt);
2018 RT_LOCK(rt);
2019 }
2020
2021 if (was_router) {
2022 struct route_event rt_ev;
2023 route_event_init(&rt_ev, rt, NULL, ROUTE_LLENTRY_DELETED);
2024 RT_UNLOCK(rt);
2025 (void) rnh->rnh_walktree(rnh,
2026 route_event_walktree, (void *)&rt_ev);
2027 RT_LOCK(rt);
2028 }
2029
2030 /*
2031 * Remove any external references we may have.
2032 */
2033 if ((gwrt = rt->rt_gwroute) != NULL) {
2034 rt->rt_gwroute = NULL;
2035 }
2036
2037 /*
2038 * give the protocol a chance to keep things in sync.
2039 */
2040 if ((ifa = rt->rt_ifa) != NULL) {
2041 IFA_LOCK_SPIN(ifa);
2042 ifa_rtrequest = ifa->ifa_rtrequest;
2043 IFA_UNLOCK(ifa);
2044 if (ifa_rtrequest != NULL) {
2045 ifa_rtrequest(RTM_DELETE, rt, NULL);
2046 }
2047 /* keep reference on rt_ifa */
2048 ifa = NULL;
2049 }
2050
2051 /*
2052 * one more rtentry floating around that is not
2053 * linked to the routing table.
2054 */
2055 (void) OSIncrementAtomic(&rttrash);
2056 if (rte_debug & RTD_DEBUG) {
2057 TAILQ_INSERT_TAIL(&rttrash_head,
2058 (struct rtentry_dbg *)rt, rtd_trash_link);
2059 }
2060
2061 /*
2062 * If this is the (non-scoped) default route, clear
2063 * the interface index used for the primary ifscope.
2064 */
2065 if (rt_primary_default(rt, rt_key(rt))) {
2066 set_primary_ifscope(rt_key(rt)->sa_family,
2067 IFSCOPE_NONE);
2068 if ((rt->rt_flags & RTF_STATIC) &&
2069 rt_key(rt)->sa_family == PF_INET6) {
2070 trigger_v6_defrtr_select = TRUE;
2071 }
2072 }
2073
2074 #if NECP
2075 /*
2076 * If this is a change in a default route, update
2077 * necp client watchers to re-evaluate
2078 */
2079 if (SA_DEFAULT(rt_key(rt))) {
2080 if (rt->rt_ifp != NULL) {
2081 ifnet_touch_lastupdown(rt->rt_ifp);
2082 }
2083 necp_update_all_clients();
2084 }
2085 #endif /* NECP */
2086
2087 RT_UNLOCK(rt);
2088
2089 /*
2090 * This might result in another rtentry being freed if
2091 * we held its last reference. Do this after the rtentry
2092 * lock is dropped above, as it could lead to the same
2093 * lock being acquired if gwrt is a clone of rt.
2094 */
2095 if (gwrt != NULL) {
2096 rtfree_locked(gwrt);
2097 }
2098
2099 /*
2100 * If the caller wants it, then it can have it,
2101 * but it's up to it to free the rtentry as we won't be
2102 * doing it.
2103 */
2104 if (ret_nrt != NULL) {
2105 /* Return the route to caller with reference intact */
2106 *ret_nrt = rt;
2107 } else {
2108 /* Dereference or deallocate the route */
2109 rtfree_locked(rt);
2110 }
2111 if (af == AF_INET) {
2112 routegenid_inet_update();
2113 } else if (af == AF_INET6) {
2114 routegenid_inet6_update();
2115 }
2116 break;
2117 }
2118 case RTM_RESOLVE:
2119 if (ret_nrt == NULL || (rt = *ret_nrt) == NULL) {
2120 senderr(EINVAL);
2121 }
2122 /*
2123 * According to the UNIX conformance tests, we need to return
2124 * ENETUNREACH when the parent route is RTF_REJECT.
2125 * However, there isn't any point in cloning RTF_REJECT
2126 * routes, so we immediately return an error.
2127 */
2128 if (rt->rt_flags & RTF_REJECT) {
2129 if (rt->rt_flags & RTF_HOST) {
2130 senderr(EHOSTUNREACH);
2131 } else {
2132 senderr(ENETUNREACH);
2133 }
2134 }
2135 /*
2136 * If cloning, we have the parent route given by the caller
2137 * and will use its rt_gateway, rt_rmx as part of the cloning
2138 * process below. Since rnh_lock is held at this point, the
2139 * parent's rt_ifa and rt_gateway will not change, and its
2140 * relevant rt_flags will not change as well. The only thing
2141 * that could change are the metrics, and thus we hold the
2142 * parent route's rt_lock later on during the actual copying
2143 * of rt_rmx.
2144 */
2145 ifa = rt->rt_ifa;
2146 IFA_ADDREF(ifa);
2147 flags = rt->rt_flags &
2148 ~(RTF_CLONING | RTF_PRCLONING | RTF_STATIC);
2149 flags |= RTF_WASCLONED;
2150 gateway = rt->rt_gateway;
2151 if ((netmask = rt->rt_genmask) == NULL) {
2152 flags |= RTF_HOST;
2153 }
2154
2155 if (af != AF_INET && af != AF_INET6) {
2156 goto makeroute;
2157 }
2158
2159 /*
2160 * When scoped routing is enabled, cloned entries are
2161 * always scoped according to the interface portion of
2162 * the parent route. The exception to this are IPv4
2163 * link local addresses, or those routes that are cloned
2164 * from a RTF_PROXY route. For the latter, the clone
2165 * gets to keep the RTF_PROXY flag.
2166 */
2167 if ((af == AF_INET &&
2168 IN_LINKLOCAL(ntohl(SIN(dst)->sin_addr.s_addr))) ||
2169 (rt->rt_flags & RTF_PROXY)) {
2170 ifscope = IFSCOPE_NONE;
2171 flags &= ~RTF_IFSCOPE;
2172 /*
2173 * These types of cloned routes aren't currently
2174 * eligible for idle interface reference counting.
2175 */
2176 flags |= RTF_NOIFREF;
2177 } else {
2178 if (flags & RTF_IFSCOPE) {
2179 ifscope = (af == AF_INET) ?
2180 sin_get_ifscope(rt_key(rt)) :
2181 sin6_get_ifscope(rt_key(rt));
2182 } else {
2183 ifscope = rt->rt_ifp->if_index;
2184 flags |= RTF_IFSCOPE;
2185 }
2186 VERIFY(ifscope != IFSCOPE_NONE);
2187 }
2188
2189 /*
2190 * Transform dst into the internal routing table form,
2191 * clearing out the scope ID field if ifscope isn't set.
2192 */
2193 dst = sa_copy(dst, &ss, (ifscope == IFSCOPE_NONE) ?
2194 NULL : &ifscope);
2195
2196 /* Transform netmask into the internal routing table form */
2197 if (netmask != NULL) {
2198 netmask = ma_copy(af, netmask, &mask, ifscope);
2199 }
2200
2201 goto makeroute;
2202
2203 case RTM_ADD:
2204 if ((flags & RTF_GATEWAY) && !gateway) {
2205 panic("rtrequest: RTF_GATEWAY but no gateway");
2206 /* NOTREACHED */
2207 }
2208 if (flags & RTF_IFSCOPE) {
2209 ifa = ifa_ifwithroute_scoped_locked(flags, dst0,
2210 gateway, ifscope);
2211 } else {
2212 ifa = ifa_ifwithroute_locked(flags, dst0, gateway);
2213 }
2214 if (ifa == NULL) {
2215 senderr(ENETUNREACH);
2216 }
2217 makeroute:
2218 /*
2219 * We land up here for both RTM_RESOLVE and RTM_ADD
2220 * when we decide to create a route.
2221 */
2222 if ((rt = rte_alloc()) == NULL) {
2223 senderr(ENOBUFS);
2224 }
2225 Bzero(rt, sizeof(*rt));
2226 rte_lock_init(rt);
2227 eventhandler_lists_ctxt_init(&rt->rt_evhdlr_ctxt);
2228 getmicrotime(&caltime);
2229 rt->base_calendartime = caltime.tv_sec;
2230 rt->base_uptime = net_uptime();
2231 RT_LOCK(rt);
2232 rt->rt_flags = RTF_UP | flags;
2233
2234 /*
2235 * Point the generation ID to the tree's.
2236 */
2237 switch (af) {
2238 case AF_INET:
2239 rt->rt_tree_genid = &route_genid_inet;
2240 break;
2241 case AF_INET6:
2242 rt->rt_tree_genid = &route_genid_inet6;
2243 break;
2244 default:
2245 break;
2246 }
2247
2248 /*
2249 * Add the gateway. Possibly re-malloc-ing the storage for it
2250 * also add the rt_gwroute if possible.
2251 */
2252 if ((error = rt_setgate(rt, dst, gateway)) != 0) {
2253 int tmp = error;
2254 RT_UNLOCK(rt);
2255 nstat_route_detach(rt);
2256 rte_lock_destroy(rt);
2257 rte_free(rt);
2258 senderr(tmp);
2259 }
2260
2261 /*
2262 * point to the (possibly newly malloc'd) dest address.
2263 */
2264 ndst = rt_key(rt);
2265
2266 /*
2267 * make sure it contains the value we want (masked if needed).
2268 */
2269 if (netmask) {
2270 rt_maskedcopy(dst, ndst, netmask);
2271 } else {
2272 Bcopy(dst, ndst, dst->sa_len);
2273 }
2274
2275 /*
2276 * Note that we now have a reference to the ifa.
2277 * This moved from below so that rnh->rnh_addaddr() can
2278 * examine the ifa and ifa->ifa_ifp if it so desires.
2279 */
2280 rtsetifa(rt, ifa);
2281 rt->rt_ifp = rt->rt_ifa->ifa_ifp;
2282
2283 /* XXX mtu manipulation will be done in rnh_addaddr -- itojun */
2284
2285 rn = rnh->rnh_addaddr((caddr_t)ndst, (caddr_t)netmask,
2286 rnh, rt->rt_nodes);
2287 if (rn == 0) {
2288 struct rtentry *rt2;
2289 /*
2290 * Uh-oh, we already have one of these in the tree.
2291 * We do a special hack: if the route that's already
2292 * there was generated by the protocol-cloning
2293 * mechanism, then we just blow it away and retry
2294 * the insertion of the new one.
2295 */
2296 if (flags & RTF_IFSCOPE) {
2297 rt2 = rtalloc1_scoped_locked(dst0, 0,
2298 RTF_CLONING | RTF_PRCLONING, ifscope);
2299 } else {
2300 rt2 = rtalloc1_locked(dst, 0,
2301 RTF_CLONING | RTF_PRCLONING);
2302 }
2303 if (rt2 && rt2->rt_parent) {
2304 /*
2305 * rnh_lock is held here, so rt_key and
2306 * rt_gateway of rt2 will not change.
2307 */
2308 (void) rtrequest_locked(RTM_DELETE, rt_key(rt2),
2309 rt2->rt_gateway, rt_mask(rt2),
2310 rt2->rt_flags, 0);
2311 rtfree_locked(rt2);
2312 rn = rnh->rnh_addaddr((caddr_t)ndst,
2313 (caddr_t)netmask, rnh, rt->rt_nodes);
2314 } else if (rt2) {
2315 /* undo the extra ref we got */
2316 rtfree_locked(rt2);
2317 }
2318 }
2319
2320 /*
2321 * If it still failed to go into the tree,
2322 * then un-make it (this should be a function)
2323 */
2324 if (rn == NULL) {
2325 /* Clear gateway route */
2326 rt_set_gwroute(rt, rt_key(rt), NULL);
2327 if (rt->rt_ifa) {
2328 IFA_REMREF(rt->rt_ifa);
2329 rt->rt_ifa = NULL;
2330 }
2331 rt_key_free(rt);
2332 RT_UNLOCK(rt);
2333 nstat_route_detach(rt);
2334 rte_lock_destroy(rt);
2335 rte_free(rt);
2336 senderr(EEXIST);
2337 }
2338
2339 rt->rt_parent = NULL;
2340
2341 /*
2342 * If we got here from RESOLVE, then we are cloning so clone
2343 * the rest, and note that we are a clone (and increment the
2344 * parent's references). rnh_lock is still held, which prevents
2345 * a lookup from returning the newly-created route. Hence
2346 * holding and releasing the parent's rt_lock while still
2347 * holding the route's rt_lock is safe since the new route
2348 * is not yet externally visible.
2349 */
2350 if (req == RTM_RESOLVE) {
2351 RT_LOCK_SPIN(*ret_nrt);
2352 VERIFY((*ret_nrt)->rt_expire == 0 ||
2353 (*ret_nrt)->rt_rmx.rmx_expire != 0);
2354 VERIFY((*ret_nrt)->rt_expire != 0 ||
2355 (*ret_nrt)->rt_rmx.rmx_expire == 0);
2356 rt->rt_rmx = (*ret_nrt)->rt_rmx;
2357 rt_setexpire(rt, (*ret_nrt)->rt_expire);
2358 if ((*ret_nrt)->rt_flags &
2359 (RTF_CLONING | RTF_PRCLONING)) {
2360 rt->rt_parent = (*ret_nrt);
2361 RT_ADDREF_LOCKED(*ret_nrt);
2362 }
2363 RT_UNLOCK(*ret_nrt);
2364 }
2365
2366 /*
2367 * if this protocol has something to add to this then
2368 * allow it to do that as well.
2369 */
2370 IFA_LOCK_SPIN(ifa);
2371 ifa_rtrequest = ifa->ifa_rtrequest;
2372 IFA_UNLOCK(ifa);
2373 if (ifa_rtrequest != NULL) {
2374 ifa_rtrequest(req, rt, SA(ret_nrt ? *ret_nrt : NULL));
2375 }
2376 IFA_REMREF(ifa);
2377 ifa = NULL;
2378
2379 /*
2380 * If this is the (non-scoped) default route, record
2381 * the interface index used for the primary ifscope.
2382 */
2383 if (rt_primary_default(rt, rt_key(rt))) {
2384 set_primary_ifscope(rt_key(rt)->sa_family,
2385 rt->rt_ifp->if_index);
2386 }
2387
2388 #if NECP
2389 /*
2390 * If this is a change in a default route, update
2391 * necp client watchers to re-evaluate
2392 */
2393 if (SA_DEFAULT(rt_key(rt))) {
2394 /*
2395 * Mark default routes as (potentially) leading to the global internet
2396 * this can be used for policy decisions.
2397 * The clone routes will inherit this flag.
2398 * We check against the host flag as this works for default routes that have
2399 * a gateway and defaults routes when all subnets are local.
2400 */
2401 if (req == RTM_ADD && (rt->rt_flags & RTF_HOST) == 0) {
2402 rt->rt_flags |= RTF_GLOBAL;
2403 }
2404 if (rt->rt_ifp != NULL) {
2405 ifnet_touch_lastupdown(rt->rt_ifp);
2406 }
2407 necp_update_all_clients();
2408 }
2409 #endif /* NECP */
2410
2411 /*
2412 * actually return a resultant rtentry and
2413 * give the caller a single reference.
2414 */
2415 if (ret_nrt) {
2416 *ret_nrt = rt;
2417 RT_ADDREF_LOCKED(rt);
2418 }
2419
2420 if (af == AF_INET) {
2421 routegenid_inet_update();
2422 } else if (af == AF_INET6) {
2423 routegenid_inet6_update();
2424 }
2425
2426 RT_GENID_SYNC(rt);
2427
2428 /*
2429 * We repeat the same procedures from rt_setgate() here
2430 * because they weren't completed when we called it earlier,
2431 * since the node was embryonic.
2432 */
2433 if ((rt->rt_flags & RTF_GATEWAY) && rt->rt_gwroute != NULL) {
2434 rt_set_gwroute(rt, rt_key(rt), rt->rt_gwroute);
2435 }
2436
2437 if (req == RTM_ADD &&
2438 !(rt->rt_flags & RTF_HOST) && rt_mask(rt) != NULL) {
2439 struct rtfc_arg arg;
2440 arg.rnh = rnh;
2441 arg.rt0 = rt;
2442 RT_UNLOCK(rt);
2443 rnh->rnh_walktree_from(rnh, rt_key(rt), rt_mask(rt),
2444 rt_fixchange, &arg);
2445 } else {
2446 RT_UNLOCK(rt);
2447 }
2448
2449 nstat_route_new_entry(rt);
2450 break;
2451 }
2452 bad:
2453 if (ifa) {
2454 IFA_REMREF(ifa);
2455 }
2456 return error;
2457 }
2458 #undef senderr
2459
2460 int
rtrequest(int req,struct sockaddr * dst,struct sockaddr * gateway,struct sockaddr * netmask,int flags,struct rtentry ** ret_nrt)2461 rtrequest(int req, struct sockaddr *dst, struct sockaddr *gateway,
2462 struct sockaddr *netmask, int flags, struct rtentry **ret_nrt)
2463 {
2464 int error;
2465 LCK_MTX_ASSERT(rnh_lock, LCK_MTX_ASSERT_NOTOWNED);
2466 lck_mtx_lock(rnh_lock);
2467 error = rtrequest_locked(req, dst, gateway, netmask, flags, ret_nrt);
2468 lck_mtx_unlock(rnh_lock);
2469 return error;
2470 }
2471
2472 int
rtrequest_scoped(int req,struct sockaddr * dst,struct sockaddr * gateway,struct sockaddr * netmask,int flags,struct rtentry ** ret_nrt,unsigned int ifscope)2473 rtrequest_scoped(int req, struct sockaddr *dst, struct sockaddr *gateway,
2474 struct sockaddr *netmask, int flags, struct rtentry **ret_nrt,
2475 unsigned int ifscope)
2476 {
2477 int error;
2478 LCK_MTX_ASSERT(rnh_lock, LCK_MTX_ASSERT_NOTOWNED);
2479 lck_mtx_lock(rnh_lock);
2480 error = rtrequest_scoped_locked(req, dst, gateway, netmask, flags,
2481 ret_nrt, ifscope);
2482 lck_mtx_unlock(rnh_lock);
2483 return error;
2484 }
2485
2486 /*
2487 * Called from rtrequest(RTM_DELETE, ...) to fix up the route's ``family''
2488 * (i.e., the routes related to it by the operation of cloning). This
2489 * routine is iterated over all potential former-child-routes by way of
2490 * rnh->rnh_walktree_from() above, and those that actually are children of
2491 * the late parent (passed in as VP here) are themselves deleted.
2492 */
2493 static int
rt_fixdelete(struct radix_node * rn,void * vp)2494 rt_fixdelete(struct radix_node *rn, void *vp)
2495 {
2496 struct rtentry *rt = (struct rtentry *)rn;
2497 struct rtentry *rt0 = vp;
2498
2499 LCK_MTX_ASSERT(rnh_lock, LCK_MTX_ASSERT_OWNED);
2500
2501 RT_LOCK(rt);
2502 if (rt->rt_parent == rt0 &&
2503 !(rt->rt_flags & (RTF_CLONING | RTF_PRCLONING))) {
2504 /*
2505 * Safe to drop rt_lock and use rt_key, since holding
2506 * rnh_lock here prevents another thread from calling
2507 * rt_setgate() on this route.
2508 */
2509 RT_UNLOCK(rt);
2510 return rtrequest_locked(RTM_DELETE, rt_key(rt), NULL,
2511 rt_mask(rt), rt->rt_flags, NULL);
2512 }
2513 RT_UNLOCK(rt);
2514 return 0;
2515 }
2516
2517 /*
2518 * This routine is called from rt_setgate() to do the analogous thing for
2519 * adds and changes. There is the added complication in this case of a
2520 * middle insert; i.e., insertion of a new network route between an older
2521 * network route and (cloned) host routes. For this reason, a simple check
2522 * of rt->rt_parent is insufficient; each candidate route must be tested
2523 * against the (mask, value) of the new route (passed as before in vp)
2524 * to see if the new route matches it.
2525 *
2526 * XXX - it may be possible to do fixdelete() for changes and reserve this
2527 * routine just for adds. I'm not sure why I thought it was necessary to do
2528 * changes this way.
2529 */
2530 static int
rt_fixchange(struct radix_node * rn,void * vp)2531 rt_fixchange(struct radix_node *rn, void *vp)
2532 {
2533 struct rtentry *rt = (struct rtentry *)rn;
2534 struct rtfc_arg *ap = vp;
2535 struct rtentry *rt0 = ap->rt0;
2536 struct radix_node_head *rnh = ap->rnh;
2537 u_char *xk1, *xm1, *xk2, *xmp;
2538 int i, len;
2539
2540 LCK_MTX_ASSERT(rnh_lock, LCK_MTX_ASSERT_OWNED);
2541
2542 RT_LOCK(rt);
2543
2544 if (!rt->rt_parent ||
2545 (rt->rt_flags & (RTF_CLONING | RTF_PRCLONING))) {
2546 RT_UNLOCK(rt);
2547 return 0;
2548 }
2549
2550 if (rt->rt_parent == rt0) {
2551 goto delete_rt;
2552 }
2553
2554 /*
2555 * There probably is a function somewhere which does this...
2556 * if not, there should be.
2557 */
2558 len = imin(rt_key(rt0)->sa_len, rt_key(rt)->sa_len);
2559
2560 xk1 = (u_char *)rt_key(rt0);
2561 xm1 = (u_char *)rt_mask(rt0);
2562 xk2 = (u_char *)rt_key(rt);
2563
2564 /*
2565 * Avoid applying a less specific route; do this only if the parent
2566 * route (rt->rt_parent) is a network route, since otherwise its mask
2567 * will be NULL if it is a cloning host route.
2568 */
2569 if ((xmp = (u_char *)rt_mask(rt->rt_parent)) != NULL) {
2570 int mlen = rt_mask(rt->rt_parent)->sa_len;
2571 if (mlen > rt_mask(rt0)->sa_len) {
2572 RT_UNLOCK(rt);
2573 return 0;
2574 }
2575
2576 for (i = rnh->rnh_treetop->rn_offset; i < mlen; i++) {
2577 if ((xmp[i] & ~(xmp[i] ^ xm1[i])) != xmp[i]) {
2578 RT_UNLOCK(rt);
2579 return 0;
2580 }
2581 }
2582 }
2583
2584 for (i = rnh->rnh_treetop->rn_offset; i < len; i++) {
2585 if ((xk2[i] & xm1[i]) != xk1[i]) {
2586 RT_UNLOCK(rt);
2587 return 0;
2588 }
2589 }
2590
2591 /*
2592 * OK, this node is a clone, and matches the node currently being
2593 * changed/added under the node's mask. So, get rid of it.
2594 */
2595 delete_rt:
2596 /*
2597 * Safe to drop rt_lock and use rt_key, since holding rnh_lock here
2598 * prevents another thread from calling rt_setgate() on this route.
2599 */
2600 RT_UNLOCK(rt);
2601 return rtrequest_locked(RTM_DELETE, rt_key(rt), NULL,
2602 rt_mask(rt), rt->rt_flags, NULL);
2603 }
2604
2605 /*
2606 * Round up sockaddr len to multiples of 32-bytes. This will reduce
2607 * or even eliminate the need to re-allocate the chunk of memory used
2608 * for rt_key and rt_gateway in the event the gateway portion changes.
2609 * Certain code paths (e.g. IPsec) are notorious for caching the address
2610 * of rt_gateway; this rounding-up would help ensure that the gateway
2611 * portion never gets deallocated (though it may change contents) and
2612 * thus greatly simplifies things.
2613 */
2614 #define SA_SIZE(x) (-(-((uintptr_t)(x)) & -(32)))
2615
2616 /*
2617 * Sets the gateway and/or gateway route portion of a route; may be
2618 * called on an existing route to modify the gateway portion. Both
2619 * rt_key and rt_gateway are allocated out of the same memory chunk.
2620 * Route entry lock must be held by caller; this routine will return
2621 * with the lock held.
2622 */
2623 int
rt_setgate(struct rtentry * rt,struct sockaddr * dst,struct sockaddr * gate)2624 rt_setgate(struct rtentry *rt, struct sockaddr *dst, struct sockaddr *gate)
2625 {
2626 int dlen = (int)SA_SIZE(dst->sa_len), glen = (int)SA_SIZE(gate->sa_len);
2627 struct radix_node_head *rnh = NULL;
2628 boolean_t loop = FALSE;
2629
2630 if (dst->sa_family != AF_INET && dst->sa_family != AF_INET6) {
2631 return EINVAL;
2632 }
2633
2634 rnh = rt_tables[dst->sa_family];
2635 LCK_MTX_ASSERT(rnh_lock, LCK_MTX_ASSERT_OWNED);
2636 RT_LOCK_ASSERT_HELD(rt);
2637
2638 /*
2639 * If this is for a route that is on its way of being removed,
2640 * or is temporarily frozen, reject the modification request.
2641 */
2642 if (rt->rt_flags & RTF_CONDEMNED) {
2643 return EBUSY;
2644 }
2645
2646 /* Add an extra ref for ourselves */
2647 RT_ADDREF_LOCKED(rt);
2648
2649 if (rt->rt_flags & RTF_GATEWAY) {
2650 if ((dst->sa_len == gate->sa_len) &&
2651 (dst->sa_family == AF_INET || dst->sa_family == AF_INET6)) {
2652 struct sockaddr_storage dst_ss, gate_ss;
2653
2654 (void) sa_copy(dst, &dst_ss, NULL);
2655 (void) sa_copy(gate, &gate_ss, NULL);
2656
2657 loop = sa_equal(SA(&dst_ss), SA(&gate_ss));
2658 } else {
2659 loop = (dst->sa_len == gate->sa_len &&
2660 sa_equal(dst, gate));
2661 }
2662 }
2663
2664 /*
2665 * A (cloning) network route with the destination equal to the gateway
2666 * will create an endless loop (see notes below), so disallow it.
2667 */
2668 if (((rt->rt_flags & (RTF_HOST | RTF_GATEWAY | RTF_LLINFO)) ==
2669 RTF_GATEWAY) && loop) {
2670 /* Release extra ref */
2671 RT_REMREF_LOCKED(rt);
2672 return EADDRNOTAVAIL;
2673 }
2674
2675 /*
2676 * A host route with the destination equal to the gateway
2677 * will interfere with keeping LLINFO in the routing
2678 * table, so disallow it.
2679 */
2680 if (((rt->rt_flags & (RTF_HOST | RTF_GATEWAY | RTF_LLINFO)) ==
2681 (RTF_HOST | RTF_GATEWAY)) && loop) {
2682 /*
2683 * The route might already exist if this is an RTM_CHANGE
2684 * or a routing redirect, so try to delete it.
2685 */
2686 if (rt_key(rt) != NULL) {
2687 /*
2688 * Safe to drop rt_lock and use rt_key, rt_gateway,
2689 * since holding rnh_lock here prevents another thread
2690 * from calling rt_setgate() on this route.
2691 */
2692 RT_UNLOCK(rt);
2693 (void) rtrequest_locked(RTM_DELETE, rt_key(rt),
2694 rt->rt_gateway, rt_mask(rt), rt->rt_flags, NULL);
2695 RT_LOCK(rt);
2696 }
2697 /* Release extra ref */
2698 RT_REMREF_LOCKED(rt);
2699 return EADDRNOTAVAIL;
2700 }
2701
2702 /*
2703 * The destination is not directly reachable. Get a route
2704 * to the next-hop gateway and store it in rt_gwroute.
2705 */
2706 if (rt->rt_flags & RTF_GATEWAY) {
2707 struct rtentry *gwrt;
2708 unsigned int ifscope;
2709
2710 if (dst->sa_family == AF_INET) {
2711 ifscope = sin_get_ifscope(dst);
2712 } else if (dst->sa_family == AF_INET6) {
2713 ifscope = sin6_get_ifscope(dst);
2714 } else {
2715 ifscope = IFSCOPE_NONE;
2716 }
2717
2718 RT_UNLOCK(rt);
2719 /*
2720 * Don't ignore RTF_CLONING, since we prefer that rt_gwroute
2721 * points to a clone rather than a cloning route; see above
2722 * check for cloning loop avoidance (dst == gate).
2723 */
2724 gwrt = rtalloc1_scoped_locked(gate, 1, RTF_PRCLONING, ifscope);
2725 if (gwrt != NULL) {
2726 RT_LOCK_ASSERT_NOTHELD(gwrt);
2727 }
2728 RT_LOCK(rt);
2729
2730 /*
2731 * Cloning loop avoidance:
2732 *
2733 * In the presence of protocol-cloning and bad configuration,
2734 * it is possible to get stuck in bottomless mutual recursion
2735 * (rtrequest rt_setgate rtalloc1). We avoid this by not
2736 * allowing protocol-cloning to operate for gateways (which
2737 * is probably the correct choice anyway), and avoid the
2738 * resulting reference loops by disallowing any route to run
2739 * through itself as a gateway. This is obviously mandatory
2740 * when we get rt->rt_output(). It implies that a route to
2741 * the gateway must already be present in the system in order
2742 * for the gateway to be referred to by another route.
2743 */
2744 if (gwrt == rt) {
2745 RT_REMREF_LOCKED(gwrt);
2746 /* Release extra ref */
2747 RT_REMREF_LOCKED(rt);
2748 return EADDRINUSE; /* failure */
2749 }
2750
2751 /*
2752 * If scoped, the gateway route must use the same interface;
2753 * we're holding rnh_lock now, so rt_gateway and rt_ifp of gwrt
2754 * should not change and are freely accessible.
2755 */
2756 if (ifscope != IFSCOPE_NONE && (rt->rt_flags & RTF_IFSCOPE) &&
2757 gwrt != NULL && gwrt->rt_ifp != NULL &&
2758 gwrt->rt_ifp->if_index != ifscope) {
2759 rtfree_locked(gwrt); /* rt != gwrt, no deadlock */
2760 /* Release extra ref */
2761 RT_REMREF_LOCKED(rt);
2762 return (rt->rt_flags & RTF_HOST) ?
2763 EHOSTUNREACH : ENETUNREACH;
2764 }
2765
2766 /* Check again since we dropped the lock above */
2767 if (rt->rt_flags & RTF_CONDEMNED) {
2768 if (gwrt != NULL) {
2769 rtfree_locked(gwrt);
2770 }
2771 /* Release extra ref */
2772 RT_REMREF_LOCKED(rt);
2773 return EBUSY;
2774 }
2775
2776 /* Set gateway route; callee adds ref to gwrt if non-NULL */
2777 rt_set_gwroute(rt, dst, gwrt);
2778
2779 /*
2780 * In case the (non-scoped) default route gets modified via
2781 * an ICMP redirect, record the interface index used for the
2782 * primary ifscope. Also done in rt_setif() to take care
2783 * of the non-redirect cases.
2784 */
2785 if (rt_primary_default(rt, dst) && rt->rt_ifp != NULL) {
2786 set_primary_ifscope(dst->sa_family,
2787 rt->rt_ifp->if_index);
2788 }
2789
2790 #if NECP
2791 /*
2792 * If this is a change in a default route, update
2793 * necp client watchers to re-evaluate
2794 */
2795 if (SA_DEFAULT(dst)) {
2796 necp_update_all_clients();
2797 }
2798 #endif /* NECP */
2799
2800 /*
2801 * Tell the kernel debugger about the new default gateway
2802 * if the gateway route uses the primary interface, or
2803 * if we are in a transient state before the non-scoped
2804 * default gateway is installed (similar to how the system
2805 * was behaving in the past). In future, it would be good
2806 * to do all this only when KDP is enabled.
2807 */
2808 if ((dst->sa_family == AF_INET) &&
2809 gwrt != NULL && gwrt->rt_gateway->sa_family == AF_LINK &&
2810 (gwrt->rt_ifp->if_index == get_primary_ifscope(AF_INET) ||
2811 get_primary_ifscope(AF_INET) == IFSCOPE_NONE)) {
2812 kdp_set_gateway_mac(SDL((void *)gwrt->rt_gateway)->
2813 sdl_data);
2814 }
2815
2816 /* Release extra ref from rtalloc1() */
2817 if (gwrt != NULL) {
2818 RT_REMREF(gwrt);
2819 }
2820 }
2821
2822 /*
2823 * Prepare to store the gateway in rt_gateway. Both dst and gateway
2824 * are stored one after the other in the same malloc'd chunk. If we
2825 * have room, reuse the old buffer since rt_gateway already points
2826 * to the right place. Otherwise, malloc a new block and update
2827 * the 'dst' address and point rt_gateway to the right place.
2828 */
2829 if (rt->rt_gateway == NULL || glen > SA_SIZE(rt->rt_gateway->sa_len)) {
2830 caddr_t new;
2831
2832 /* The underlying allocation is done with M_WAITOK set */
2833 new = kalloc_data(dlen + glen, Z_WAITOK | Z_ZERO);
2834 if (new == NULL) {
2835 /* Clear gateway route */
2836 rt_set_gwroute(rt, dst, NULL);
2837 /* Release extra ref */
2838 RT_REMREF_LOCKED(rt);
2839 return ENOBUFS;
2840 }
2841
2842 /*
2843 * Copy from 'dst' and not rt_key(rt) because we can get
2844 * here to initialize a newly allocated route entry, in
2845 * which case rt_key(rt) is NULL (and so does rt_gateway).
2846 */
2847 Bcopy(dst, new, dst->sa_len);
2848 rt_key_free(rt); /* free old block; NULL is okay */
2849 rt->rt_nodes->rn_key = new;
2850 rt->rt_gateway = (struct sockaddr *)(new + dlen);
2851 }
2852
2853 /*
2854 * Copy the new gateway value into the memory chunk.
2855 */
2856 Bcopy(gate, rt->rt_gateway, gate->sa_len);
2857
2858 /*
2859 * For consistency between rt_gateway and rt_key(gwrt).
2860 */
2861 if ((rt->rt_flags & RTF_GATEWAY) && rt->rt_gwroute != NULL &&
2862 (rt->rt_gwroute->rt_flags & RTF_IFSCOPE)) {
2863 if (rt->rt_gateway->sa_family == AF_INET &&
2864 rt_key(rt->rt_gwroute)->sa_family == AF_INET) {
2865 sin_set_ifscope(rt->rt_gateway,
2866 sin_get_ifscope(rt_key(rt->rt_gwroute)));
2867 } else if (rt->rt_gateway->sa_family == AF_INET6 &&
2868 rt_key(rt->rt_gwroute)->sa_family == AF_INET6) {
2869 sin6_set_ifscope(rt->rt_gateway,
2870 sin6_get_ifscope(rt_key(rt->rt_gwroute)));
2871 }
2872 }
2873
2874 /*
2875 * This isn't going to do anything useful for host routes, so
2876 * don't bother. Also make sure we have a reasonable mask
2877 * (we don't yet have one during adds).
2878 */
2879 if (!(rt->rt_flags & RTF_HOST) && rt_mask(rt) != 0) {
2880 struct rtfc_arg arg;
2881 arg.rnh = rnh;
2882 arg.rt0 = rt;
2883 RT_UNLOCK(rt);
2884 rnh->rnh_walktree_from(rnh, rt_key(rt), rt_mask(rt),
2885 rt_fixchange, &arg);
2886 RT_LOCK(rt);
2887 }
2888
2889 /* Release extra ref */
2890 RT_REMREF_LOCKED(rt);
2891 return 0;
2892 }
2893
2894 #undef SA_SIZE
2895
2896 void
rt_set_gwroute(struct rtentry * rt,struct sockaddr * dst,struct rtentry * gwrt)2897 rt_set_gwroute(struct rtentry *rt, struct sockaddr *dst, struct rtentry *gwrt)
2898 {
2899 boolean_t gwrt_isrouter;
2900
2901 LCK_MTX_ASSERT(rnh_lock, LCK_MTX_ASSERT_OWNED);
2902 RT_LOCK_ASSERT_HELD(rt);
2903
2904 if (gwrt != NULL) {
2905 RT_ADDREF(gwrt); /* for this routine */
2906 }
2907 /*
2908 * Get rid of existing gateway route; if rt_gwroute is already
2909 * set to gwrt, this is slightly redundant (though safe since
2910 * we held an extra ref above) but makes the code simpler.
2911 */
2912 if (rt->rt_gwroute != NULL) {
2913 struct rtentry *ogwrt = rt->rt_gwroute;
2914
2915 VERIFY(rt != ogwrt); /* sanity check */
2916 rt->rt_gwroute = NULL;
2917 RT_UNLOCK(rt);
2918 rtfree_locked(ogwrt);
2919 RT_LOCK(rt);
2920 VERIFY(rt->rt_gwroute == NULL);
2921 }
2922
2923 /*
2924 * And associate the new gateway route.
2925 */
2926 if ((rt->rt_gwroute = gwrt) != NULL) {
2927 RT_ADDREF(gwrt); /* for rt */
2928
2929 if (rt->rt_flags & RTF_WASCLONED) {
2930 /* rt_parent might be NULL if rt is embryonic */
2931 gwrt_isrouter = (rt->rt_parent != NULL &&
2932 SA_DEFAULT(rt_key(rt->rt_parent)) &&
2933 !RT_HOST(rt->rt_parent));
2934 } else {
2935 gwrt_isrouter = (SA_DEFAULT(dst) && !RT_HOST(rt));
2936 }
2937
2938 /* If gwrt points to a default router, mark it accordingly */
2939 if (gwrt_isrouter && RT_HOST(gwrt) &&
2940 !(gwrt->rt_flags & RTF_ROUTER)) {
2941 RT_LOCK(gwrt);
2942 gwrt->rt_flags |= RTF_ROUTER;
2943 RT_UNLOCK(gwrt);
2944 }
2945
2946 RT_REMREF(gwrt); /* for this routine */
2947 }
2948 }
2949
2950 static void
rt_maskedcopy(const struct sockaddr * src,struct sockaddr * dst,const struct sockaddr * netmask)2951 rt_maskedcopy(const struct sockaddr *src, struct sockaddr *dst,
2952 const struct sockaddr *netmask)
2953 {
2954 const char *netmaskp = &netmask->sa_data[0];
2955 const char *srcp = &src->sa_data[0];
2956 char *dstp = &dst->sa_data[0];
2957 const char *maskend = (char *)dst
2958 + MIN(netmask->sa_len, src->sa_len);
2959 const char *srcend = (char *)dst + src->sa_len;
2960
2961 dst->sa_len = src->sa_len;
2962 dst->sa_family = src->sa_family;
2963
2964 while (dstp < maskend) {
2965 *dstp++ = *srcp++ & *netmaskp++;
2966 }
2967 if (dstp < srcend) {
2968 memset(dstp, 0, (size_t)(srcend - dstp));
2969 }
2970 }
2971
2972 /*
2973 * Lookup an AF_INET/AF_INET6 scoped or non-scoped route depending on the
2974 * ifscope value passed in by the caller (IFSCOPE_NONE implies non-scoped).
2975 */
2976 static struct radix_node *
node_lookup(struct sockaddr * dst,struct sockaddr * netmask,unsigned int ifscope)2977 node_lookup(struct sockaddr *dst, struct sockaddr *netmask,
2978 unsigned int ifscope)
2979 {
2980 struct radix_node_head *rnh;
2981 struct radix_node *rn;
2982 struct sockaddr_storage ss, mask;
2983 int af = dst->sa_family;
2984 struct matchleaf_arg ma = { .ifscope = ifscope };
2985 rn_matchf_t *f = rn_match_ifscope;
2986 void *w = &ma;
2987
2988 if (af != AF_INET && af != AF_INET6) {
2989 return NULL;
2990 }
2991
2992 rnh = rt_tables[af];
2993
2994 /*
2995 * Transform dst into the internal routing table form,
2996 * clearing out the scope ID field if ifscope isn't set.
2997 */
2998 dst = sa_copy(dst, &ss, (ifscope == IFSCOPE_NONE) ? NULL : &ifscope);
2999
3000 /* Transform netmask into the internal routing table form */
3001 if (netmask != NULL) {
3002 netmask = ma_copy(af, netmask, &mask, ifscope);
3003 }
3004
3005 if (ifscope == IFSCOPE_NONE) {
3006 f = w = NULL;
3007 }
3008
3009 rn = rnh->rnh_lookup_args(dst, netmask, rnh, f, w);
3010 if (rn != NULL && (rn->rn_flags & RNF_ROOT)) {
3011 rn = NULL;
3012 }
3013
3014 return rn;
3015 }
3016
3017 /*
3018 * Lookup the AF_INET/AF_INET6 non-scoped default route.
3019 */
3020 static struct radix_node *
node_lookup_default(int af)3021 node_lookup_default(int af)
3022 {
3023 struct radix_node_head *rnh;
3024
3025 VERIFY(af == AF_INET || af == AF_INET6);
3026 rnh = rt_tables[af];
3027
3028 return af == AF_INET ? rnh->rnh_lookup(&sin_def, NULL, rnh) :
3029 rnh->rnh_lookup(&sin6_def, NULL, rnh);
3030 }
3031
3032 boolean_t
rt_ifa_is_dst(struct sockaddr * dst,struct ifaddr * ifa)3033 rt_ifa_is_dst(struct sockaddr *dst, struct ifaddr *ifa)
3034 {
3035 boolean_t result = FALSE;
3036
3037 if (ifa == NULL || ifa->ifa_addr == NULL) {
3038 return result;
3039 }
3040
3041 IFA_LOCK_SPIN(ifa);
3042
3043 if (dst->sa_family == ifa->ifa_addr->sa_family &&
3044 ((dst->sa_family == AF_INET &&
3045 SIN(dst)->sin_addr.s_addr ==
3046 SIN(ifa->ifa_addr)->sin_addr.s_addr) ||
3047 (dst->sa_family == AF_INET6 &&
3048 SA6_ARE_ADDR_EQUAL(SIN6(dst), SIN6(ifa->ifa_addr))))) {
3049 result = TRUE;
3050 }
3051
3052 IFA_UNLOCK(ifa);
3053
3054 return result;
3055 }
3056
3057 /*
3058 * Common routine to lookup/match a route. It invokes the lookup/matchaddr
3059 * callback which could be address family-specific. The main difference
3060 * between the two (at least for AF_INET/AF_INET6) is that a lookup does
3061 * not alter the expiring state of a route, whereas a match would unexpire
3062 * or revalidate the route.
3063 *
3064 * The optional scope or interface index property of a route allows for a
3065 * per-interface route instance. This permits multiple route entries having
3066 * the same destination (but not necessarily the same gateway) to exist in
3067 * the routing table; each of these entries is specific to the corresponding
3068 * interface. This is made possible by storing the scope ID value into the
3069 * radix key, thus making each route entry unique. These scoped entries
3070 * exist along with the regular, non-scoped entries in the same radix tree
3071 * for a given address family (AF_INET/AF_INET6); the scope logically
3072 * partitions it into multiple per-interface sub-trees.
3073 *
3074 * When a scoped route lookup is performed, the routing table is searched for
3075 * the best match that would result in a route using the same interface as the
3076 * one associated with the scope (the exception to this are routes that point
3077 * to the loopback interface). The search rule follows the longest matching
3078 * prefix with the additional interface constraint.
3079 */
3080 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)3081 rt_lookup_common(boolean_t lookup_only, boolean_t coarse, struct sockaddr *dst,
3082 struct sockaddr *netmask, struct radix_node_head *rnh, unsigned int ifscope)
3083 {
3084 struct radix_node *rn0, *rn = NULL;
3085 int af = dst->sa_family;
3086 struct sockaddr_storage dst_ss;
3087 struct sockaddr_storage mask_ss;
3088 boolean_t dontcare;
3089 #if (DEVELOPMENT || DEBUG)
3090 char dbuf[MAX_SCOPE_ADDR_STR_LEN], gbuf[MAX_IPv6_STR_LEN];
3091 char s_dst[MAX_IPv6_STR_LEN], s_netmask[MAX_IPv6_STR_LEN];
3092 #endif
3093 VERIFY(!coarse || ifscope == IFSCOPE_NONE);
3094
3095 LCK_MTX_ASSERT(rnh_lock, LCK_MTX_ASSERT_OWNED);
3096 /*
3097 * While we have rnh_lock held, see if we need to schedule the timer.
3098 */
3099 if (nd6_sched_timeout_want) {
3100 nd6_sched_timeout(NULL, NULL);
3101 }
3102
3103 if (!lookup_only) {
3104 netmask = NULL;
3105 }
3106
3107 /*
3108 * Non-scoped route lookup.
3109 */
3110 if (af != AF_INET && af != AF_INET6) {
3111 rn = rnh->rnh_matchaddr(dst, rnh);
3112
3113 /*
3114 * Don't return a root node; also, rnh_matchaddr callback
3115 * would have done the necessary work to clear RTPRF_OURS
3116 * for certain protocol families.
3117 */
3118 if (rn != NULL && (rn->rn_flags & RNF_ROOT)) {
3119 rn = NULL;
3120 }
3121 if (rn != NULL) {
3122 RT_LOCK_SPIN(RT(rn));
3123 if (!(RT(rn)->rt_flags & RTF_CONDEMNED)) {
3124 RT_ADDREF_LOCKED(RT(rn));
3125 RT_UNLOCK(RT(rn));
3126 } else {
3127 RT_UNLOCK(RT(rn));
3128 rn = NULL;
3129 }
3130 }
3131 return RT(rn);
3132 }
3133
3134 /* Transform dst/netmask into the internal routing table form */
3135 dst = sa_copy(dst, &dst_ss, &ifscope);
3136 if (netmask != NULL) {
3137 netmask = ma_copy(af, netmask, &mask_ss, ifscope);
3138 }
3139 dontcare = (ifscope == IFSCOPE_NONE);
3140
3141 #if (DEVELOPMENT || DEBUG)
3142 if (rt_verbose) {
3143 if (af == AF_INET) {
3144 (void) inet_ntop(af, &SIN(dst)->sin_addr.s_addr,
3145 s_dst, sizeof(s_dst));
3146 } else {
3147 (void) inet_ntop(af, &SIN6(dst)->sin6_addr,
3148 s_dst, sizeof(s_dst));
3149 }
3150
3151 if (netmask != NULL && af == AF_INET) {
3152 (void) inet_ntop(af, &SIN(netmask)->sin_addr.s_addr,
3153 s_netmask, sizeof(s_netmask));
3154 }
3155 if (netmask != NULL && af == AF_INET6) {
3156 (void) inet_ntop(af, &SIN6(netmask)->sin6_addr,
3157 s_netmask, sizeof(s_netmask));
3158 } else {
3159 *s_netmask = '\0';
3160 }
3161 os_log(OS_LOG_DEFAULT, "%s:%d (%d, %d, %s, %s, %u)\n",
3162 __func__, __LINE__, lookup_only, coarse, s_dst, s_netmask, ifscope);
3163 }
3164 #endif
3165
3166 /*
3167 * Scoped route lookup:
3168 *
3169 * We first perform a non-scoped lookup for the original result.
3170 * Afterwards, depending on whether or not the caller has specified
3171 * a scope, we perform a more specific scoped search and fallback
3172 * to this original result upon failure.
3173 */
3174 rn0 = rn = node_lookup(dst, netmask, IFSCOPE_NONE);
3175
3176 /*
3177 * If the caller did not specify a scope, use the primary scope
3178 * derived from the system's non-scoped default route. If, for
3179 * any reason, there is no primary interface, ifscope will be
3180 * set to IFSCOPE_NONE; if the above lookup resulted in a route,
3181 * we'll do a more-specific search below, scoped to the interface
3182 * of that route.
3183 */
3184 if (dontcare) {
3185 ifscope = get_primary_ifscope(af);
3186 }
3187
3188 /*
3189 * Keep the original result if either of the following is true:
3190 *
3191 * 1) The interface portion of the route has the same interface
3192 * index as the scope value and it is marked with RTF_IFSCOPE.
3193 * 2) The route uses the loopback interface, in which case the
3194 * destination (host/net) is local/loopback.
3195 *
3196 * Otherwise, do a more specified search using the scope;
3197 * we're holding rnh_lock now, so rt_ifp should not change.
3198 */
3199 if (rn != NULL) {
3200 struct rtentry *rt = RT(rn);
3201 #if (DEVELOPMENT || DEBUG)
3202 if (rt_verbose) {
3203 rt_str(rt, dbuf, sizeof(dbuf), gbuf, sizeof(gbuf));
3204 os_log(OS_LOG_DEFAULT, "%s unscoped search %p to %s->%s->%s ifa_ifp %s\n",
3205 __func__, rt,
3206 dbuf, gbuf,
3207 (rt->rt_ifp != NULL) ? rt->rt_ifp->if_xname : "",
3208 (rt->rt_ifa->ifa_ifp != NULL) ?
3209 rt->rt_ifa->ifa_ifp->if_xname : "");
3210 }
3211 #endif
3212 if (!(rt->rt_ifp->if_flags & IFF_LOOPBACK) ||
3213 (rt->rt_flags & RTF_GATEWAY)) {
3214 if (rt->rt_ifp->if_index != ifscope) {
3215 /*
3216 * Wrong interface; keep the original result
3217 * only if the caller did not specify a scope,
3218 * and do a more specific scoped search using
3219 * the scope of the found route. Otherwise,
3220 * start again from scratch.
3221 *
3222 * For loopback scope we keep the unscoped
3223 * route for local addresses
3224 */
3225 rn = NULL;
3226 if (dontcare) {
3227 ifscope = rt->rt_ifp->if_index;
3228 } else if (ifscope != lo_ifp->if_index ||
3229 rt_ifa_is_dst(dst, rt->rt_ifa) == FALSE) {
3230 rn0 = NULL;
3231 }
3232 } else if (!(rt->rt_flags & RTF_IFSCOPE)) {
3233 /*
3234 * Right interface, except that this route
3235 * isn't marked with RTF_IFSCOPE. Do a more
3236 * specific scoped search. Keep the original
3237 * result and return it it in case the scoped
3238 * search fails.
3239 */
3240 rn = NULL;
3241 }
3242 }
3243 }
3244
3245 /*
3246 * Scoped search. Find the most specific entry having the same
3247 * interface scope as the one requested. The following will result
3248 * in searching for the longest prefix scoped match.
3249 */
3250 if (rn == NULL) {
3251 rn = node_lookup(dst, netmask, ifscope);
3252 #if (DEVELOPMENT || DEBUG)
3253 if (rt_verbose && rn != NULL) {
3254 struct rtentry *rt = RT(rn);
3255
3256 rt_str(rt, dbuf, sizeof(dbuf), gbuf, sizeof(gbuf));
3257 os_log(OS_LOG_DEFAULT, "%s scoped search %p to %s->%s->%s ifa %s\n",
3258 __func__, rt,
3259 dbuf, gbuf,
3260 (rt->rt_ifp != NULL) ? rt->rt_ifp->if_xname : "",
3261 (rt->rt_ifa->ifa_ifp != NULL) ?
3262 rt->rt_ifa->ifa_ifp->if_xname : "");
3263 }
3264 #endif
3265 }
3266 /*
3267 * Use the original result if either of the following is true:
3268 *
3269 * 1) The scoped search did not yield any result.
3270 * 2) The caller insists on performing a coarse-grained lookup.
3271 * 3) The result from the scoped search is a scoped default route,
3272 * and the original (non-scoped) result is not a default route,
3273 * i.e. the original result is a more specific host/net route.
3274 * 4) The scoped search yielded a net route but the original
3275 * result is a host route, i.e. the original result is treated
3276 * as a more specific route.
3277 */
3278 if (rn == NULL || coarse || (rn0 != NULL &&
3279 ((SA_DEFAULT(rt_key(RT(rn))) && !SA_DEFAULT(rt_key(RT(rn0)))) ||
3280 (!RT_HOST(rn) && RT_HOST(rn0))))) {
3281 rn = rn0;
3282 }
3283
3284 /*
3285 * If we still don't have a route, use the non-scoped default
3286 * route as long as the interface portion satistifes the scope.
3287 */
3288 if (rn == NULL && (rn = node_lookup_default(af)) != NULL &&
3289 RT(rn)->rt_ifp->if_index != ifscope) {
3290 rn = NULL;
3291 }
3292
3293 if (rn != NULL) {
3294 /*
3295 * Manually clear RTPRF_OURS using rt_validate() and
3296 * bump up the reference count after, and not before;
3297 * we only get here for AF_INET/AF_INET6. node_lookup()
3298 * has done the check against RNF_ROOT, so we can be sure
3299 * that we're not returning a root node here.
3300 */
3301 RT_LOCK_SPIN(RT(rn));
3302 if (rt_validate(RT(rn))) {
3303 RT_ADDREF_LOCKED(RT(rn));
3304 RT_UNLOCK(RT(rn));
3305 } else {
3306 RT_UNLOCK(RT(rn));
3307 rn = NULL;
3308 }
3309 }
3310 #if (DEVELOPMENT || DEBUG)
3311 if (rt_verbose) {
3312 if (rn == NULL) {
3313 os_log(OS_LOG_DEFAULT, "%s %u return NULL\n", __func__, ifscope);
3314 } else {
3315 struct rtentry *rt = RT(rn);
3316
3317 rt_str(rt, dbuf, sizeof(dbuf), gbuf, sizeof(gbuf));
3318
3319 os_log(OS_LOG_DEFAULT, "%s %u return %p to %s->%s->%s ifa_ifp %s\n",
3320 __func__, ifscope, rt,
3321 dbuf, gbuf,
3322 (rt->rt_ifp != NULL) ? rt->rt_ifp->if_xname : "",
3323 (rt->rt_ifa->ifa_ifp != NULL) ?
3324 rt->rt_ifa->ifa_ifp->if_xname : "");
3325 }
3326 }
3327 #endif
3328 return RT(rn);
3329 }
3330
3331 struct rtentry *
rt_lookup(boolean_t lookup_only,struct sockaddr * dst,struct sockaddr * netmask,struct radix_node_head * rnh,unsigned int ifscope)3332 rt_lookup(boolean_t lookup_only, struct sockaddr *dst, struct sockaddr *netmask,
3333 struct radix_node_head *rnh, unsigned int ifscope)
3334 {
3335 return rt_lookup_common(lookup_only, FALSE, dst, netmask,
3336 rnh, ifscope);
3337 }
3338
3339 struct rtentry *
rt_lookup_coarse(boolean_t lookup_only,struct sockaddr * dst,struct sockaddr * netmask,struct radix_node_head * rnh)3340 rt_lookup_coarse(boolean_t lookup_only, struct sockaddr *dst,
3341 struct sockaddr *netmask, struct radix_node_head *rnh)
3342 {
3343 return rt_lookup_common(lookup_only, TRUE, dst, netmask,
3344 rnh, IFSCOPE_NONE);
3345 }
3346
3347 boolean_t
rt_validate(struct rtentry * rt)3348 rt_validate(struct rtentry *rt)
3349 {
3350 RT_LOCK_ASSERT_HELD(rt);
3351
3352 if ((rt->rt_flags & (RTF_UP | RTF_CONDEMNED)) == RTF_UP) {
3353 int af = rt_key(rt)->sa_family;
3354
3355 if (af == AF_INET) {
3356 (void) in_validate(RN(rt));
3357 } else if (af == AF_INET6) {
3358 (void) in6_validate(RN(rt));
3359 }
3360 } else {
3361 rt = NULL;
3362 }
3363
3364 return rt != NULL;
3365 }
3366
3367 /*
3368 * Set up a routing table entry, normally
3369 * for an interface.
3370 */
3371 int
rtinit(struct ifaddr * ifa,uint8_t cmd,int flags)3372 rtinit(struct ifaddr *ifa, uint8_t cmd, int flags)
3373 {
3374 int error;
3375
3376 LCK_MTX_ASSERT(rnh_lock, LCK_MTX_ASSERT_NOTOWNED);
3377
3378 lck_mtx_lock(rnh_lock);
3379 error = rtinit_locked(ifa, cmd, flags);
3380 lck_mtx_unlock(rnh_lock);
3381
3382 return error;
3383 }
3384
3385 int
rtinit_locked(struct ifaddr * ifa,uint8_t cmd,int flags)3386 rtinit_locked(struct ifaddr *ifa, uint8_t cmd, int flags)
3387 {
3388 struct radix_node_head *rnh;
3389 uint8_t nbuf[128]; /* long enough for IPv6 */
3390 #if (DEVELOPMENT || DEBUG)
3391 char dbuf[MAX_IPv6_STR_LEN], gbuf[MAX_IPv6_STR_LEN];
3392 char abuf[MAX_IPv6_STR_LEN];
3393 #endif
3394 struct rtentry *rt = NULL;
3395 struct sockaddr *dst;
3396 struct sockaddr *netmask;
3397 int error = 0;
3398
3399 /*
3400 * Holding rnh_lock here prevents the possibility of ifa from
3401 * changing (e.g. in_ifinit), so it is safe to access its
3402 * ifa_{dst}addr (here and down below) without locking.
3403 */
3404 LCK_MTX_ASSERT(rnh_lock, LCK_MTX_ASSERT_OWNED);
3405
3406 if (flags & RTF_HOST) {
3407 dst = ifa->ifa_dstaddr;
3408 netmask = NULL;
3409 } else {
3410 dst = ifa->ifa_addr;
3411 netmask = ifa->ifa_netmask;
3412 }
3413
3414 if (dst->sa_len == 0) {
3415 log(LOG_ERR, "%s: %s failed, invalid dst sa_len %d\n",
3416 __func__, rtm2str(cmd), dst->sa_len);
3417 error = EINVAL;
3418 goto done;
3419 }
3420 if (netmask != NULL && netmask->sa_len > sizeof(nbuf)) {
3421 log(LOG_ERR, "%s: %s failed, mask sa_len %d too large\n",
3422 __func__, rtm2str(cmd), dst->sa_len);
3423 error = EINVAL;
3424 goto done;
3425 }
3426
3427 #if (DEVELOPMENT || DEBUG)
3428 if (dst->sa_family == AF_INET) {
3429 (void) inet_ntop(AF_INET, &SIN(dst)->sin_addr.s_addr,
3430 abuf, sizeof(abuf));
3431 } else if (dst->sa_family == AF_INET6) {
3432 (void) inet_ntop(AF_INET6, &SIN6(dst)->sin6_addr,
3433 abuf, sizeof(abuf));
3434 }
3435 #endif /* (DEVELOPMENT || DEBUG) */
3436
3437 if ((rnh = rt_tables[dst->sa_family]) == NULL) {
3438 error = EINVAL;
3439 goto done;
3440 }
3441
3442 /*
3443 * If it's a delete, check that if it exists, it's on the correct
3444 * interface or we might scrub a route to another ifa which would
3445 * be confusing at best and possibly worse.
3446 */
3447 if (cmd == RTM_DELETE) {
3448 /*
3449 * It's a delete, so it should already exist..
3450 * If it's a net, mask off the host bits
3451 * (Assuming we have a mask)
3452 */
3453 if (netmask != NULL) {
3454 rt_maskedcopy(dst, SA(nbuf), netmask);
3455 dst = SA(nbuf);
3456 }
3457 /*
3458 * Get an rtentry that is in the routing tree and contains
3459 * the correct info. Note that we perform a coarse-grained
3460 * lookup here, in case there is a scoped variant of the
3461 * subnet/prefix route which we should ignore, as we never
3462 * add a scoped subnet/prefix route as part of adding an
3463 * interface address.
3464 */
3465 rt = rt_lookup_coarse(TRUE, dst, NULL, rnh);
3466 if (rt != NULL) {
3467 #if (DEVELOPMENT || DEBUG)
3468 rt_str(rt, dbuf, sizeof(dbuf), gbuf, sizeof(gbuf));
3469 #endif
3470 /*
3471 * Ok so we found the rtentry. it has an extra reference
3472 * for us at this stage. we won't need that so
3473 * lop that off now.
3474 */
3475 RT_LOCK(rt);
3476 if (rt->rt_ifa != ifa) {
3477 /*
3478 * If the interface address in the rtentry
3479 * doesn't match the interface we are using,
3480 * then we don't want to delete it, so return
3481 * an error. This seems to be the only point
3482 * of this whole RTM_DELETE clause.
3483 */
3484 #if (DEVELOPMENT || DEBUG)
3485 if (rt_verbose) {
3486 log(LOG_DEBUG, "%s: not removing "
3487 "route to %s->%s->%s, flags %b, "
3488 "ifaddr %s, rt_ifa 0x%llx != "
3489 "ifa 0x%llx\n", __func__, dbuf,
3490 gbuf, ((rt->rt_ifp != NULL) ?
3491 rt->rt_ifp->if_xname : ""),
3492 rt->rt_flags, RTF_BITS, abuf,
3493 (uint64_t)VM_KERNEL_ADDRPERM(
3494 rt->rt_ifa),
3495 (uint64_t)VM_KERNEL_ADDRPERM(ifa));
3496 }
3497 #endif /* (DEVELOPMENT || DEBUG) */
3498 RT_REMREF_LOCKED(rt);
3499 RT_UNLOCK(rt);
3500 rt = NULL;
3501 error = ((flags & RTF_HOST) ?
3502 EHOSTUNREACH : ENETUNREACH);
3503 goto done;
3504 } else if (rt->rt_flags & RTF_STATIC) {
3505 /*
3506 * Don't remove the subnet/prefix route if
3507 * this was manually added from above.
3508 */
3509 #if (DEVELOPMENT || DEBUG)
3510 if (rt_verbose) {
3511 log(LOG_DEBUG, "%s: not removing "
3512 "static route to %s->%s->%s, "
3513 "flags %b, ifaddr %s\n", __func__,
3514 dbuf, gbuf, ((rt->rt_ifp != NULL) ?
3515 rt->rt_ifp->if_xname : ""),
3516 rt->rt_flags, RTF_BITS, abuf);
3517 }
3518 #endif /* (DEVELOPMENT || DEBUG) */
3519 RT_REMREF_LOCKED(rt);
3520 RT_UNLOCK(rt);
3521 rt = NULL;
3522 error = EBUSY;
3523 goto done;
3524 }
3525 #if (DEVELOPMENT || DEBUG)
3526 if (rt_verbose) {
3527 log(LOG_DEBUG, "%s: removing route to "
3528 "%s->%s->%s, flags %b, ifaddr %s\n",
3529 __func__, dbuf, gbuf,
3530 ((rt->rt_ifp != NULL) ?
3531 rt->rt_ifp->if_xname : ""),
3532 rt->rt_flags, RTF_BITS, abuf);
3533 }
3534 #endif /* (DEVELOPMENT || DEBUG) */
3535 RT_REMREF_LOCKED(rt);
3536 RT_UNLOCK(rt);
3537 rt = NULL;
3538 }
3539 }
3540 /*
3541 * Do the actual request
3542 */
3543 if ((error = rtrequest_locked(cmd, dst, ifa->ifa_addr, netmask,
3544 flags | ifa->ifa_flags, &rt)) != 0) {
3545 goto done;
3546 }
3547
3548 VERIFY(rt != NULL);
3549 #if (DEVELOPMENT || DEBUG)
3550 rt_str(rt, dbuf, sizeof(dbuf), gbuf, sizeof(gbuf));
3551 #endif /* (DEVELOPMENT || DEBUG) */
3552 switch (cmd) {
3553 case RTM_DELETE:
3554 /*
3555 * If we are deleting, and we found an entry, then it's
3556 * been removed from the tree. Notify any listening
3557 * routing agents of the change and throw it away.
3558 */
3559 RT_LOCK(rt);
3560 rt_newaddrmsg(cmd, ifa, error, rt);
3561 RT_UNLOCK(rt);
3562 #if (DEVELOPMENT || DEBUG)
3563 if (rt_verbose) {
3564 log(LOG_DEBUG, "%s: removed route to %s->%s->%s, "
3565 "flags %b, ifaddr %s\n", __func__, dbuf, gbuf,
3566 ((rt->rt_ifp != NULL) ? rt->rt_ifp->if_xname : ""),
3567 rt->rt_flags, RTF_BITS, abuf);
3568 }
3569 #endif /* (DEVELOPMENT || DEBUG) */
3570 rtfree_locked(rt);
3571 break;
3572
3573 case RTM_ADD:
3574 /*
3575 * We are adding, and we have a returned routing entry.
3576 * We need to sanity check the result. If it came back
3577 * with an unexpected interface, then it must have already
3578 * existed or something.
3579 */
3580 RT_LOCK(rt);
3581 if (rt->rt_ifa != ifa) {
3582 void (*ifa_rtrequest)
3583 (int, struct rtentry *, struct sockaddr *);
3584 #if (DEVELOPMENT || DEBUG)
3585 if (rt_verbose) {
3586 if (!(rt->rt_ifa->ifa_ifp->if_flags &
3587 (IFF_POINTOPOINT | IFF_LOOPBACK))) {
3588 log(LOG_ERR, "%s: %s route to %s->%s->%s, "
3589 "flags %b, ifaddr %s, rt_ifa 0x%llx != "
3590 "ifa 0x%llx\n", __func__, rtm2str(cmd),
3591 dbuf, gbuf, ((rt->rt_ifp != NULL) ?
3592 rt->rt_ifp->if_xname : ""), rt->rt_flags,
3593 RTF_BITS, abuf,
3594 (uint64_t)VM_KERNEL_ADDRPERM(rt->rt_ifa),
3595 (uint64_t)VM_KERNEL_ADDRPERM(ifa));
3596 }
3597
3598 log(LOG_DEBUG, "%s: %s route to %s->%s->%s, "
3599 "flags %b, ifaddr %s, rt_ifa was 0x%llx "
3600 "now 0x%llx\n", __func__, rtm2str(cmd),
3601 dbuf, gbuf, ((rt->rt_ifp != NULL) ?
3602 rt->rt_ifp->if_xname : ""), rt->rt_flags,
3603 RTF_BITS, abuf,
3604 (uint64_t)VM_KERNEL_ADDRPERM(rt->rt_ifa),
3605 (uint64_t)VM_KERNEL_ADDRPERM(ifa));
3606 }
3607 #endif /* (DEVELOPMENT || DEBUG) */
3608
3609 /*
3610 * Ask that the protocol in question
3611 * remove anything it has associated with
3612 * this route and ifaddr.
3613 */
3614 ifa_rtrequest = rt->rt_ifa->ifa_rtrequest;
3615 if (ifa_rtrequest != NULL) {
3616 ifa_rtrequest(RTM_DELETE, rt, NULL);
3617 }
3618 /*
3619 * Set the route's ifa.
3620 */
3621 rtsetifa(rt, ifa);
3622
3623 if (rt->rt_ifp != ifa->ifa_ifp) {
3624 /*
3625 * Purge any link-layer info caching.
3626 */
3627 if (rt->rt_llinfo_purge != NULL) {
3628 rt->rt_llinfo_purge(rt);
3629 }
3630 /*
3631 * Adjust route ref count for the interfaces.
3632 */
3633 if (rt->rt_if_ref_fn != NULL) {
3634 rt->rt_if_ref_fn(ifa->ifa_ifp, 1);
3635 rt->rt_if_ref_fn(rt->rt_ifp, -1);
3636 }
3637 }
3638
3639 /*
3640 * And substitute in references to the ifaddr
3641 * we are adding.
3642 */
3643 rt->rt_ifp = ifa->ifa_ifp;
3644 /*
3645 * If rmx_mtu is not locked, update it
3646 * to the MTU used by the new interface.
3647 */
3648 if (!(rt->rt_rmx.rmx_locks & RTV_MTU)) {
3649 rt->rt_rmx.rmx_mtu = rt->rt_ifp->if_mtu;
3650 if (dst->sa_family == AF_INET &&
3651 INTF_ADJUST_MTU_FOR_CLAT46(rt->rt_ifp)) {
3652 rt->rt_rmx.rmx_mtu = IN6_LINKMTU(rt->rt_ifp);
3653 /* Further adjust the size for CLAT46 expansion */
3654 rt->rt_rmx.rmx_mtu -= CLAT46_HDR_EXPANSION_OVERHD;
3655 }
3656 }
3657
3658 /*
3659 * Now ask the protocol to check if it needs
3660 * any special processing in its new form.
3661 */
3662 ifa_rtrequest = ifa->ifa_rtrequest;
3663 if (ifa_rtrequest != NULL) {
3664 ifa_rtrequest(RTM_ADD, rt, NULL);
3665 }
3666 } else {
3667 #if (DEVELOPMENT || DEBUG)
3668 if (rt_verbose) {
3669 log(LOG_DEBUG, "%s: added route to %s->%s->%s, "
3670 "flags %b, ifaddr %s\n", __func__, dbuf,
3671 gbuf, ((rt->rt_ifp != NULL) ?
3672 rt->rt_ifp->if_xname : ""), rt->rt_flags,
3673 RTF_BITS, abuf);
3674 }
3675 #endif /* (DEVELOPMENT || DEBUG) */
3676 }
3677 /*
3678 * notify any listenning routing agents of the change
3679 */
3680 rt_newaddrmsg(cmd, ifa, error, rt);
3681 /*
3682 * We just wanted to add it; we don't actually need a
3683 * reference. This will result in a route that's added
3684 * to the routing table without a reference count. The
3685 * RTM_DELETE code will do the necessary step to adjust
3686 * the reference count at deletion time.
3687 */
3688 RT_REMREF_LOCKED(rt);
3689 RT_UNLOCK(rt);
3690 break;
3691
3692 default:
3693 VERIFY(0);
3694 /* NOTREACHED */
3695 }
3696 done:
3697 return error;
3698 }
3699
3700 static void
rt_set_idleref(struct rtentry * rt)3701 rt_set_idleref(struct rtentry *rt)
3702 {
3703 RT_LOCK_ASSERT_HELD(rt);
3704
3705 /*
3706 * We currently keep idle refcnt only on unicast cloned routes
3707 * that aren't marked with RTF_NOIFREF.
3708 */
3709 if (rt->rt_parent != NULL && !(rt->rt_flags &
3710 (RTF_NOIFREF | RTF_BROADCAST | RTF_MULTICAST)) &&
3711 (rt->rt_flags & (RTF_UP | RTF_WASCLONED | RTF_IFREF)) ==
3712 (RTF_UP | RTF_WASCLONED)) {
3713 rt_clear_idleref(rt); /* drop existing refcnt if any */
3714 rt->rt_if_ref_fn = rte_if_ref;
3715 /* Become a regular mutex, just in case */
3716 RT_CONVERT_LOCK(rt);
3717 rt->rt_if_ref_fn(rt->rt_ifp, 1);
3718 rt->rt_flags |= RTF_IFREF;
3719 }
3720 }
3721
3722 void
rt_clear_idleref(struct rtentry * rt)3723 rt_clear_idleref(struct rtentry *rt)
3724 {
3725 RT_LOCK_ASSERT_HELD(rt);
3726
3727 if (rt->rt_if_ref_fn != NULL) {
3728 VERIFY((rt->rt_flags & (RTF_NOIFREF | RTF_IFREF)) == RTF_IFREF);
3729 /* Become a regular mutex, just in case */
3730 RT_CONVERT_LOCK(rt);
3731 rt->rt_if_ref_fn(rt->rt_ifp, -1);
3732 rt->rt_flags &= ~RTF_IFREF;
3733 rt->rt_if_ref_fn = NULL;
3734 }
3735 }
3736
3737 void
rt_set_proxy(struct rtentry * rt,boolean_t set)3738 rt_set_proxy(struct rtentry *rt, boolean_t set)
3739 {
3740 lck_mtx_lock(rnh_lock);
3741 RT_LOCK(rt);
3742 /*
3743 * Search for any cloned routes which might have
3744 * been formed from this node, and delete them.
3745 */
3746 if (rt->rt_flags & (RTF_CLONING | RTF_PRCLONING)) {
3747 struct radix_node_head *rnh = rt_tables[rt_key(rt)->sa_family];
3748
3749 if (set) {
3750 rt->rt_flags |= RTF_PROXY;
3751 } else {
3752 rt->rt_flags &= ~RTF_PROXY;
3753 }
3754
3755 RT_UNLOCK(rt);
3756 if (rnh != NULL && rt_mask(rt)) {
3757 rnh->rnh_walktree_from(rnh, rt_key(rt), rt_mask(rt),
3758 rt_fixdelete, rt);
3759 }
3760 } else {
3761 RT_UNLOCK(rt);
3762 }
3763 lck_mtx_unlock(rnh_lock);
3764 }
3765
3766 static void
rte_lock_init(struct rtentry * rt)3767 rte_lock_init(struct rtentry *rt)
3768 {
3769 lck_mtx_init(&rt->rt_lock, &rte_mtx_grp, &rte_mtx_attr);
3770 }
3771
3772 static void
rte_lock_destroy(struct rtentry * rt)3773 rte_lock_destroy(struct rtentry *rt)
3774 {
3775 RT_LOCK_ASSERT_NOTHELD(rt);
3776 lck_mtx_destroy(&rt->rt_lock, &rte_mtx_grp);
3777 }
3778
3779 void
rt_lock(struct rtentry * rt,boolean_t spin)3780 rt_lock(struct rtentry *rt, boolean_t spin)
3781 {
3782 RT_LOCK_ASSERT_NOTHELD(rt);
3783 if (spin) {
3784 lck_mtx_lock_spin(&rt->rt_lock);
3785 } else {
3786 lck_mtx_lock(&rt->rt_lock);
3787 }
3788 if (rte_debug & RTD_DEBUG) {
3789 rte_lock_debug((struct rtentry_dbg *)rt);
3790 }
3791 }
3792
3793 void
rt_unlock(struct rtentry * rt)3794 rt_unlock(struct rtentry *rt)
3795 {
3796 if (rte_debug & RTD_DEBUG) {
3797 rte_unlock_debug((struct rtentry_dbg *)rt);
3798 }
3799 lck_mtx_unlock(&rt->rt_lock);
3800 }
3801
3802 static inline void
rte_lock_debug(struct rtentry_dbg * rte)3803 rte_lock_debug(struct rtentry_dbg *rte)
3804 {
3805 uint32_t idx;
3806
3807 RT_LOCK_ASSERT_HELD((struct rtentry *)rte);
3808 idx = atomic_add_32_ov(&rte->rtd_lock_cnt, 1) % CTRACE_HIST_SIZE;
3809 if (rte_debug & RTD_TRACE) {
3810 ctrace_record(&rte->rtd_lock[idx]);
3811 }
3812 }
3813
3814 static inline void
rte_unlock_debug(struct rtentry_dbg * rte)3815 rte_unlock_debug(struct rtentry_dbg *rte)
3816 {
3817 uint32_t idx;
3818
3819 RT_LOCK_ASSERT_HELD((struct rtentry *)rte);
3820 idx = atomic_add_32_ov(&rte->rtd_unlock_cnt, 1) % CTRACE_HIST_SIZE;
3821 if (rte_debug & RTD_TRACE) {
3822 ctrace_record(&rte->rtd_unlock[idx]);
3823 }
3824 }
3825
3826 static struct rtentry *
rte_alloc(void)3827 rte_alloc(void)
3828 {
3829 if (rte_debug & RTD_DEBUG) {
3830 return rte_alloc_debug();
3831 }
3832
3833 return (struct rtentry *)zalloc(rte_zone);
3834 }
3835
3836 static void
rte_free(struct rtentry * p)3837 rte_free(struct rtentry *p)
3838 {
3839 if (rte_debug & RTD_DEBUG) {
3840 rte_free_debug(p);
3841 return;
3842 }
3843
3844 if (p->rt_refcnt != 0) {
3845 panic("rte_free: rte=%p refcnt=%d non-zero", p, p->rt_refcnt);
3846 /* NOTREACHED */
3847 }
3848
3849 zfree(rte_zone, p);
3850 }
3851
3852 static void
rte_if_ref(struct ifnet * ifp,int cnt)3853 rte_if_ref(struct ifnet *ifp, int cnt)
3854 {
3855 struct kev_msg ev_msg;
3856 struct net_event_data ev_data;
3857 uint32_t old;
3858
3859 /* Force cnt to 1 increment/decrement */
3860 if (cnt < -1 || cnt > 1) {
3861 panic("%s: invalid count argument (%d)", __func__, cnt);
3862 /* NOTREACHED */
3863 }
3864 old = atomic_add_32_ov(&ifp->if_route_refcnt, cnt);
3865 if (cnt < 0 && old == 0) {
3866 panic("%s: ifp=%p negative route refcnt!", __func__, ifp);
3867 /* NOTREACHED */
3868 }
3869 /*
3870 * The following is done without first holding the ifnet lock,
3871 * for performance reasons. The relevant ifnet fields, with
3872 * the exception of the if_idle_flags, are never changed
3873 * during the lifetime of the ifnet. The if_idle_flags
3874 * may possibly be modified, so in the event that the value
3875 * is stale because IFRF_IDLE_NOTIFY was cleared, we'd end up
3876 * sending the event anyway. This is harmless as it is just
3877 * a notification to the monitoring agent in user space, and
3878 * it is expected to check via SIOCGIFGETRTREFCNT again anyway.
3879 */
3880 if ((ifp->if_idle_flags & IFRF_IDLE_NOTIFY) && cnt < 0 && old == 1) {
3881 bzero(&ev_msg, sizeof(ev_msg));
3882 bzero(&ev_data, sizeof(ev_data));
3883
3884 ev_msg.vendor_code = KEV_VENDOR_APPLE;
3885 ev_msg.kev_class = KEV_NETWORK_CLASS;
3886 ev_msg.kev_subclass = KEV_DL_SUBCLASS;
3887 ev_msg.event_code = KEV_DL_IF_IDLE_ROUTE_REFCNT;
3888
3889 strlcpy(&ev_data.if_name[0], ifp->if_name, IFNAMSIZ);
3890
3891 ev_data.if_family = ifp->if_family;
3892 ev_data.if_unit = ifp->if_unit;
3893 ev_msg.dv[0].data_length = sizeof(struct net_event_data);
3894 ev_msg.dv[0].data_ptr = &ev_data;
3895
3896 dlil_post_complete_msg(NULL, &ev_msg);
3897 }
3898 }
3899
3900 static inline struct rtentry *
rte_alloc_debug(void)3901 rte_alloc_debug(void)
3902 {
3903 struct rtentry_dbg *rte;
3904
3905 rte = ((struct rtentry_dbg *)zalloc(rte_zone));
3906 if (rte != NULL) {
3907 bzero(rte, sizeof(*rte));
3908 if (rte_debug & RTD_TRACE) {
3909 ctrace_record(&rte->rtd_alloc);
3910 }
3911 rte->rtd_inuse = RTD_INUSE;
3912 }
3913 return (struct rtentry *)rte;
3914 }
3915
3916 static inline void
rte_free_debug(struct rtentry * p)3917 rte_free_debug(struct rtentry *p)
3918 {
3919 struct rtentry_dbg *rte = (struct rtentry_dbg *)p;
3920
3921 if (p->rt_refcnt != 0) {
3922 panic("rte_free: rte=%p refcnt=%d", p, p->rt_refcnt);
3923 /* NOTREACHED */
3924 }
3925 if (rte->rtd_inuse == RTD_FREED) {
3926 panic("rte_free: double free rte=%p", rte);
3927 /* NOTREACHED */
3928 } else if (rte->rtd_inuse != RTD_INUSE) {
3929 panic("rte_free: corrupted rte=%p", rte);
3930 /* NOTREACHED */
3931 }
3932 bcopy((caddr_t)p, (caddr_t)&rte->rtd_entry_saved, sizeof(*p));
3933 /* Preserve rt_lock to help catch use-after-free cases */
3934 bzero((caddr_t)p, offsetof(struct rtentry, rt_lock));
3935
3936 rte->rtd_inuse = RTD_FREED;
3937
3938 if (rte_debug & RTD_TRACE) {
3939 ctrace_record(&rte->rtd_free);
3940 }
3941
3942 if (!(rte_debug & RTD_NO_FREE)) {
3943 zfree(rte_zone, p);
3944 }
3945 }
3946
3947 void
ctrace_record(ctrace_t * tr)3948 ctrace_record(ctrace_t *tr)
3949 {
3950 tr->th = current_thread();
3951 bzero(tr->pc, sizeof(tr->pc));
3952 (void) OSBacktrace(tr->pc, CTRACE_STACK_SIZE);
3953 }
3954
3955 void
route_clear(struct route * ro)3956 route_clear(struct route *ro)
3957 {
3958 if (ro == NULL) {
3959 return;
3960 }
3961
3962 if (ro->ro_rt != NULL) {
3963 rtfree(ro->ro_rt);
3964 ro->ro_rt = NULL;
3965 }
3966
3967 if (ro->ro_lle != NULL) {
3968 LLE_REMREF(ro->ro_lle);
3969 ro->ro_lle = NULL;
3970 }
3971
3972 if (ro->ro_srcia != NULL) {
3973 IFA_REMREF(ro->ro_srcia);
3974 ro->ro_srcia = NULL;
3975 }
3976 return;
3977 }
3978
3979
3980 void
route_copyout(struct route * dst,const struct route * src,size_t length)3981 route_copyout(struct route *dst, const struct route *src, size_t length)
3982 {
3983 /* Copy everything (rt, srcif, flags, dst) from src */
3984 bcopy(src, dst, length);
3985
3986 /* Hold one reference for the local copy of struct route */
3987 if (dst->ro_rt != NULL) {
3988 RT_ADDREF(dst->ro_rt);
3989 }
3990
3991 /* Hold one reference for the local copy of struct lle */
3992 if (dst->ro_lle != NULL) {
3993 LLE_ADDREF(dst->ro_lle);
3994 }
3995
3996 /* Hold one reference for the local copy of struct ifaddr */
3997 if (dst->ro_srcia != NULL) {
3998 IFA_ADDREF(dst->ro_srcia);
3999 }
4000 }
4001
4002 void
route_copyin(struct route * src,struct route * dst,size_t length)4003 route_copyin(struct route *src, struct route *dst, size_t length)
4004 {
4005 /*
4006 * No cached route at the destination?
4007 * If none, then remove old references if present
4008 * and copy entire src route.
4009 */
4010 if (dst->ro_rt == NULL) {
4011 /*
4012 * Ditch the cached link layer reference (dst)
4013 * since we're about to take everything there is in src
4014 */
4015 if (dst->ro_lle != NULL) {
4016 LLE_REMREF(dst->ro_lle);
4017 }
4018 /*
4019 * Ditch the address in the cached copy (dst) since
4020 * we're about to take everything there is in src.
4021 */
4022 if (dst->ro_srcia != NULL) {
4023 IFA_REMREF(dst->ro_srcia);
4024 }
4025 /*
4026 * Copy everything (rt, ro_lle, srcia, flags, dst) from src; the
4027 * references to rt and/or srcia were held at the time
4028 * of storage and are kept intact.
4029 */
4030 bcopy(src, dst, length);
4031 goto done;
4032 }
4033
4034 /*
4035 * We know dst->ro_rt is not NULL here.
4036 * If the src->ro_rt is the same, update ro_lle, srcia and flags
4037 * and ditch the route in the local copy.
4038 */
4039 if (dst->ro_rt == src->ro_rt) {
4040 dst->ro_flags = src->ro_flags;
4041
4042 if (dst->ro_lle != src->ro_lle) {
4043 if (dst->ro_lle != NULL) {
4044 LLE_REMREF(dst->ro_lle);
4045 }
4046 dst->ro_lle = src->ro_lle;
4047 } else if (src->ro_lle != NULL) {
4048 LLE_REMREF(src->ro_lle);
4049 }
4050
4051 if (dst->ro_srcia != src->ro_srcia) {
4052 if (dst->ro_srcia != NULL) {
4053 IFA_REMREF(dst->ro_srcia);
4054 }
4055 dst->ro_srcia = src->ro_srcia;
4056 } else if (src->ro_srcia != NULL) {
4057 IFA_REMREF(src->ro_srcia);
4058 }
4059 rtfree(src->ro_rt);
4060 goto done;
4061 }
4062
4063 /*
4064 * If they are dst's ro_rt is not equal to src's,
4065 * and src'd rt is not NULL, then remove old references
4066 * if present and copy entire src route.
4067 */
4068 if (src->ro_rt != NULL) {
4069 rtfree(dst->ro_rt);
4070
4071 if (dst->ro_lle != NULL) {
4072 LLE_REMREF(dst->ro_lle);
4073 }
4074 if (dst->ro_srcia != NULL) {
4075 IFA_REMREF(dst->ro_srcia);
4076 }
4077 bcopy(src, dst, length);
4078 goto done;
4079 }
4080
4081 /*
4082 * Here, dst's cached route is not NULL but source's is.
4083 * Just get rid of all the other cached reference in src.
4084 */
4085 if (src->ro_srcia != NULL) {
4086 /*
4087 * Ditch src address in the local copy (src) since we're
4088 * not caching the route entry anyway (ro_rt is NULL).
4089 */
4090 IFA_REMREF(src->ro_srcia);
4091 }
4092 if (src->ro_lle != NULL) {
4093 /*
4094 * Ditch cache lle in the local copy (src) since we're
4095 * not caching the route anyway (ro_rt is NULL).
4096 */
4097 LLE_REMREF(src->ro_lle);
4098 }
4099 done:
4100 /* This function consumes the references on src */
4101 src->ro_lle = NULL;
4102 src->ro_rt = NULL;
4103 src->ro_srcia = NULL;
4104 }
4105
4106 /*
4107 * route_to_gwroute will find the gateway route for a given route.
4108 *
4109 * If the route is down, look the route up again.
4110 * If the route goes through a gateway, get the route to the gateway.
4111 * If the gateway route is down, look it up again.
4112 * If the route is set to reject, verify it hasn't expired.
4113 *
4114 * If the returned route is non-NULL, the caller is responsible for
4115 * releasing the reference and unlocking the route.
4116 */
4117 #define senderr(e) { error = (e); goto bad; }
4118 errno_t
route_to_gwroute(const struct sockaddr * net_dest,struct rtentry * hint0,struct rtentry ** out_route)4119 route_to_gwroute(const struct sockaddr *net_dest, struct rtentry *hint0,
4120 struct rtentry **out_route)
4121 {
4122 uint64_t timenow;
4123 struct rtentry *rt = hint0, *hint = hint0;
4124 errno_t error = 0;
4125 unsigned int ifindex;
4126 boolean_t gwroute;
4127
4128 *out_route = NULL;
4129
4130 if (rt == NULL) {
4131 return 0;
4132 }
4133
4134 /*
4135 * Next hop determination. Because we may involve the gateway route
4136 * in addition to the original route, locking is rather complicated.
4137 * The general concept is that regardless of whether the route points
4138 * to the original route or to the gateway route, this routine takes
4139 * an extra reference on such a route. This extra reference will be
4140 * released at the end.
4141 *
4142 * Care must be taken to ensure that the "hint0" route never gets freed
4143 * via rtfree(), since the caller may have stored it inside a struct
4144 * route with a reference held for that placeholder.
4145 */
4146 RT_LOCK_SPIN(rt);
4147 ifindex = rt->rt_ifp->if_index;
4148 RT_ADDREF_LOCKED(rt);
4149 if (!(rt->rt_flags & RTF_UP)) {
4150 RT_REMREF_LOCKED(rt);
4151 RT_UNLOCK(rt);
4152 /* route is down, find a new one */
4153 hint = rt = rtalloc1_scoped((struct sockaddr *)
4154 (size_t)net_dest, 1, 0, ifindex);
4155 if (hint != NULL) {
4156 RT_LOCK_SPIN(rt);
4157 ifindex = rt->rt_ifp->if_index;
4158 } else {
4159 senderr(EHOSTUNREACH);
4160 }
4161 }
4162
4163 /*
4164 * We have a reference to "rt" by now; it will either
4165 * be released or freed at the end of this routine.
4166 */
4167 RT_LOCK_ASSERT_HELD(rt);
4168 if ((gwroute = (rt->rt_flags & RTF_GATEWAY))) {
4169 struct rtentry *gwrt = rt->rt_gwroute;
4170 struct sockaddr_storage ss;
4171 struct sockaddr *gw = (struct sockaddr *)&ss;
4172
4173 VERIFY(rt == hint);
4174 RT_ADDREF_LOCKED(hint);
4175
4176 /* If there's no gateway rt, look it up */
4177 if (gwrt == NULL) {
4178 bcopy(rt->rt_gateway, gw, MIN(sizeof(ss),
4179 rt->rt_gateway->sa_len));
4180 gw->sa_len = MIN(sizeof(ss), rt->rt_gateway->sa_len);
4181 RT_UNLOCK(rt);
4182 goto lookup;
4183 }
4184 /* Become a regular mutex */
4185 RT_CONVERT_LOCK(rt);
4186
4187 /*
4188 * Take gwrt's lock while holding route's lock;
4189 * this is okay since gwrt never points back
4190 * to "rt", so no lock ordering issues.
4191 */
4192 RT_LOCK_SPIN(gwrt);
4193 if (!(gwrt->rt_flags & RTF_UP)) {
4194 rt->rt_gwroute = NULL;
4195 RT_UNLOCK(gwrt);
4196 bcopy(rt->rt_gateway, gw, MIN(sizeof(ss),
4197 rt->rt_gateway->sa_len));
4198 gw->sa_len = MIN(sizeof(ss), rt->rt_gateway->sa_len);
4199 RT_UNLOCK(rt);
4200 rtfree(gwrt);
4201 lookup:
4202 lck_mtx_lock(rnh_lock);
4203 gwrt = rtalloc1_scoped_locked(gw, 1, 0, ifindex);
4204
4205 RT_LOCK(rt);
4206 /*
4207 * Bail out if the route is down, no route
4208 * to gateway, circular route, or if the
4209 * gateway portion of "rt" has changed.
4210 */
4211 if (!(rt->rt_flags & RTF_UP) || gwrt == NULL ||
4212 gwrt == rt || !sa_equal(gw, rt->rt_gateway)) {
4213 if (gwrt == rt) {
4214 RT_REMREF_LOCKED(gwrt);
4215 gwrt = NULL;
4216 }
4217 VERIFY(rt == hint);
4218 RT_REMREF_LOCKED(hint);
4219 hint = NULL;
4220 RT_UNLOCK(rt);
4221 if (gwrt != NULL) {
4222 rtfree_locked(gwrt);
4223 }
4224 lck_mtx_unlock(rnh_lock);
4225 senderr(EHOSTUNREACH);
4226 }
4227 VERIFY(gwrt != NULL);
4228 /*
4229 * Set gateway route; callee adds ref to gwrt;
4230 * gwrt has an extra ref from rtalloc1() for
4231 * this routine.
4232 */
4233 rt_set_gwroute(rt, rt_key(rt), gwrt);
4234 VERIFY(rt == hint);
4235 RT_REMREF_LOCKED(rt); /* hint still holds a refcnt */
4236 RT_UNLOCK(rt);
4237 lck_mtx_unlock(rnh_lock);
4238 rt = gwrt;
4239 } else {
4240 RT_ADDREF_LOCKED(gwrt);
4241 RT_UNLOCK(gwrt);
4242 VERIFY(rt == hint);
4243 RT_REMREF_LOCKED(rt); /* hint still holds a refcnt */
4244 RT_UNLOCK(rt);
4245 rt = gwrt;
4246 }
4247 VERIFY(rt == gwrt && rt != hint);
4248
4249 /*
4250 * This is an opportunity to revalidate the parent route's
4251 * rt_gwroute, in case it now points to a dead route entry.
4252 * Parent route won't go away since the clone (hint) holds
4253 * a reference to it. rt == gwrt.
4254 */
4255 RT_LOCK_SPIN(hint);
4256 if ((hint->rt_flags & (RTF_WASCLONED | RTF_UP)) ==
4257 (RTF_WASCLONED | RTF_UP)) {
4258 struct rtentry *prt = hint->rt_parent;
4259 VERIFY(prt != NULL);
4260
4261 RT_CONVERT_LOCK(hint);
4262 RT_ADDREF(prt);
4263 RT_UNLOCK(hint);
4264 rt_revalidate_gwroute(prt, rt);
4265 RT_REMREF(prt);
4266 } else {
4267 RT_UNLOCK(hint);
4268 }
4269
4270 /* Clean up "hint" now; see notes above regarding hint0 */
4271 if (hint == hint0) {
4272 RT_REMREF(hint);
4273 } else {
4274 rtfree(hint);
4275 }
4276 hint = NULL;
4277
4278 /* rt == gwrt; if it is now down, give up */
4279 RT_LOCK_SPIN(rt);
4280 if (!(rt->rt_flags & RTF_UP)) {
4281 RT_UNLOCK(rt);
4282 senderr(EHOSTUNREACH);
4283 }
4284 }
4285
4286 if (rt->rt_flags & RTF_REJECT) {
4287 VERIFY(rt->rt_expire == 0 || rt->rt_rmx.rmx_expire != 0);
4288 VERIFY(rt->rt_expire != 0 || rt->rt_rmx.rmx_expire == 0);
4289 timenow = net_uptime();
4290 if (rt->rt_expire == 0 || timenow < rt->rt_expire) {
4291 RT_UNLOCK(rt);
4292 senderr(!gwroute ? EHOSTDOWN : EHOSTUNREACH);
4293 }
4294 }
4295
4296 /* Become a regular mutex */
4297 RT_CONVERT_LOCK(rt);
4298
4299 /* Caller is responsible for cleaning up "rt" */
4300 *out_route = rt;
4301 return 0;
4302
4303 bad:
4304 /* Clean up route (either it is "rt" or "gwrt") */
4305 if (rt != NULL) {
4306 RT_LOCK_SPIN(rt);
4307 if (rt == hint0) {
4308 RT_REMREF_LOCKED(rt);
4309 RT_UNLOCK(rt);
4310 } else {
4311 RT_UNLOCK(rt);
4312 rtfree(rt);
4313 }
4314 }
4315 return error;
4316 }
4317 #undef senderr
4318
4319 void
rt_revalidate_gwroute(struct rtentry * rt,struct rtentry * gwrt)4320 rt_revalidate_gwroute(struct rtentry *rt, struct rtentry *gwrt)
4321 {
4322 VERIFY(gwrt != NULL);
4323
4324 RT_LOCK_SPIN(rt);
4325 if ((rt->rt_flags & (RTF_GATEWAY | RTF_UP)) == (RTF_GATEWAY | RTF_UP) &&
4326 rt->rt_ifp == gwrt->rt_ifp && rt->rt_gateway->sa_family ==
4327 rt_key(gwrt)->sa_family && (rt->rt_gwroute == NULL ||
4328 !(rt->rt_gwroute->rt_flags & RTF_UP))) {
4329 boolean_t isequal;
4330 VERIFY(rt->rt_flags & (RTF_CLONING | RTF_PRCLONING));
4331
4332 if (rt->rt_gateway->sa_family == AF_INET ||
4333 rt->rt_gateway->sa_family == AF_INET6) {
4334 struct sockaddr_storage key_ss, gw_ss;
4335 /*
4336 * We need to compare rt_key and rt_gateway; create
4337 * local copies to get rid of any ifscope association.
4338 */
4339 (void) sa_copy(rt_key(gwrt), &key_ss, NULL);
4340 (void) sa_copy(rt->rt_gateway, &gw_ss, NULL);
4341
4342 isequal = sa_equal(SA(&key_ss), SA(&gw_ss));
4343 } else {
4344 isequal = sa_equal(rt_key(gwrt), rt->rt_gateway);
4345 }
4346
4347 /* If they are the same, update gwrt */
4348 if (isequal) {
4349 RT_UNLOCK(rt);
4350 lck_mtx_lock(rnh_lock);
4351 RT_LOCK(rt);
4352 rt_set_gwroute(rt, rt_key(rt), gwrt);
4353 RT_UNLOCK(rt);
4354 lck_mtx_unlock(rnh_lock);
4355 } else {
4356 RT_UNLOCK(rt);
4357 }
4358 } else {
4359 RT_UNLOCK(rt);
4360 }
4361 }
4362
4363 static void
rt_str4(struct rtentry * rt,char * ds,uint32_t dslen,char * gs,uint32_t gslen)4364 rt_str4(struct rtentry *rt, char *ds, uint32_t dslen, char *gs, uint32_t gslen)
4365 {
4366 VERIFY(rt_key(rt)->sa_family == AF_INET);
4367
4368 if (ds != NULL) {
4369 (void) inet_ntop(AF_INET,
4370 &SIN(rt_key(rt))->sin_addr.s_addr, ds, dslen);
4371 if (dslen >= MAX_SCOPE_ADDR_STR_LEN &&
4372 SINIFSCOPE(rt_key(rt))->sin_scope_id != IFSCOPE_NONE) {
4373 char scpstr[16];
4374
4375 snprintf(scpstr, sizeof(scpstr), "@%u",
4376 SINIFSCOPE(rt_key(rt))->sin_scope_id);
4377
4378 strlcat(ds, scpstr, dslen);
4379 }
4380 }
4381
4382 if (gs != NULL) {
4383 if (rt->rt_flags & RTF_GATEWAY) {
4384 (void) inet_ntop(AF_INET,
4385 &SIN(rt->rt_gateway)->sin_addr.s_addr, gs, gslen);
4386 } else if (rt->rt_ifp != NULL) {
4387 snprintf(gs, gslen, "link#%u", rt->rt_ifp->if_unit);
4388 } else {
4389 snprintf(gs, gslen, "%s", "link");
4390 }
4391 }
4392 }
4393
4394 static void
rt_str6(struct rtentry * rt,char * ds,uint32_t dslen,char * gs,uint32_t gslen)4395 rt_str6(struct rtentry *rt, char *ds, uint32_t dslen, char *gs, uint32_t gslen)
4396 {
4397 VERIFY(rt_key(rt)->sa_family == AF_INET6);
4398
4399 if (ds != NULL) {
4400 (void) inet_ntop(AF_INET6,
4401 &SIN6(rt_key(rt))->sin6_addr, ds, dslen);
4402 if (dslen >= MAX_SCOPE_ADDR_STR_LEN &&
4403 SIN6IFSCOPE(rt_key(rt))->sin6_scope_id != IFSCOPE_NONE) {
4404 char scpstr[16];
4405
4406 snprintf(scpstr, sizeof(scpstr), "@%u",
4407 SIN6IFSCOPE(rt_key(rt))->sin6_scope_id);
4408
4409 strlcat(ds, scpstr, dslen);
4410 }
4411 }
4412
4413 if (gs != NULL) {
4414 if (rt->rt_flags & RTF_GATEWAY) {
4415 (void) inet_ntop(AF_INET6,
4416 &SIN6(rt->rt_gateway)->sin6_addr, gs, gslen);
4417 } else if (rt->rt_ifp != NULL) {
4418 snprintf(gs, gslen, "link#%u", rt->rt_ifp->if_unit);
4419 } else {
4420 snprintf(gs, gslen, "%s", "link");
4421 }
4422 }
4423 }
4424
4425 void
rt_str(struct rtentry * rt,char * ds,uint32_t dslen,char * gs,uint32_t gslen)4426 rt_str(struct rtentry *rt, char *ds, uint32_t dslen, char *gs, uint32_t gslen)
4427 {
4428 switch (rt_key(rt)->sa_family) {
4429 case AF_INET:
4430 rt_str4(rt, ds, dslen, gs, gslen);
4431 break;
4432 case AF_INET6:
4433 rt_str6(rt, ds, dslen, gs, gslen);
4434 break;
4435 default:
4436 if (ds != NULL) {
4437 bzero(ds, dslen);
4438 }
4439 if (gs != NULL) {
4440 bzero(gs, gslen);
4441 }
4442 break;
4443 }
4444 }
4445
4446 void
route_event_init(struct route_event * p_route_ev,struct rtentry * rt,struct rtentry * gwrt,int route_ev_code)4447 route_event_init(struct route_event *p_route_ev, struct rtentry *rt,
4448 struct rtentry *gwrt, int route_ev_code)
4449 {
4450 VERIFY(p_route_ev != NULL);
4451 bzero(p_route_ev, sizeof(*p_route_ev));
4452
4453 p_route_ev->rt = rt;
4454 p_route_ev->gwrt = gwrt;
4455 p_route_ev->route_event_code = route_ev_code;
4456 }
4457
4458 struct route_event_nwk_wq_entry {
4459 struct nwk_wq_entry nwk_wqe;
4460 struct route_event rt_ev_arg;
4461 };
4462
4463 static void
route_event_callback(struct nwk_wq_entry * nwk_item)4464 route_event_callback(struct nwk_wq_entry *nwk_item)
4465 {
4466 struct route_event_nwk_wq_entry *p_ev = __container_of(nwk_item,
4467 struct route_event_nwk_wq_entry, nwk_wqe);
4468
4469 struct rtentry *rt = p_ev->rt_ev_arg.rt;
4470 eventhandler_tag evtag = p_ev->rt_ev_arg.evtag;
4471 int route_ev_code = p_ev->rt_ev_arg.route_event_code;
4472
4473 if (route_ev_code == ROUTE_EVHDLR_DEREGISTER) {
4474 VERIFY(evtag != NULL);
4475 EVENTHANDLER_DEREGISTER(&rt->rt_evhdlr_ctxt, route_event,
4476 evtag);
4477 rtfree(rt);
4478 kfree_type(struct route_event_nwk_wq_entry, p_ev);
4479 return;
4480 }
4481
4482 EVENTHANDLER_INVOKE(&rt->rt_evhdlr_ctxt, route_event, rt_key(rt),
4483 route_ev_code, (struct sockaddr *)&p_ev->rt_ev_arg.rt_addr,
4484 rt->rt_flags);
4485
4486 /* The code enqueuing the route event held a reference */
4487 rtfree(rt);
4488 /* XXX No reference is taken on gwrt */
4489 kfree_type(struct route_event_nwk_wq_entry, p_ev);
4490 }
4491
4492 int
route_event_walktree(struct radix_node * rn,void * arg)4493 route_event_walktree(struct radix_node *rn, void *arg)
4494 {
4495 struct route_event *p_route_ev = (struct route_event *)arg;
4496 struct rtentry *rt = (struct rtentry *)rn;
4497 struct rtentry *gwrt = p_route_ev->rt;
4498
4499 LCK_MTX_ASSERT(rnh_lock, LCK_MTX_ASSERT_OWNED);
4500
4501 RT_LOCK(rt);
4502
4503 /* Return if the entry is pending cleanup */
4504 if (rt->rt_flags & RTPRF_OURS) {
4505 RT_UNLOCK(rt);
4506 return 0;
4507 }
4508
4509 /* Return if it is not an indirect route */
4510 if (!(rt->rt_flags & RTF_GATEWAY)) {
4511 RT_UNLOCK(rt);
4512 return 0;
4513 }
4514
4515 if (rt->rt_gwroute != gwrt) {
4516 RT_UNLOCK(rt);
4517 return 0;
4518 }
4519
4520 route_event_enqueue_nwk_wq_entry(rt, gwrt, p_route_ev->route_event_code,
4521 NULL, TRUE);
4522 RT_UNLOCK(rt);
4523
4524 return 0;
4525 }
4526
4527 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)4528 route_event_enqueue_nwk_wq_entry(struct rtentry *rt, struct rtentry *gwrt,
4529 uint32_t route_event_code, eventhandler_tag evtag, boolean_t rt_locked)
4530 {
4531 struct route_event_nwk_wq_entry *p_rt_ev = NULL;
4532 struct sockaddr *p_gw_saddr = NULL;
4533
4534 p_rt_ev = kalloc_type(struct route_event_nwk_wq_entry,
4535 Z_WAITOK | Z_ZERO | Z_NOFAIL);
4536
4537 /*
4538 * If the intent is to de-register, don't take
4539 * reference, route event registration already takes
4540 * a reference on route.
4541 */
4542 if (route_event_code != ROUTE_EVHDLR_DEREGISTER) {
4543 /* The reference is released by route_event_callback */
4544 if (rt_locked) {
4545 RT_ADDREF_LOCKED(rt);
4546 } else {
4547 RT_ADDREF(rt);
4548 }
4549 }
4550
4551 p_rt_ev->rt_ev_arg.rt = rt;
4552 p_rt_ev->rt_ev_arg.gwrt = gwrt;
4553 p_rt_ev->rt_ev_arg.evtag = evtag;
4554
4555 if (gwrt != NULL) {
4556 p_gw_saddr = gwrt->rt_gateway;
4557 } else {
4558 p_gw_saddr = rt->rt_gateway;
4559 }
4560
4561 VERIFY(p_gw_saddr->sa_len <= sizeof(p_rt_ev->rt_ev_arg.rt_addr));
4562 bcopy(p_gw_saddr, &(p_rt_ev->rt_ev_arg.rt_addr), p_gw_saddr->sa_len);
4563
4564 p_rt_ev->rt_ev_arg.route_event_code = route_event_code;
4565 p_rt_ev->nwk_wqe.func = route_event_callback;
4566 nwk_wq_enqueue(&p_rt_ev->nwk_wqe);
4567 }
4568
4569 const char *
route_event2str(int route_event)4570 route_event2str(int route_event)
4571 {
4572 const char *route_event_str = "ROUTE_EVENT_UNKNOWN";
4573 switch (route_event) {
4574 case ROUTE_STATUS_UPDATE:
4575 route_event_str = "ROUTE_STATUS_UPDATE";
4576 break;
4577 case ROUTE_ENTRY_REFRESH:
4578 route_event_str = "ROUTE_ENTRY_REFRESH";
4579 break;
4580 case ROUTE_ENTRY_DELETED:
4581 route_event_str = "ROUTE_ENTRY_DELETED";
4582 break;
4583 case ROUTE_LLENTRY_RESOLVED:
4584 route_event_str = "ROUTE_LLENTRY_RESOLVED";
4585 break;
4586 case ROUTE_LLENTRY_UNREACH:
4587 route_event_str = "ROUTE_LLENTRY_UNREACH";
4588 break;
4589 case ROUTE_LLENTRY_CHANGED:
4590 route_event_str = "ROUTE_LLENTRY_CHANGED";
4591 break;
4592 case ROUTE_LLENTRY_STALE:
4593 route_event_str = "ROUTE_LLENTRY_STALE";
4594 break;
4595 case ROUTE_LLENTRY_TIMEDOUT:
4596 route_event_str = "ROUTE_LLENTRY_TIMEDOUT";
4597 break;
4598 case ROUTE_LLENTRY_DELETED:
4599 route_event_str = "ROUTE_LLENTRY_DELETED";
4600 break;
4601 case ROUTE_LLENTRY_EXPIRED:
4602 route_event_str = "ROUTE_LLENTRY_EXPIRED";
4603 break;
4604 case ROUTE_LLENTRY_PROBED:
4605 route_event_str = "ROUTE_LLENTRY_PROBED";
4606 break;
4607 case ROUTE_EVHDLR_DEREGISTER:
4608 route_event_str = "ROUTE_EVHDLR_DEREGISTER";
4609 break;
4610 default:
4611 /* Init'd to ROUTE_EVENT_UNKNOWN */
4612 break;
4613 }
4614 return route_event_str;
4615 }
4616
4617 int
route_op_entitlement_check(struct socket * so,kauth_cred_t cred,int route_op_type,boolean_t allow_root)4618 route_op_entitlement_check(struct socket *so,
4619 kauth_cred_t cred,
4620 int route_op_type,
4621 boolean_t allow_root)
4622 {
4623 if (so != NULL) {
4624 if (route_op_type == ROUTE_OP_READ) {
4625 /*
4626 * If needed we can later extend this for more
4627 * granular entitlements and return a bit set of
4628 * allowed accesses.
4629 */
4630 if (soopt_cred_check(so, PRIV_NET_RESTRICTED_ROUTE_NC_READ,
4631 allow_root, false) == 0) {
4632 return 0;
4633 } else {
4634 return -1;
4635 }
4636 }
4637 } else if (cred != NULL) {
4638 uid_t uid = kauth_cred_getuid(cred);
4639
4640 /* uid is 0 for root */
4641 if (uid != 0 || !allow_root) {
4642 if (route_op_type == ROUTE_OP_READ) {
4643 if (priv_check_cred(cred,
4644 PRIV_NET_RESTRICTED_ROUTE_NC_READ, 0) == 0) {
4645 return 0;
4646 } else {
4647 return -1;
4648 }
4649 }
4650 }
4651 }
4652 return -1;
4653 }
4654
4655 /*
4656 * RTM_xxx.
4657 *
4658 * The switch statement below does nothing at runtime, as it serves as a
4659 * compile time check to ensure that all of the RTM_xxx constants are
4660 * unique. This works as long as this routine gets updated each time a
4661 * new RTM_xxx constant gets added.
4662 *
4663 * Any failures at compile time indicates duplicated RTM_xxx values.
4664 */
4665 static __attribute__((unused)) void
rtm_cassert(void)4666 rtm_cassert(void)
4667 {
4668 /*
4669 * This is equivalent to _CASSERT() and the compiler wouldn't
4670 * generate any instructions, thus for compile time only.
4671 */
4672 switch ((u_int16_t)0) {
4673 case 0:
4674
4675 /* bsd/net/route.h */
4676 case RTM_ADD:
4677 case RTM_DELETE:
4678 case RTM_CHANGE:
4679 case RTM_GET:
4680 case RTM_LOSING:
4681 case RTM_REDIRECT:
4682 case RTM_MISS:
4683 case RTM_LOCK:
4684 case RTM_OLDADD:
4685 case RTM_OLDDEL:
4686 case RTM_RESOLVE:
4687 case RTM_NEWADDR:
4688 case RTM_DELADDR:
4689 case RTM_IFINFO:
4690 case RTM_NEWMADDR:
4691 case RTM_DELMADDR:
4692 case RTM_IFINFO2:
4693 case RTM_NEWMADDR2:
4694 case RTM_GET2:
4695
4696 /* bsd/net/route_private.h */
4697 case RTM_GET_SILENT:
4698 case RTM_GET_EXT:
4699 ;
4700 }
4701 }
4702
4703 static __attribute__((unused)) void
rtv_cassert(void)4704 rtv_cassert(void)
4705 {
4706 switch ((u_int16_t)0) {
4707 case 0:
4708
4709 /* bsd/net/route.h */
4710 case RTV_MTU:
4711 case RTV_HOPCOUNT:
4712 case RTV_EXPIRE:
4713 case RTV_RPIPE:
4714 case RTV_SPIPE:
4715 case RTV_SSTHRESH:
4716 case RTV_RTT:
4717 case RTV_RTTVAR:
4718
4719 /* net/route_private.h */
4720 case RTV_REFRESH_HOST:
4721 ;
4722 }
4723 }
4724