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