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