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