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