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