xref: /freebsd-12.1/sys/net/route.c (revision 4e4a6755)
1 /*-
2  * SPDX-License-Identifier: BSD-3-Clause
3  *
4  * Copyright (c) 1980, 1986, 1991, 1993
5  *	The Regents of the University of California.  All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  * 3. Neither the name of the University nor the names of its contributors
16  *    may be used to endorse or promote products derived from this software
17  *    without specific prior written permission.
18  *
19  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
20  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
22  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
23  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
25  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
26  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
27  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
28  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
29  * SUCH DAMAGE.
30  *
31  *	@(#)route.c	8.3.1.1 (Berkeley) 2/23/95
32  * $FreeBSD$
33  */
34 /************************************************************************
35  * Note: In this file a 'fib' is a "forwarding information base"	*
36  * Which is the new name for an in kernel routing (next hop) table.	*
37  ***********************************************************************/
38 
39 #include "opt_inet.h"
40 #include "opt_inet6.h"
41 #include "opt_route.h"
42 #include "opt_sctp.h"
43 #include "opt_mrouting.h"
44 #include "opt_mpath.h"
45 
46 #include <sys/param.h>
47 #include <sys/systm.h>
48 #include <sys/malloc.h>
49 #include <sys/mbuf.h>
50 #include <sys/socket.h>
51 #include <sys/sysctl.h>
52 #include <sys/syslog.h>
53 #include <sys/sysproto.h>
54 #include <sys/proc.h>
55 #include <sys/domain.h>
56 #include <sys/kernel.h>
57 #include <sys/lock.h>
58 #include <sys/rmlock.h>
59 
60 #include <net/if.h>
61 #include <net/if_var.h>
62 #include <net/if_dl.h>
63 #include <net/route.h>
64 #include <net/route_var.h>
65 #include <net/vnet.h>
66 
67 #ifdef RADIX_MPATH
68 #include <net/radix_mpath.h>
69 #endif
70 
71 #include <netinet/in.h>
72 #include <netinet/ip_mroute.h>
73 
74 #include <vm/uma.h>
75 
76 #define	RT_MAXFIBS	UINT16_MAX
77 
78 /* Kernel config default option. */
79 #ifdef ROUTETABLES
80 #if ROUTETABLES <= 0
81 #error "ROUTETABLES defined too low"
82 #endif
83 #if ROUTETABLES > RT_MAXFIBS
84 #error "ROUTETABLES defined too big"
85 #endif
86 #define	RT_NUMFIBS	ROUTETABLES
87 #endif /* ROUTETABLES */
88 /* Initialize to default if not otherwise set. */
89 #ifndef	RT_NUMFIBS
90 #define	RT_NUMFIBS	1
91 #endif
92 
93 #if defined(INET) || defined(INET6)
94 #ifdef SCTP
95 extern void sctp_addr_change(struct ifaddr *ifa, int cmd);
96 #endif /* SCTP */
97 #endif
98 
99 
100 /* This is read-only.. */
101 u_int rt_numfibs = RT_NUMFIBS;
102 SYSCTL_UINT(_net, OID_AUTO, fibs, CTLFLAG_RDTUN, &rt_numfibs, 0, "");
103 
104 /*
105  * By default add routes to all fibs for new interfaces.
106  * Once this is set to 0 then only allocate routes on interface
107  * changes for the FIB of the caller when adding a new set of addresses
108  * to an interface.  XXX this is a shotgun aproach to a problem that needs
109  * a more fine grained solution.. that will come.
110  * XXX also has the problems getting the FIB from curthread which will not
111  * always work given the fib can be overridden and prefixes can be added
112  * from the network stack context.
113  */
114 VNET_DEFINE(u_int, rt_add_addr_allfibs) = 1;
115 SYSCTL_UINT(_net, OID_AUTO, add_addr_allfibs, CTLFLAG_RWTUN | CTLFLAG_VNET,
116     &VNET_NAME(rt_add_addr_allfibs), 0, "");
117 
118 VNET_DEFINE(struct rtstat, rtstat);
119 #define	V_rtstat	VNET(rtstat)
120 
121 VNET_DEFINE(struct rib_head *, rt_tables);
122 #define	V_rt_tables	VNET(rt_tables)
123 
124 VNET_DEFINE(int, rttrash);		/* routes not in table but not freed */
125 #define	V_rttrash	VNET(rttrash)
126 
127 
128 /*
129  * Convert a 'struct radix_node *' to a 'struct rtentry *'.
130  * The operation can be done safely (in this code) because a
131  * 'struct rtentry' starts with two 'struct radix_node''s, the first
132  * one representing leaf nodes in the routing tree, which is
133  * what the code in radix.c passes us as a 'struct radix_node'.
134  *
135  * But because there are a lot of assumptions in this conversion,
136  * do not cast explicitly, but always use the macro below.
137  */
138 #define RNTORT(p)	((struct rtentry *)(p))
139 
140 VNET_DEFINE_STATIC(uma_zone_t, rtzone);		/* Routing table UMA zone. */
141 #define	V_rtzone	VNET(rtzone)
142 
143 static int rtrequest1_fib_change(struct rib_head *, struct rt_addrinfo *,
144     struct rtentry **, u_int);
145 static void rt_setmetrics(const struct rt_addrinfo *, struct rtentry *);
146 static int rt_ifdelroute(const struct rtentry *rt, void *arg);
147 static struct rtentry *rt_unlinkrte(struct rib_head *rnh,
148     struct rt_addrinfo *info, int *perror);
149 static void rt_notifydelete(struct rtentry *rt, struct rt_addrinfo *info);
150 #ifdef RADIX_MPATH
151 static struct radix_node *rt_mpath_unlink(struct rib_head *rnh,
152     struct rt_addrinfo *info, struct rtentry *rto, int *perror);
153 #endif
154 static int rt_exportinfo(struct rtentry *rt, struct rt_addrinfo *info,
155     int flags);
156 
157 struct if_mtuinfo
158 {
159 	struct ifnet	*ifp;
160 	int		mtu;
161 };
162 
163 static int	if_updatemtu_cb(struct radix_node *, void *);
164 
165 /*
166  * handler for net.my_fibnum
167  */
168 static int
sysctl_my_fibnum(SYSCTL_HANDLER_ARGS)169 sysctl_my_fibnum(SYSCTL_HANDLER_ARGS)
170 {
171         int fibnum;
172         int error;
173 
174         fibnum = curthread->td_proc->p_fibnum;
175         error = sysctl_handle_int(oidp, &fibnum, 0, req);
176         return (error);
177 }
178 
179 SYSCTL_PROC(_net, OID_AUTO, my_fibnum, CTLTYPE_INT|CTLFLAG_RD,
180             NULL, 0, &sysctl_my_fibnum, "I", "default FIB of caller");
181 
182 static __inline struct rib_head **
rt_tables_get_rnh_ptr(int table,int fam)183 rt_tables_get_rnh_ptr(int table, int fam)
184 {
185 	struct rib_head **rnh;
186 
187 	KASSERT(table >= 0 && table < rt_numfibs, ("%s: table out of bounds.",
188 	    __func__));
189 	KASSERT(fam >= 0 && fam < (AF_MAX+1), ("%s: fam out of bounds.",
190 	    __func__));
191 
192 	/* rnh is [fib=0][af=0]. */
193 	rnh = (struct rib_head **)V_rt_tables;
194 	/* Get the offset to the requested table and fam. */
195 	rnh += table * (AF_MAX+1) + fam;
196 
197 	return (rnh);
198 }
199 
200 struct rib_head *
rt_tables_get_rnh(int table,int fam)201 rt_tables_get_rnh(int table, int fam)
202 {
203 
204 	return (*rt_tables_get_rnh_ptr(table, fam));
205 }
206 
207 u_int
rt_tables_get_gen(int table,int fam)208 rt_tables_get_gen(int table, int fam)
209 {
210 	struct rib_head *rnh;
211 
212 	rnh = *rt_tables_get_rnh_ptr(table, fam);
213 	KASSERT(rnh != NULL, ("%s: NULL rib_head pointer table %d fam %d",
214 	    __func__, table, fam));
215 	return (rnh->rnh_gen);
216 }
217 
218 
219 /*
220  * route initialization must occur before ip6_init2(), which happenas at
221  * SI_ORDER_MIDDLE.
222  */
223 static void
route_init(void)224 route_init(void)
225 {
226 
227 	/* whack the tunable ints into  line. */
228 	if (rt_numfibs > RT_MAXFIBS)
229 		rt_numfibs = RT_MAXFIBS;
230 	if (rt_numfibs == 0)
231 		rt_numfibs = 1;
232 }
233 SYSINIT(route_init, SI_SUB_PROTO_DOMAIN, SI_ORDER_THIRD, route_init, NULL);
234 
235 static int
rtentry_zinit(void * mem,int size,int how)236 rtentry_zinit(void *mem, int size, int how)
237 {
238 	struct rtentry *rt = mem;
239 
240 	rt->rt_pksent = counter_u64_alloc(how);
241 	if (rt->rt_pksent == NULL)
242 		return (ENOMEM);
243 
244 	RT_LOCK_INIT(rt);
245 
246 	return (0);
247 }
248 
249 static void
rtentry_zfini(void * mem,int size)250 rtentry_zfini(void *mem, int size)
251 {
252 	struct rtentry *rt = mem;
253 
254 	RT_LOCK_DESTROY(rt);
255 	counter_u64_free(rt->rt_pksent);
256 }
257 
258 static int
rtentry_ctor(void * mem,int size,void * arg,int how)259 rtentry_ctor(void *mem, int size, void *arg, int how)
260 {
261 	struct rtentry *rt = mem;
262 
263 	bzero(rt, offsetof(struct rtentry, rt_endzero));
264 	counter_u64_zero(rt->rt_pksent);
265 	rt->rt_chain = NULL;
266 
267 	return (0);
268 }
269 
270 static void
rtentry_dtor(void * mem,int size,void * arg)271 rtentry_dtor(void *mem, int size, void *arg)
272 {
273 	struct rtentry *rt = mem;
274 
275 	RT_UNLOCK_COND(rt);
276 }
277 
278 static void
vnet_route_init(const void * unused __unused)279 vnet_route_init(const void *unused __unused)
280 {
281 	struct domain *dom;
282 	struct rib_head **rnh;
283 	int table;
284 	int fam;
285 
286 	V_rt_tables = malloc(rt_numfibs * (AF_MAX+1) *
287 	    sizeof(struct rib_head *), M_RTABLE, M_WAITOK|M_ZERO);
288 
289 	V_rtzone = uma_zcreate("rtentry", sizeof(struct rtentry),
290 	    rtentry_ctor, rtentry_dtor,
291 	    rtentry_zinit, rtentry_zfini, UMA_ALIGN_PTR, 0);
292 	for (dom = domains; dom; dom = dom->dom_next) {
293 		if (dom->dom_rtattach == NULL)
294 			continue;
295 
296 		for  (table = 0; table < rt_numfibs; table++) {
297 			fam = dom->dom_family;
298 			if (table != 0 && fam != AF_INET6 && fam != AF_INET)
299 				break;
300 
301 			rnh = rt_tables_get_rnh_ptr(table, fam);
302 			if (rnh == NULL)
303 				panic("%s: rnh NULL", __func__);
304 			dom->dom_rtattach((void **)rnh, 0);
305 		}
306 	}
307 }
308 VNET_SYSINIT(vnet_route_init, SI_SUB_PROTO_DOMAIN, SI_ORDER_FOURTH,
309     vnet_route_init, 0);
310 
311 #ifdef VIMAGE
312 static void
vnet_route_uninit(const void * unused __unused)313 vnet_route_uninit(const void *unused __unused)
314 {
315 	int table;
316 	int fam;
317 	struct domain *dom;
318 	struct rib_head **rnh;
319 
320 	for (dom = domains; dom; dom = dom->dom_next) {
321 		if (dom->dom_rtdetach == NULL)
322 			continue;
323 
324 		for (table = 0; table < rt_numfibs; table++) {
325 			fam = dom->dom_family;
326 
327 			if (table != 0 && fam != AF_INET6 && fam != AF_INET)
328 				break;
329 
330 			rnh = rt_tables_get_rnh_ptr(table, fam);
331 			if (rnh == NULL)
332 				panic("%s: rnh NULL", __func__);
333 			dom->dom_rtdetach((void **)rnh, 0);
334 		}
335 	}
336 
337 	free(V_rt_tables, M_RTABLE);
338 	uma_zdestroy(V_rtzone);
339 }
340 VNET_SYSUNINIT(vnet_route_uninit, SI_SUB_PROTO_DOMAIN, SI_ORDER_FIRST,
341     vnet_route_uninit, 0);
342 #endif
343 
344 struct rib_head *
rt_table_init(int offset)345 rt_table_init(int offset)
346 {
347 	struct rib_head *rh;
348 
349 	rh = malloc(sizeof(struct rib_head), M_RTABLE, M_WAITOK | M_ZERO);
350 
351 	/* TODO: These details should be hidded inside radix.c */
352 	/* Init masks tree */
353 	rn_inithead_internal(&rh->head, rh->rnh_nodes, offset);
354 	rn_inithead_internal(&rh->rmhead.head, rh->rmhead.mask_nodes, 0);
355 	rh->head.rnh_masks = &rh->rmhead;
356 
357 	/* Init locks */
358 	RIB_LOCK_INIT(rh);
359 
360 	/* Finally, set base callbacks */
361 	rh->rnh_addaddr = rn_addroute;
362 	rh->rnh_deladdr = rn_delete;
363 	rh->rnh_matchaddr = rn_match;
364 	rh->rnh_lookup = rn_lookup;
365 	rh->rnh_walktree = rn_walktree;
366 	rh->rnh_walktree_from = rn_walktree_from;
367 
368 	return (rh);
369 }
370 
371 static int
rt_freeentry(struct radix_node * rn,void * arg)372 rt_freeentry(struct radix_node *rn, void *arg)
373 {
374 	struct radix_head * const rnh = arg;
375 	struct radix_node *x;
376 
377 	x = (struct radix_node *)rn_delete(rn + 2, NULL, rnh);
378 	if (x != NULL)
379 		R_Free(x);
380 	return (0);
381 }
382 
383 void
rt_table_destroy(struct rib_head * rh)384 rt_table_destroy(struct rib_head *rh)
385 {
386 
387 	rn_walktree(&rh->rmhead.head, rt_freeentry, &rh->rmhead.head);
388 
389 	/* Assume table is already empty */
390 	RIB_LOCK_DESTROY(rh);
391 	free(rh, M_RTABLE);
392 }
393 
394 
395 #ifndef _SYS_SYSPROTO_H_
396 struct setfib_args {
397 	int     fibnum;
398 };
399 #endif
400 int
sys_setfib(struct thread * td,struct setfib_args * uap)401 sys_setfib(struct thread *td, struct setfib_args *uap)
402 {
403 	if (uap->fibnum < 0 || uap->fibnum >= rt_numfibs)
404 		return EINVAL;
405 	td->td_proc->p_fibnum = uap->fibnum;
406 	return (0);
407 }
408 
409 /*
410  * Packet routing routines.
411  */
412 void
rtalloc_ign_fib(struct route * ro,u_long ignore,u_int fibnum)413 rtalloc_ign_fib(struct route *ro, u_long ignore, u_int fibnum)
414 {
415 	struct rtentry *rt;
416 
417 	if ((rt = ro->ro_rt) != NULL) {
418 		if (rt->rt_ifp != NULL && rt->rt_flags & RTF_UP)
419 			return;
420 		RTFREE(rt);
421 		ro->ro_rt = NULL;
422 	}
423 	ro->ro_rt = rtalloc1_fib(&ro->ro_dst, 1, ignore, fibnum);
424 	if (ro->ro_rt)
425 		RT_UNLOCK(ro->ro_rt);
426 }
427 
428 /*
429  * Look up the route that matches the address given
430  * Or, at least try.. Create a cloned route if needed.
431  *
432  * The returned route, if any, is locked.
433  */
434 struct rtentry *
rtalloc1(struct sockaddr * dst,int report,u_long ignflags)435 rtalloc1(struct sockaddr *dst, int report, u_long ignflags)
436 {
437 
438 	return (rtalloc1_fib(dst, report, ignflags, RT_DEFAULT_FIB));
439 }
440 
441 struct rtentry *
rtalloc1_fib(struct sockaddr * dst,int report,u_long ignflags,u_int fibnum)442 rtalloc1_fib(struct sockaddr *dst, int report, u_long ignflags,
443 		    u_int fibnum)
444 {
445 	RIB_RLOCK_TRACKER;
446 	struct rib_head *rh;
447 	struct radix_node *rn;
448 	struct rtentry *newrt;
449 	struct rt_addrinfo info;
450 	int err = 0, msgtype = RTM_MISS;
451 
452 	KASSERT((fibnum < rt_numfibs), ("rtalloc1_fib: bad fibnum"));
453 	rh = rt_tables_get_rnh(fibnum, dst->sa_family);
454 	newrt = NULL;
455 	if (rh == NULL)
456 		goto miss;
457 
458 	/*
459 	 * Look up the address in the table for that Address Family
460 	 */
461 	if ((ignflags & RTF_RNH_LOCKED) == 0)
462 		RIB_RLOCK(rh);
463 #ifdef INVARIANTS
464 	else
465 		RIB_LOCK_ASSERT(rh);
466 #endif
467 	rn = rh->rnh_matchaddr(dst, &rh->head);
468 	if (rn && ((rn->rn_flags & RNF_ROOT) == 0)) {
469 		newrt = RNTORT(rn);
470 		RT_LOCK(newrt);
471 		RT_ADDREF(newrt);
472 		if ((ignflags & RTF_RNH_LOCKED) == 0)
473 			RIB_RUNLOCK(rh);
474 		return (newrt);
475 
476 	} else if ((ignflags & RTF_RNH_LOCKED) == 0)
477 		RIB_RUNLOCK(rh);
478 	/*
479 	 * Either we hit the root or could not find any match,
480 	 * which basically means: "cannot get there from here".
481 	 */
482 miss:
483 	V_rtstat.rts_unreach++;
484 
485 	if (report) {
486 		/*
487 		 * If required, report the failure to the supervising
488 		 * Authorities.
489 		 * For a delete, this is not an error. (report == 0)
490 		 */
491 		bzero(&info, sizeof(info));
492 		info.rti_info[RTAX_DST] = dst;
493 		rt_missmsg_fib(msgtype, &info, 0, err, fibnum);
494 	}
495 	return (newrt);
496 }
497 
498 /*
499  * Remove a reference count from an rtentry.
500  * If the count gets low enough, take it out of the routing table
501  */
502 void
rtfree(struct rtentry * rt)503 rtfree(struct rtentry *rt)
504 {
505 	struct rib_head *rnh;
506 
507 	KASSERT(rt != NULL,("%s: NULL rt", __func__));
508 	rnh = rt_tables_get_rnh(rt->rt_fibnum, rt_key(rt)->sa_family);
509 	KASSERT(rnh != NULL,("%s: NULL rnh", __func__));
510 
511 	RT_LOCK_ASSERT(rt);
512 
513 	/*
514 	 * The callers should use RTFREE_LOCKED() or RTFREE(), so
515 	 * we should come here exactly with the last reference.
516 	 */
517 	RT_REMREF(rt);
518 	if (rt->rt_refcnt > 0) {
519 		log(LOG_DEBUG, "%s: %p has %d refs\n", __func__, rt, rt->rt_refcnt);
520 		goto done;
521 	}
522 
523 	/*
524 	 * On last reference give the "close method" a chance
525 	 * to cleanup private state.  This also permits (for
526 	 * IPv4 and IPv6) a chance to decide if the routing table
527 	 * entry should be purged immediately or at a later time.
528 	 * When an immediate purge is to happen the close routine
529 	 * typically calls rtexpunge which clears the RTF_UP flag
530 	 * on the entry so that the code below reclaims the storage.
531 	 */
532 	if (rt->rt_refcnt == 0 && rnh->rnh_close)
533 		rnh->rnh_close((struct radix_node *)rt, &rnh->head);
534 
535 	/*
536 	 * If we are no longer "up" (and ref == 0)
537 	 * then we can free the resources associated
538 	 * with the route.
539 	 */
540 	if ((rt->rt_flags & RTF_UP) == 0) {
541 		if (rt->rt_nodes->rn_flags & (RNF_ACTIVE | RNF_ROOT))
542 			panic("rtfree 2");
543 		/*
544 		 * the rtentry must have been removed from the routing table
545 		 * so it is represented in rttrash.. remove that now.
546 		 */
547 		V_rttrash--;
548 #ifdef	DIAGNOSTIC
549 		if (rt->rt_refcnt < 0) {
550 			printf("rtfree: %p not freed (neg refs)\n", rt);
551 			goto done;
552 		}
553 #endif
554 		/*
555 		 * release references on items we hold them on..
556 		 * e.g other routes and ifaddrs.
557 		 */
558 		if (rt->rt_ifa)
559 			ifa_free(rt->rt_ifa);
560 		/*
561 		 * The key is separatly alloc'd so free it (see rt_setgate()).
562 		 * This also frees the gateway, as they are always malloc'd
563 		 * together.
564 		 */
565 		R_Free(rt_key(rt));
566 
567 		/*
568 		 * and the rtentry itself of course
569 		 */
570 		uma_zfree(V_rtzone, rt);
571 		return;
572 	}
573 done:
574 	RT_UNLOCK(rt);
575 }
576 
577 
578 /*
579  * Force a routing table entry to the specified
580  * destination to go through the given gateway.
581  * Normally called as a result of a routing redirect
582  * message from the network layer.
583  */
584 void
rtredirect_fib(struct sockaddr * dst,struct sockaddr * gateway,struct sockaddr * netmask,int flags,struct sockaddr * src,u_int fibnum)585 rtredirect_fib(struct sockaddr *dst,
586 	struct sockaddr *gateway,
587 	struct sockaddr *netmask,
588 	int flags,
589 	struct sockaddr *src,
590 	u_int fibnum)
591 {
592 	struct rtentry *rt;
593 	int error = 0;
594 	short *stat = NULL;
595 	struct rt_addrinfo info;
596 	struct ifaddr *ifa;
597 	struct rib_head *rnh;
598 
599 	ifa = NULL;
600 	NET_EPOCH_ENTER();
601 	rnh = rt_tables_get_rnh(fibnum, dst->sa_family);
602 	if (rnh == NULL) {
603 		error = EAFNOSUPPORT;
604 		goto out;
605 	}
606 	/* verify the gateway is directly reachable */
607 	if ((ifa = ifa_ifwithnet(gateway, 0, fibnum)) == NULL) {
608 		error = ENETUNREACH;
609 		goto out;
610 	}
611 	rt = rtalloc1_fib(dst, 0, 0UL, fibnum);	/* NB: rt is locked */
612 	/*
613 	 * If the redirect isn't from our current router for this dst,
614 	 * it's either old or wrong.  If it redirects us to ourselves,
615 	 * we have a routing loop, perhaps as a result of an interface
616 	 * going down recently.
617 	 */
618 	if (!(flags & RTF_DONE) && rt) {
619 		if (!sa_equal(src, rt->rt_gateway)) {
620 			error = EINVAL;
621 			goto done;
622 		}
623 		if (rt->rt_ifa != ifa && ifa->ifa_addr->sa_family != AF_LINK) {
624 			error = EINVAL;
625 			goto done;
626 		}
627 	}
628 	if ((flags & RTF_GATEWAY) && ifa_ifwithaddr_check(gateway)) {
629 		error = EHOSTUNREACH;
630 		goto done;
631 	}
632 	/*
633 	 * Create a new entry if we just got back a wildcard entry
634 	 * or the lookup failed.  This is necessary for hosts
635 	 * which use routing redirects generated by smart gateways
636 	 * to dynamically build the routing tables.
637 	 */
638 	if (rt == NULL || (rt_mask(rt) && rt_mask(rt)->sa_len < 2))
639 		goto create;
640 	/*
641 	 * Don't listen to the redirect if it's
642 	 * for a route to an interface.
643 	 */
644 	if (rt->rt_flags & RTF_GATEWAY) {
645 		if (((rt->rt_flags & RTF_HOST) == 0) && (flags & RTF_HOST)) {
646 			/*
647 			 * Changing from route to net => route to host.
648 			 * Create new route, rather than smashing route to net.
649 			 */
650 		create:
651 			if (rt != NULL)
652 				RTFREE_LOCKED(rt);
653 
654 			flags |= RTF_DYNAMIC;
655 			bzero((caddr_t)&info, sizeof(info));
656 			info.rti_info[RTAX_DST] = dst;
657 			info.rti_info[RTAX_GATEWAY] = gateway;
658 			info.rti_info[RTAX_NETMASK] = netmask;
659 			ifa_ref(ifa);
660 			info.rti_ifa = ifa;
661 			info.rti_flags = flags;
662 			error = rtrequest1_fib(RTM_ADD, &info, &rt, fibnum);
663 			if (rt != NULL) {
664 				RT_LOCK(rt);
665 				flags = rt->rt_flags;
666 			}
667 
668 			stat = &V_rtstat.rts_dynamic;
669 		} else {
670 
671 			/*
672 			 * Smash the current notion of the gateway to
673 			 * this destination.  Should check about netmask!!!
674 			 */
675 			if ((flags & RTF_GATEWAY) == 0)
676 				rt->rt_flags &= ~RTF_GATEWAY;
677 			rt->rt_flags |= RTF_MODIFIED;
678 			flags |= RTF_MODIFIED;
679 			stat = &V_rtstat.rts_newgateway;
680 			/*
681 			 * add the key and gateway (in one malloc'd chunk).
682 			 */
683 			RT_UNLOCK(rt);
684 			RIB_WLOCK(rnh);
685 			RT_LOCK(rt);
686 			rt_setgate(rt, rt_key(rt), gateway);
687 			RIB_WUNLOCK(rnh);
688 		}
689 	} else
690 		error = EHOSTUNREACH;
691 done:
692 	if (rt)
693 		RTFREE_LOCKED(rt);
694  out:
695 	NET_EPOCH_EXIT();
696 	if (error)
697 		V_rtstat.rts_badredirect++;
698 	else if (stat != NULL)
699 		(*stat)++;
700 	bzero((caddr_t)&info, sizeof(info));
701 	info.rti_info[RTAX_DST] = dst;
702 	info.rti_info[RTAX_GATEWAY] = gateway;
703 	info.rti_info[RTAX_NETMASK] = netmask;
704 	info.rti_info[RTAX_AUTHOR] = src;
705 	rt_missmsg_fib(RTM_REDIRECT, &info, flags, error, fibnum);
706 }
707 
708 /*
709  * Routing table ioctl interface.
710  */
711 int
rtioctl_fib(u_long req,caddr_t data,u_int fibnum)712 rtioctl_fib(u_long req, caddr_t data, u_int fibnum)
713 {
714 
715 	/*
716 	 * If more ioctl commands are added here, make sure the proper
717 	 * super-user checks are being performed because it is possible for
718 	 * prison-root to make it this far if raw sockets have been enabled
719 	 * in jails.
720 	 */
721 #ifdef INET
722 	/* Multicast goop, grrr... */
723 	return mrt_ioctl ? mrt_ioctl(req, data, fibnum) : EOPNOTSUPP;
724 #else /* INET */
725 	return ENXIO;
726 #endif /* INET */
727 }
728 
729 struct ifaddr *
ifa_ifwithroute(int flags,const struct sockaddr * dst,struct sockaddr * gateway,u_int fibnum)730 ifa_ifwithroute(int flags, const struct sockaddr *dst, struct sockaddr *gateway,
731 				u_int fibnum)
732 {
733 	struct ifaddr *ifa;
734 	int not_found = 0;
735 
736 	MPASS(in_epoch(net_epoch_preempt));
737 	if ((flags & RTF_GATEWAY) == 0) {
738 		/*
739 		 * If we are adding a route to an interface,
740 		 * and the interface is a pt to pt link
741 		 * we should search for the destination
742 		 * as our clue to the interface.  Otherwise
743 		 * we can use the local address.
744 		 */
745 		ifa = NULL;
746 		if (flags & RTF_HOST)
747 			ifa = ifa_ifwithdstaddr(dst, fibnum);
748 		if (ifa == NULL)
749 			ifa = ifa_ifwithaddr(gateway);
750 	} else {
751 		/*
752 		 * If we are adding a route to a remote net
753 		 * or host, the gateway may still be on the
754 		 * other end of a pt to pt link.
755 		 */
756 		ifa = ifa_ifwithdstaddr(gateway, fibnum);
757 	}
758 	if (ifa == NULL)
759 		ifa = ifa_ifwithnet(gateway, 0, fibnum);
760 	if (ifa == NULL) {
761 		struct rtentry *rt;
762 
763 		rt = rtalloc1_fib(gateway, 0, flags, fibnum);
764 		if (rt == NULL)
765 			goto out;
766 		/*
767 		 * dismiss a gateway that is reachable only
768 		 * through the default router
769 		 */
770 		switch (gateway->sa_family) {
771 		case AF_INET:
772 			if (satosin(rt_key(rt))->sin_addr.s_addr == INADDR_ANY)
773 				not_found = 1;
774 			break;
775 		case AF_INET6:
776 			if (IN6_IS_ADDR_UNSPECIFIED(&satosin6(rt_key(rt))->sin6_addr))
777 				not_found = 1;
778 			break;
779 		default:
780 			break;
781 		}
782 		if (!not_found && rt->rt_ifa != NULL) {
783 			ifa = rt->rt_ifa;
784 		}
785 		RT_REMREF(rt);
786 		RT_UNLOCK(rt);
787 		if (not_found || ifa == NULL)
788 			goto out;
789 	}
790 	if (ifa->ifa_addr->sa_family != dst->sa_family) {
791 		struct ifaddr *oifa = ifa;
792 		ifa = ifaof_ifpforaddr(dst, ifa->ifa_ifp);
793 		if (ifa == NULL)
794 			ifa = oifa;
795 	}
796  out:
797 	return (ifa);
798 }
799 
800 /*
801  * Do appropriate manipulations of a routing tree given
802  * all the bits of info needed
803  */
804 int
rtrequest_fib(int req,struct sockaddr * dst,struct sockaddr * gateway,struct sockaddr * netmask,int flags,struct rtentry ** ret_nrt,u_int fibnum)805 rtrequest_fib(int req,
806 	struct sockaddr *dst,
807 	struct sockaddr *gateway,
808 	struct sockaddr *netmask,
809 	int flags,
810 	struct rtentry **ret_nrt,
811 	u_int fibnum)
812 {
813 	struct rt_addrinfo info;
814 
815 	if (dst->sa_len == 0)
816 		return(EINVAL);
817 
818 	bzero((caddr_t)&info, sizeof(info));
819 	info.rti_flags = flags;
820 	info.rti_info[RTAX_DST] = dst;
821 	info.rti_info[RTAX_GATEWAY] = gateway;
822 	info.rti_info[RTAX_NETMASK] = netmask;
823 	return rtrequest1_fib(req, &info, ret_nrt, fibnum);
824 }
825 
826 
827 /*
828  * Copy most of @rt data into @info.
829  *
830  * If @flags contains NHR_COPY, copies dst,netmask and gw to the
831  * pointers specified by @info structure. Assume such pointers
832  * are zeroed sockaddr-like structures with sa_len field initialized
833  * to reflect size of the provided buffer. if no NHR_COPY is specified,
834  * point dst,netmask and gw @info fields to appropriate @rt values.
835  *
836  * if @flags contains NHR_REF, do refcouting on rt_ifp.
837  *
838  * Returns 0 on success.
839  */
840 int
rt_exportinfo(struct rtentry * rt,struct rt_addrinfo * info,int flags)841 rt_exportinfo(struct rtentry *rt, struct rt_addrinfo *info, int flags)
842 {
843 	struct rt_metrics *rmx;
844 	struct sockaddr *src, *dst;
845 	int sa_len;
846 
847 	if (flags & NHR_COPY) {
848 		/* Copy destination if dst is non-zero */
849 		src = rt_key(rt);
850 		dst = info->rti_info[RTAX_DST];
851 		sa_len = src->sa_len;
852 		if (dst != NULL) {
853 			if (src->sa_len > dst->sa_len)
854 				return (ENOMEM);
855 			memcpy(dst, src, src->sa_len);
856 			info->rti_addrs |= RTA_DST;
857 		}
858 
859 		/* Copy mask if set && dst is non-zero */
860 		src = rt_mask(rt);
861 		dst = info->rti_info[RTAX_NETMASK];
862 		if (src != NULL && dst != NULL) {
863 
864 			/*
865 			 * Radix stores different value in sa_len,
866 			 * assume rt_mask() to have the same length
867 			 * as rt_key()
868 			 */
869 			if (sa_len > dst->sa_len)
870 				return (ENOMEM);
871 			memcpy(dst, src, src->sa_len);
872 			info->rti_addrs |= RTA_NETMASK;
873 		}
874 
875 		/* Copy gateway is set && dst is non-zero */
876 		src = rt->rt_gateway;
877 		dst = info->rti_info[RTAX_GATEWAY];
878 		if ((rt->rt_flags & RTF_GATEWAY) && src != NULL && dst != NULL){
879 			if (src->sa_len > dst->sa_len)
880 				return (ENOMEM);
881 			memcpy(dst, src, src->sa_len);
882 			info->rti_addrs |= RTA_GATEWAY;
883 		}
884 	} else {
885 		info->rti_info[RTAX_DST] = rt_key(rt);
886 		info->rti_addrs |= RTA_DST;
887 		if (rt_mask(rt) != NULL) {
888 			info->rti_info[RTAX_NETMASK] = rt_mask(rt);
889 			info->rti_addrs |= RTA_NETMASK;
890 		}
891 		if (rt->rt_flags & RTF_GATEWAY) {
892 			info->rti_info[RTAX_GATEWAY] = rt->rt_gateway;
893 			info->rti_addrs |= RTA_GATEWAY;
894 		}
895 	}
896 
897 	rmx = info->rti_rmx;
898 	if (rmx != NULL) {
899 		info->rti_mflags |= RTV_MTU;
900 		rmx->rmx_mtu = rt->rt_mtu;
901 	}
902 
903 	info->rti_flags = rt->rt_flags;
904 	info->rti_ifp = rt->rt_ifp;
905 	info->rti_ifa = rt->rt_ifa;
906 	ifa_ref(info->rti_ifa);
907 	if (flags & NHR_REF) {
908 		/* Do 'traditional' refcouting */
909 		if_ref(info->rti_ifp);
910 	}
911 
912 	return (0);
913 }
914 
915 /*
916  * Lookups up route entry for @dst in RIB database for fib @fibnum.
917  * Exports entry data to @info using rt_exportinfo().
918  *
919  * if @flags contains NHR_REF, refcouting is performed on rt_ifp.
920  *   All references can be released later by calling rib_free_info()
921  *
922  * Returns 0 on success.
923  * Returns ENOENT for lookup failure, ENOMEM for export failure.
924  */
925 int
rib_lookup_info(uint32_t fibnum,const struct sockaddr * dst,uint32_t flags,uint32_t flowid,struct rt_addrinfo * info)926 rib_lookup_info(uint32_t fibnum, const struct sockaddr *dst, uint32_t flags,
927     uint32_t flowid, struct rt_addrinfo *info)
928 {
929 	RIB_RLOCK_TRACKER;
930 	struct rib_head *rh;
931 	struct radix_node *rn;
932 	struct rtentry *rt;
933 	int error;
934 
935 	KASSERT((fibnum < rt_numfibs), ("rib_lookup_rte: bad fibnum"));
936 	rh = rt_tables_get_rnh(fibnum, dst->sa_family);
937 	if (rh == NULL)
938 		return (ENOENT);
939 
940 	RIB_RLOCK(rh);
941 	rn = rh->rnh_matchaddr(__DECONST(void *, dst), &rh->head);
942 	if (rn != NULL && ((rn->rn_flags & RNF_ROOT) == 0)) {
943 		rt = RNTORT(rn);
944 		/* Ensure route & ifp is UP */
945 		if (RT_LINK_IS_UP(rt->rt_ifp)) {
946 			flags = (flags & NHR_REF) | NHR_COPY;
947 			error = rt_exportinfo(rt, info, flags);
948 			RIB_RUNLOCK(rh);
949 
950 			return (error);
951 		}
952 	}
953 	RIB_RUNLOCK(rh);
954 
955 	return (ENOENT);
956 }
957 
958 /*
959  * Releases all references acquired by rib_lookup_info() when
960  * called with NHR_REF flags.
961  */
962 void
rib_free_info(struct rt_addrinfo * info)963 rib_free_info(struct rt_addrinfo *info)
964 {
965 
966 	if_rele(info->rti_ifp);
967 }
968 
969 /*
970  * Iterates over all existing fibs in system calling
971  *  @setwa_f function prior to traversing each fib.
972  *  Calls @wa_f function for each element in current fib.
973  * If af is not AF_UNSPEC, iterates over fibs in particular
974  * address family.
975  */
976 void
rt_foreach_fib_walk(int af,rt_setwarg_t * setwa_f,rt_walktree_f_t * wa_f,void * arg)977 rt_foreach_fib_walk(int af, rt_setwarg_t *setwa_f, rt_walktree_f_t *wa_f,
978     void *arg)
979 {
980 	struct rib_head *rnh;
981 	uint32_t fibnum;
982 	int i;
983 
984 	for (fibnum = 0; fibnum < rt_numfibs; fibnum++) {
985 		/* Do we want some specific family? */
986 		if (af != AF_UNSPEC) {
987 			rnh = rt_tables_get_rnh(fibnum, af);
988 			if (rnh == NULL)
989 				continue;
990 			if (setwa_f != NULL)
991 				setwa_f(rnh, fibnum, af, arg);
992 
993 			RIB_WLOCK(rnh);
994 			rnh->rnh_walktree(&rnh->head, (walktree_f_t *)wa_f,arg);
995 			RIB_WUNLOCK(rnh);
996 			continue;
997 		}
998 
999 		for (i = 1; i <= AF_MAX; i++) {
1000 			rnh = rt_tables_get_rnh(fibnum, i);
1001 			if (rnh == NULL)
1002 				continue;
1003 			if (setwa_f != NULL)
1004 				setwa_f(rnh, fibnum, i, arg);
1005 
1006 			RIB_WLOCK(rnh);
1007 			rnh->rnh_walktree(&rnh->head, (walktree_f_t *)wa_f,arg);
1008 			RIB_WUNLOCK(rnh);
1009 		}
1010 	}
1011 }
1012 
1013 struct rt_delinfo
1014 {
1015 	struct rt_addrinfo info;
1016 	struct rib_head *rnh;
1017 	struct rtentry *head;
1018 };
1019 
1020 /*
1021  * Conditionally unlinks @rn from radix tree based
1022  * on info data passed in @arg.
1023  */
1024 static int
rt_checkdelroute(struct radix_node * rn,void * arg)1025 rt_checkdelroute(struct radix_node *rn, void *arg)
1026 {
1027 	struct rt_delinfo *di;
1028 	struct rt_addrinfo *info;
1029 	struct rtentry *rt;
1030 	int error;
1031 
1032 	di = (struct rt_delinfo *)arg;
1033 	rt = (struct rtentry *)rn;
1034 	info = &di->info;
1035 	error = 0;
1036 
1037 	info->rti_info[RTAX_DST] = rt_key(rt);
1038 	info->rti_info[RTAX_NETMASK] = rt_mask(rt);
1039 	info->rti_info[RTAX_GATEWAY] = rt->rt_gateway;
1040 
1041 	rt = rt_unlinkrte(di->rnh, info, &error);
1042 	if (rt == NULL) {
1043 		/* Either not allowed or not matched. Skip entry */
1044 		return (0);
1045 	}
1046 
1047 	/* Entry was unlinked. Add to the list and return */
1048 	rt->rt_chain = di->head;
1049 	di->head = rt;
1050 
1051 	return (0);
1052 }
1053 
1054 /*
1055  * Iterates over all existing fibs in system.
1056  * Deletes each element for which @filter_f function returned
1057  * non-zero value.
1058  * If @af is not AF_UNSPEC, iterates over fibs in particular
1059  * address family.
1060  */
1061 void
rt_foreach_fib_walk_del(int af,rt_filter_f_t * filter_f,void * arg)1062 rt_foreach_fib_walk_del(int af, rt_filter_f_t *filter_f, void *arg)
1063 {
1064 	struct rib_head *rnh;
1065 	struct rt_delinfo di;
1066 	struct rtentry *rt;
1067 	uint32_t fibnum;
1068 	int i, start, end;
1069 
1070 	bzero(&di, sizeof(di));
1071 	di.info.rti_filter = filter_f;
1072 	di.info.rti_filterdata = arg;
1073 
1074 	for (fibnum = 0; fibnum < rt_numfibs; fibnum++) {
1075 		/* Do we want some specific family? */
1076 		if (af != AF_UNSPEC) {
1077 			start = af;
1078 			end = af;
1079 		} else {
1080 			start = 1;
1081 			end = AF_MAX;
1082 		}
1083 
1084 		for (i = start; i <= end; i++) {
1085 			rnh = rt_tables_get_rnh(fibnum, i);
1086 			if (rnh == NULL)
1087 				continue;
1088 			di.rnh = rnh;
1089 
1090 			RIB_WLOCK(rnh);
1091 			rnh->rnh_walktree(&rnh->head, rt_checkdelroute, &di);
1092 			RIB_WUNLOCK(rnh);
1093 
1094 			if (di.head == NULL)
1095 				continue;
1096 
1097 			/* We might have something to reclaim */
1098 			while (di.head != NULL) {
1099 				rt = di.head;
1100 				di.head = rt->rt_chain;
1101 				rt->rt_chain = NULL;
1102 
1103 				/* TODO std rt -> rt_addrinfo export */
1104 				di.info.rti_info[RTAX_DST] = rt_key(rt);
1105 				di.info.rti_info[RTAX_NETMASK] = rt_mask(rt);
1106 
1107 				rt_notifydelete(rt, &di.info);
1108 				RTFREE_LOCKED(rt);
1109 			}
1110 
1111 		}
1112 	}
1113 }
1114 
1115 /*
1116  * Delete Routes for a Network Interface
1117  *
1118  * Called for each routing entry via the rnh->rnh_walktree() call above
1119  * to delete all route entries referencing a detaching network interface.
1120  *
1121  * Arguments:
1122  *	rt	pointer to rtentry
1123  *	arg	argument passed to rnh->rnh_walktree() - detaching interface
1124  *
1125  * Returns:
1126  *	0	successful
1127  *	errno	failed - reason indicated
1128  */
1129 static int
rt_ifdelroute(const struct rtentry * rt,void * arg)1130 rt_ifdelroute(const struct rtentry *rt, void *arg)
1131 {
1132 	struct ifnet	*ifp = arg;
1133 
1134 	if (rt->rt_ifp != ifp)
1135 		return (0);
1136 
1137 	/*
1138 	 * Protect (sorta) against walktree recursion problems
1139 	 * with cloned routes
1140 	 */
1141 	if ((rt->rt_flags & RTF_UP) == 0)
1142 		return (0);
1143 
1144 	return (1);
1145 }
1146 
1147 /*
1148  * Delete all remaining routes using this interface
1149  * Unfortuneatly the only way to do this is to slog through
1150  * the entire routing table looking for routes which point
1151  * to this interface...oh well...
1152  */
1153 void
rt_flushifroutes_af(struct ifnet * ifp,int af)1154 rt_flushifroutes_af(struct ifnet *ifp, int af)
1155 {
1156 	KASSERT((af >= 1 && af <= AF_MAX), ("%s: af %d not >= 1 and <= %d",
1157 	    __func__, af, AF_MAX));
1158 
1159 	rt_foreach_fib_walk_del(af, rt_ifdelroute, ifp);
1160 }
1161 
1162 void
rt_flushifroutes(struct ifnet * ifp)1163 rt_flushifroutes(struct ifnet *ifp)
1164 {
1165 
1166 	rt_foreach_fib_walk_del(AF_UNSPEC, rt_ifdelroute, ifp);
1167 }
1168 
1169 /*
1170  * Conditionally unlinks rtentry matching data inside @info from @rnh.
1171  * Returns unlinked, locked and referenced @rtentry on success,
1172  * Returns NULL and sets @perror to:
1173  * ESRCH - if prefix was not found,
1174  * EADDRINUSE - if trying to delete PINNED route without appropriate flag.
1175  * ENOENT - if supplied filter function returned 0 (not matched).
1176  */
1177 static struct rtentry *
rt_unlinkrte(struct rib_head * rnh,struct rt_addrinfo * info,int * perror)1178 rt_unlinkrte(struct rib_head *rnh, struct rt_addrinfo *info, int *perror)
1179 {
1180 	struct sockaddr *dst, *netmask;
1181 	struct rtentry *rt;
1182 	struct radix_node *rn;
1183 
1184 	dst = info->rti_info[RTAX_DST];
1185 	netmask = info->rti_info[RTAX_NETMASK];
1186 
1187 	rt = (struct rtentry *)rnh->rnh_lookup(dst, netmask, &rnh->head);
1188 	if (rt == NULL) {
1189 		*perror = ESRCH;
1190 		return (NULL);
1191 	}
1192 
1193 	if ((info->rti_flags & RTF_PINNED) == 0) {
1194 		/* Check if target route can be deleted */
1195 		if (rt->rt_flags & RTF_PINNED) {
1196 			*perror = EADDRINUSE;
1197 			return (NULL);
1198 		}
1199 	}
1200 
1201 	if (info->rti_filter != NULL) {
1202 		if (info->rti_filter(rt, info->rti_filterdata) == 0) {
1203 			/* Not matched */
1204 			*perror = ENOENT;
1205 			return (NULL);
1206 		}
1207 
1208 		/*
1209 		 * Filter function requested rte deletion.
1210 		 * Ease the caller work by filling in remaining info
1211 		 * from that particular entry.
1212 		 */
1213 		info->rti_info[RTAX_GATEWAY] = rt->rt_gateway;
1214 	}
1215 
1216 	/*
1217 	 * Remove the item from the tree and return it.
1218 	 * Complain if it is not there and do no more processing.
1219 	 */
1220 	*perror = ESRCH;
1221 #ifdef RADIX_MPATH
1222 	if (rt_mpath_capable(rnh))
1223 		rn = rt_mpath_unlink(rnh, info, rt, perror);
1224 	else
1225 #endif
1226 	rn = rnh->rnh_deladdr(dst, netmask, &rnh->head);
1227 	if (rn == NULL)
1228 		return (NULL);
1229 
1230 	if (rn->rn_flags & (RNF_ACTIVE | RNF_ROOT))
1231 		panic ("rtrequest delete");
1232 
1233 	rt = RNTORT(rn);
1234 	RT_LOCK(rt);
1235 	RT_ADDREF(rt);
1236 	rt->rt_flags &= ~RTF_UP;
1237 
1238 	*perror = 0;
1239 
1240 	return (rt);
1241 }
1242 
1243 static void
rt_notifydelete(struct rtentry * rt,struct rt_addrinfo * info)1244 rt_notifydelete(struct rtentry *rt, struct rt_addrinfo *info)
1245 {
1246 	struct ifaddr *ifa;
1247 
1248 	/*
1249 	 * give the protocol a chance to keep things in sync.
1250 	 */
1251 	ifa = rt->rt_ifa;
1252 	if (ifa != NULL && ifa->ifa_rtrequest != NULL)
1253 		ifa->ifa_rtrequest(RTM_DELETE, rt, info);
1254 
1255 	/*
1256 	 * One more rtentry floating around that is not
1257 	 * linked to the routing table. rttrash will be decremented
1258 	 * when RTFREE(rt) is eventually called.
1259 	 */
1260 	V_rttrash++;
1261 }
1262 
1263 
1264 /*
1265  * These (questionable) definitions of apparent local variables apply
1266  * to the next two functions.  XXXXXX!!!
1267  */
1268 #define	dst	info->rti_info[RTAX_DST]
1269 #define	gateway	info->rti_info[RTAX_GATEWAY]
1270 #define	netmask	info->rti_info[RTAX_NETMASK]
1271 #define	ifaaddr	info->rti_info[RTAX_IFA]
1272 #define	ifpaddr	info->rti_info[RTAX_IFP]
1273 #define	flags	info->rti_flags
1274 
1275 /*
1276  * Look up rt_addrinfo for a specific fib.  Note that if rti_ifa is defined,
1277  * it will be referenced so the caller must free it.
1278  */
1279 int
rt_getifa_fib(struct rt_addrinfo * info,u_int fibnum)1280 rt_getifa_fib(struct rt_addrinfo *info, u_int fibnum)
1281 {
1282 	struct ifaddr *ifa;
1283 	int needref, error;
1284 
1285 	/*
1286 	 * ifp may be specified by sockaddr_dl
1287 	 * when protocol address is ambiguous.
1288 	 */
1289 	error = 0;
1290 	needref = (info->rti_ifa == NULL);
1291 	NET_EPOCH_ENTER();
1292 	if (info->rti_ifp == NULL && ifpaddr != NULL &&
1293 	    ifpaddr->sa_family == AF_LINK &&
1294 	    (ifa = ifa_ifwithnet(ifpaddr, 0, fibnum)) != NULL) {
1295 		info->rti_ifp = ifa->ifa_ifp;
1296 	}
1297 	if (info->rti_ifa == NULL && ifaaddr != NULL)
1298 		info->rti_ifa = ifa_ifwithaddr(ifaaddr);
1299 	if (info->rti_ifa == NULL) {
1300 		struct sockaddr *sa;
1301 
1302 		sa = ifaaddr != NULL ? ifaaddr :
1303 		    (gateway != NULL ? gateway : dst);
1304 		if (sa != NULL && info->rti_ifp != NULL)
1305 			info->rti_ifa = ifaof_ifpforaddr(sa, info->rti_ifp);
1306 		else if (dst != NULL && gateway != NULL)
1307 			info->rti_ifa = ifa_ifwithroute(flags, dst, gateway,
1308 							fibnum);
1309 		else if (sa != NULL)
1310 			info->rti_ifa = ifa_ifwithroute(flags, sa, sa,
1311 							fibnum);
1312 	}
1313 	if (needref && info->rti_ifa != NULL) {
1314 		if (info->rti_ifp == NULL)
1315 			info->rti_ifp = info->rti_ifa->ifa_ifp;
1316 		ifa_ref(info->rti_ifa);
1317 	} else
1318 		error = ENETUNREACH;
1319 	NET_EPOCH_EXIT();
1320 	return (error);
1321 }
1322 
1323 static int
if_updatemtu_cb(struct radix_node * rn,void * arg)1324 if_updatemtu_cb(struct radix_node *rn, void *arg)
1325 {
1326 	struct rtentry *rt;
1327 	struct if_mtuinfo *ifmtu;
1328 
1329 	rt = (struct rtentry *)rn;
1330 	ifmtu = (struct if_mtuinfo *)arg;
1331 
1332 	if (rt->rt_ifp != ifmtu->ifp)
1333 		return (0);
1334 
1335 	if (rt->rt_mtu >= ifmtu->mtu) {
1336 		/* We have to decrease mtu regardless of flags */
1337 		rt->rt_mtu = ifmtu->mtu;
1338 		return (0);
1339 	}
1340 
1341 	/*
1342 	 * New MTU is bigger. Check if are allowed to alter it
1343 	 */
1344 	if ((rt->rt_flags & (RTF_FIXEDMTU | RTF_GATEWAY | RTF_HOST)) != 0) {
1345 
1346 		/*
1347 		 * Skip routes with user-supplied MTU and
1348 		 * non-interface routes
1349 		 */
1350 		return (0);
1351 	}
1352 
1353 	/* We are safe to update route MTU */
1354 	rt->rt_mtu = ifmtu->mtu;
1355 
1356 	return (0);
1357 }
1358 
1359 void
rt_updatemtu(struct ifnet * ifp)1360 rt_updatemtu(struct ifnet *ifp)
1361 {
1362 	struct if_mtuinfo ifmtu;
1363 	struct rib_head *rnh;
1364 	int i, j;
1365 
1366 	ifmtu.ifp = ifp;
1367 
1368 	/*
1369 	 * Try to update rt_mtu for all routes using this interface
1370 	 * Unfortunately the only way to do this is to traverse all
1371 	 * routing tables in all fibs/domains.
1372 	 */
1373 	for (i = 1; i <= AF_MAX; i++) {
1374 		ifmtu.mtu = if_getmtu_family(ifp, i);
1375 		for (j = 0; j < rt_numfibs; j++) {
1376 			rnh = rt_tables_get_rnh(j, i);
1377 			if (rnh == NULL)
1378 				continue;
1379 			RIB_WLOCK(rnh);
1380 			rnh->rnh_walktree(&rnh->head, if_updatemtu_cb, &ifmtu);
1381 			RIB_WUNLOCK(rnh);
1382 		}
1383 	}
1384 }
1385 
1386 
1387 #if 0
1388 int p_sockaddr(char *buf, int buflen, struct sockaddr *s);
1389 int rt_print(char *buf, int buflen, struct rtentry *rt);
1390 
1391 int
1392 p_sockaddr(char *buf, int buflen, struct sockaddr *s)
1393 {
1394 	void *paddr = NULL;
1395 
1396 	switch (s->sa_family) {
1397 	case AF_INET:
1398 		paddr = &((struct sockaddr_in *)s)->sin_addr;
1399 		break;
1400 	case AF_INET6:
1401 		paddr = &((struct sockaddr_in6 *)s)->sin6_addr;
1402 		break;
1403 	}
1404 
1405 	if (paddr == NULL)
1406 		return (0);
1407 
1408 	if (inet_ntop(s->sa_family, paddr, buf, buflen) == NULL)
1409 		return (0);
1410 
1411 	return (strlen(buf));
1412 }
1413 
1414 int
1415 rt_print(char *buf, int buflen, struct rtentry *rt)
1416 {
1417 	struct sockaddr *addr, *mask;
1418 	int i = 0;
1419 
1420 	addr = rt_key(rt);
1421 	mask = rt_mask(rt);
1422 
1423 	i = p_sockaddr(buf, buflen, addr);
1424 	if (!(rt->rt_flags & RTF_HOST)) {
1425 		buf[i++] = '/';
1426 		i += p_sockaddr(buf + i, buflen - i, mask);
1427 	}
1428 
1429 	if (rt->rt_flags & RTF_GATEWAY) {
1430 		buf[i++] = '>';
1431 		i += p_sockaddr(buf + i, buflen - i, rt->rt_gateway);
1432 	}
1433 
1434 	return (i);
1435 }
1436 #endif
1437 
1438 #ifdef RADIX_MPATH
1439 /*
1440  * Deletes key for single-path routes, unlinks rtentry with
1441  * gateway specified in @info from multi-path routes.
1442  *
1443  * Returnes unlinked entry. In case of failure, returns NULL
1444  * and sets @perror to ESRCH.
1445  */
1446 static struct radix_node *
rt_mpath_unlink(struct rib_head * rnh,struct rt_addrinfo * info,struct rtentry * rto,int * perror)1447 rt_mpath_unlink(struct rib_head *rnh, struct rt_addrinfo *info,
1448     struct rtentry *rto, int *perror)
1449 {
1450 	/*
1451 	 * if we got multipath routes, we require users to specify
1452 	 * a matching RTAX_GATEWAY.
1453 	 */
1454 	struct rtentry *rt; // *rto = NULL;
1455 	struct radix_node *rn;
1456 	struct sockaddr *gw;
1457 
1458 	gw = info->rti_info[RTAX_GATEWAY];
1459 	rt = rt_mpath_matchgate(rto, gw);
1460 	if (rt == NULL) {
1461 		*perror = ESRCH;
1462 		return (NULL);
1463 	}
1464 
1465 	/*
1466 	 * this is the first entry in the chain
1467 	 */
1468 	if (rto == rt) {
1469 		rn = rn_mpath_next((struct radix_node *)rt);
1470 		/*
1471 		 * there is another entry, now it's active
1472 		 */
1473 		if (rn) {
1474 			rto = RNTORT(rn);
1475 			RT_LOCK(rto);
1476 			rto->rt_flags |= RTF_UP;
1477 			RT_UNLOCK(rto);
1478 		} else if (rt->rt_flags & RTF_GATEWAY) {
1479 			/*
1480 			 * For gateway routes, we need to
1481 			 * make sure that we we are deleting
1482 			 * the correct gateway.
1483 			 * rt_mpath_matchgate() does not
1484 			 * check the case when there is only
1485 			 * one route in the chain.
1486 			 */
1487 			if (gw &&
1488 			    (rt->rt_gateway->sa_len != gw->sa_len ||
1489 				memcmp(rt->rt_gateway, gw, gw->sa_len))) {
1490 				*perror = ESRCH;
1491 				return (NULL);
1492 			}
1493 		}
1494 
1495 		/*
1496 		 * use the normal delete code to remove
1497 		 * the first entry
1498 		 */
1499 		rn = rnh->rnh_deladdr(dst, netmask, &rnh->head);
1500 		*perror = 0;
1501 		return (rn);
1502 	}
1503 
1504 	/*
1505 	 * if the entry is 2nd and on up
1506 	 */
1507 	if (rt_mpath_deldup(rto, rt) == 0)
1508 		panic ("rtrequest1: rt_mpath_deldup");
1509 	*perror = 0;
1510 	rn = (struct radix_node *)rt;
1511 	return (rn);
1512 }
1513 #endif
1514 
1515 int
rtrequest1_fib(int req,struct rt_addrinfo * info,struct rtentry ** ret_nrt,u_int fibnum)1516 rtrequest1_fib(int req, struct rt_addrinfo *info, struct rtentry **ret_nrt,
1517 				u_int fibnum)
1518 {
1519 	int error = 0;
1520 	struct rtentry *rt, *rt_old;
1521 	struct radix_node *rn;
1522 	struct rib_head *rnh;
1523 	struct ifaddr *ifa;
1524 	struct sockaddr *ndst;
1525 	struct sockaddr_storage mdst;
1526 
1527 	KASSERT((fibnum < rt_numfibs), ("rtrequest1_fib: bad fibnum"));
1528 	KASSERT((flags & RTF_RNH_LOCKED) == 0, ("rtrequest1_fib: locked"));
1529 	switch (dst->sa_family) {
1530 	case AF_INET6:
1531 	case AF_INET:
1532 		/* We support multiple FIBs. */
1533 		break;
1534 	default:
1535 		fibnum = RT_DEFAULT_FIB;
1536 		break;
1537 	}
1538 
1539 	/*
1540 	 * Find the correct routing tree to use for this Address Family
1541 	 */
1542 	rnh = rt_tables_get_rnh(fibnum, dst->sa_family);
1543 	if (rnh == NULL)
1544 		return (EAFNOSUPPORT);
1545 
1546 	/*
1547 	 * If we are adding a host route then we don't want to put
1548 	 * a netmask in the tree, nor do we want to clone it.
1549 	 */
1550 	if (flags & RTF_HOST)
1551 		netmask = NULL;
1552 
1553 	switch (req) {
1554 	case RTM_DELETE:
1555 		if (netmask) {
1556 			if (dst->sa_len > sizeof(mdst))
1557 				return (EINVAL);
1558 			rt_maskedcopy(dst, (struct sockaddr *)&mdst, netmask);
1559 			dst = (struct sockaddr *)&mdst;
1560 		}
1561 
1562 		RIB_WLOCK(rnh);
1563 		rt = rt_unlinkrte(rnh, info, &error);
1564 		RIB_WUNLOCK(rnh);
1565 		if (error != 0)
1566 			return (error);
1567 
1568 		rt_notifydelete(rt, info);
1569 
1570 		/*
1571 		 * If the caller wants it, then it can have it,
1572 		 * but it's up to it to free the rtentry as we won't be
1573 		 * doing it.
1574 		 */
1575 		if (ret_nrt) {
1576 			*ret_nrt = rt;
1577 			RT_UNLOCK(rt);
1578 		} else
1579 			RTFREE_LOCKED(rt);
1580 		break;
1581 	case RTM_RESOLVE:
1582 		/*
1583 		 * resolve was only used for route cloning
1584 		 * here for compat
1585 		 */
1586 		break;
1587 	case RTM_ADD:
1588 		if ((flags & RTF_GATEWAY) && !gateway)
1589 			return (EINVAL);
1590 		if (dst && gateway && (dst->sa_family != gateway->sa_family) &&
1591 		    (gateway->sa_family != AF_UNSPEC) && (gateway->sa_family != AF_LINK))
1592 			return (EINVAL);
1593 
1594 		if (info->rti_ifa == NULL) {
1595 			error = rt_getifa_fib(info, fibnum);
1596 			if (error)
1597 				return (error);
1598 		}
1599 		rt = uma_zalloc(V_rtzone, M_NOWAIT);
1600 		if (rt == NULL) {
1601 			return (ENOBUFS);
1602 		}
1603 		rt->rt_flags = RTF_UP | flags;
1604 		rt->rt_fibnum = fibnum;
1605 		/*
1606 		 * Add the gateway. Possibly re-malloc-ing the storage for it.
1607 		 */
1608 		if ((error = rt_setgate(rt, dst, gateway)) != 0) {
1609 			uma_zfree(V_rtzone, rt);
1610 			return (error);
1611 		}
1612 
1613 		/*
1614 		 * point to the (possibly newly malloc'd) dest address.
1615 		 */
1616 		ndst = (struct sockaddr *)rt_key(rt);
1617 
1618 		/*
1619 		 * make sure it contains the value we want (masked if needed).
1620 		 */
1621 		if (netmask) {
1622 			rt_maskedcopy(dst, ndst, netmask);
1623 		} else
1624 			bcopy(dst, ndst, dst->sa_len);
1625 
1626 		/*
1627 		 * We use the ifa reference returned by rt_getifa_fib().
1628 		 * This moved from below so that rnh->rnh_addaddr() can
1629 		 * examine the ifa and  ifa->ifa_ifp if it so desires.
1630 		 */
1631 		ifa = info->rti_ifa;
1632 		ifa_ref(ifa);
1633 		rt->rt_ifa = ifa;
1634 		rt->rt_ifp = ifa->ifa_ifp;
1635 		rt->rt_weight = 1;
1636 
1637 		rt_setmetrics(info, rt);
1638 
1639 		RIB_WLOCK(rnh);
1640 		RT_LOCK(rt);
1641 #ifdef RADIX_MPATH
1642 		/* do not permit exactly the same dst/mask/gw pair */
1643 		if (rt_mpath_capable(rnh) &&
1644 			rt_mpath_conflict(rnh, rt, netmask)) {
1645 			RIB_WUNLOCK(rnh);
1646 
1647 			ifa_free(rt->rt_ifa);
1648 			R_Free(rt_key(rt));
1649 			uma_zfree(V_rtzone, rt);
1650 			return (EEXIST);
1651 		}
1652 #endif
1653 
1654 		/* XXX mtu manipulation will be done in rnh_addaddr -- itojun */
1655 		rn = rnh->rnh_addaddr(ndst, netmask, &rnh->head, rt->rt_nodes);
1656 
1657 		rt_old = NULL;
1658 		if (rn == NULL && (info->rti_flags & RTF_PINNED) != 0) {
1659 
1660 			/*
1661 			 * Force removal and re-try addition
1662 			 * TODO: better multipath&pinned support
1663 			 */
1664 			struct sockaddr *info_dst = info->rti_info[RTAX_DST];
1665 			info->rti_info[RTAX_DST] = ndst;
1666 			/* Do not delete existing PINNED(interface) routes */
1667 			info->rti_flags &= ~RTF_PINNED;
1668 			rt_old = rt_unlinkrte(rnh, info, &error);
1669 			info->rti_flags |= RTF_PINNED;
1670 			info->rti_info[RTAX_DST] = info_dst;
1671 			if (rt_old != NULL)
1672 				rn = rnh->rnh_addaddr(ndst, netmask, &rnh->head,
1673 				    rt->rt_nodes);
1674 		}
1675 		RIB_WUNLOCK(rnh);
1676 
1677 		if (rt_old != NULL)
1678 			RT_UNLOCK(rt_old);
1679 
1680 		/*
1681 		 * If it still failed to go into the tree,
1682 		 * then un-make it (this should be a function)
1683 		 */
1684 		if (rn == NULL) {
1685 			ifa_free(rt->rt_ifa);
1686 			R_Free(rt_key(rt));
1687 			uma_zfree(V_rtzone, rt);
1688 			return (EEXIST);
1689 		}
1690 
1691 		if (rt_old != NULL) {
1692 			rt_notifydelete(rt_old, info);
1693 			RTFREE(rt_old);
1694 		}
1695 
1696 		/*
1697 		 * If this protocol has something to add to this then
1698 		 * allow it to do that as well.
1699 		 */
1700 		if (ifa->ifa_rtrequest)
1701 			ifa->ifa_rtrequest(req, rt, info);
1702 
1703 		/*
1704 		 * actually return a resultant rtentry and
1705 		 * give the caller a single reference.
1706 		 */
1707 		if (ret_nrt) {
1708 			*ret_nrt = rt;
1709 			RT_ADDREF(rt);
1710 		}
1711 		rnh->rnh_gen++;		/* Routing table updated */
1712 		RT_UNLOCK(rt);
1713 		break;
1714 	case RTM_CHANGE:
1715 		RIB_WLOCK(rnh);
1716 		error = rtrequest1_fib_change(rnh, info, ret_nrt, fibnum);
1717 		RIB_WUNLOCK(rnh);
1718 		break;
1719 	default:
1720 		error = EOPNOTSUPP;
1721 	}
1722 
1723 	return (error);
1724 }
1725 
1726 #undef dst
1727 #undef gateway
1728 #undef netmask
1729 #undef ifaaddr
1730 #undef ifpaddr
1731 #undef flags
1732 
1733 static int
rtrequest1_fib_change(struct rib_head * rnh,struct rt_addrinfo * info,struct rtentry ** ret_nrt,u_int fibnum)1734 rtrequest1_fib_change(struct rib_head *rnh, struct rt_addrinfo *info,
1735     struct rtentry **ret_nrt, u_int fibnum)
1736 {
1737 	struct rtentry *rt = NULL;
1738 	int error = 0;
1739 	int free_ifa = 0;
1740 	int family, mtu;
1741 	struct if_mtuinfo ifmtu;
1742 
1743 	RIB_WLOCK_ASSERT(rnh);
1744 
1745 	rt = (struct rtentry *)rnh->rnh_lookup(info->rti_info[RTAX_DST],
1746 	    info->rti_info[RTAX_NETMASK], &rnh->head);
1747 
1748 	if (rt == NULL)
1749 		return (ESRCH);
1750 
1751 #ifdef RADIX_MPATH
1752 	/*
1753 	 * If we got multipath routes,
1754 	 * we require users to specify a matching RTAX_GATEWAY.
1755 	 */
1756 	if (rt_mpath_capable(rnh)) {
1757 		rt = rt_mpath_matchgate(rt, info->rti_info[RTAX_GATEWAY]);
1758 		if (rt == NULL)
1759 			return (ESRCH);
1760 	}
1761 #endif
1762 
1763 	RT_LOCK(rt);
1764 
1765 	rt_setmetrics(info, rt);
1766 
1767 	/*
1768 	 * New gateway could require new ifaddr, ifp;
1769 	 * flags may also be different; ifp may be specified
1770 	 * by ll sockaddr when protocol address is ambiguous
1771 	 */
1772 	if (((rt->rt_flags & RTF_GATEWAY) &&
1773 	    info->rti_info[RTAX_GATEWAY] != NULL) ||
1774 	    info->rti_info[RTAX_IFP] != NULL ||
1775 	    (info->rti_info[RTAX_IFA] != NULL &&
1776 	     !sa_equal(info->rti_info[RTAX_IFA], rt->rt_ifa->ifa_addr))) {
1777 		/*
1778 		 * XXX: Temporarily set RTF_RNH_LOCKED flag in the rti_flags
1779 		 *	to avoid rlock in the ifa_ifwithroute().
1780 		 */
1781 		info->rti_flags |= RTF_RNH_LOCKED;
1782 		error = rt_getifa_fib(info, fibnum);
1783 		info->rti_flags &= ~RTF_RNH_LOCKED;
1784 		if (info->rti_ifa != NULL)
1785 			free_ifa = 1;
1786 
1787 		if (error != 0)
1788 			goto bad;
1789 	}
1790 
1791 	/* Check if outgoing interface has changed */
1792 	if (info->rti_ifa != NULL && info->rti_ifa != rt->rt_ifa &&
1793 	    rt->rt_ifa != NULL) {
1794 		if (rt->rt_ifa->ifa_rtrequest != NULL)
1795 			rt->rt_ifa->ifa_rtrequest(RTM_DELETE, rt, info);
1796 		ifa_free(rt->rt_ifa);
1797 		rt->rt_ifa = NULL;
1798 	}
1799 	/* Update gateway address */
1800 	if (info->rti_info[RTAX_GATEWAY] != NULL) {
1801 		error = rt_setgate(rt, rt_key(rt), info->rti_info[RTAX_GATEWAY]);
1802 		if (error != 0)
1803 			goto bad;
1804 
1805 		rt->rt_flags &= ~RTF_GATEWAY;
1806 		rt->rt_flags |= (RTF_GATEWAY & info->rti_flags);
1807 	}
1808 
1809 	if (info->rti_ifa != NULL && info->rti_ifa != rt->rt_ifa) {
1810 		ifa_ref(info->rti_ifa);
1811 		rt->rt_ifa = info->rti_ifa;
1812 		rt->rt_ifp = info->rti_ifp;
1813 	}
1814 	/* Allow some flags to be toggled on change. */
1815 	rt->rt_flags &= ~RTF_FMASK;
1816 	rt->rt_flags |= info->rti_flags & RTF_FMASK;
1817 
1818 	if (rt->rt_ifa && rt->rt_ifa->ifa_rtrequest != NULL)
1819 	       rt->rt_ifa->ifa_rtrequest(RTM_ADD, rt, info);
1820 
1821 	/* Alter route MTU if necessary */
1822 	if (rt->rt_ifp != NULL) {
1823 		family = info->rti_info[RTAX_DST]->sa_family;
1824 		mtu = if_getmtu_family(rt->rt_ifp, family);
1825 		/* Set default MTU */
1826 		if (rt->rt_mtu == 0)
1827 			rt->rt_mtu = mtu;
1828 		if (rt->rt_mtu != mtu) {
1829 			/* Check if we really need to update */
1830 			ifmtu.ifp = rt->rt_ifp;
1831 			ifmtu.mtu = mtu;
1832 			if_updatemtu_cb(rt->rt_nodes, &ifmtu);
1833 		}
1834 	}
1835 
1836 	/*
1837 	 * This route change may have modified the route's gateway.  In that
1838 	 * case, any inpcbs that have cached this route need to invalidate their
1839 	 * llentry cache.
1840 	 */
1841 	rnh->rnh_gen++;
1842 
1843 	if (ret_nrt) {
1844 		*ret_nrt = rt;
1845 		RT_ADDREF(rt);
1846 	}
1847 bad:
1848 	RT_UNLOCK(rt);
1849 	if (free_ifa != 0) {
1850 		ifa_free(info->rti_ifa);
1851 		info->rti_ifa = NULL;
1852 	}
1853 	return (error);
1854 }
1855 
1856 static void
rt_setmetrics(const struct rt_addrinfo * info,struct rtentry * rt)1857 rt_setmetrics(const struct rt_addrinfo *info, struct rtentry *rt)
1858 {
1859 
1860 	if (info->rti_mflags & RTV_MTU) {
1861 		if (info->rti_rmx->rmx_mtu != 0) {
1862 
1863 			/*
1864 			 * MTU was explicitly provided by user.
1865 			 * Keep it.
1866 			 */
1867 			rt->rt_flags |= RTF_FIXEDMTU;
1868 		} else {
1869 
1870 			/*
1871 			 * User explicitly sets MTU to 0.
1872 			 * Assume rollback to default.
1873 			 */
1874 			rt->rt_flags &= ~RTF_FIXEDMTU;
1875 		}
1876 		rt->rt_mtu = info->rti_rmx->rmx_mtu;
1877 	}
1878 	if (info->rti_mflags & RTV_WEIGHT)
1879 		rt->rt_weight = info->rti_rmx->rmx_weight;
1880 	/* Kernel -> userland timebase conversion. */
1881 	if (info->rti_mflags & RTV_EXPIRE)
1882 		rt->rt_expire = info->rti_rmx->rmx_expire ?
1883 		    info->rti_rmx->rmx_expire - time_second + time_uptime : 0;
1884 }
1885 
1886 int
rt_setgate(struct rtentry * rt,struct sockaddr * dst,struct sockaddr * gate)1887 rt_setgate(struct rtentry *rt, struct sockaddr *dst, struct sockaddr *gate)
1888 {
1889 	/* XXX dst may be overwritten, can we move this to below */
1890 	int dlen = SA_SIZE(dst), glen = SA_SIZE(gate);
1891 
1892 	/*
1893 	 * Prepare to store the gateway in rt->rt_gateway.
1894 	 * Both dst and gateway are stored one after the other in the same
1895 	 * malloc'd chunk. If we have room, we can reuse the old buffer,
1896 	 * rt_gateway already points to the right place.
1897 	 * Otherwise, malloc a new block and update the 'dst' address.
1898 	 */
1899 	if (rt->rt_gateway == NULL || glen > SA_SIZE(rt->rt_gateway)) {
1900 		caddr_t new;
1901 
1902 		R_Malloc(new, caddr_t, dlen + glen);
1903 		if (new == NULL)
1904 			return ENOBUFS;
1905 		/*
1906 		 * XXX note, we copy from *dst and not *rt_key(rt) because
1907 		 * rt_setgate() can be called to initialize a newly
1908 		 * allocated route entry, in which case rt_key(rt) == NULL
1909 		 * (and also rt->rt_gateway == NULL).
1910 		 * Free()/free() handle a NULL argument just fine.
1911 		 */
1912 		bcopy(dst, new, dlen);
1913 		R_Free(rt_key(rt));	/* free old block, if any */
1914 		rt_key(rt) = (struct sockaddr *)new;
1915 		rt->rt_gateway = (struct sockaddr *)(new + dlen);
1916 	}
1917 
1918 	/*
1919 	 * Copy the new gateway value into the memory chunk.
1920 	 */
1921 	bcopy(gate, rt->rt_gateway, glen);
1922 
1923 	return (0);
1924 }
1925 
1926 void
rt_maskedcopy(struct sockaddr * src,struct sockaddr * dst,struct sockaddr * netmask)1927 rt_maskedcopy(struct sockaddr *src, struct sockaddr *dst, struct sockaddr *netmask)
1928 {
1929 	u_char *cp1 = (u_char *)src;
1930 	u_char *cp2 = (u_char *)dst;
1931 	u_char *cp3 = (u_char *)netmask;
1932 	u_char *cplim = cp2 + *cp3;
1933 	u_char *cplim2 = cp2 + *cp1;
1934 
1935 	*cp2++ = *cp1++; *cp2++ = *cp1++; /* copies sa_len & sa_family */
1936 	cp3 += 2;
1937 	if (cplim > cplim2)
1938 		cplim = cplim2;
1939 	while (cp2 < cplim)
1940 		*cp2++ = *cp1++ & *cp3++;
1941 	if (cp2 < cplim2)
1942 		bzero((caddr_t)cp2, (unsigned)(cplim2 - cp2));
1943 }
1944 
1945 /*
1946  * Set up a routing table entry, normally
1947  * for an interface.
1948  */
1949 #define _SOCKADDR_TMPSIZE 128 /* Not too big.. kernel stack size is limited */
1950 static inline  int
rtinit1(struct ifaddr * ifa,int cmd,int flags,int fibnum)1951 rtinit1(struct ifaddr *ifa, int cmd, int flags, int fibnum)
1952 {
1953 	RIB_RLOCK_TRACKER;
1954 	struct sockaddr *dst;
1955 	struct sockaddr *netmask;
1956 	struct rtentry *rt = NULL;
1957 	struct rt_addrinfo info;
1958 	int error = 0;
1959 	int startfib, endfib;
1960 	char tempbuf[_SOCKADDR_TMPSIZE];
1961 	int didwork = 0;
1962 	int a_failure = 0;
1963 	static struct sockaddr_dl null_sdl = {sizeof(null_sdl), AF_LINK};
1964 	struct rib_head *rnh;
1965 
1966 	if (flags & RTF_HOST) {
1967 		dst = ifa->ifa_dstaddr;
1968 		netmask = NULL;
1969 	} else {
1970 		dst = ifa->ifa_addr;
1971 		netmask = ifa->ifa_netmask;
1972 	}
1973 	if (dst->sa_len == 0)
1974 		return(EINVAL);
1975 	switch (dst->sa_family) {
1976 	case AF_INET6:
1977 	case AF_INET:
1978 		/* We support multiple FIBs. */
1979 		break;
1980 	default:
1981 		fibnum = RT_DEFAULT_FIB;
1982 		break;
1983 	}
1984 	if (fibnum == RT_ALL_FIBS) {
1985 		if (V_rt_add_addr_allfibs == 0 && cmd == (int)RTM_ADD)
1986 			startfib = endfib = ifa->ifa_ifp->if_fib;
1987 		else {
1988 			startfib = 0;
1989 			endfib = rt_numfibs - 1;
1990 		}
1991 	} else {
1992 		KASSERT((fibnum < rt_numfibs), ("rtinit1: bad fibnum"));
1993 		startfib = fibnum;
1994 		endfib = fibnum;
1995 	}
1996 
1997 	/*
1998 	 * If it's a delete, check that if it exists,
1999 	 * it's on the correct interface or we might scrub
2000 	 * a route to another ifa which would
2001 	 * be confusing at best and possibly worse.
2002 	 */
2003 	if (cmd == RTM_DELETE) {
2004 		/*
2005 		 * It's a delete, so it should already exist..
2006 		 * If it's a net, mask off the host bits
2007 		 * (Assuming we have a mask)
2008 		 * XXX this is kinda inet specific..
2009 		 */
2010 		if (netmask != NULL) {
2011 			rt_maskedcopy(dst, (struct sockaddr *)tempbuf, netmask);
2012 			dst = (struct sockaddr *)tempbuf;
2013 		}
2014 	}
2015 	/*
2016 	 * Now go through all the requested tables (fibs) and do the
2017 	 * requested action. Realistically, this will either be fib 0
2018 	 * for protocols that don't do multiple tables or all the
2019 	 * tables for those that do.
2020 	 */
2021 	for ( fibnum = startfib; fibnum <= endfib; fibnum++) {
2022 		if (cmd == RTM_DELETE) {
2023 			struct radix_node *rn;
2024 			/*
2025 			 * Look up an rtentry that is in the routing tree and
2026 			 * contains the correct info.
2027 			 */
2028 			rnh = rt_tables_get_rnh(fibnum, dst->sa_family);
2029 			if (rnh == NULL)
2030 				/* this table doesn't exist but others might */
2031 				continue;
2032 			RIB_RLOCK(rnh);
2033 			rn = rnh->rnh_lookup(dst, netmask, &rnh->head);
2034 #ifdef RADIX_MPATH
2035 			if (rt_mpath_capable(rnh)) {
2036 
2037 				if (rn == NULL)
2038 					error = ESRCH;
2039 				else {
2040 					rt = RNTORT(rn);
2041 					/*
2042 					 * for interface route the
2043 					 * rt->rt_gateway is sockaddr_intf
2044 					 * for cloning ARP entries, so
2045 					 * rt_mpath_matchgate must use the
2046 					 * interface address
2047 					 */
2048 					rt = rt_mpath_matchgate(rt,
2049 					    ifa->ifa_addr);
2050 					if (rt == NULL)
2051 						error = ESRCH;
2052 				}
2053 			}
2054 #endif
2055 			error = (rn == NULL ||
2056 			    (rn->rn_flags & RNF_ROOT) ||
2057 			    RNTORT(rn)->rt_ifa != ifa);
2058 			RIB_RUNLOCK(rnh);
2059 			if (error) {
2060 				/* this is only an error if bad on ALL tables */
2061 				continue;
2062 			}
2063 		}
2064 		/*
2065 		 * Do the actual request
2066 		 */
2067 		bzero((caddr_t)&info, sizeof(info));
2068 		ifa_ref(ifa);
2069 		info.rti_ifa = ifa;
2070 		info.rti_flags = flags |
2071 		    (ifa->ifa_flags & ~IFA_RTSELF) | RTF_PINNED;
2072 		info.rti_info[RTAX_DST] = dst;
2073 		/*
2074 		 * doing this for compatibility reasons
2075 		 */
2076 		if (cmd == RTM_ADD)
2077 			info.rti_info[RTAX_GATEWAY] =
2078 			    (struct sockaddr *)&null_sdl;
2079 		else
2080 			info.rti_info[RTAX_GATEWAY] = ifa->ifa_addr;
2081 		info.rti_info[RTAX_NETMASK] = netmask;
2082 		error = rtrequest1_fib(cmd, &info, &rt, fibnum);
2083 
2084 		if (error == 0 && rt != NULL) {
2085 			/*
2086 			 * notify any listening routing agents of the change
2087 			 */
2088 			RT_LOCK(rt);
2089 #ifdef RADIX_MPATH
2090 			/*
2091 			 * in case address alias finds the first address
2092 			 * e.g. ifconfig bge0 192.0.2.246/24
2093 			 * e.g. ifconfig bge0 192.0.2.247/24
2094 			 * the address set in the route is 192.0.2.246
2095 			 * so we need to replace it with 192.0.2.247
2096 			 */
2097 			if (memcmp(rt->rt_ifa->ifa_addr,
2098 			    ifa->ifa_addr, ifa->ifa_addr->sa_len)) {
2099 				ifa_free(rt->rt_ifa);
2100 				ifa_ref(ifa);
2101 				rt->rt_ifp = ifa->ifa_ifp;
2102 				rt->rt_ifa = ifa;
2103 			}
2104 #endif
2105 			/*
2106 			 * doing this for compatibility reasons
2107 			 */
2108 			if (cmd == RTM_ADD) {
2109 			    ((struct sockaddr_dl *)rt->rt_gateway)->sdl_type  =
2110 				rt->rt_ifp->if_type;
2111 			    ((struct sockaddr_dl *)rt->rt_gateway)->sdl_index =
2112 				rt->rt_ifp->if_index;
2113 			}
2114 			RT_ADDREF(rt);
2115 			RT_UNLOCK(rt);
2116 			rt_newaddrmsg_fib(cmd, ifa, error, rt, fibnum);
2117 			RT_LOCK(rt);
2118 			RT_REMREF(rt);
2119 			if (cmd == RTM_DELETE) {
2120 				/*
2121 				 * If we are deleting, and we found an entry,
2122 				 * then it's been removed from the tree..
2123 				 * now throw it away.
2124 				 */
2125 				RTFREE_LOCKED(rt);
2126 			} else {
2127 				if (cmd == RTM_ADD) {
2128 					/*
2129 					 * We just wanted to add it..
2130 					 * we don't actually need a reference.
2131 					 */
2132 					RT_REMREF(rt);
2133 				}
2134 				RT_UNLOCK(rt);
2135 			}
2136 			didwork = 1;
2137 		}
2138 		if (error)
2139 			a_failure = error;
2140 	}
2141 	if (cmd == RTM_DELETE) {
2142 		if (didwork) {
2143 			error = 0;
2144 		} else {
2145 			/* we only give an error if it wasn't in any table */
2146 			error = ((flags & RTF_HOST) ?
2147 			    EHOSTUNREACH : ENETUNREACH);
2148 		}
2149 	} else {
2150 		if (a_failure) {
2151 			/* return an error if any of them failed */
2152 			error = a_failure;
2153 		}
2154 	}
2155 	return (error);
2156 }
2157 
2158 /*
2159  * Set up a routing table entry, normally
2160  * for an interface.
2161  */
2162 int
rtinit(struct ifaddr * ifa,int cmd,int flags)2163 rtinit(struct ifaddr *ifa, int cmd, int flags)
2164 {
2165 	struct sockaddr *dst;
2166 	int fib = RT_DEFAULT_FIB;
2167 
2168 	if (flags & RTF_HOST) {
2169 		dst = ifa->ifa_dstaddr;
2170 	} else {
2171 		dst = ifa->ifa_addr;
2172 	}
2173 
2174 	switch (dst->sa_family) {
2175 	case AF_INET6:
2176 	case AF_INET:
2177 		/* We do support multiple FIBs. */
2178 		fib = RT_ALL_FIBS;
2179 		break;
2180 	}
2181 	return (rtinit1(ifa, cmd, flags, fib));
2182 }
2183 
2184 /*
2185  * Announce interface address arrival/withdraw
2186  * Returns 0 on success.
2187  */
2188 int
rt_addrmsg(int cmd,struct ifaddr * ifa,int fibnum)2189 rt_addrmsg(int cmd, struct ifaddr *ifa, int fibnum)
2190 {
2191 
2192 	KASSERT(cmd == RTM_ADD || cmd == RTM_DELETE,
2193 	    ("unexpected cmd %d", cmd));
2194 
2195 	KASSERT(fibnum == RT_ALL_FIBS || (fibnum >= 0 && fibnum < rt_numfibs),
2196 	    ("%s: fib out of range 0 <=%d<%d", __func__, fibnum, rt_numfibs));
2197 
2198 #if defined(INET) || defined(INET6)
2199 #ifdef SCTP
2200 	/*
2201 	 * notify the SCTP stack
2202 	 * this will only get called when an address is added/deleted
2203 	 * XXX pass the ifaddr struct instead if ifa->ifa_addr...
2204 	 */
2205 	sctp_addr_change(ifa, cmd);
2206 #endif /* SCTP */
2207 #endif
2208 	return (rtsock_addrmsg(cmd, ifa, fibnum));
2209 }
2210 
2211 /*
2212  * Announce route addition/removal.
2213  * Users of this function MUST validate input data BEFORE calling.
2214  * However we have to be able to handle invalid data:
2215  * if some userland app sends us "invalid" route message (invalid mask,
2216  * no dst, wrong address families, etc...) we need to pass it back
2217  * to app (and any other rtsock consumers) with rtm_errno field set to
2218  * non-zero value.
2219  * Returns 0 on success.
2220  */
2221 int
rt_routemsg(int cmd,struct ifnet * ifp,int error,struct rtentry * rt,int fibnum)2222 rt_routemsg(int cmd, struct ifnet *ifp, int error, struct rtentry *rt,
2223     int fibnum)
2224 {
2225 
2226 	KASSERT(cmd == RTM_ADD || cmd == RTM_DELETE,
2227 	    ("unexpected cmd %d", cmd));
2228 
2229 	KASSERT(fibnum == RT_ALL_FIBS || (fibnum >= 0 && fibnum < rt_numfibs),
2230 	    ("%s: fib out of range 0 <=%d<%d", __func__, fibnum, rt_numfibs));
2231 
2232 	KASSERT(rt_key(rt) != NULL, (":%s: rt_key must be supplied", __func__));
2233 
2234 	return (rtsock_routemsg(cmd, ifp, error, rt, fibnum));
2235 }
2236 
2237 void
rt_newaddrmsg(int cmd,struct ifaddr * ifa,int error,struct rtentry * rt)2238 rt_newaddrmsg(int cmd, struct ifaddr *ifa, int error, struct rtentry *rt)
2239 {
2240 
2241 	rt_newaddrmsg_fib(cmd, ifa, error, rt, RT_ALL_FIBS);
2242 }
2243 
2244 /*
2245  * This is called to generate messages from the routing socket
2246  * indicating a network interface has had addresses associated with it.
2247  */
2248 void
rt_newaddrmsg_fib(int cmd,struct ifaddr * ifa,int error,struct rtentry * rt,int fibnum)2249 rt_newaddrmsg_fib(int cmd, struct ifaddr *ifa, int error, struct rtentry *rt,
2250     int fibnum)
2251 {
2252 
2253 	KASSERT(cmd == RTM_ADD || cmd == RTM_DELETE,
2254 		("unexpected cmd %u", cmd));
2255 	KASSERT(fibnum == RT_ALL_FIBS || (fibnum >= 0 && fibnum < rt_numfibs),
2256 	    ("%s: fib out of range 0 <=%d<%d", __func__, fibnum, rt_numfibs));
2257 
2258 	if (cmd == RTM_ADD) {
2259 		rt_addrmsg(cmd, ifa, fibnum);
2260 		if (rt != NULL)
2261 			rt_routemsg(cmd, ifa->ifa_ifp, error, rt, fibnum);
2262 	} else {
2263 		if (rt != NULL)
2264 			rt_routemsg(cmd, ifa->ifa_ifp, error, rt, fibnum);
2265 		rt_addrmsg(cmd, ifa, fibnum);
2266 	}
2267 }
2268 
2269