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