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