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