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