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