xref: /freebsd/sys/net/route.c (revision f9218d3d4fd34f082473b3a021c6d4d109fb47cf)
1 /*
2  * Copyright (c) 1980, 1986, 1991, 1993
3  *	The Regents of the University of California.  All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  * 3. All advertising materials mentioning features or use of this software
14  *    must display the following acknowledgement:
15  *	This product includes software developed by the University of
16  *	California, Berkeley and its contributors.
17  * 4. Neither the name of the University nor the names of its contributors
18  *    may be used to endorse or promote products derived from this software
19  *    without specific prior written permission.
20  *
21  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
22  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
25  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31  * SUCH DAMAGE.
32  *
33  *	@(#)route.c	8.3.1.1 (Berkeley) 2/23/95
34  * $FreeBSD$
35  */
36 
37 #include "opt_inet.h"
38 #include "opt_mrouting.h"
39 
40 #include <sys/param.h>
41 #include <sys/systm.h>
42 #include <sys/malloc.h>
43 #include <sys/mbuf.h>
44 #include <sys/socket.h>
45 #include <sys/domain.h>
46 #include <sys/kernel.h>
47 
48 #include <net/if.h>
49 #include <net/route.h>
50 
51 #include <netinet/in.h>
52 #include <netinet/ip_mroute.h>
53 
54 #define	SA(p) ((struct sockaddr *)(p))
55 
56 struct route_cb route_cb;
57 static struct rtstat rtstat;
58 struct radix_node_head *rt_tables[AF_MAX+1];
59 
60 static int	rttrash;		/* routes not in table but not freed */
61 
62 static void rt_maskedcopy(struct sockaddr *,
63 	    struct sockaddr *, struct sockaddr *);
64 static void rtable_init(void **);
65 
66 static void
67 rtable_init(table)
68 	void **table;
69 {
70 	struct domain *dom;
71 	for (dom = domains; dom; dom = dom->dom_next)
72 		if (dom->dom_rtattach)
73 			dom->dom_rtattach(&table[dom->dom_family],
74 			    dom->dom_rtoffset);
75 }
76 
77 void
78 route_init()
79 {
80 	rn_init();	/* initialize all zeroes, all ones, mask table */
81 	rtable_init((void **)rt_tables);
82 }
83 
84 /*
85  * Packet routing routines.
86  */
87 void
88 rtalloc(ro)
89 	register struct route *ro;
90 {
91 	rtalloc_ign(ro, 0UL);
92 }
93 
94 void
95 rtalloc_ign(ro, ignore)
96 	register struct route *ro;
97 	u_long ignore;
98 {
99 	struct rtentry *rt;
100 	int s;
101 
102 	if ((rt = ro->ro_rt) != NULL) {
103 		if (rt->rt_ifp != NULL && rt->rt_flags & RTF_UP)
104 			return;
105 		/* XXX - We are probably always at splnet here already. */
106 		s = splnet();
107 		RTFREE(rt);
108 		ro->ro_rt = NULL;
109 		splx(s);
110 	}
111 	ro->ro_rt = rtalloc1(&ro->ro_dst, 1, ignore);
112 }
113 
114 /*
115  * Look up the route that matches the address given
116  * Or, at least try.. Create a cloned route if needed.
117  */
118 struct rtentry *
119 rtalloc1(dst, report, ignflags)
120 	register struct sockaddr *dst;
121 	int report;
122 	u_long ignflags;
123 {
124 	register struct radix_node_head *rnh = rt_tables[dst->sa_family];
125 	register struct rtentry *rt;
126 	register struct radix_node *rn;
127 	struct rtentry *newrt = 0;
128 	struct rt_addrinfo info;
129 	u_long nflags;
130 	int  s = splnet(), err = 0, msgtype = RTM_MISS;
131 
132 	/*
133 	 * Look up the address in the table for that Address Family
134 	 */
135 	if (rnh == NULL) {
136 		rtstat.rts_unreach++;
137 		goto miss2;
138 	}
139 	RADIX_NODE_HEAD_LOCK(rnh);
140 	if ((rn = rnh->rnh_matchaddr((caddr_t)dst, rnh)) &&
141 	    ((rn->rn_flags & RNF_ROOT) == 0)) {
142 		/*
143 		 * If we find it and it's not the root node, then
144 		 * get a refernce on the rtentry associated.
145 		 */
146 		newrt = rt = (struct rtentry *)rn;
147 		nflags = rt->rt_flags & ~ignflags;
148 		if (report && (nflags & (RTF_CLONING | RTF_PRCLONING))) {
149 			/*
150 			 * We are apparently adding (report = 0 in delete).
151 			 * If it requires that it be cloned, do so.
152 			 * (This implies it wasn't a HOST route.)
153 			 */
154 			err = rtrequest(RTM_RESOLVE, dst, SA(0),
155 					      SA(0), 0, &newrt);
156 			if (err) {
157 				/*
158 				 * If the cloning didn't succeed, maybe
159 				 * what we have will do. Return that.
160 				 */
161 				newrt = rt;
162 				rt->rt_refcnt++;
163 				goto miss;
164 			}
165 			if ((rt = newrt) && (rt->rt_flags & RTF_XRESOLVE)) {
166 				/*
167 				 * If the new route specifies it be
168 				 * externally resolved, then go do that.
169 				 */
170 				msgtype = RTM_RESOLVE;
171 				goto miss;
172 			}
173 			/* Inform listeners of the new route. */
174 			bzero(&info, sizeof(info));
175 			info.rti_info[RTAX_DST] = rt_key(rt);
176 			info.rti_info[RTAX_NETMASK] = rt_mask(rt);
177 			info.rti_info[RTAX_GATEWAY] = rt->rt_gateway;
178 			if (rt->rt_ifp != NULL) {
179 				info.rti_info[RTAX_IFP] =
180 				    TAILQ_FIRST(&rt->rt_ifp->if_addrhead)->ifa_addr;
181 				info.rti_info[RTAX_IFA] = rt->rt_ifa->ifa_addr;
182 			}
183 			rt_missmsg(RTM_ADD, &info, rt->rt_flags, 0);
184 		} else
185 			rt->rt_refcnt++;
186 		RADIX_NODE_HEAD_UNLOCK(rnh);
187 	} else {
188 		/*
189 		 * Either we hit the root or couldn't find any match,
190 		 * Which basically means
191 		 * "caint get there frm here"
192 		 */
193 		rtstat.rts_unreach++;
194 	miss:
195 		RADIX_NODE_HEAD_UNLOCK(rnh);
196 	miss2:	if (report) {
197 			/*
198 			 * If required, report the failure to the supervising
199 			 * Authorities.
200 			 * For a delete, this is not an error. (report == 0)
201 			 */
202 			bzero((caddr_t)&info, sizeof(info));
203 			info.rti_info[RTAX_DST] = dst;
204 			rt_missmsg(msgtype, &info, 0, err);
205 		}
206 	}
207 	splx(s);
208 	return (newrt);
209 }
210 
211 /*
212  * Remove a reference count from an rtentry.
213  * If the count gets low enough, take it out of the routing table
214  */
215 void
216 rtfree(rt)
217 	register struct rtentry *rt;
218 {
219 	/*
220 	 * find the tree for that address family
221 	 */
222 	struct radix_node_head *rnh = rt_tables[rt_key(rt)->sa_family];
223 
224 	if (rt == 0 || rnh == 0)
225 		panic("rtfree");
226 
227 	/*
228 	 * decrement the reference count by one and if it reaches 0,
229 	 * and there is a close function defined, call the close function
230 	 */
231 	rt->rt_refcnt--;
232 	if (rnh->rnh_close && rt->rt_refcnt == 0) {
233 		rnh->rnh_close((struct radix_node *)rt, rnh);
234 	}
235 
236 	/*
237 	 * If we are no longer "up" (and ref == 0)
238 	 * then we can free the resources associated
239 	 * with the route.
240 	 */
241 	if (rt->rt_refcnt <= 0 && (rt->rt_flags & RTF_UP) == 0) {
242 		if (rt->rt_nodes->rn_flags & (RNF_ACTIVE | RNF_ROOT))
243 			panic ("rtfree 2");
244 		/*
245 		 * the rtentry must have been removed from the routing table
246 		 * so it is represented in rttrash.. remove that now.
247 		 */
248 		rttrash--;
249 
250 #ifdef	DIAGNOSTIC
251 		if (rt->rt_refcnt < 0) {
252 			printf("rtfree: %p not freed (neg refs)\n", rt);
253 			return;
254 		}
255 #endif
256 
257 		/*
258 		 * release references on items we hold them on..
259 		 * e.g other routes and ifaddrs.
260 		 */
261 		if (rt->rt_ifa)
262 			IFAFREE(rt->rt_ifa);
263 		if (rt->rt_parent)
264 			RTFREE(rt->rt_parent);
265 
266 		/*
267 		 * The key is separatly alloc'd so free it (see rt_setgate()).
268 		 * This also frees the gateway, as they are always malloc'd
269 		 * together.
270 		 */
271 		Free(rt_key(rt));
272 
273 		/*
274 		 * and the rtentry itself of course
275 		 */
276 		Free(rt);
277 	}
278 }
279 
280 /* compare two sockaddr structures */
281 #define	sa_equal(a1, a2) (bcmp((a1), (a2), (a1)->sa_len) == 0)
282 
283 /*
284  * Force a routing table entry to the specified
285  * destination to go through the given gateway.
286  * Normally called as a result of a routing redirect
287  * message from the network layer.
288  *
289  * N.B.: must be called at splnet
290  *
291  */
292 void
293 rtredirect(dst, gateway, netmask, flags, src, rtp)
294 	struct sockaddr *dst, *gateway, *netmask, *src;
295 	int flags;
296 	struct rtentry **rtp;
297 {
298 	struct rtentry *rt;
299 	int error = 0;
300 	short *stat = 0;
301 	struct rt_addrinfo info;
302 	struct ifaddr *ifa;
303 
304 	/* verify the gateway is directly reachable */
305 	if ((ifa = ifa_ifwithnet(gateway)) == 0) {
306 		error = ENETUNREACH;
307 		goto out;
308 	}
309 	rt = rtalloc1(dst, 0, 0UL);
310 	/*
311 	 * If the redirect isn't from our current router for this dst,
312 	 * it's either old or wrong.  If it redirects us to ourselves,
313 	 * we have a routing loop, perhaps as a result of an interface
314 	 * going down recently.
315 	 */
316 	if (!(flags & RTF_DONE) && rt &&
317 	     (!sa_equal(src, rt->rt_gateway) || rt->rt_ifa != ifa))
318 		error = EINVAL;
319 	else if (ifa_ifwithaddr(gateway))
320 		error = EHOSTUNREACH;
321 	if (error)
322 		goto done;
323 	/*
324 	 * Create a new entry if we just got back a wildcard entry
325 	 * or the the lookup failed.  This is necessary for hosts
326 	 * which use routing redirects generated by smart gateways
327 	 * to dynamically build the routing tables.
328 	 */
329 	if ((rt == 0) || (rt_mask(rt) && rt_mask(rt)->sa_len < 2))
330 		goto create;
331 	/*
332 	 * Don't listen to the redirect if it's
333 	 * for a route to an interface.
334 	 */
335 	if (rt->rt_flags & RTF_GATEWAY) {
336 		if (((rt->rt_flags & RTF_HOST) == 0) && (flags & RTF_HOST)) {
337 			/*
338 			 * Changing from route to net => route to host.
339 			 * Create new route, rather than smashing route to net.
340 			 */
341 		create:
342 			if (rt)
343 				rtfree(rt);
344 			flags |=  RTF_GATEWAY | RTF_DYNAMIC;
345 			bzero((caddr_t)&info, sizeof(info));
346 			info.rti_info[RTAX_DST] = dst;
347 			info.rti_info[RTAX_GATEWAY] = gateway;
348 			info.rti_info[RTAX_NETMASK] = netmask;
349 			info.rti_ifa = ifa;
350 			info.rti_flags = flags;
351 			rt = NULL;
352 			error = rtrequest1(RTM_ADD, &info, &rt);
353 			if (rt != NULL)
354 				flags = rt->rt_flags;
355 			stat = &rtstat.rts_dynamic;
356 		} else {
357 			/*
358 			 * Smash the current notion of the gateway to
359 			 * this destination.  Should check about netmask!!!
360 			 */
361 			rt->rt_flags |= RTF_MODIFIED;
362 			flags |= RTF_MODIFIED;
363 			stat = &rtstat.rts_newgateway;
364 			/*
365 			 * add the key and gateway (in one malloc'd chunk).
366 			 */
367 			rt_setgate(rt, rt_key(rt), gateway);
368 		}
369 	} else
370 		error = EHOSTUNREACH;
371 done:
372 	if (rt) {
373 		if (rtp && !error)
374 			*rtp = rt;
375 		else
376 			rtfree(rt);
377 	}
378 out:
379 	if (error)
380 		rtstat.rts_badredirect++;
381 	else if (stat != NULL)
382 		(*stat)++;
383 	bzero((caddr_t)&info, sizeof(info));
384 	info.rti_info[RTAX_DST] = dst;
385 	info.rti_info[RTAX_GATEWAY] = gateway;
386 	info.rti_info[RTAX_NETMASK] = netmask;
387 	info.rti_info[RTAX_AUTHOR] = src;
388 	rt_missmsg(RTM_REDIRECT, &info, flags, error);
389 }
390 
391 /*
392  * Routing table ioctl interface.
393  */
394 int
395 rtioctl(req, data)
396 	u_long req;
397 	caddr_t data;
398 {
399 #ifdef INET
400 	/* Multicast goop, grrr... */
401 	return mrt_ioctl ? mrt_ioctl(req, data) : EOPNOTSUPP;
402 #else /* INET */
403 	return ENXIO;
404 #endif /* INET */
405 }
406 
407 struct ifaddr *
408 ifa_ifwithroute(flags, dst, gateway)
409 	int flags;
410 	struct sockaddr	*dst, *gateway;
411 {
412 	register struct ifaddr *ifa;
413 	if ((flags & RTF_GATEWAY) == 0) {
414 		/*
415 		 * If we are adding a route to an interface,
416 		 * and the interface is a pt to pt link
417 		 * we should search for the destination
418 		 * as our clue to the interface.  Otherwise
419 		 * we can use the local address.
420 		 */
421 		ifa = 0;
422 		if (flags & RTF_HOST) {
423 			ifa = ifa_ifwithdstaddr(dst);
424 		}
425 		if (ifa == 0)
426 			ifa = ifa_ifwithaddr(gateway);
427 	} else {
428 		/*
429 		 * If we are adding a route to a remote net
430 		 * or host, the gateway may still be on the
431 		 * other end of a pt to pt link.
432 		 */
433 		ifa = ifa_ifwithdstaddr(gateway);
434 	}
435 	if (ifa == 0)
436 		ifa = ifa_ifwithnet(gateway);
437 	if (ifa == 0) {
438 		struct rtentry *rt = rtalloc1(gateway, 0, 0UL);
439 		if (rt == 0)
440 			return (0);
441 		--rt->rt_refcnt;
442 		if ((ifa = rt->rt_ifa) == 0)
443 			return (0);
444 	}
445 	if (ifa->ifa_addr->sa_family != dst->sa_family) {
446 		struct ifaddr *oifa = ifa;
447 		ifa = ifaof_ifpforaddr(dst, ifa->ifa_ifp);
448 		if (ifa == 0)
449 			ifa = oifa;
450 	}
451 	return (ifa);
452 }
453 
454 static int rt_fixdelete(struct radix_node *, void *);
455 static int rt_fixchange(struct radix_node *, void *);
456 
457 struct rtfc_arg {
458 	struct rtentry *rt0;
459 	struct radix_node_head *rnh;
460 };
461 
462 /*
463  * Do appropriate manipulations of a routing tree given
464  * all the bits of info needed
465  */
466 int
467 rtrequest(req, dst, gateway, netmask, flags, ret_nrt)
468 	int req, flags;
469 	struct sockaddr *dst, *gateway, *netmask;
470 	struct rtentry **ret_nrt;
471 {
472 	struct rt_addrinfo info;
473 
474 	bzero((caddr_t)&info, sizeof(info));
475 	info.rti_flags = flags;
476 	info.rti_info[RTAX_DST] = dst;
477 	info.rti_info[RTAX_GATEWAY] = gateway;
478 	info.rti_info[RTAX_NETMASK] = netmask;
479 	return rtrequest1(req, &info, ret_nrt);
480 }
481 
482 /*
483  * These (questionable) definitions of apparent local variables apply
484  * to the next two functions.  XXXXXX!!!
485  */
486 #define	dst	info->rti_info[RTAX_DST]
487 #define	gateway	info->rti_info[RTAX_GATEWAY]
488 #define	netmask	info->rti_info[RTAX_NETMASK]
489 #define	ifaaddr	info->rti_info[RTAX_IFA]
490 #define	ifpaddr	info->rti_info[RTAX_IFP]
491 #define	flags	info->rti_flags
492 
493 int
494 rt_getifa(info)
495 	struct rt_addrinfo *info;
496 {
497 	struct ifaddr *ifa;
498 	int error = 0;
499 
500 	/*
501 	 * ifp may be specified by sockaddr_dl
502 	 * when protocol address is ambiguous.
503 	 */
504 	if (info->rti_ifp == NULL && ifpaddr != NULL &&
505 	    ifpaddr->sa_family == AF_LINK &&
506 	    (ifa = ifa_ifwithnet(ifpaddr)) != NULL)
507 		info->rti_ifp = ifa->ifa_ifp;
508 	if (info->rti_ifa == NULL && ifaaddr != NULL)
509 		info->rti_ifa = ifa_ifwithaddr(ifaaddr);
510 	if (info->rti_ifa == NULL) {
511 		struct sockaddr *sa;
512 
513 		sa = ifaaddr != NULL ? ifaaddr :
514 		    (gateway != NULL ? gateway : dst);
515 		if (sa != NULL && info->rti_ifp != NULL)
516 			info->rti_ifa = ifaof_ifpforaddr(sa, info->rti_ifp);
517 		else if (dst != NULL && gateway != NULL)
518 			info->rti_ifa = ifa_ifwithroute(flags, dst, gateway);
519 		else if (sa != NULL)
520 			info->rti_ifa = ifa_ifwithroute(flags, sa, sa);
521 	}
522 	if ((ifa = info->rti_ifa) != NULL) {
523 		if (info->rti_ifp == NULL)
524 			info->rti_ifp = ifa->ifa_ifp;
525 	} else
526 		error = ENETUNREACH;
527 	return (error);
528 }
529 
530 int
531 rtrequest1(req, info, ret_nrt)
532 	int req;
533 	struct rt_addrinfo *info;
534 	struct rtentry **ret_nrt;
535 {
536 	int s = splnet(); int error = 0;
537 	register struct rtentry *rt;
538 	register struct radix_node *rn;
539 	register struct radix_node_head *rnh;
540 	struct ifaddr *ifa;
541 	struct sockaddr *ndst;
542 #define senderr(x) { error = x ; goto bad; }
543 
544 	/*
545 	 * Find the correct routing tree to use for this Address Family
546 	 */
547 	if ((rnh = rt_tables[dst->sa_family]) == 0)
548 		senderr(EAFNOSUPPORT);
549 	RADIX_NODE_HEAD_LOCK(rnh);
550 	/*
551 	 * If we are adding a host route then we don't want to put
552 	 * a netmask in the tree, nor do we want to clone it.
553 	 */
554 	if (flags & RTF_HOST) {
555 		netmask = 0;
556 		flags &= ~(RTF_CLONING | RTF_PRCLONING);
557 	}
558 	switch (req) {
559 	case RTM_DELETE:
560 		/*
561 		 * Remove the item from the tree and return it.
562 		 * Complain if it is not there and do no more processing.
563 		 */
564 		if ((rn = rnh->rnh_deladdr(dst, netmask, rnh)) == 0)
565 			senderr(ESRCH);
566 		if (rn->rn_flags & (RNF_ACTIVE | RNF_ROOT))
567 			panic ("rtrequest delete");
568 		rt = (struct rtentry *)rn;
569 		rt->rt_refcnt++;
570 		rt->rt_flags &= ~RTF_UP;
571 
572 		/*
573 		 * Now search what's left of the subtree for any cloned
574 		 * routes which might have been formed from this node.
575 		 */
576 		if ((rt->rt_flags & (RTF_CLONING | RTF_PRCLONING)) &&
577 		    rt_mask(rt)) {
578 			rnh->rnh_walktree_from(rnh, dst, rt_mask(rt),
579 					       rt_fixdelete, rt);
580 		}
581 
582 		/*
583 		 * Remove any external references we may have.
584 		 * This might result in another rtentry being freed if
585 		 * we held its last reference.
586 		 */
587 		if (rt->rt_gwroute) {
588 			rt = rt->rt_gwroute;
589 			RTFREE(rt);
590 			(rt = (struct rtentry *)rn)->rt_gwroute = 0;
591 		}
592 
593 		/*
594 		 * give the protocol a chance to keep things in sync.
595 		 */
596 		if ((ifa = rt->rt_ifa) && ifa->ifa_rtrequest)
597 			ifa->ifa_rtrequest(RTM_DELETE, rt, info);
598 
599 		/*
600 		 * one more rtentry floating around that is not
601 		 * linked to the routing table.
602 		 */
603 		rttrash++;
604 
605 		/*
606 		 * If the caller wants it, then it can have it,
607 		 * but it's up to it to free the rtentry as we won't be
608 		 * doing it.
609 		 */
610 		if (ret_nrt)
611 			*ret_nrt = rt;
612 		else
613 			RTFREE(rt);
614 		break;
615 
616 	case RTM_RESOLVE:
617 		if (ret_nrt == 0 || (rt = *ret_nrt) == 0)
618 			senderr(EINVAL);
619 		ifa = rt->rt_ifa;
620 		flags = rt->rt_flags &
621 		    ~(RTF_CLONING | RTF_PRCLONING | RTF_STATIC);
622 		flags |= RTF_WASCLONED;
623 		gateway = rt->rt_gateway;
624 		if ((netmask = rt->rt_genmask) == 0)
625 			flags |= RTF_HOST;
626 		goto makeroute;
627 
628 	case RTM_ADD:
629 		if ((flags & RTF_GATEWAY) && !gateway)
630 			panic("rtrequest: GATEWAY but no gateway");
631 
632 		if (info->rti_ifa == NULL && (error = rt_getifa(info)))
633 			senderr(error);
634 		ifa = info->rti_ifa;
635 
636 	makeroute:
637 		R_Malloc(rt, struct rtentry *, sizeof(*rt));
638 		if (rt == 0)
639 			senderr(ENOBUFS);
640 		Bzero(rt, sizeof(*rt));
641 		rt->rt_flags = RTF_UP | flags;
642 		/*
643 		 * Add the gateway. Possibly re-malloc-ing the storage for it
644 		 * also add the rt_gwroute if possible.
645 		 */
646 		if ((error = rt_setgate(rt, dst, gateway)) != 0) {
647 			Free(rt);
648 			senderr(error);
649 		}
650 
651 		/*
652 		 * point to the (possibly newly malloc'd) dest address.
653 		 */
654 		ndst = rt_key(rt);
655 
656 		/*
657 		 * make sure it contains the value we want (masked if needed).
658 		 */
659 		if (netmask) {
660 			rt_maskedcopy(dst, ndst, netmask);
661 		} else
662 			Bcopy(dst, ndst, dst->sa_len);
663 
664 		/*
665 		 * Note that we now have a reference to the ifa.
666 		 * This moved from below so that rnh->rnh_addaddr() can
667 		 * examine the ifa and  ifa->ifa_ifp if it so desires.
668 		 */
669 		IFAREF(ifa);
670 		rt->rt_ifa = ifa;
671 		rt->rt_ifp = ifa->ifa_ifp;
672 		/* XXX mtu manipulation will be done in rnh_addaddr -- itojun */
673 
674 		rn = rnh->rnh_addaddr((caddr_t)ndst, (caddr_t)netmask,
675 					rnh, rt->rt_nodes);
676 		if (rn == 0) {
677 			struct rtentry *rt2;
678 			/*
679 			 * Uh-oh, we already have one of these in the tree.
680 			 * We do a special hack: if the route that's already
681 			 * there was generated by the protocol-cloning
682 			 * mechanism, then we just blow it away and retry
683 			 * the insertion of the new one.
684 			 */
685 			rt2 = rtalloc1(dst, 0, RTF_PRCLONING);
686 			if (rt2 && rt2->rt_parent) {
687 				rtrequest(RTM_DELETE,
688 					  (struct sockaddr *)rt_key(rt2),
689 					  rt2->rt_gateway,
690 					  rt_mask(rt2), rt2->rt_flags, 0);
691 				RTFREE(rt2);
692 				rn = rnh->rnh_addaddr((caddr_t)ndst,
693 						      (caddr_t)netmask,
694 						      rnh, rt->rt_nodes);
695 			} else if (rt2) {
696 				/* undo the extra ref we got */
697 				RTFREE(rt2);
698 			}
699 		}
700 
701 		/*
702 		 * If it still failed to go into the tree,
703 		 * then un-make it (this should be a function)
704 		 */
705 		if (rn == 0) {
706 			if (rt->rt_gwroute)
707 				rtfree(rt->rt_gwroute);
708 			if (rt->rt_ifa) {
709 				IFAFREE(rt->rt_ifa);
710 			}
711 			Free(rt_key(rt));
712 			Free(rt);
713 			senderr(EEXIST);
714 		}
715 
716 		rt->rt_parent = 0;
717 
718 		/*
719 		 * If we got here from RESOLVE, then we are cloning
720 		 * so clone the rest, and note that we
721 		 * are a clone (and increment the parent's references)
722 		 */
723 		if (req == RTM_RESOLVE) {
724 			rt->rt_rmx = (*ret_nrt)->rt_rmx; /* copy metrics */
725 			rt->rt_rmx.rmx_pksent = 0; /* reset packet counter */
726 			if ((*ret_nrt)->rt_flags & (RTF_CLONING | RTF_PRCLONING)) {
727 				rt->rt_parent = (*ret_nrt);
728 				(*ret_nrt)->rt_refcnt++;
729 			}
730 		}
731 
732 		/*
733 		 * if this protocol has something to add to this then
734 		 * allow it to do that as well.
735 		 */
736 		if (ifa->ifa_rtrequest)
737 			ifa->ifa_rtrequest(req, rt, info);
738 
739 		/*
740 		 * We repeat the same procedure from rt_setgate() here because
741 		 * it doesn't fire when we call it there because the node
742 		 * hasn't been added to the tree yet.
743 		 */
744 		if (req == RTM_ADD &&
745 		    !(rt->rt_flags & RTF_HOST) && rt_mask(rt) != 0) {
746 			struct rtfc_arg arg;
747 			arg.rnh = rnh;
748 			arg.rt0 = rt;
749 			rnh->rnh_walktree_from(rnh, rt_key(rt), rt_mask(rt),
750 					       rt_fixchange, &arg);
751 		}
752 
753 		/*
754 		 * actually return a resultant rtentry and
755 		 * give the caller a single reference.
756 		 */
757 		if (ret_nrt) {
758 			*ret_nrt = rt;
759 			rt->rt_refcnt++;
760 		}
761 		break;
762 	default:
763 		error = EOPNOTSUPP;
764 	}
765 bad:
766 	RADIX_NODE_HEAD_UNLOCK(rnh);
767 	splx(s);
768 	return (error);
769 #undef dst
770 #undef gateway
771 #undef netmask
772 #undef ifaaddr
773 #undef ifpaddr
774 #undef flags
775 }
776 
777 /*
778  * Called from rtrequest(RTM_DELETE, ...) to fix up the route's ``family''
779  * (i.e., the routes related to it by the operation of cloning).  This
780  * routine is iterated over all potential former-child-routes by way of
781  * rnh->rnh_walktree_from() above, and those that actually are children of
782  * the late parent (passed in as VP here) are themselves deleted.
783  */
784 static int
785 rt_fixdelete(rn, vp)
786 	struct radix_node *rn;
787 	void *vp;
788 {
789 	struct rtentry *rt = (struct rtentry *)rn;
790 	struct rtentry *rt0 = vp;
791 
792 	if (rt->rt_parent == rt0 &&
793 	    !(rt->rt_flags & (RTF_PINNED | RTF_CLONING | RTF_PRCLONING))) {
794 		return rtrequest(RTM_DELETE, rt_key(rt),
795 				 (struct sockaddr *)0, rt_mask(rt),
796 				 rt->rt_flags, (struct rtentry **)0);
797 	}
798 	return 0;
799 }
800 
801 /*
802  * This routine is called from rt_setgate() to do the analogous thing for
803  * adds and changes.  There is the added complication in this case of a
804  * middle insert; i.e., insertion of a new network route between an older
805  * network route and (cloned) host routes.  For this reason, a simple check
806  * of rt->rt_parent is insufficient; each candidate route must be tested
807  * against the (mask, value) of the new route (passed as before in vp)
808  * to see if the new route matches it.
809  *
810  * XXX - it may be possible to do fixdelete() for changes and reserve this
811  * routine just for adds.  I'm not sure why I thought it was necessary to do
812  * changes this way.
813  */
814 #ifdef DEBUG
815 static int rtfcdebug = 0;
816 #endif
817 
818 static int
819 rt_fixchange(rn, vp)
820 	struct radix_node *rn;
821 	void *vp;
822 {
823 	struct rtentry *rt = (struct rtentry *)rn;
824 	struct rtfc_arg *ap = vp;
825 	struct rtentry *rt0 = ap->rt0;
826 	struct radix_node_head *rnh = ap->rnh;
827 	u_char *xk1, *xm1, *xk2, *xmp;
828 	int i, len, mlen;
829 
830 #ifdef DEBUG
831 	if (rtfcdebug)
832 		printf("rt_fixchange: rt %p, rt0 %p\n", rt, rt0);
833 #endif
834 
835 	if (!rt->rt_parent ||
836 	    (rt->rt_flags & (RTF_PINNED | RTF_CLONING | RTF_PRCLONING))) {
837 #ifdef DEBUG
838 		if(rtfcdebug) printf("no parent, pinned or cloning\n");
839 #endif
840 		return 0;
841 	}
842 
843 	if (rt->rt_parent == rt0) {
844 #ifdef DEBUG
845 		if(rtfcdebug) printf("parent match\n");
846 #endif
847 		return rtrequest(RTM_DELETE, rt_key(rt),
848 				 (struct sockaddr *)0, rt_mask(rt),
849 				 rt->rt_flags, (struct rtentry **)0);
850 	}
851 
852 	/*
853 	 * There probably is a function somewhere which does this...
854 	 * if not, there should be.
855 	 */
856 	len = imin(((struct sockaddr *)rt_key(rt0))->sa_len,
857 		   ((struct sockaddr *)rt_key(rt))->sa_len);
858 
859 	xk1 = (u_char *)rt_key(rt0);
860 	xm1 = (u_char *)rt_mask(rt0);
861 	xk2 = (u_char *)rt_key(rt);
862 
863 	/* avoid applying a less specific route */
864 	xmp = (u_char *)rt_mask(rt->rt_parent);
865 	mlen = ((struct sockaddr *)rt_key(rt->rt_parent))->sa_len;
866 	if (mlen > ((struct sockaddr *)rt_key(rt0))->sa_len) {
867 #ifdef DEBUG
868 		if (rtfcdebug)
869 			printf("rt_fixchange: inserting a less "
870 			       "specific route\n");
871 #endif
872 		return 0;
873 	}
874 	for (i = rnh->rnh_treetop->rn_offset; i < mlen; i++) {
875 		if ((xmp[i] & ~(xmp[i] ^ xm1[i])) != xmp[i]) {
876 #ifdef DEBUG
877 			if (rtfcdebug)
878 				printf("rt_fixchange: inserting a less "
879 				       "specific route\n");
880 #endif
881 			return 0;
882 		}
883 	}
884 
885 	for (i = rnh->rnh_treetop->rn_offset; i < len; i++) {
886 		if ((xk2[i] & xm1[i]) != xk1[i]) {
887 #ifdef DEBUG
888 			if(rtfcdebug) printf("no match\n");
889 #endif
890 			return 0;
891 		}
892 	}
893 
894 	/*
895 	 * OK, this node is a clone, and matches the node currently being
896 	 * changed/added under the node's mask.  So, get rid of it.
897 	 */
898 #ifdef DEBUG
899 	if(rtfcdebug) printf("deleting\n");
900 #endif
901 	return rtrequest(RTM_DELETE, rt_key(rt), (struct sockaddr *)0,
902 			 rt_mask(rt), rt->rt_flags, (struct rtentry **)0);
903 }
904 
905 #define ROUNDUP(a) (a>0 ? (1 + (((a) - 1) | (sizeof(long) - 1))) : sizeof(long))
906 
907 int
908 rt_setgate(rt0, dst, gate)
909 	struct rtentry *rt0;
910 	struct sockaddr *dst, *gate;
911 {
912 	caddr_t new, old;
913 	int dlen = ROUNDUP(dst->sa_len), glen = ROUNDUP(gate->sa_len);
914 	register struct rtentry *rt = rt0;
915 	struct radix_node_head *rnh = rt_tables[dst->sa_family];
916 
917 	/*
918 	 * A host route with the destination equal to the gateway
919 	 * will interfere with keeping LLINFO in the routing
920 	 * table, so disallow it.
921 	 */
922 	if (((rt0->rt_flags & (RTF_HOST|RTF_GATEWAY|RTF_LLINFO)) ==
923 					(RTF_HOST|RTF_GATEWAY)) &&
924 	    (dst->sa_len == gate->sa_len) &&
925 	    (bcmp(dst, gate, dst->sa_len) == 0)) {
926 		/*
927 		 * The route might already exist if this is an RTM_CHANGE
928 		 * or a routing redirect, so try to delete it.
929 		 */
930 		if (rt_key(rt0))
931 			rtrequest(RTM_DELETE, (struct sockaddr *)rt_key(rt0),
932 			    rt0->rt_gateway, rt_mask(rt0), rt0->rt_flags, 0);
933 		return EADDRNOTAVAIL;
934 	}
935 
936 	/*
937 	 * Both dst and gateway are stored in the same malloc'd chunk
938 	 * (If I ever get my hands on....)
939 	 * if we need to malloc a new chunk, then keep the old one around
940 	 * till we don't need it any more.
941 	 */
942 	if (rt->rt_gateway == 0 || glen > ROUNDUP(rt->rt_gateway->sa_len)) {
943 		old = (caddr_t)rt_key(rt);
944 		R_Malloc(new, caddr_t, dlen + glen);
945 		if (new == 0)
946 			return ENOBUFS;
947 		rt->rt_nodes->rn_key = new;
948 	} else {
949 		/*
950 		 * otherwise just overwrite the old one
951 		 */
952 		new = rt->rt_nodes->rn_key;
953 		old = 0;
954 	}
955 
956 	/*
957 	 * copy the new gateway value into the memory chunk
958 	 */
959 	Bcopy(gate, (rt->rt_gateway = (struct sockaddr *)(new + dlen)), glen);
960 
961 	/*
962 	 * if we are replacing the chunk (or it's new) we need to
963 	 * replace the dst as well
964 	 */
965 	if (old) {
966 		Bcopy(dst, new, dlen);
967 		Free(old);
968 	}
969 
970 	/*
971 	 * If there is already a gwroute, it's now almost definitly wrong
972 	 * so drop it.
973 	 */
974 	if (rt->rt_gwroute != NULL) {
975 		RTFREE(rt->rt_gwroute);
976 		rt->rt_gwroute = NULL;
977 	}
978 	/*
979 	 * Cloning loop avoidance:
980 	 * In the presence of protocol-cloning and bad configuration,
981 	 * it is possible to get stuck in bottomless mutual recursion
982 	 * (rtrequest rt_setgate rtalloc1).  We avoid this by not allowing
983 	 * protocol-cloning to operate for gateways (which is probably the
984 	 * correct choice anyway), and avoid the resulting reference loops
985 	 * by disallowing any route to run through itself as a gateway.
986 	 * This is obviously mandatory when we get rt->rt_output().
987 	 */
988 	if (rt->rt_flags & RTF_GATEWAY) {
989 		rt->rt_gwroute = rtalloc1(gate, 1, RTF_PRCLONING);
990 		if (rt->rt_gwroute == rt) {
991 			RTFREE(rt->rt_gwroute);
992 			rt->rt_gwroute = 0;
993 			return EDQUOT; /* failure */
994 		}
995 	}
996 
997 	/*
998 	 * This isn't going to do anything useful for host routes, so
999 	 * don't bother.  Also make sure we have a reasonable mask
1000 	 * (we don't yet have one during adds).
1001 	 */
1002 	if (!(rt->rt_flags & RTF_HOST) && rt_mask(rt) != 0) {
1003 		struct rtfc_arg arg;
1004 		arg.rnh = rnh;
1005 		arg.rt0 = rt;
1006 		RADIX_NODE_HEAD_LOCK(rnh);
1007 		rnh->rnh_walktree_from(rnh, rt_key(rt), rt_mask(rt),
1008 				       rt_fixchange, &arg);
1009 		RADIX_NODE_HEAD_UNLOCK(rnh);
1010 	}
1011 
1012 	return 0;
1013 }
1014 
1015 static void
1016 rt_maskedcopy(src, dst, netmask)
1017 	struct sockaddr *src, *dst, *netmask;
1018 {
1019 	register u_char *cp1 = (u_char *)src;
1020 	register u_char *cp2 = (u_char *)dst;
1021 	register u_char *cp3 = (u_char *)netmask;
1022 	u_char *cplim = cp2 + *cp3;
1023 	u_char *cplim2 = cp2 + *cp1;
1024 
1025 	*cp2++ = *cp1++; *cp2++ = *cp1++; /* copies sa_len & sa_family */
1026 	cp3 += 2;
1027 	if (cplim > cplim2)
1028 		cplim = cplim2;
1029 	while (cp2 < cplim)
1030 		*cp2++ = *cp1++ & *cp3++;
1031 	if (cp2 < cplim2)
1032 		bzero((caddr_t)cp2, (unsigned)(cplim2 - cp2));
1033 }
1034 
1035 /*
1036  * Set up a routing table entry, normally
1037  * for an interface.
1038  */
1039 int
1040 rtinit(ifa, cmd, flags)
1041 	register struct ifaddr *ifa;
1042 	int cmd, flags;
1043 {
1044 	register struct rtentry *rt;
1045 	register struct sockaddr *dst;
1046 	register struct sockaddr *deldst;
1047 	struct sockaddr *netmask;
1048 	struct mbuf *m = 0;
1049 	struct rtentry *nrt = 0;
1050 	struct radix_node_head *rnh;
1051 	struct radix_node *rn;
1052 	int error;
1053 	struct rt_addrinfo info;
1054 
1055 	if (flags & RTF_HOST) {
1056 		dst = ifa->ifa_dstaddr;
1057 		netmask = NULL;
1058 	} else {
1059 		dst = ifa->ifa_addr;
1060 		netmask = ifa->ifa_netmask;
1061 	}
1062 	/*
1063 	 * If it's a delete, check that if it exists, it's on the correct
1064 	 * interface or we might scrub a route to another ifa which would
1065 	 * be confusing at best and possibly worse.
1066 	 */
1067 	if (cmd == RTM_DELETE) {
1068 		/*
1069 		 * It's a delete, so it should already exist..
1070 		 * If it's a net, mask off the host bits
1071 		 * (Assuming we have a mask)
1072 		 */
1073 		if (netmask != NULL) {
1074 			m = m_get(M_DONTWAIT, MT_SONAME);
1075 			if (m == NULL)
1076 				return(ENOBUFS);
1077 			deldst = mtod(m, struct sockaddr *);
1078 			rt_maskedcopy(dst, deldst, netmask);
1079 			dst = deldst;
1080 		}
1081 		/*
1082 		 * Look up an rtentry that is in the routing tree and
1083 		 * contains the correct info.
1084 		 */
1085 		if ((rnh = rt_tables[dst->sa_family]) == NULL)
1086 			goto bad;
1087 		RADIX_NODE_HEAD_LOCK(rnh);
1088 		error = ((rn = rnh->rnh_lookup(dst, netmask, rnh)) == NULL ||
1089 		    (rn->rn_flags & RNF_ROOT) ||
1090 		    ((struct rtentry *)rn)->rt_ifa != ifa ||
1091 		    !sa_equal(SA(rn->rn_key), dst));
1092 		RADIX_NODE_HEAD_UNLOCK(rnh);
1093 		if (error) {
1094 bad:
1095 			if (m)
1096 				(void) m_free(m);
1097 			return (flags & RTF_HOST ? EHOSTUNREACH : ENETUNREACH);
1098 		}
1099 	}
1100 	/*
1101 	 * Do the actual request
1102 	 */
1103 	bzero((caddr_t)&info, sizeof(info));
1104 	info.rti_ifa = ifa;
1105 	info.rti_flags = flags | ifa->ifa_flags;
1106 	info.rti_info[RTAX_DST] = dst;
1107 	info.rti_info[RTAX_GATEWAY] = ifa->ifa_addr;
1108 	info.rti_info[RTAX_NETMASK] = netmask;
1109 	error = rtrequest1(cmd, &info, &nrt);
1110 	if (error == 0 && (rt = nrt) != NULL) {
1111 		/*
1112 		 * notify any listening routing agents of the change
1113 		 */
1114 		rt_newaddrmsg(cmd, ifa, error, rt);
1115 		if (cmd == RTM_DELETE) {
1116 			/*
1117 			 * If we are deleting, and we found an entry, then
1118 			 * it's been removed from the tree.. now throw it away.
1119 			 */
1120 			RTFREE(rt);
1121 		} else if (cmd == RTM_ADD) {
1122 			/*
1123 			 * We just wanted to add it.. we don't actually
1124 			 * need a reference.
1125 			 */
1126 			rt->rt_refcnt--;
1127 		}
1128 	}
1129 	if (m)
1130 		(void) m_free(m);
1131 	return (error);
1132 }
1133 
1134 int
1135 rt_check(lrt, lrt0, dst)
1136 	struct rtentry **lrt;
1137 	struct rtentry **lrt0;
1138 	struct sockaddr *dst;
1139 {
1140 	struct rtentry *rt;
1141 	struct rtentry *rt0;
1142 	int error;
1143 
1144 	rt = *lrt;
1145 	rt0 = *lrt0;
1146 	error = 0;
1147 
1148 	rt = rt0;
1149 
1150 	if (rt != NULL) {
1151 		if ((rt->rt_flags & RTF_UP) == 0) {
1152 			rt0 = rt = rtalloc1(dst, 1, 0UL);
1153 			if (rt0 != NULL)
1154 				rt->rt_refcnt--;
1155 			else
1156 				senderr(EHOSTUNREACH);
1157 		}
1158 		if (rt->rt_flags & RTF_GATEWAY) {
1159 			if (rt->rt_gwroute == NULL)
1160 				goto lookup;
1161 
1162 			rt = rt->rt_gwroute;
1163 			if ((rt->rt_flags & RTF_UP) == 0) {
1164 				rtfree(rt);
1165 				rt = rt0;
1166 			lookup:
1167 				rt->rt_gwroute = rtalloc1(rt->rt_gateway, 1, 0UL);
1168 				rt = rt->rt_gwroute;
1169 				if (rt == NULL)
1170 					senderr(EHOSTUNREACH);
1171 			}
1172 		}
1173 		if (rt->rt_flags & RTF_REJECT)
1174 			if (rt->rt_rmx.rmx_expire == 0 ||
1175 				time_second < rt->rt_rmx.rmx_expire)
1176 				senderr(rt == rt0 ? EHOSTDOWN : EHOSTUNREACH);
1177 	}
1178 
1179 bad:
1180 	*lrt = rt;
1181 	*lrt0 = rt0;
1182 	return (error);
1183 }
1184 
1185 /* This must be before ip6_init2(), which is now SI_ORDER_MIDDLE */
1186 SYSINIT(route, SI_SUB_PROTO_DOMAIN, SI_ORDER_THIRD, route_init, 0);
1187