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