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