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