xref: /xnu-11417.140.69/bsd/net/route.c (revision 43a90889846e00bfb5cf1d255cdc0a701a1e05a4)
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 	boolean_t empty_dst;
3189 	char gbuf[MAX_IPv6_STR_LEN], s_dst[MAX_IPv6_STR_LEN], s_netmask[MAX_IPv6_STR_LEN];
3190 	VERIFY(!coarse || ifscope == IFSCOPE_NONE);
3191 
3192 	LCK_MTX_ASSERT(rnh_lock, LCK_MTX_ASSERT_OWNED);
3193 	/*
3194 	 * While we have rnh_lock held, see if we need to schedule the timer.
3195 	 */
3196 	if (nd6_sched_timeout_want) {
3197 		nd6_sched_timeout(NULL, NULL);
3198 	}
3199 
3200 	if (!lookup_only) {
3201 		netmask = NULL;
3202 	}
3203 
3204 	if (rt_verbose > 1) {
3205 		empty_dst = ((af == AF_INET && SIN(dst)->sin_addr.s_addr == 0) ||
3206 				     (af == AF_INET6 && IN6_IS_ADDR_UNSPECIFIED(&SIN6(dst)->sin6_addr)));
3207 	}
3208 
3209 	/*
3210 	 * Non-scoped route lookup.
3211 	 */
3212 	if (af != AF_INET && af != AF_INET6) {
3213 		rn = rnh->rnh_matchaddr(dst, rnh);
3214 
3215 		/*
3216 		 * Don't return a root node; also, rnh_matchaddr callback
3217 		 * would have done the necessary work to clear RTPRF_OURS
3218 		 * for certain protocol families.
3219 		 */
3220 		if (rn != NULL && (rn->rn_flags & RNF_ROOT)) {
3221 			rn = NULL;
3222 		}
3223 		if (rn != NULL) {
3224 			RT_LOCK_SPIN(RT(rn));
3225 			if (!(RT(rn)->rt_flags & RTF_CONDEMNED)) {
3226 				RT_ADDREF_LOCKED(RT(rn));
3227 				RT_UNLOCK(RT(rn));
3228 			} else {
3229 				RT_UNLOCK(RT(rn));
3230 				rn = NULL;
3231 			}
3232 		}
3233 		return RT(rn);
3234 	}
3235 
3236 	/* Transform dst/netmask into the internal routing table form */
3237 	dst = sa_copy(dst, &dst_ss, &ifscope);
3238 	if (netmask != NULL) {
3239 		netmask = ma_copy(af, netmask, &mask_ss, ifscope);
3240 	}
3241 	dontcare = (ifscope == IFSCOPE_NONE);
3242 
3243 #if (DEVELOPMENT || DEBUG)
3244 	if (rt_verbose > 2 && !empty_dst) {
3245 		if (af == AF_INET) {
3246 			(void) inet_ntop(af, &SIN(dst)->sin_addr.s_addr,
3247 			    s_dst, sizeof(s_dst));
3248 		} else {
3249 			(void) inet_ntop(af, &SIN6(dst)->sin6_addr,
3250 			    s_dst, sizeof(s_dst));
3251 		}
3252 
3253 		if (netmask != NULL && af == AF_INET) {
3254 			(void) inet_ntop(af, &SIN(netmask)->sin_addr.s_addr,
3255 			    s_netmask, sizeof(s_netmask));
3256 		}
3257 		if (netmask != NULL && af == AF_INET6) {
3258 			(void) inet_ntop(af, &SIN6(netmask)->sin6_addr,
3259 			    s_netmask, sizeof(s_netmask));
3260 		} else {
3261 			*s_netmask = '\0';
3262 		}
3263 		os_log(OS_LOG_DEFAULT, "%s:%d (%d, %d, %s, %s, %u)\n",
3264 		    __func__, __LINE__, lookup_only, coarse, s_dst, s_netmask, ifscope);
3265 	}
3266 #endif
3267 
3268 	/*
3269 	 * Scoped route lookup:
3270 	 *
3271 	 * We first perform a non-scoped lookup for the original result.
3272 	 * Afterwards, depending on whether or not the caller has specified
3273 	 * a scope, we perform a more specific scoped search and fallback
3274 	 * to this original result upon failure.
3275 	 */
3276 	rn0 = rn = node_lookup(dst, netmask, IFSCOPE_NONE);
3277 
3278 	/*
3279 	 * If the caller did not specify a scope, use the primary scope
3280 	 * derived from the system's non-scoped default route.  If, for
3281 	 * any reason, there is no primary interface, ifscope will be
3282 	 * set to IFSCOPE_NONE; if the above lookup resulted in a route,
3283 	 * we'll do a more-specific search below, scoped to the interface
3284 	 * of that route.
3285 	 */
3286 	if (dontcare) {
3287 		ifscope = get_primary_ifscope(af);
3288 	}
3289 
3290 	/*
3291 	 * Keep the original result if either of the following is true:
3292 	 *
3293 	 *   1) The interface portion of the route has the same interface
3294 	 *	index as the scope value and it is marked with RTF_IFSCOPE.
3295 	 *   2) The route uses the loopback interface, in which case the
3296 	 *	destination (host/net) is local/loopback.
3297 	 *
3298 	 * Otherwise, do a more specified search using the scope;
3299 	 * we're holding rnh_lock now, so rt_ifp should not change.
3300 	 */
3301 	if (rn != NULL) {
3302 		rtentry_ref_t rt = RT(rn);
3303 		if (rt_verbose > 2) {
3304 			char dbuf[MAX_SCOPE_ADDR_STR_LEN];
3305 			rt_str(rt, dbuf, sizeof(dbuf), gbuf, sizeof(gbuf));
3306 			os_log(OS_LOG_DEFAULT, "%s unscoped search %p to %s->%s->%s ifa_ifp %s\n",
3307 			    __func__, rt,
3308 			    dbuf, gbuf,
3309 			    (rt->rt_ifp != NULL) ? rt->rt_ifp->if_xname : "",
3310 			    (rt->rt_ifa->ifa_ifp != NULL) ?
3311 			    rt->rt_ifa->ifa_ifp->if_xname : "");
3312 		}
3313 		if (!(rt->rt_ifp->if_flags & IFF_LOOPBACK) ||
3314 		    (rt->rt_flags & RTF_GATEWAY)) {
3315 			if (rt->rt_ifp->if_index != ifscope) {
3316 				/*
3317 				 * Wrong interface; keep the original result
3318 				 * only if the caller did not specify a scope,
3319 				 * and do a more specific scoped search using
3320 				 * the scope of the found route.  Otherwise,
3321 				 * start again from scratch.
3322 				 *
3323 				 * For loopback scope we keep the unscoped
3324 				 * route for local addresses
3325 				 */
3326 				rn = NULL;
3327 				if (dontcare) {
3328 					ifscope = rt->rt_ifp->if_index;
3329 				} else if (ifscope != lo_ifp->if_index ||
3330 				    rt_ifa_is_dst(dst, rt->rt_ifa) == FALSE) {
3331 					rn0 = NULL;
3332 				}
3333 			} else if (!(rt->rt_flags & RTF_IFSCOPE)) {
3334 				/*
3335 				 * Right interface, except that this route
3336 				 * isn't marked with RTF_IFSCOPE.  Do a more
3337 				 * specific scoped search.  Keep the original
3338 				 * result and return it it in case the scoped
3339 				 * search fails.
3340 				 */
3341 				rn = NULL;
3342 			}
3343 		}
3344 	}
3345 
3346 	/*
3347 	 * Scoped search.  Find the most specific entry having the same
3348 	 * interface scope as the one requested.  The following will result
3349 	 * in searching for the longest prefix scoped match.
3350 	 */
3351 	if (rn == NULL) {
3352 		rn = node_lookup(dst, netmask, ifscope);
3353 #if (DEVELOPMENT || DEBUG)
3354 		if (rt_verbose > 2 && rn != NULL) {
3355 			char dbuf[MAX_SCOPE_ADDR_STR_LEN];
3356 			rtentry_ref_t rt = RT(rn);
3357 
3358 			rt_str(rt, dbuf, sizeof(dbuf), gbuf, sizeof(gbuf));
3359 			os_log(OS_LOG_DEFAULT, "%s scoped search %p to %s->%s->%s ifa %s\n",
3360 			    __func__, rt,
3361 			    dbuf, gbuf,
3362 			    (rt->rt_ifp != NULL) ? rt->rt_ifp->if_xname : "",
3363 			    (rt->rt_ifa->ifa_ifp != NULL) ?
3364 			    rt->rt_ifa->ifa_ifp->if_xname : "");
3365 		}
3366 #endif
3367 	}
3368 	/*
3369 	 * Use the original result if either of the following is true:
3370 	 *
3371 	 *   1) The scoped search did not yield any result.
3372 	 *   2) The caller insists on performing a coarse-grained lookup.
3373 	 *   3) The result from the scoped search is a scoped default route,
3374 	 *	and the original (non-scoped) result is not a default route,
3375 	 *	i.e. the original result is a more specific host/net route.
3376 	 *   4)	The scoped search yielded a net route but the original
3377 	 *	result is a host route, i.e. the original result is treated
3378 	 *	as a more specific route.
3379 	 */
3380 	if (rn == NULL || coarse || (rn0 != NULL &&
3381 	    ((SA_DEFAULT(rt_key(RT(rn))) && !SA_DEFAULT(rt_key(RT(rn0)))) ||
3382 	    (!RT_HOST(RT(rn)) && RT_HOST(RT(rn0)))))) {
3383 		rn = rn0;
3384 	}
3385 
3386 	/*
3387 	 * If we still don't have a route, use the non-scoped default
3388 	 * route as long as the interface portion satistifes the scope.
3389 	 */
3390 	if (rn == NULL && (rn = node_lookup_default(af)) != NULL &&
3391 	    RT(rn)->rt_ifp->if_index != ifscope) {
3392 		rn = NULL;
3393 	}
3394 
3395 	if (rn != NULL) {
3396 		/*
3397 		 * Manually clear RTPRF_OURS using rt_validate() and
3398 		 * bump up the reference count after, and not before;
3399 		 * we only get here for AF_INET/AF_INET6.  node_lookup()
3400 		 * has done the check against RNF_ROOT, so we can be sure
3401 		 * that we're not returning a root node here.
3402 		 */
3403 		RT_LOCK_SPIN(RT(rn));
3404 		if (rt_validate(RT(rn))) {
3405 			RT_ADDREF_LOCKED(RT(rn));
3406 			RT_UNLOCK(RT(rn));
3407 		} else {
3408 			RT_UNLOCK(RT(rn));
3409 			rn = NULL;
3410 		}
3411 	}
3412 
3413     if (rn == NULL) {
3414         if (rt_verbose > 1 && !empty_dst) {
3415             if (af == AF_INET) {
3416                 (void) inet_ntop(af, &SIN(dst)->sin_addr.s_addr,
3417                         s_dst, sizeof(s_dst));
3418             } else {
3419                 (void) inet_ntop(af, &SIN6(dst)->sin6_addr,
3420                         s_dst, sizeof(s_dst));
3421             }
3422 
3423             if (netmask != NULL && af == AF_INET) {
3424                 (void) inet_ntop(af, &SIN(netmask)->sin_addr.s_addr,
3425                         s_netmask, sizeof(s_netmask));
3426             }
3427             if (netmask != NULL && af == AF_INET6) {
3428                 (void) inet_ntop(af, &SIN6(netmask)->sin6_addr,
3429                         s_netmask, sizeof(s_netmask));
3430             } else {
3431                 *s_netmask = '\0';
3432             }
3433             os_log(OS_LOG_DEFAULT, "%s:%d (%s, %s, %u) return NULL\n",
3434                     __func__, __LINE__, s_dst, s_netmask, ifscope);
3435         }
3436     } else if (rt_verbose > 2) {
3437         char dbuf[MAX_SCOPE_ADDR_STR_LEN];
3438         rtentry_ref_t rt = RT(rn);
3439 
3440         rt_str(rt, dbuf, sizeof(dbuf), gbuf, sizeof(gbuf));
3441 
3442         os_log(OS_LOG_DEFAULT, "%s %u return %p to %s->%s->%s ifa_ifp %s\n",
3443                 __func__, ifscope, rt,
3444                 dbuf, gbuf,
3445                 (rt->rt_ifp != NULL) ? rt->rt_ifp->if_xname : "",
3446                 (rt->rt_ifa->ifa_ifp != NULL) ?
3447                 rt->rt_ifa->ifa_ifp->if_xname : "");
3448     }
3449 
3450     return RT(rn);
3451 }
3452 
3453 struct rtentry *
rt_lookup(boolean_t lookup_only,struct sockaddr * dst,struct sockaddr * netmask,struct radix_node_head * rnh,unsigned int ifscope)3454 rt_lookup(boolean_t lookup_only, struct sockaddr *dst, struct sockaddr *netmask,
3455     struct radix_node_head *rnh, unsigned int ifscope)
3456 {
3457 	return rt_lookup_common(lookup_only, FALSE, dst, netmask,
3458 	           rnh, ifscope);
3459 }
3460 
3461 struct rtentry *
rt_lookup_coarse(boolean_t lookup_only,struct sockaddr * dst,struct sockaddr * netmask,struct radix_node_head * rnh)3462 rt_lookup_coarse(boolean_t lookup_only, struct sockaddr *dst,
3463     struct sockaddr *netmask, struct radix_node_head *rnh)
3464 {
3465 	return rt_lookup_common(lookup_only, TRUE, dst, netmask,
3466 	           rnh, IFSCOPE_NONE);
3467 }
3468 
3469 boolean_t
rt_validate(struct rtentry * rt)3470 rt_validate(struct rtentry *rt)
3471 {
3472 	RT_LOCK_ASSERT_HELD(rt);
3473 
3474 	if ((rt->rt_flags & (RTF_UP | RTF_CONDEMNED)) == RTF_UP) {
3475 		int af = rt_key(rt)->sa_family;
3476 
3477 		if (af == AF_INET) {
3478 			(void) in_validate(RN(rt));
3479 		} else if (af == AF_INET6) {
3480 			(void) in6_validate(RN(rt));
3481 		}
3482 	} else {
3483 		rt = NULL;
3484 	}
3485 
3486 	return rt != NULL;
3487 }
3488 
3489 /*
3490  * Set up a routing table entry, normally
3491  * for an interface.
3492  */
3493 int
rtinit(struct ifaddr * ifa,uint8_t cmd,int flags)3494 rtinit(struct ifaddr *ifa, uint8_t cmd, int flags)
3495 {
3496 	int error;
3497 
3498 	LCK_MTX_ASSERT(rnh_lock, LCK_MTX_ASSERT_NOTOWNED);
3499 
3500 	lck_mtx_lock(rnh_lock);
3501 	error = rtinit_locked(ifa, cmd, flags);
3502 	lck_mtx_unlock(rnh_lock);
3503 
3504 	return error;
3505 }
3506 
3507 int
rtinit_locked(struct ifaddr * ifa,uint8_t cmd,int flags)3508 rtinit_locked(struct ifaddr *ifa, uint8_t cmd, int flags)
3509 {
3510 	struct radix_node_head *rnh;
3511 	uint8_t nbuf[128];      /* long enough for IPv6 */
3512 	char dbuf[MAX_IPv6_STR_LEN], gbuf[MAX_IPv6_STR_LEN];
3513 	char abuf[MAX_IPv6_STR_LEN];
3514 	rtentry_ref_t rt = NULL;
3515 	struct sockaddr *dst;
3516 	struct sockaddr *netmask;
3517 	int error = 0;
3518 
3519 	/*
3520 	 * Holding rnh_lock here prevents the possibility of ifa from
3521 	 * changing (e.g. in_ifinit), so it is safe to access its
3522 	 * ifa_{dst}addr (here and down below) without locking.
3523 	 */
3524 	LCK_MTX_ASSERT(rnh_lock, LCK_MTX_ASSERT_OWNED);
3525 
3526 	if (flags & RTF_HOST) {
3527 		dst = ifa->ifa_dstaddr;
3528 		netmask = NULL;
3529 	} else {
3530 		dst = ifa->ifa_addr;
3531 		netmask = ifa->ifa_netmask;
3532 	}
3533 
3534 	if (dst->sa_len == 0) {
3535 		os_log_error(OS_LOG_DEFAULT, "%s: %s failed, invalid dst sa_len %d\n",
3536 		    __func__, rtm2str(cmd), dst->sa_len);
3537 		error = EINVAL;
3538 		goto done;
3539 	}
3540 	if (netmask != NULL && netmask->sa_len > sizeof(nbuf)) {
3541 		os_log_error(OS_LOG_DEFAULT, "%s: %s failed, mask sa_len %d too large\n",
3542 		    __func__, rtm2str(cmd), dst->sa_len);
3543 		error = EINVAL;
3544 		goto done;
3545 	}
3546 
3547 	if (rt_verbose) {
3548 		if (dst->sa_family == AF_INET) {
3549 			(void) inet_ntop(AF_INET, &SIN(dst)->sin_addr.s_addr,
3550 			    abuf, sizeof(abuf));
3551 		} else if (dst->sa_family == AF_INET6) {
3552 			(void) inet_ntop(AF_INET6, &SIN6(dst)->sin6_addr,
3553 			    abuf, sizeof(abuf));
3554 		}
3555 	}
3556 
3557 	if ((rnh = rt_tables[dst->sa_family]) == NULL) {
3558 		error = EINVAL;
3559 		goto done;
3560 	}
3561 
3562 	/*
3563 	 * If it's a delete, check that if it exists, it's on the correct
3564 	 * interface or we might scrub a route to another ifa which would
3565 	 * be confusing at best and possibly worse.
3566 	 */
3567 	if (cmd == RTM_DELETE) {
3568 		/*
3569 		 * It's a delete, so it should already exist..
3570 		 * If it's a net, mask off the host bits
3571 		 * (Assuming we have a mask)
3572 		 */
3573 		if (netmask != NULL) {
3574 			rt_maskedcopy(dst, SA(nbuf), netmask);
3575 			dst = SA(nbuf);
3576 		}
3577 		/*
3578 		 * Get an rtentry that is in the routing tree and contains
3579 		 * the correct info.  Note that we perform a coarse-grained
3580 		 * lookup here, in case there is a scoped variant of the
3581 		 * subnet/prefix route which we should ignore, as we never
3582 		 * add a scoped subnet/prefix route as part of adding an
3583 		 * interface address.
3584 		 */
3585 		rt = rt_lookup_coarse(TRUE, dst, NULL, rnh);
3586 		if (rt != NULL) {
3587 			if (rt_verbose) {
3588 				rt_str(rt, dbuf, sizeof(dbuf), gbuf, sizeof(gbuf));
3589 			}
3590 
3591 			/*
3592 			 * Ok so we found the rtentry. it has an extra reference
3593 			 * for us at this stage. we won't need that so
3594 			 * lop that off now.
3595 			 */
3596 			RT_LOCK(rt);
3597 			if (rt->rt_ifa != ifa) {
3598 				/*
3599 				 * If the interface address in the rtentry
3600 				 * doesn't match the interface we are using,
3601 				 * then we don't want to delete it, so return
3602 				 * an error.  This seems to be the only point
3603 				 * of this whole RTM_DELETE clause.
3604 				 */
3605 #if (DEVELOPMENT || DEBUG)
3606 				if (rt_verbose) {
3607 					os_log_debug(OS_LOG_DEFAULT, "%s: not removing "
3608 					    "route to %s->%s->%s, flags 0x%x, "
3609 					    "ifaddr %s, rt_ifa 0x%llx != "
3610 					    "ifa 0x%llx\n", __func__, dbuf,
3611 					    gbuf, ((rt->rt_ifp != NULL) ?
3612 					    rt->rt_ifp->if_xname : ""),
3613 					    rt->rt_flags, abuf,
3614 					    (uint64_t)VM_KERNEL_ADDRPERM(
3615 						    rt->rt_ifa),
3616 					    (uint64_t)VM_KERNEL_ADDRPERM(ifa));
3617 				}
3618 #endif /* (DEVELOPMENT || DEBUG) */
3619 				RT_REMREF_LOCKED(rt);
3620 				RT_UNLOCK(rt);
3621 				rt = NULL;
3622 				error = ((flags & RTF_HOST) ?
3623 				    EHOSTUNREACH : ENETUNREACH);
3624 				goto done;
3625 			} else if (rt->rt_flags & RTF_STATIC) {
3626 				/*
3627 				 * Don't remove the subnet/prefix route if
3628 				 * this was manually added from above.
3629 				 */
3630 #if (DEVELOPMENT || DEBUG)
3631 				if (rt_verbose) {
3632 					os_log_debug(OS_LOG_DEFAULT, "%s: not removing "
3633 					    "static route to %s->%s->%s, "
3634 					    "flags 0x%x, ifaddr %s\n", __func__,
3635 					    dbuf, gbuf, ((rt->rt_ifp != NULL) ?
3636 					    rt->rt_ifp->if_xname : ""),
3637 					    rt->rt_flags, abuf);
3638 				}
3639 #endif /* (DEVELOPMENT || DEBUG) */
3640 				RT_REMREF_LOCKED(rt);
3641 				RT_UNLOCK(rt);
3642 				rt = NULL;
3643 				error = EBUSY;
3644 				goto done;
3645 			}
3646 			if (rt_verbose) {
3647 				os_log_info(OS_LOG_DEFAULT, "%s: removing route to "
3648 				    "%s->%s->%s, flags 0x%x, ifaddr %s\n",
3649 				    __func__, dbuf, gbuf,
3650 				    ((rt->rt_ifp != NULL) ?
3651 				    rt->rt_ifp->if_xname : ""),
3652 				    rt->rt_flags, abuf);
3653 			}
3654 			RT_REMREF_LOCKED(rt);
3655 			RT_UNLOCK(rt);
3656 			rt = NULL;
3657 		}
3658 	}
3659 	/*
3660 	 * Do the actual request
3661 	 */
3662 	if ((error = rtrequest_locked(cmd, dst, ifa->ifa_addr, netmask,
3663 	    flags | ifa->ifa_flags, &rt)) != 0) {
3664 		goto done;
3665 	}
3666 
3667 	VERIFY(rt != NULL);
3668 
3669 	if (rt_verbose) {
3670 		rt_str(rt, dbuf, sizeof(dbuf), gbuf, sizeof(gbuf));
3671 	}
3672 
3673 	switch (cmd) {
3674 	case RTM_DELETE:
3675 		/*
3676 		 * If we are deleting, and we found an entry, then it's
3677 		 * been removed from the tree.   Notify any listening
3678 		 * routing agents of the change and throw it away.
3679 		 */
3680 		RT_LOCK(rt);
3681 		rt_newaddrmsg(cmd, ifa, error, rt);
3682 		RT_UNLOCK(rt);
3683 		if (rt_verbose) {
3684 			os_log_info(OS_LOG_DEFAULT, "%s: removed route to %s->%s->%s, "
3685 			    "flags 0x%x, ifaddr %s\n", __func__, dbuf, gbuf,
3686 			    ((rt->rt_ifp != NULL) ? rt->rt_ifp->if_xname : ""),
3687 			    rt->rt_flags, abuf);
3688 		}
3689 		rtfree_locked(rt);
3690 		break;
3691 
3692 	case RTM_ADD:
3693 		/*
3694 		 * We are adding, and we have a returned routing entry.
3695 		 * We need to sanity check the result.  If it came back
3696 		 * with an unexpected interface, then it must have already
3697 		 * existed or something.
3698 		 */
3699 		RT_LOCK(rt);
3700 		if (rt->rt_ifa != ifa) {
3701 			void (*ifa_rtrequest)
3702 			(int, struct rtentry *, struct sockaddr *);
3703 #if (DEVELOPMENT || DEBUG)
3704 			if (rt_verbose) {
3705 				if (!(rt->rt_ifa->ifa_ifp->if_flags &
3706 				    (IFF_POINTOPOINT | IFF_LOOPBACK))) {
3707 					os_log_error(OS_LOG_DEFAULT, "%s: %s route to %s->%s->%s, "
3708 					    "flags 0x%x, ifaddr %s, rt_ifa 0x%llx != "
3709 					    "ifa 0x%llx\n", __func__, rtm2str(cmd),
3710 					    dbuf, gbuf, ((rt->rt_ifp != NULL) ?
3711 					    rt->rt_ifp->if_xname : ""), rt->rt_flags,
3712 					    abuf,
3713 					    (uint64_t)VM_KERNEL_ADDRPERM(rt->rt_ifa),
3714 					    (uint64_t)VM_KERNEL_ADDRPERM(ifa));
3715 				}
3716 
3717 				os_log_debug(OS_LOG_DEFAULT, "%s: %s route to %s->%s->%s, "
3718 				    "flags 0x%x, ifaddr %s, rt_ifa was 0x%llx "
3719 				    "now 0x%llx\n", __func__, rtm2str(cmd),
3720 				    dbuf, gbuf, ((rt->rt_ifp != NULL) ?
3721 				    rt->rt_ifp->if_xname : ""), rt->rt_flags,
3722 				    abuf,
3723 				    (uint64_t)VM_KERNEL_ADDRPERM(rt->rt_ifa),
3724 				    (uint64_t)VM_KERNEL_ADDRPERM(ifa));
3725 			}
3726 #endif /* (DEVELOPMENT || DEBUG) */
3727 
3728 			/*
3729 			 * Ask that the protocol in question
3730 			 * remove anything it has associated with
3731 			 * this route and ifaddr.
3732 			 */
3733 			ifa_rtrequest = rt->rt_ifa->ifa_rtrequest;
3734 			if (ifa_rtrequest != NULL) {
3735 				ifa_rtrequest(RTM_DELETE, rt, NULL);
3736 			}
3737 			/*
3738 			 * Set the route's ifa.
3739 			 */
3740 			rtsetifa(rt, ifa);
3741 
3742 			if (rt->rt_ifp != ifa->ifa_ifp) {
3743 				/*
3744 				 * Purge any link-layer info caching.
3745 				 */
3746 				if (rt->rt_llinfo_purge != NULL) {
3747 					rt->rt_llinfo_purge(rt);
3748 				}
3749 				/*
3750 				 * Adjust route ref count for the interfaces.
3751 				 */
3752 				if (rt->rt_if_ref_fn != NULL) {
3753 					rt->rt_if_ref_fn(ifa->ifa_ifp, 1);
3754 					rt->rt_if_ref_fn(rt->rt_ifp, -1);
3755 				}
3756 			}
3757 
3758 			/*
3759 			 * And substitute in references to the ifaddr
3760 			 * we are adding.
3761 			 */
3762 			rt->rt_ifp = ifa->ifa_ifp;
3763 			/*
3764 			 * If rmx_mtu is not locked, update it
3765 			 * to the MTU used by the new interface.
3766 			 */
3767 			if (!(rt->rt_rmx.rmx_locks & RTV_MTU)) {
3768 				rt->rt_rmx.rmx_mtu = rt->rt_ifp->if_mtu;
3769 				if (dst->sa_family == AF_INET &&
3770 				    INTF_ADJUST_MTU_FOR_CLAT46(rt->rt_ifp)) {
3771 					rt->rt_rmx.rmx_mtu = IN6_LINKMTU(rt->rt_ifp);
3772 					/* Further adjust the size for CLAT46 expansion */
3773 					rt->rt_rmx.rmx_mtu -= CLAT46_HDR_EXPANSION_OVERHD;
3774 				}
3775 			}
3776 
3777 			/*
3778 			 * Now ask the protocol to check if it needs
3779 			 * any special processing in its new form.
3780 			 */
3781 			ifa_rtrequest = ifa->ifa_rtrequest;
3782 			if (ifa_rtrequest != NULL) {
3783 				ifa_rtrequest(RTM_ADD, rt, NULL);
3784 			}
3785 		} else {
3786 			if (rt_verbose) {
3787 				os_log_info(OS_LOG_DEFAULT, "%s: added route to %s->%s->%s, "
3788 				    "flags 0x%x, ifaddr %s\n", __func__, dbuf,
3789 				    gbuf, ((rt->rt_ifp != NULL) ?
3790 				    rt->rt_ifp->if_xname : ""), rt->rt_flags,
3791 				    abuf);
3792 			}
3793 		}
3794 		/*
3795 		 * notify any listening routing agents of the change
3796 		 */
3797 		rt_newaddrmsg(cmd, ifa, error, rt);
3798 		/*
3799 		 * We just wanted to add it; we don't actually need a
3800 		 * reference.  This will result in a route that's added
3801 		 * to the routing table without a reference count.  The
3802 		 * RTM_DELETE code will do the necessary step to adjust
3803 		 * the reference count at deletion time.
3804 		 */
3805 		RT_REMREF_LOCKED(rt);
3806 		RT_UNLOCK(rt);
3807 		break;
3808 
3809 	default:
3810 		VERIFY(0);
3811 		/* NOTREACHED */
3812 	}
3813 done:
3814 	return error;
3815 }
3816 
3817 static void
rt_set_idleref(struct rtentry * rt)3818 rt_set_idleref(struct rtentry *rt)
3819 {
3820 	RT_LOCK_ASSERT_HELD(rt);
3821 
3822 	/*
3823 	 * We currently keep idle refcnt only on unicast cloned routes
3824 	 * that aren't marked with RTF_NOIFREF.
3825 	 */
3826 	if (rt->rt_parent != NULL && !(rt->rt_flags &
3827 	    (RTF_NOIFREF | RTF_BROADCAST | RTF_MULTICAST)) &&
3828 	    (rt->rt_flags & (RTF_UP | RTF_WASCLONED | RTF_IFREF)) ==
3829 	    (RTF_UP | RTF_WASCLONED)) {
3830 		rt_clear_idleref(rt);   /* drop existing refcnt if any  */
3831 		rt->rt_if_ref_fn = rte_if_ref;
3832 		/* Become a regular mutex, just in case */
3833 		RT_CONVERT_LOCK(rt);
3834 		rt->rt_if_ref_fn(rt->rt_ifp, 1);
3835 		rt->rt_flags |= RTF_IFREF;
3836 	}
3837 }
3838 
3839 void
rt_clear_idleref(struct rtentry * rt)3840 rt_clear_idleref(struct rtentry *rt)
3841 {
3842 	RT_LOCK_ASSERT_HELD(rt);
3843 
3844 	if (rt->rt_if_ref_fn != NULL) {
3845 		VERIFY((rt->rt_flags & (RTF_NOIFREF | RTF_IFREF)) == RTF_IFREF);
3846 		/* Become a regular mutex, just in case */
3847 		RT_CONVERT_LOCK(rt);
3848 		rt->rt_if_ref_fn(rt->rt_ifp, -1);
3849 		rt->rt_flags &= ~RTF_IFREF;
3850 		rt->rt_if_ref_fn = NULL;
3851 	}
3852 }
3853 
3854 void
rt_set_proxy(struct rtentry * rt,boolean_t set)3855 rt_set_proxy(struct rtentry *rt, boolean_t set)
3856 {
3857 	lck_mtx_lock(rnh_lock);
3858 	RT_LOCK(rt);
3859 	/*
3860 	 * Search for any cloned routes which might have
3861 	 * been formed from this node, and delete them.
3862 	 */
3863 	if (rt->rt_flags & (RTF_CLONING | RTF_PRCLONING)) {
3864 		struct radix_node_head *rnh = rt_tables[rt_key(rt)->sa_family];
3865 
3866 		if (set) {
3867 			rt->rt_flags |= RTF_PROXY;
3868 		} else {
3869 			rt->rt_flags &= ~RTF_PROXY;
3870 		}
3871 
3872 		RT_UNLOCK(rt);
3873 		if (rnh != NULL && rt_mask(rt)) {
3874 			rnh->rnh_walktree_from(rnh, rt_key(rt), rt_mask(rt),
3875 			    rt_fixdelete, rt);
3876 		}
3877 	} else {
3878 		RT_UNLOCK(rt);
3879 	}
3880 	lck_mtx_unlock(rnh_lock);
3881 }
3882 
3883 static void
rte_lock_init(struct rtentry * rt)3884 rte_lock_init(struct rtentry *rt)
3885 {
3886 	lck_mtx_init(&rt->rt_lock, &rte_mtx_grp, &rte_mtx_attr);
3887 }
3888 
3889 static void
rte_lock_destroy(struct rtentry * rt)3890 rte_lock_destroy(struct rtentry *rt)
3891 {
3892 	RT_LOCK_ASSERT_NOTHELD(rt);
3893 	lck_mtx_destroy(&rt->rt_lock, &rte_mtx_grp);
3894 }
3895 
3896 void
rt_lock(struct rtentry * rt,boolean_t spin)3897 rt_lock(struct rtentry *rt, boolean_t spin)
3898 {
3899 	RT_LOCK_ASSERT_NOTHELD(rt);
3900 	if (spin) {
3901 		lck_mtx_lock_spin(&rt->rt_lock);
3902 	} else {
3903 		lck_mtx_lock(&rt->rt_lock);
3904 	}
3905 	if (rte_debug & RTD_DEBUG) {
3906 		rte_lock_debug(RTENTRY_DBG(rt));
3907 	}
3908 }
3909 
3910 void
rt_unlock(struct rtentry * rt)3911 rt_unlock(struct rtentry *rt)
3912 {
3913 	if (rte_debug & RTD_DEBUG) {
3914 		rte_unlock_debug(RTENTRY_DBG(rt));
3915 	}
3916 	lck_mtx_unlock(&rt->rt_lock);
3917 }
3918 
3919 static inline void
rte_lock_debug(struct rtentry_dbg * rte)3920 rte_lock_debug(struct rtentry_dbg *rte)
3921 {
3922 	uint32_t idx;
3923 
3924 	RT_LOCK_ASSERT_HELD((struct rtentry *)rte);
3925 	idx = os_atomic_inc_orig(&rte->rtd_lock_cnt, relaxed) % CTRACE_HIST_SIZE;
3926 	if (rte_debug & RTD_TRACE) {
3927 		ctrace_record(&rte->rtd_lock[idx]);
3928 	}
3929 }
3930 
3931 static inline void
rte_unlock_debug(struct rtentry_dbg * rte)3932 rte_unlock_debug(struct rtentry_dbg *rte)
3933 {
3934 	uint32_t idx;
3935 
3936 	RT_LOCK_ASSERT_HELD((struct rtentry *)rte);
3937 	idx = os_atomic_inc_orig(&rte->rtd_unlock_cnt, relaxed) % CTRACE_HIST_SIZE;
3938 	if (rte_debug & RTD_TRACE) {
3939 		ctrace_record(&rte->rtd_unlock[idx]);
3940 	}
3941 }
3942 
3943 static struct rtentry *
rte_alloc(void)3944 rte_alloc(void)
3945 {
3946 	if (rte_debug & RTD_DEBUG) {
3947 		return rte_alloc_debug();
3948 	}
3949 
3950 	return (rtentry_ref_t)kalloc_type(struct rtentry, Z_ZERO);
3951 }
3952 
3953 /*
3954  * Resets the contents of the routing entry, with caveats:
3955  * 1. If `preserve_lock' is set, the locking info will be preserved.
3956  * 2. The debugging information, if present, is unconditionally preserved.
3957  */
3958 static void
rte_reset(struct rtentry * p,bool preserve_lock)3959 rte_reset(struct rtentry *p, bool preserve_lock)
3960 {
3961 	size_t bcnt = preserve_lock
3962 	    ? __offsetof(struct rtentry, rt_lock)
3963 	    : sizeof(struct rtentry);
3964 	uint8_t *bp = __unsafe_forge_bidi_indexable(uint8_t *, p, bcnt);
3965 	bzero(bp, bcnt);
3966 }
3967 
3968 static void
rte_free(struct rtentry * p)3969 rte_free(struct rtentry *p)
3970 {
3971 	if (rte_debug & RTD_DEBUG) {
3972 		rte_free_debug(p);
3973 		return;
3974 	}
3975 
3976 	if (p->rt_refcnt != 0) {
3977 		panic("rte_free: rte=%p refcnt=%d non-zero", p, p->rt_refcnt);
3978 		/* NOTREACHED */
3979 	}
3980 
3981 	kfree_type(struct rtentry, p);
3982 }
3983 
3984 static void
rte_if_ref(struct ifnet * ifp,int cnt)3985 rte_if_ref(struct ifnet *ifp, int cnt)
3986 {
3987 	struct kev_msg ev_msg;
3988 	struct net_event_data ev_data;
3989 	uint32_t old;
3990 
3991 	/* Force cnt to 1 increment/decrement */
3992 	if (cnt < -1 || cnt > 1) {
3993 		panic("%s: invalid count argument (%d)", __func__, cnt);
3994 		/* NOTREACHED */
3995 	}
3996 	old = os_atomic_add_orig(&ifp->if_route_refcnt, cnt, relaxed);
3997 	if (cnt < 0 && old == 0) {
3998 		panic("%s: ifp=%p negative route refcnt!", __func__, ifp);
3999 		/* NOTREACHED */
4000 	}
4001 	/*
4002 	 * The following is done without first holding the ifnet lock,
4003 	 * for performance reasons.  The relevant ifnet fields, with
4004 	 * the exception of the if_idle_flags, are never changed
4005 	 * during the lifetime of the ifnet.  The if_idle_flags
4006 	 * may possibly be modified, so in the event that the value
4007 	 * is stale because IFRF_IDLE_NOTIFY was cleared, we'd end up
4008 	 * sending the event anyway.  This is harmless as it is just
4009 	 * a notification to the monitoring agent in user space, and
4010 	 * it is expected to check via SIOCGIFGETRTREFCNT again anyway.
4011 	 */
4012 	if ((ifp->if_idle_flags & IFRF_IDLE_NOTIFY) && cnt < 0 && old == 1) {
4013 		bzero(&ev_msg, sizeof(ev_msg));
4014 		bzero(&ev_data, sizeof(ev_data));
4015 
4016 		ev_msg.vendor_code      = KEV_VENDOR_APPLE;
4017 		ev_msg.kev_class        = KEV_NETWORK_CLASS;
4018 		ev_msg.kev_subclass     = KEV_DL_SUBCLASS;
4019 		ev_msg.event_code       = KEV_DL_IF_IDLE_ROUTE_REFCNT;
4020 
4021 		strlcpy(&ev_data.if_name[0], ifp->if_name, IFNAMSIZ);
4022 
4023 		ev_data.if_family       = ifp->if_family;
4024 		ev_data.if_unit         = ifp->if_unit;
4025 		ev_msg.dv[0].data_length = sizeof(struct net_event_data);
4026 		ev_msg.dv[0].data_ptr   = &ev_data;
4027 
4028 		dlil_post_complete_msg(NULL, &ev_msg);
4029 	}
4030 }
4031 
4032 static inline struct rtentry *
rte_alloc_debug(void)4033 rte_alloc_debug(void)
4034 {
4035 	rtentry_dbg_ref_t rte;
4036 
4037 	rte = kalloc_type(struct rtentry_dbg, Z_ZERO);
4038 	if (rte != NULL) {
4039 		if (rte_debug & RTD_TRACE) {
4040 			ctrace_record(&rte->rtd_alloc);
4041 		}
4042 		rte->rtd_inuse = RTD_INUSE;
4043 	}
4044 	return &rte->rtd_entry;
4045 }
4046 
4047 static inline void
rte_free_debug(struct rtentry * p)4048 rte_free_debug(struct rtentry *p)
4049 {
4050 	rtentry_dbg_ref_t rte = RTENTRY_DBG(p);
4051 
4052 	if (p->rt_refcnt != 0) {
4053 		panic("rte_free: rte=%p refcnt=%d", p, p->rt_refcnt);
4054 		/* NOTREACHED */
4055 	}
4056 	if (rte->rtd_inuse == RTD_FREED) {
4057 		panic("rte_free: double free rte=%p", rte);
4058 		/* NOTREACHED */
4059 	} else if (rte->rtd_inuse != RTD_INUSE) {
4060 		panic("rte_free: corrupted rte=%p", rte);
4061 		/* NOTREACHED */
4062 	}
4063 
4064 	bcopy(p, &rte->rtd_entry_saved, sizeof(*p));
4065 	/* Preserve rt_lock to help catch use-after-free cases */
4066 	rte_reset(p, true);
4067 
4068 	rte->rtd_inuse = RTD_FREED;
4069 
4070 	if (rte_debug & RTD_TRACE) {
4071 		ctrace_record(&rte->rtd_free);
4072 	}
4073 
4074 	if (!(rte_debug & RTD_NO_FREE)) {
4075 		kfree_type(struct rtentry_dbg, rte);
4076 	}
4077 }
4078 
4079 void
ctrace_record(ctrace_t * tr)4080 ctrace_record(ctrace_t *tr)
4081 {
4082 	tr->th = current_thread();
4083 	bzero(tr->pc, sizeof(tr->pc));
4084 	(void) OSBacktrace(tr->pc, CTRACE_STACK_SIZE);
4085 }
4086 
4087 void
route_clear(struct route * ro)4088 route_clear(struct route *ro)
4089 {
4090 	if (ro == NULL) {
4091 		return;
4092 	}
4093 
4094 	if (ro->ro_rt != NULL) {
4095 		rtfree(ro->ro_rt);
4096 		ro->ro_rt = NULL;
4097 	}
4098 
4099 	if (ro->ro_srcia != NULL) {
4100 		ifa_remref(ro->ro_srcia);
4101 		ro->ro_srcia = NULL;
4102 	}
4103 	return;
4104 }
4105 
4106 
4107 void
route_copyout(struct route * dst,const struct route * src,size_t length)4108 route_copyout(struct route *dst, const struct route *src, size_t length)
4109 {
4110 	/* Copy everything (rt, srcif, flags, dst) from src */
4111 	__route_copy(src, dst, length);
4112 
4113 	/* Hold one reference for the local copy of struct route */
4114 	if (dst->ro_rt != NULL) {
4115 		RT_ADDREF(dst->ro_rt);
4116 	}
4117 
4118 	/* Hold one reference for the local copy of struct ifaddr */
4119 	if (dst->ro_srcia != NULL) {
4120 		ifa_addref(dst->ro_srcia);
4121 	}
4122 }
4123 
4124 void
route_copyin(struct route * src,struct route * dst,size_t length)4125 route_copyin(struct route *src, struct route *dst, size_t length)
4126 {
4127 	/*
4128 	 * No cached route at the destination?
4129 	 * If none, then remove old references if present
4130 	 * and copy entire src route.
4131 	 */
4132 	if (dst->ro_rt == NULL) {
4133 		/*
4134 		 * Ditch the address in the cached copy (dst) since
4135 		 * we're about to take everything there is in src.
4136 		 */
4137 		if (dst->ro_srcia != NULL) {
4138 			ifa_remref(dst->ro_srcia);
4139 		}
4140 		/*
4141 		 * Copy everything (rt, srcia, flags, dst) from src; the
4142 		 * references to rt and/or srcia were held at the time
4143 		 * of storage and are kept intact.
4144 		 */
4145 		__route_copy(src, dst, length);
4146 		goto done;
4147 	}
4148 
4149 	/*
4150 	 * We know dst->ro_rt is not NULL here.
4151 	 * If the src->ro_rt is the same, update srcia and flags
4152 	 * and ditch the route in the local copy.
4153 	 */
4154 	if (dst->ro_rt == src->ro_rt) {
4155 		dst->ro_flags = src->ro_flags;
4156 
4157 		if (dst->ro_srcia != src->ro_srcia) {
4158 			if (dst->ro_srcia != NULL) {
4159 				ifa_remref(dst->ro_srcia);
4160 			}
4161 			dst->ro_srcia = src->ro_srcia;
4162 		} else if (src->ro_srcia != NULL) {
4163 			ifa_remref(src->ro_srcia);
4164 		}
4165 		rtfree(src->ro_rt);
4166 		goto done;
4167 	}
4168 
4169 	/*
4170 	 * If they are dst's ro_rt is not equal to src's,
4171 	 * and src'd rt is not NULL, then remove old references
4172 	 * if present and copy entire src route.
4173 	 */
4174 	if (src->ro_rt != NULL) {
4175 		rtfree(dst->ro_rt);
4176 
4177 		if (dst->ro_srcia != NULL) {
4178 			ifa_remref(dst->ro_srcia);
4179 		}
4180 		__route_copy(src, dst, length);
4181 		goto done;
4182 	}
4183 
4184 	/*
4185 	 * Here, dst's cached route is not NULL but source's is.
4186 	 * Just get rid of all the other cached reference in src.
4187 	 */
4188 	if (src->ro_srcia != NULL) {
4189 		/*
4190 		 * Ditch src address in the local copy (src) since we're
4191 		 * not caching the route entry anyway (ro_rt is NULL).
4192 		 */
4193 		ifa_remref(src->ro_srcia);
4194 	}
4195 done:
4196 	/* This function consumes the references on src */
4197 	src->ro_rt = NULL;
4198 	src->ro_srcia = NULL;
4199 }
4200 
4201 /*
4202  * route_to_gwroute will find the gateway route for a given route.
4203  *
4204  * If the route is down, look the route up again.
4205  * If the route goes through a gateway, get the route to the gateway.
4206  * If the gateway route is down, look it up again.
4207  * If the route is set to reject, verify it hasn't expired.
4208  *
4209  * If the returned route is non-NULL, the caller is responsible for
4210  * releasing the reference and unlocking the route.
4211  */
4212 #define senderr(e) { error = (e); goto bad; }
4213 errno_t
route_to_gwroute(const struct sockaddr * net_dest,struct rtentry * hint0,struct rtentry ** out_route)4214 route_to_gwroute(const struct sockaddr *net_dest, struct rtentry *hint0,
4215     struct rtentry **out_route)
4216 {
4217 	uint64_t timenow;
4218 	rtentry_ref_t rt = hint0;
4219 	rtentry_ref_t hint = hint0;
4220 	errno_t error = 0;
4221 	unsigned int ifindex;
4222 	boolean_t gwroute;
4223 
4224 	*out_route = NULL;
4225 
4226 	if (rt == NULL) {
4227 		return 0;
4228 	}
4229 
4230 	/*
4231 	 * Next hop determination.  Because we may involve the gateway route
4232 	 * in addition to the original route, locking is rather complicated.
4233 	 * The general concept is that regardless of whether the route points
4234 	 * to the original route or to the gateway route, this routine takes
4235 	 * an extra reference on such a route.  This extra reference will be
4236 	 * released at the end.
4237 	 *
4238 	 * Care must be taken to ensure that the "hint0" route never gets freed
4239 	 * via rtfree(), since the caller may have stored it inside a struct
4240 	 * route with a reference held for that placeholder.
4241 	 */
4242 	RT_LOCK_SPIN(rt);
4243 	ifindex = rt->rt_ifp->if_index;
4244 	RT_ADDREF_LOCKED(rt);
4245 	if (!(rt->rt_flags & RTF_UP)) {
4246 		RT_REMREF_LOCKED(rt);
4247 		RT_UNLOCK(rt);
4248 		/* route is down, find a new one */
4249 		hint = rt = rtalloc1_scoped(
4250 			__DECONST_SA(net_dest), 1, 0, ifindex);
4251 		if (hint != NULL) {
4252 			RT_LOCK_SPIN(rt);
4253 			ifindex = rt->rt_ifp->if_index;
4254 		} else {
4255 			senderr(EHOSTUNREACH);
4256 		}
4257 	}
4258 
4259 	/*
4260 	 * We have a reference to "rt" by now; it will either
4261 	 * be released or freed at the end of this routine.
4262 	 */
4263 	RT_LOCK_ASSERT_HELD(rt);
4264 	if ((gwroute = (rt->rt_flags & RTF_GATEWAY))) {
4265 		rtentry_ref_t gwrt = rt->rt_gwroute;
4266 		struct sockaddr_storage ss;
4267 		struct sockaddr *gw = SA(&ss);
4268 
4269 		VERIFY(rt == hint);
4270 		RT_ADDREF_LOCKED(hint);
4271 
4272 		/* If there's no gateway rt, look it up */
4273 		if (gwrt == NULL) {
4274 			SOCKADDR_COPY(rt->rt_gateway, gw, MIN(sizeof(ss),
4275 			    rt->rt_gateway->sa_len));
4276 			gw->sa_len = MIN(sizeof(ss), rt->rt_gateway->sa_len);
4277 			RT_UNLOCK(rt);
4278 			goto lookup;
4279 		}
4280 		/* Become a regular mutex */
4281 		RT_CONVERT_LOCK(rt);
4282 
4283 		/*
4284 		 * Take gwrt's lock while holding route's lock;
4285 		 * this is okay since gwrt never points back
4286 		 * to "rt", so no lock ordering issues.
4287 		 */
4288 		RT_LOCK_SPIN(gwrt);
4289 		if (!(gwrt->rt_flags & RTF_UP)) {
4290 			rt->rt_gwroute = NULL;
4291 			RT_UNLOCK(gwrt);
4292 			SOCKADDR_COPY(rt->rt_gateway, gw, MIN(sizeof(ss),
4293 			    rt->rt_gateway->sa_len));
4294 			gw->sa_len = MIN(sizeof(ss), rt->rt_gateway->sa_len);
4295 			RT_UNLOCK(rt);
4296 			rtfree(gwrt);
4297 lookup:
4298 			lck_mtx_lock(rnh_lock);
4299 			gwrt = rtalloc1_scoped_locked(gw, 1, 0, ifindex);
4300 
4301 			RT_LOCK(rt);
4302 			/*
4303 			 * Bail out if the route is down, no route
4304 			 * to gateway, circular route, or if the
4305 			 * gateway portion of "rt" has changed.
4306 			 */
4307 			if (!(rt->rt_flags & RTF_UP) || gwrt == NULL ||
4308 			    gwrt == rt || !sa_equal(gw, rt->rt_gateway)) {
4309 				if (gwrt == rt) {
4310 					RT_REMREF_LOCKED(gwrt);
4311 					gwrt = NULL;
4312 				}
4313 				VERIFY(rt == hint);
4314 				RT_REMREF_LOCKED(hint);
4315 				hint = NULL;
4316 				RT_UNLOCK(rt);
4317 				if (gwrt != NULL) {
4318 					rtfree_locked(gwrt);
4319 				}
4320 				lck_mtx_unlock(rnh_lock);
4321 				senderr(EHOSTUNREACH);
4322 			}
4323 			VERIFY(gwrt != NULL);
4324 			/*
4325 			 * Set gateway route; callee adds ref to gwrt;
4326 			 * gwrt has an extra ref from rtalloc1() for
4327 			 * this routine.
4328 			 */
4329 			rt_set_gwroute(rt, rt_key(rt), gwrt);
4330 			VERIFY(rt == hint);
4331 			RT_REMREF_LOCKED(rt);   /* hint still holds a refcnt */
4332 			RT_UNLOCK(rt);
4333 			lck_mtx_unlock(rnh_lock);
4334 			rt = gwrt;
4335 		} else {
4336 			RT_ADDREF_LOCKED(gwrt);
4337 			RT_UNLOCK(gwrt);
4338 			VERIFY(rt == hint);
4339 			RT_REMREF_LOCKED(rt);   /* hint still holds a refcnt */
4340 			RT_UNLOCK(rt);
4341 			rt = gwrt;
4342 		}
4343 		VERIFY(rt == gwrt && rt != hint);
4344 
4345 		/*
4346 		 * This is an opportunity to revalidate the parent route's
4347 		 * rt_gwroute, in case it now points to a dead route entry.
4348 		 * Parent route won't go away since the clone (hint) holds
4349 		 * a reference to it.  rt == gwrt.
4350 		 */
4351 		RT_LOCK_SPIN(hint);
4352 		if ((hint->rt_flags & (RTF_WASCLONED | RTF_UP)) ==
4353 		    (RTF_WASCLONED | RTF_UP)) {
4354 			rtentry_ref_t prt = hint->rt_parent;
4355 			VERIFY(prt != NULL);
4356 
4357 			RT_CONVERT_LOCK(hint);
4358 			RT_ADDREF(prt);
4359 			RT_UNLOCK(hint);
4360 			rt_revalidate_gwroute(prt, rt);
4361 			RT_REMREF(prt);
4362 		} else {
4363 			RT_UNLOCK(hint);
4364 		}
4365 
4366 		/* Clean up "hint" now; see notes above regarding hint0 */
4367 		if (hint == hint0) {
4368 			RT_REMREF(hint);
4369 		} else {
4370 			rtfree(hint);
4371 		}
4372 		hint = NULL;
4373 
4374 		/* rt == gwrt; if it is now down, give up */
4375 		RT_LOCK_SPIN(rt);
4376 		if (!(rt->rt_flags & RTF_UP)) {
4377 			RT_UNLOCK(rt);
4378 			senderr(EHOSTUNREACH);
4379 		}
4380 	}
4381 
4382 	if (rt->rt_flags & RTF_REJECT) {
4383 		VERIFY(rt->rt_expire == 0 || rt->rt_rmx.rmx_expire != 0);
4384 		VERIFY(rt->rt_expire != 0 || rt->rt_rmx.rmx_expire == 0);
4385 		timenow = net_uptime();
4386 		if (rt->rt_expire == 0 || timenow < rt->rt_expire) {
4387 			RT_UNLOCK(rt);
4388 			senderr(!gwroute ? EHOSTDOWN : EHOSTUNREACH);
4389 		}
4390 	}
4391 
4392 	/* Become a regular mutex */
4393 	RT_CONVERT_LOCK(rt);
4394 
4395 	/* Caller is responsible for cleaning up "rt" */
4396 	*out_route = rt;
4397 	return 0;
4398 
4399 bad:
4400 	/* Clean up route (either it is "rt" or "gwrt") */
4401 	if (rt != NULL) {
4402 		RT_LOCK_SPIN(rt);
4403 		if (rt == hint0) {
4404 			RT_REMREF_LOCKED(rt);
4405 			RT_UNLOCK(rt);
4406 		} else {
4407 			RT_UNLOCK(rt);
4408 			rtfree(rt);
4409 		}
4410 	}
4411 	return error;
4412 }
4413 #undef senderr
4414 
4415 void
rt_revalidate_gwroute(struct rtentry * rt,struct rtentry * gwrt)4416 rt_revalidate_gwroute(struct rtentry *rt, struct rtentry *gwrt)
4417 {
4418 	VERIFY(gwrt != NULL);
4419 
4420 	RT_LOCK_SPIN(rt);
4421 	if ((rt->rt_flags & (RTF_GATEWAY | RTF_UP)) == (RTF_GATEWAY | RTF_UP) &&
4422 	    rt->rt_ifp == gwrt->rt_ifp && rt->rt_gateway->sa_family ==
4423 	    rt_key(gwrt)->sa_family && (rt->rt_gwroute == NULL ||
4424 	    !(rt->rt_gwroute->rt_flags & RTF_UP))) {
4425 		boolean_t isequal;
4426 		VERIFY(rt->rt_flags & (RTF_CLONING | RTF_PRCLONING));
4427 
4428 		if (rt->rt_gateway->sa_family == AF_INET ||
4429 		    rt->rt_gateway->sa_family == AF_INET6) {
4430 			struct sockaddr_storage key_ss, gw_ss;
4431 			/*
4432 			 * We need to compare rt_key and rt_gateway; create
4433 			 * local copies to get rid of any ifscope association.
4434 			 */
4435 			(void) sa_copy(rt_key(gwrt), &key_ss, NULL);
4436 			(void) sa_copy(rt->rt_gateway, &gw_ss, NULL);
4437 
4438 			isequal = sa_equal(SA(&key_ss), SA(&gw_ss));
4439 		} else {
4440 			isequal = sa_equal(rt_key(gwrt), rt->rt_gateway);
4441 		}
4442 
4443 		/* If they are the same, update gwrt */
4444 		if (isequal) {
4445 			RT_UNLOCK(rt);
4446 			lck_mtx_lock(rnh_lock);
4447 			RT_LOCK(rt);
4448 			rt_set_gwroute(rt, rt_key(rt), gwrt);
4449 			RT_UNLOCK(rt);
4450 			lck_mtx_unlock(rnh_lock);
4451 		} else {
4452 			RT_UNLOCK(rt);
4453 		}
4454 	} else {
4455 		RT_UNLOCK(rt);
4456 	}
4457 }
4458 
4459 static void
rt_str4(struct rtentry * rt,char * ds __sized_by (dslen),uint32_t dslen,char * gs __sized_by (gslen),uint32_t gslen)4460 rt_str4(struct rtentry *rt, char *ds __sized_by(dslen), uint32_t dslen, char *gs __sized_by(gslen), uint32_t gslen)
4461 {
4462 	VERIFY(rt_key(rt)->sa_family == AF_INET);
4463 
4464 	if (ds != NULL) {
4465 		(void) inet_ntop(AF_INET,
4466 		    &SIN(rt_key(rt))->sin_addr.s_addr, ds, dslen);
4467 		if (dslen >= MAX_SCOPE_ADDR_STR_LEN &&
4468 		    SINIFSCOPE(rt_key(rt))->sin_scope_id != IFSCOPE_NONE) {
4469 			char scpstr[16];
4470 
4471 			snprintf(scpstr, sizeof(scpstr), "@%u",
4472 			    SINIFSCOPE(rt_key(rt))->sin_scope_id);
4473 
4474 			strbufcat(ds, dslen, scpstr, sizeof(scpstr));
4475 		}
4476 	}
4477 
4478 	if (gs != NULL) {
4479 		if (rt->rt_flags & RTF_GATEWAY) {
4480 			(void) inet_ntop(AF_INET,
4481 			    &SIN(rt->rt_gateway)->sin_addr.s_addr, gs, gslen);
4482 		} else if (rt->rt_ifp != NULL) {
4483 			snprintf(gs, gslen, "link#%u", rt->rt_ifp->if_unit);
4484 		} else {
4485 			snprintf(gs, gslen, "%s", "link");
4486 		}
4487 	}
4488 }
4489 
4490 static void
rt_str6(struct rtentry * rt,char * ds __sized_by (dslen),uint32_t dslen,char * gs __sized_by (gslen),uint32_t gslen)4491 rt_str6(struct rtentry *rt, char *ds __sized_by(dslen), uint32_t dslen, char *gs __sized_by(gslen), uint32_t gslen)
4492 {
4493 	VERIFY(rt_key(rt)->sa_family == AF_INET6);
4494 
4495 	if (ds != NULL) {
4496 		(void) inet_ntop(AF_INET6,
4497 		    &SIN6(rt_key(rt))->sin6_addr, ds, dslen);
4498 		if (dslen >= MAX_SCOPE_ADDR_STR_LEN &&
4499 		    SIN6IFSCOPE(rt_key(rt))->sin6_scope_id != IFSCOPE_NONE) {
4500 			char scpstr[16];
4501 
4502 			snprintf(scpstr, sizeof(scpstr), "@%u",
4503 			    SIN6IFSCOPE(rt_key(rt))->sin6_scope_id);
4504 
4505 			strbufcat(ds, dslen, scpstr, sizeof(scpstr));
4506 		}
4507 	}
4508 
4509 	if (gs != NULL) {
4510 		if (rt->rt_flags & RTF_GATEWAY) {
4511 			(void) inet_ntop(AF_INET6,
4512 			    &SIN6(rt->rt_gateway)->sin6_addr, gs, gslen);
4513 		} else if (rt->rt_ifp != NULL) {
4514 			snprintf(gs, gslen, "link#%u", rt->rt_ifp->if_unit);
4515 		} else {
4516 			snprintf(gs, gslen, "%s", "link");
4517 		}
4518 	}
4519 }
4520 
4521 void
rt_str(struct rtentry * rt,char * ds __sized_by (dslen),uint32_t dslen,char * gs __sized_by (gslen),uint32_t gslen)4522 rt_str(struct rtentry *rt, char *ds __sized_by(dslen), uint32_t dslen, char *gs __sized_by(gslen), uint32_t gslen)
4523 {
4524 	switch (rt_key(rt)->sa_family) {
4525 	case AF_INET:
4526 		rt_str4(rt, ds, dslen, gs, gslen);
4527 		break;
4528 	case AF_INET6:
4529 		rt_str6(rt, ds, dslen, gs, gslen);
4530 		break;
4531 	default:
4532 		if (ds != NULL) {
4533 			bzero(ds, dslen);
4534 		}
4535 		if (gs != NULL) {
4536 			bzero(gs, gslen);
4537 		}
4538 		break;
4539 	}
4540 }
4541 
4542 void
route_event_init(struct route_event * p_route_ev,struct rtentry * rt,struct rtentry * gwrt,int route_ev_code)4543 route_event_init(struct route_event *p_route_ev, struct rtentry *rt,
4544     struct rtentry *gwrt, int route_ev_code)
4545 {
4546 	VERIFY(p_route_ev != NULL);
4547 	bzero(p_route_ev, sizeof(*p_route_ev));
4548 
4549 	p_route_ev->rt = rt;
4550 	p_route_ev->gwrt = gwrt;
4551 	p_route_ev->route_event_code = route_ev_code;
4552 }
4553 
4554 struct route_event_nwk_wq_entry {
4555 	struct nwk_wq_entry nwk_wqe;
4556 	struct route_event rt_ev_arg;
4557 };
4558 
4559 static void
__route_copy(const struct route * src,struct route * dst,size_t len)4560 __route_copy(const struct route *src, struct route *dst, size_t len)
4561 {
4562 	uint8_t *bdst = __unsafe_forge_bidi_indexable(uint8_t *, dst, len);
4563 	const uint8_t *bsrc = __unsafe_forge_bidi_indexable(const uint8_t *, src, len);
4564 	bcopy(bsrc, bdst, len);
4565 }
4566 
4567 
4568 static void
route_event_callback(struct nwk_wq_entry * nwk_item)4569 route_event_callback(struct nwk_wq_entry *nwk_item)
4570 {
4571 	struct route_event_nwk_wq_entry *p_ev = __container_of(nwk_item,
4572 	    struct route_event_nwk_wq_entry, nwk_wqe);
4573 
4574 	rtentry_ref_t rt = p_ev->rt_ev_arg.rt;
4575 	eventhandler_tag evtag = p_ev->rt_ev_arg.evtag;
4576 	int route_ev_code = p_ev->rt_ev_arg.route_event_code;
4577 
4578 	if (route_ev_code == ROUTE_EVHDLR_DEREGISTER) {
4579 		VERIFY(evtag != NULL);
4580 		EVENTHANDLER_DEREGISTER(&rt->rt_evhdlr_ctxt, route_event,
4581 		    evtag);
4582 		rtfree(rt);
4583 		kfree_type(struct route_event_nwk_wq_entry, p_ev);
4584 		return;
4585 	}
4586 
4587 	EVENTHANDLER_INVOKE(&rt->rt_evhdlr_ctxt, route_event, rt_key(rt),
4588 	    route_ev_code, SA(&p_ev->rt_ev_arg.rtev_ipaddr),
4589 	    rt->rt_flags);
4590 
4591 	/* The code enqueuing the route event held a reference */
4592 	rtfree(rt);
4593 	/* XXX No reference is taken on gwrt */
4594 	kfree_type(struct route_event_nwk_wq_entry, p_ev);
4595 }
4596 
4597 int
route_event_walktree(struct radix_node * rn,void * arg)4598 route_event_walktree(struct radix_node *rn, void *arg)
4599 {
4600 	struct route_event *p_route_ev = (struct route_event *)arg;
4601 	rtentry_ref_t rt = RT(rn);
4602 	rtentry_ref_t gwrt = p_route_ev->rt;
4603 
4604 	LCK_MTX_ASSERT(rnh_lock, LCK_MTX_ASSERT_OWNED);
4605 
4606 	RT_LOCK(rt);
4607 
4608 	/* Return if the entry is pending cleanup */
4609 	if (rt->rt_flags & RTPRF_OURS) {
4610 		RT_UNLOCK(rt);
4611 		return 0;
4612 	}
4613 
4614 	/* Return if it is not an indirect route */
4615 	if (!(rt->rt_flags & RTF_GATEWAY)) {
4616 		RT_UNLOCK(rt);
4617 		return 0;
4618 	}
4619 
4620 	if (rt->rt_gwroute != gwrt) {
4621 		RT_UNLOCK(rt);
4622 		return 0;
4623 	}
4624 
4625 	route_event_enqueue_nwk_wq_entry(rt, gwrt, p_route_ev->route_event_code,
4626 	    NULL, TRUE);
4627 	RT_UNLOCK(rt);
4628 
4629 	return 0;
4630 }
4631 
4632 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)4633 route_event_enqueue_nwk_wq_entry(struct rtentry *rt, struct rtentry *gwrt,
4634     uint32_t route_event_code, eventhandler_tag evtag, boolean_t rt_locked)
4635 {
4636 	struct route_event_nwk_wq_entry *p_rt_ev = NULL;
4637 	struct sockaddr *p_gw_saddr = NULL;
4638 
4639 	p_rt_ev = kalloc_type(struct route_event_nwk_wq_entry,
4640 	    Z_WAITOK | Z_ZERO | Z_NOFAIL);
4641 
4642 	/*
4643 	 * If the intent is to de-register, don't take
4644 	 * reference, route event registration already takes
4645 	 * a reference on route.
4646 	 */
4647 	if (route_event_code != ROUTE_EVHDLR_DEREGISTER) {
4648 		/* The reference is released by route_event_callback */
4649 		if (rt_locked) {
4650 			RT_ADDREF_LOCKED(rt);
4651 		} else {
4652 			RT_ADDREF(rt);
4653 		}
4654 	}
4655 
4656 	p_rt_ev->rt_ev_arg.rt = rt;
4657 	p_rt_ev->rt_ev_arg.gwrt = gwrt;
4658 	p_rt_ev->rt_ev_arg.evtag = evtag;
4659 
4660 	if (gwrt != NULL) {
4661 		p_gw_saddr = gwrt->rt_gateway;
4662 	} else {
4663 		p_gw_saddr = rt->rt_gateway;
4664 	}
4665 
4666 	VERIFY(p_gw_saddr->sa_len <= sizeof(p_rt_ev->rt_ev_arg.rt_addr));
4667 	SOCKADDR_COPY(p_gw_saddr, &(p_rt_ev->rt_ev_arg.rtev_ipaddr), p_gw_saddr->sa_len);
4668 
4669 	p_rt_ev->rt_ev_arg.route_event_code = route_event_code;
4670 	p_rt_ev->nwk_wqe.func = route_event_callback;
4671 
4672 	evhlog(debug, "%s: eventhandler enqueuing event of type=route_event event_code=%s",
4673 	    __func__, route_event2str(route_event_code));
4674 
4675 	nwk_wq_enqueue(&p_rt_ev->nwk_wqe);
4676 }
4677 
4678 const char *
route_event2str(int route_event)4679 route_event2str(int route_event)
4680 {
4681 	const char *route_event_str __null_terminated = "ROUTE_EVENT_UNKNOWN";
4682 	switch (route_event) {
4683 	case ROUTE_STATUS_UPDATE:
4684 		route_event_str = "ROUTE_STATUS_UPDATE";
4685 		break;
4686 	case ROUTE_ENTRY_REFRESH:
4687 		route_event_str = "ROUTE_ENTRY_REFRESH";
4688 		break;
4689 	case ROUTE_ENTRY_DELETED:
4690 		route_event_str = "ROUTE_ENTRY_DELETED";
4691 		break;
4692 	case ROUTE_LLENTRY_RESOLVED:
4693 		route_event_str = "ROUTE_LLENTRY_RESOLVED";
4694 		break;
4695 	case ROUTE_LLENTRY_UNREACH:
4696 		route_event_str = "ROUTE_LLENTRY_UNREACH";
4697 		break;
4698 	case ROUTE_LLENTRY_CHANGED:
4699 		route_event_str = "ROUTE_LLENTRY_CHANGED";
4700 		break;
4701 	case ROUTE_LLENTRY_STALE:
4702 		route_event_str = "ROUTE_LLENTRY_STALE";
4703 		break;
4704 	case ROUTE_LLENTRY_TIMEDOUT:
4705 		route_event_str = "ROUTE_LLENTRY_TIMEDOUT";
4706 		break;
4707 	case ROUTE_LLENTRY_DELETED:
4708 		route_event_str = "ROUTE_LLENTRY_DELETED";
4709 		break;
4710 	case ROUTE_LLENTRY_EXPIRED:
4711 		route_event_str = "ROUTE_LLENTRY_EXPIRED";
4712 		break;
4713 	case ROUTE_LLENTRY_PROBED:
4714 		route_event_str = "ROUTE_LLENTRY_PROBED";
4715 		break;
4716 	case ROUTE_EVHDLR_DEREGISTER:
4717 		route_event_str = "ROUTE_EVHDLR_DEREGISTER";
4718 		break;
4719 	default:
4720 		/* Init'd to ROUTE_EVENT_UNKNOWN */
4721 		break;
4722 	}
4723 	return route_event_str;
4724 }
4725 
4726 int
route_op_entitlement_check(struct socket * so,kauth_cred_t cred,int route_op_type,boolean_t allow_root)4727 route_op_entitlement_check(struct socket *so,
4728     kauth_cred_t cred,
4729     int route_op_type,
4730     boolean_t allow_root)
4731 {
4732 	if (so != NULL) {
4733 		if (route_op_type == ROUTE_OP_READ) {
4734 			/*
4735 			 * If needed we can later extend this for more
4736 			 * granular entitlements and return a bit set of
4737 			 * allowed accesses.
4738 			 */
4739 			if (soopt_cred_check(so, PRIV_NET_RESTRICTED_ROUTE_NC_READ,
4740 			    allow_root, false) == 0) {
4741 				return 0;
4742 			} else {
4743 				return -1;
4744 			}
4745 		}
4746 	} else if (cred != NULL) {
4747 		uid_t uid = kauth_cred_getuid(cred);
4748 
4749 		/* uid is 0 for root */
4750 		if (uid != 0 || !allow_root) {
4751 			if (route_op_type == ROUTE_OP_READ) {
4752 				if (priv_check_cred(cred,
4753 				    PRIV_NET_RESTRICTED_ROUTE_NC_READ, 0) == 0) {
4754 					return 0;
4755 				} else {
4756 					return -1;
4757 				}
4758 			}
4759 		}
4760 	}
4761 	return -1;
4762 }
4763 
4764 /*
4765  * RTM_xxx.
4766  *
4767  * The switch statement below does nothing at runtime, as it serves as a
4768  * compile time check to ensure that all of the RTM_xxx constants are
4769  * unique.  This works as long as this routine gets updated each time a
4770  * new RTM_xxx constant gets added.
4771  *
4772  * Any failures at compile time indicates duplicated RTM_xxx values.
4773  */
4774 static __attribute__((unused)) void
rtm_cassert(void)4775 rtm_cassert(void)
4776 {
4777 	/*
4778 	 * This is equivalent to _CASSERT() and the compiler wouldn't
4779 	 * generate any instructions, thus for compile time only.
4780 	 */
4781 	switch ((u_int16_t)0) {
4782 	case 0:
4783 
4784 	/* bsd/net/route.h */
4785 	case RTM_ADD:
4786 	case RTM_DELETE:
4787 	case RTM_CHANGE:
4788 	case RTM_GET:
4789 	case RTM_LOSING:
4790 	case RTM_REDIRECT:
4791 	case RTM_MISS:
4792 	case RTM_LOCK:
4793 	case RTM_OLDADD:
4794 	case RTM_OLDDEL:
4795 	case RTM_RESOLVE:
4796 	case RTM_NEWADDR:
4797 	case RTM_DELADDR:
4798 	case RTM_IFINFO:
4799 	case RTM_NEWMADDR:
4800 	case RTM_DELMADDR:
4801 	case RTM_IFINFO2:
4802 	case RTM_NEWMADDR2:
4803 	case RTM_GET2:
4804 
4805 	/* bsd/net/route_private.h */
4806 	case RTM_GET_SILENT:
4807 	case RTM_GET_EXT:
4808 		;
4809 	}
4810 }
4811 
4812 static __attribute__((unused)) void
rtv_cassert(void)4813 rtv_cassert(void)
4814 {
4815 	switch ((u_int16_t)0) {
4816 	case 0:
4817 
4818 	/* bsd/net/route.h */
4819 	case RTV_MTU:
4820 	case RTV_HOPCOUNT:
4821 	case RTV_EXPIRE:
4822 	case RTV_RPIPE:
4823 	case RTV_SPIPE:
4824 	case RTV_SSTHRESH:
4825 	case RTV_RTT:
4826 	case RTV_RTTVAR:
4827 
4828 	/* net/route_private.h */
4829 	case RTV_REFRESH_HOST:
4830 		;
4831 	}
4832 }
4833