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