]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/net/route.c
Naming consistency fix. The routing code defines
[FreeBSD/FreeBSD.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  * 4. Neither the name of the University nor the names of its contributors
14  *    may be used to endorse or promote products derived from this software
15  *    without specific prior written permission.
16  *
17  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
18  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
21  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
27  * SUCH DAMAGE.
28  *
29  *      @(#)route.c     8.3.1.1 (Berkeley) 2/23/95
30  * $FreeBSD$
31  */
32 /************************************************************************
33  * Note: In this file a 'fib' is a "forwarding information base"        *
34  * Which is the new name for an in kernel routing (next hop) table.     *
35  ***********************************************************************/
36
37 #include "opt_inet.h"
38 #include "opt_inet6.h"
39 #include "opt_route.h"
40 #include "opt_sctp.h"
41 #include "opt_mrouting.h"
42 #include "opt_mpath.h"
43
44 #include <sys/param.h>
45 #include <sys/systm.h>
46 #include <sys/syslog.h>
47 #include <sys/malloc.h>
48 #include <sys/mbuf.h>
49 #include <sys/socket.h>
50 #include <sys/sysctl.h>
51 #include <sys/syslog.h>
52 #include <sys/sysproto.h>
53 #include <sys/proc.h>
54 #include <sys/domain.h>
55 #include <sys/kernel.h>
56
57 #include <net/if.h>
58 #include <net/if_var.h>
59 #include <net/if_dl.h>
60 #include <net/route.h>
61 #include <net/vnet.h>
62 #include <net/flowtable.h>
63
64 #ifdef RADIX_MPATH
65 #include <net/radix_mpath.h>
66 #endif
67
68 #include <netinet/in.h>
69 #include <netinet/ip_mroute.h>
70
71 #include <vm/uma.h>
72
73 #define RT_MAXFIBS      UINT16_MAX
74
75 /* Kernel config default option. */
76 #ifdef ROUTETABLES
77 #if ROUTETABLES <= 0
78 #error "ROUTETABLES defined too low"
79 #endif
80 #if ROUTETABLES > RT_MAXFIBS
81 #error "ROUTETABLES defined too big"
82 #endif
83 #define RT_NUMFIBS      ROUTETABLES
84 #endif /* ROUTETABLES */
85 /* Initialize to default if not otherwise set. */
86 #ifndef RT_NUMFIBS
87 #define RT_NUMFIBS      1
88 #endif
89
90 #if defined(INET) || defined(INET6)
91 #ifdef SCTP
92 extern void sctp_addr_change(struct ifaddr *ifa, int cmd);
93 #endif /* SCTP */
94 #endif
95
96
97 /* This is read-only.. */
98 u_int rt_numfibs = RT_NUMFIBS;
99 SYSCTL_UINT(_net, OID_AUTO, fibs, CTLFLAG_RD, &rt_numfibs, 0, "");
100 /* and this can be set too big but will be fixed before it is used */
101 TUNABLE_INT("net.fibs", &rt_numfibs);
102
103 /*
104  * By default add routes to all fibs for new interfaces.
105  * Once this is set to 0 then only allocate routes on interface
106  * changes for the FIB of the caller when adding a new set of addresses
107  * to an interface.  XXX this is a shotgun aproach to a problem that needs
108  * a more fine grained solution.. that will come.
109  * XXX also has the problems getting the FIB from curthread which will not
110  * always work given the fib can be overridden and prefixes can be added
111  * from the network stack context.
112  */
113 u_int rt_add_addr_allfibs = 1;
114 SYSCTL_UINT(_net, OID_AUTO, add_addr_allfibs, CTLFLAG_RW,
115     &rt_add_addr_allfibs, 0, "");
116 TUNABLE_INT("net.add_addr_allfibs", &rt_add_addr_allfibs);
117
118 VNET_DEFINE(struct rtstat, rtstat);
119 #define V_rtstat        VNET(rtstat)
120
121 VNET_DEFINE(struct radix_node_head *, rt_tables);
122 #define V_rt_tables     VNET(rt_tables)
123
124 VNET_DEFINE(int, rttrash);              /* routes not in table but not freed */
125 #define V_rttrash       VNET(rttrash)
126
127
128 /* compare two sockaddr structures */
129 #define sa_equal(a1, a2) (((a1)->sa_len == (a2)->sa_len) && \
130     (bcmp((a1), (a2), (a1)->sa_len) == 0))
131
132 /*
133  * Convert a 'struct radix_node *' to a 'struct rtentry *'.
134  * The operation can be done safely (in this code) because a
135  * 'struct rtentry' starts with two 'struct radix_node''s, the first
136  * one representing leaf nodes in the routing tree, which is
137  * what the code in radix.c passes us as a 'struct radix_node'.
138  *
139  * But because there are a lot of assumptions in this conversion,
140  * do not cast explicitly, but always use the macro below.
141  */
142 #define RNTORT(p)       ((struct rtentry *)(p))
143
144 static VNET_DEFINE(uma_zone_t, rtzone);         /* Routing table UMA zone. */
145 #define V_rtzone        VNET(rtzone)
146
147 /*
148  * handler for net.my_fibnum
149  */
150 static int
151 sysctl_my_fibnum(SYSCTL_HANDLER_ARGS)
152 {
153         int fibnum;
154         int error;
155  
156         fibnum = curthread->td_proc->p_fibnum;
157         error = sysctl_handle_int(oidp, &fibnum, 0, req);
158         return (error);
159 }
160
161 SYSCTL_PROC(_net, OID_AUTO, my_fibnum, CTLTYPE_INT|CTLFLAG_RD,
162             NULL, 0, &sysctl_my_fibnum, "I", "default FIB of caller");
163
164 static __inline struct radix_node_head **
165 rt_tables_get_rnh_ptr(int table, int fam)
166 {
167         struct radix_node_head **rnh;
168
169         KASSERT(table >= 0 && table < rt_numfibs, ("%s: table out of bounds.",
170             __func__));
171         KASSERT(fam >= 0 && fam < (AF_MAX+1), ("%s: fam out of bounds.",
172             __func__));
173
174         /* rnh is [fib=0][af=0]. */
175         rnh = (struct radix_node_head **)V_rt_tables;
176         /* Get the offset to the requested table and fam. */
177         rnh += table * (AF_MAX+1) + fam;
178
179         return (rnh);
180 }
181
182 struct radix_node_head *
183 rt_tables_get_rnh(int table, int fam)
184 {
185
186         return (*rt_tables_get_rnh_ptr(table, fam));
187 }
188
189 /*
190  * route initialization must occur before ip6_init2(), which happenas at
191  * SI_ORDER_MIDDLE.
192  */
193 static void
194 route_init(void)
195 {
196
197         /* whack the tunable ints into  line. */
198         if (rt_numfibs > RT_MAXFIBS)
199                 rt_numfibs = RT_MAXFIBS;
200         if (rt_numfibs == 0)
201                 rt_numfibs = 1;
202 }
203 SYSINIT(route_init, SI_SUB_PROTO_DOMAIN, SI_ORDER_THIRD, route_init, 0);
204
205 static void
206 vnet_route_init(const void *unused __unused)
207 {
208         struct domain *dom;
209         struct radix_node_head **rnh;
210         int table;
211         int fam;
212
213         V_rt_tables = malloc(rt_numfibs * (AF_MAX+1) *
214             sizeof(struct radix_node_head *), M_RTABLE, M_WAITOK|M_ZERO);
215
216         V_rtzone = uma_zcreate("rtentry", sizeof(struct rtentry), NULL, NULL,
217             NULL, NULL, UMA_ALIGN_PTR, 0);
218         for (dom = domains; dom; dom = dom->dom_next) {
219                 if (dom->dom_rtattach == NULL)
220                         continue;
221
222                 for  (table = 0; table < rt_numfibs; table++) {
223                         fam = dom->dom_family;
224                         if (table != 0 && fam != AF_INET6 && fam != AF_INET)
225                                 break;
226
227                         /*
228                          * XXX MRT rtattach will be also called from
229                          * vfs_export.c but the offset will be 0 (only for
230                          * AF_INET and AF_INET6 which don't need it anyhow).
231                          */
232                         rnh = rt_tables_get_rnh_ptr(table, fam);
233                         if (rnh == NULL)
234                                 panic("%s: rnh NULL", __func__);
235                         dom->dom_rtattach((void **)rnh, dom->dom_rtoffset);
236                 }
237         }
238 }
239 VNET_SYSINIT(vnet_route_init, SI_SUB_PROTO_DOMAIN, SI_ORDER_FOURTH,
240     vnet_route_init, 0);
241
242 #ifdef VIMAGE
243 static void
244 vnet_route_uninit(const void *unused __unused)
245 {
246         int table;
247         int fam;
248         struct domain *dom;
249         struct radix_node_head **rnh;
250
251         for (dom = domains; dom; dom = dom->dom_next) {
252                 if (dom->dom_rtdetach == NULL)
253                         continue;
254
255                 for (table = 0; table < rt_numfibs; table++) {
256                         fam = dom->dom_family;
257
258                         if (table != 0 && fam != AF_INET6 && fam != AF_INET)
259                                 break;
260
261                         rnh = rt_tables_get_rnh_ptr(table, fam);
262                         if (rnh == NULL)
263                                 panic("%s: rnh NULL", __func__);
264                         dom->dom_rtdetach((void **)rnh, dom->dom_rtoffset);
265                 }
266         }
267
268         free(V_rt_tables, M_RTABLE);
269         uma_zdestroy(V_rtzone);
270 }
271 VNET_SYSUNINIT(vnet_route_uninit, SI_SUB_PROTO_DOMAIN, SI_ORDER_THIRD,
272     vnet_route_uninit, 0);
273 #endif
274
275 #ifndef _SYS_SYSPROTO_H_
276 struct setfib_args {
277         int     fibnum;
278 };
279 #endif
280 int
281 sys_setfib(struct thread *td, struct setfib_args *uap)
282 {
283         if (uap->fibnum < 0 || uap->fibnum >= rt_numfibs)
284                 return EINVAL;
285         td->td_proc->p_fibnum = uap->fibnum;
286         return (0);
287 }
288
289 /*
290  * Packet routing routines.
291  */
292 void
293 rtalloc(struct route *ro)
294 {
295
296         rtalloc_ign_fib(ro, 0UL, RT_DEFAULT_FIB);
297 }
298
299 void
300 rtalloc_fib(struct route *ro, u_int fibnum)
301 {
302         rtalloc_ign_fib(ro, 0UL, fibnum);
303 }
304
305 void
306 rtalloc_ign(struct route *ro, u_long ignore)
307 {
308         struct rtentry *rt;
309
310         if ((rt = ro->ro_rt) != NULL) {
311                 if (rt->rt_ifp != NULL && rt->rt_flags & RTF_UP)
312                         return;
313                 RTFREE(rt);
314                 ro->ro_rt = NULL;
315         }
316         ro->ro_rt = rtalloc1_fib(&ro->ro_dst, 1, ignore, RT_DEFAULT_FIB);
317         if (ro->ro_rt)
318                 RT_UNLOCK(ro->ro_rt);
319 }
320
321 void
322 rtalloc_ign_fib(struct route *ro, u_long ignore, u_int fibnum)
323 {
324         struct rtentry *rt;
325
326         if ((rt = ro->ro_rt) != NULL) {
327                 if (rt->rt_ifp != NULL && rt->rt_flags & RTF_UP)
328                         return;
329                 RTFREE(rt);
330                 ro->ro_rt = NULL;
331         }
332         ro->ro_rt = rtalloc1_fib(&ro->ro_dst, 1, ignore, fibnum);
333         if (ro->ro_rt)
334                 RT_UNLOCK(ro->ro_rt);
335 }
336
337 /*
338  * Look up the route that matches the address given
339  * Or, at least try.. Create a cloned route if needed.
340  *
341  * The returned route, if any, is locked.
342  */
343 struct rtentry *
344 rtalloc1(struct sockaddr *dst, int report, u_long ignflags)
345 {
346
347         return (rtalloc1_fib(dst, report, ignflags, RT_DEFAULT_FIB));
348 }
349
350 struct rtentry *
351 rtalloc1_fib(struct sockaddr *dst, int report, u_long ignflags,
352                     u_int fibnum)
353 {
354         struct radix_node_head *rnh;
355         struct radix_node *rn;
356         struct rtentry *newrt;
357         struct rt_addrinfo info;
358         int err = 0, msgtype = RTM_MISS;
359         int needlock;
360
361         KASSERT((fibnum < rt_numfibs), ("rtalloc1_fib: bad fibnum"));
362         switch (dst->sa_family) {
363         case AF_INET6:
364         case AF_INET:
365                 /* We support multiple FIBs. */
366                 break;
367         default:
368                 fibnum = RT_DEFAULT_FIB;
369                 break;
370         }
371         rnh = rt_tables_get_rnh(fibnum, dst->sa_family);
372         newrt = NULL;
373         if (rnh == NULL)
374                 goto miss;
375
376         /*
377          * Look up the address in the table for that Address Family
378          */
379         needlock = !(ignflags & RTF_RNH_LOCKED);
380         if (needlock)
381                 RADIX_NODE_HEAD_RLOCK(rnh);
382 #ifdef INVARIANTS       
383         else
384                 RADIX_NODE_HEAD_RLOCK_ASSERT(rnh);
385 #endif
386         rn = rnh->rnh_matchaddr(dst, rnh);
387         if (rn && ((rn->rn_flags & RNF_ROOT) == 0)) {
388                 newrt = RNTORT(rn);
389                 RT_LOCK(newrt);
390                 RT_ADDREF(newrt);
391                 if (needlock)
392                         RADIX_NODE_HEAD_RUNLOCK(rnh);
393                 goto done;
394
395         } else if (needlock)
396                 RADIX_NODE_HEAD_RUNLOCK(rnh);
397         
398         /*
399          * Either we hit the root or couldn't find any match,
400          * Which basically means
401          * "caint get there frm here"
402          */
403 miss:
404         V_rtstat.rts_unreach++;
405
406         if (report) {
407                 /*
408                  * If required, report the failure to the supervising
409                  * Authorities.
410                  * For a delete, this is not an error. (report == 0)
411                  */
412                 bzero(&info, sizeof(info));
413                 info.rti_info[RTAX_DST] = dst;
414                 rt_missmsg_fib(msgtype, &info, 0, err, fibnum);
415         }       
416 done:
417         if (newrt)
418                 RT_LOCK_ASSERT(newrt);
419         return (newrt);
420 }
421
422 /*
423  * Remove a reference count from an rtentry.
424  * If the count gets low enough, take it out of the routing table
425  */
426 void
427 rtfree(struct rtentry *rt)
428 {
429         struct radix_node_head *rnh;
430
431         KASSERT(rt != NULL,("%s: NULL rt", __func__));
432         rnh = rt_tables_get_rnh(rt->rt_fibnum, rt_key(rt)->sa_family);
433         KASSERT(rnh != NULL,("%s: NULL rnh", __func__));
434
435         RT_LOCK_ASSERT(rt);
436
437         /*
438          * The callers should use RTFREE_LOCKED() or RTFREE(), so
439          * we should come here exactly with the last reference.
440          */
441         RT_REMREF(rt);
442         if (rt->rt_refcnt > 0) {
443                 log(LOG_DEBUG, "%s: %p has %d refs\n", __func__, rt, rt->rt_refcnt);
444                 goto done;
445         }
446
447         /*
448          * On last reference give the "close method" a chance
449          * to cleanup private state.  This also permits (for
450          * IPv4 and IPv6) a chance to decide if the routing table
451          * entry should be purged immediately or at a later time.
452          * When an immediate purge is to happen the close routine
453          * typically calls rtexpunge which clears the RTF_UP flag
454          * on the entry so that the code below reclaims the storage.
455          */
456         if (rt->rt_refcnt == 0 && rnh->rnh_close)
457                 rnh->rnh_close((struct radix_node *)rt, rnh);
458
459         /*
460          * If we are no longer "up" (and ref == 0)
461          * then we can free the resources associated
462          * with the route.
463          */
464         if ((rt->rt_flags & RTF_UP) == 0) {
465                 if (rt->rt_nodes->rn_flags & (RNF_ACTIVE | RNF_ROOT))
466                         panic("rtfree 2");
467                 /*
468                  * the rtentry must have been removed from the routing table
469                  * so it is represented in rttrash.. remove that now.
470                  */
471                 V_rttrash--;
472 #ifdef  DIAGNOSTIC
473                 if (rt->rt_refcnt < 0) {
474                         printf("rtfree: %p not freed (neg refs)\n", rt);
475                         goto done;
476                 }
477 #endif
478                 /*
479                  * release references on items we hold them on..
480                  * e.g other routes and ifaddrs.
481                  */
482                 if (rt->rt_ifa)
483                         ifa_free(rt->rt_ifa);
484                 /*
485                  * The key is separatly alloc'd so free it (see rt_setgate()).
486                  * This also frees the gateway, as they are always malloc'd
487                  * together.
488                  */
489                 Free(rt_key(rt));
490
491                 /*
492                  * and the rtentry itself of course
493                  */
494                 RT_LOCK_DESTROY(rt);
495                 uma_zfree(V_rtzone, rt);
496                 return;
497         }
498 done:
499         RT_UNLOCK(rt);
500 }
501
502
503 /*
504  * Force a routing table entry to the specified
505  * destination to go through the given gateway.
506  * Normally called as a result of a routing redirect
507  * message from the network layer.
508  */
509 void
510 rtredirect(struct sockaddr *dst,
511         struct sockaddr *gateway,
512         struct sockaddr *netmask,
513         int flags,
514         struct sockaddr *src)
515 {
516
517         rtredirect_fib(dst, gateway, netmask, flags, src, RT_DEFAULT_FIB);
518 }
519
520 void
521 rtredirect_fib(struct sockaddr *dst,
522         struct sockaddr *gateway,
523         struct sockaddr *netmask,
524         int flags,
525         struct sockaddr *src,
526         u_int fibnum)
527 {
528         struct rtentry *rt, *rt0 = NULL;
529         int error = 0;
530         short *stat = NULL;
531         struct rt_addrinfo info;
532         struct ifaddr *ifa;
533         struct radix_node_head *rnh;
534
535         ifa = NULL;
536         rnh = rt_tables_get_rnh(fibnum, dst->sa_family);
537         if (rnh == NULL) {
538                 error = EAFNOSUPPORT;
539                 goto out;
540         }
541
542         /* verify the gateway is directly reachable */
543         if ((ifa = ifa_ifwithnet(gateway, 0)) == NULL) {
544                 error = ENETUNREACH;
545                 goto out;
546         }
547         rt = rtalloc1_fib(dst, 0, 0UL, fibnum); /* NB: rt is locked */
548         /*
549          * If the redirect isn't from our current router for this dst,
550          * it's either old or wrong.  If it redirects us to ourselves,
551          * we have a routing loop, perhaps as a result of an interface
552          * going down recently.
553          */
554         if (!(flags & RTF_DONE) && rt &&
555              (!sa_equal(src, rt->rt_gateway) || rt->rt_ifa != ifa))
556                 error = EINVAL;
557         else if (ifa_ifwithaddr_check(gateway))
558                 error = EHOSTUNREACH;
559         if (error)
560                 goto done;
561         /*
562          * Create a new entry if we just got back a wildcard entry
563          * or the lookup failed.  This is necessary for hosts
564          * which use routing redirects generated by smart gateways
565          * to dynamically build the routing tables.
566          */
567         if (rt == NULL || (rt_mask(rt) && rt_mask(rt)->sa_len < 2))
568                 goto create;
569         /*
570          * Don't listen to the redirect if it's
571          * for a route to an interface.
572          */
573         if (rt->rt_flags & RTF_GATEWAY) {
574                 if (((rt->rt_flags & RTF_HOST) == 0) && (flags & RTF_HOST)) {
575                         /*
576                          * Changing from route to net => route to host.
577                          * Create new route, rather than smashing route to net.
578                          */
579                 create:
580                         rt0 = rt;
581                         rt = NULL;
582                 
583                         flags |=  RTF_GATEWAY | RTF_DYNAMIC;
584                         bzero((caddr_t)&info, sizeof(info));
585                         info.rti_info[RTAX_DST] = dst;
586                         info.rti_info[RTAX_GATEWAY] = gateway;
587                         info.rti_info[RTAX_NETMASK] = netmask;
588                         info.rti_ifa = ifa;
589                         info.rti_flags = flags;
590                         if (rt0 != NULL)
591                                 RT_UNLOCK(rt0); /* drop lock to avoid LOR with RNH */
592                         error = rtrequest1_fib(RTM_ADD, &info, &rt, fibnum);
593                         if (rt != NULL) {
594                                 RT_LOCK(rt);
595                                 if (rt0 != NULL)
596                                         EVENTHANDLER_INVOKE(route_redirect_event, rt0, rt, dst);
597                                 flags = rt->rt_flags;
598                         }
599                         if (rt0 != NULL)
600                                 RTFREE(rt0);
601                         
602                         stat = &V_rtstat.rts_dynamic;
603                 } else {
604                         struct rtentry *gwrt;
605
606                         /*
607                          * Smash the current notion of the gateway to
608                          * this destination.  Should check about netmask!!!
609                          */
610                         rt->rt_flags |= RTF_MODIFIED;
611                         flags |= RTF_MODIFIED;
612                         stat = &V_rtstat.rts_newgateway;
613                         /*
614                          * add the key and gateway (in one malloc'd chunk).
615                          */
616                         RT_UNLOCK(rt);
617                         RADIX_NODE_HEAD_LOCK(rnh);
618                         RT_LOCK(rt);
619                         rt_setgate(rt, rt_key(rt), gateway);
620                         gwrt = rtalloc1(gateway, 1, RTF_RNH_LOCKED);
621                         RADIX_NODE_HEAD_UNLOCK(rnh);
622                         EVENTHANDLER_INVOKE(route_redirect_event, rt, gwrt, dst);
623                         RTFREE_LOCKED(gwrt);
624                 }
625         } else
626                 error = EHOSTUNREACH;
627 done:
628         if (rt)
629                 RTFREE_LOCKED(rt);
630 out:
631         if (error)
632                 V_rtstat.rts_badredirect++;
633         else if (stat != NULL)
634                 (*stat)++;
635         bzero((caddr_t)&info, sizeof(info));
636         info.rti_info[RTAX_DST] = dst;
637         info.rti_info[RTAX_GATEWAY] = gateway;
638         info.rti_info[RTAX_NETMASK] = netmask;
639         info.rti_info[RTAX_AUTHOR] = src;
640         rt_missmsg_fib(RTM_REDIRECT, &info, flags, error, fibnum);
641         if (ifa != NULL)
642                 ifa_free(ifa);
643 }
644
645 int
646 rtioctl(u_long req, caddr_t data)
647 {
648
649         return (rtioctl_fib(req, data, RT_DEFAULT_FIB));
650 }
651
652 /*
653  * Routing table ioctl interface.
654  */
655 int
656 rtioctl_fib(u_long req, caddr_t data, u_int fibnum)
657 {
658
659         /*
660          * If more ioctl commands are added here, make sure the proper
661          * super-user checks are being performed because it is possible for
662          * prison-root to make it this far if raw sockets have been enabled
663          * in jails.
664          */
665 #ifdef INET
666         /* Multicast goop, grrr... */
667         return mrt_ioctl ? mrt_ioctl(req, data, fibnum) : EOPNOTSUPP;
668 #else /* INET */
669         return ENXIO;
670 #endif /* INET */
671 }
672
673 /*
674  * For both ifa_ifwithroute() routines, 'ifa' is returned referenced.
675  */
676 struct ifaddr *
677 ifa_ifwithroute(int flags, struct sockaddr *dst, struct sockaddr *gateway)
678 {
679
680         return (ifa_ifwithroute_fib(flags, dst, gateway, RT_DEFAULT_FIB));
681 }
682
683 struct ifaddr *
684 ifa_ifwithroute_fib(int flags, struct sockaddr *dst, struct sockaddr *gateway,
685                                 u_int fibnum)
686 {
687         register struct ifaddr *ifa;
688         int not_found = 0;
689
690         if ((flags & RTF_GATEWAY) == 0) {
691                 /*
692                  * If we are adding a route to an interface,
693                  * and the interface is a pt to pt link
694                  * we should search for the destination
695                  * as our clue to the interface.  Otherwise
696                  * we can use the local address.
697                  */
698                 ifa = NULL;
699                 if (flags & RTF_HOST)
700                         ifa = ifa_ifwithdstaddr(dst);
701                 if (ifa == NULL)
702                         ifa = ifa_ifwithaddr(gateway);
703         } else {
704                 /*
705                  * If we are adding a route to a remote net
706                  * or host, the gateway may still be on the
707                  * other end of a pt to pt link.
708                  */
709                 ifa = ifa_ifwithdstaddr(gateway);
710         }
711         if (ifa == NULL)
712                 ifa = ifa_ifwithnet(gateway, 0);
713         if (ifa == NULL) {
714                 struct rtentry *rt = rtalloc1_fib(gateway, 0, RTF_RNH_LOCKED, fibnum);
715                 if (rt == NULL)
716                         return (NULL);
717                 /*
718                  * dismiss a gateway that is reachable only
719                  * through the default router
720                  */
721                 switch (gateway->sa_family) {
722                 case AF_INET:
723                         if (satosin(rt_key(rt))->sin_addr.s_addr == INADDR_ANY)
724                                 not_found = 1;
725                         break;
726                 case AF_INET6:
727                         if (IN6_IS_ADDR_UNSPECIFIED(&satosin6(rt_key(rt))->sin6_addr))
728                                 not_found = 1;
729                         break;
730                 default:
731                         break;
732                 }
733                 if (!not_found && rt->rt_ifa != NULL) {
734                         ifa = rt->rt_ifa;
735                         ifa_ref(ifa);
736                 }
737                 RT_REMREF(rt);
738                 RT_UNLOCK(rt);
739                 if (not_found || ifa == NULL)
740                         return (NULL);
741         }
742         if (ifa->ifa_addr->sa_family != dst->sa_family) {
743                 struct ifaddr *oifa = ifa;
744                 ifa = ifaof_ifpforaddr(dst, ifa->ifa_ifp);
745                 if (ifa == NULL)
746                         ifa = oifa;
747                 else
748                         ifa_free(oifa);
749         }
750         return (ifa);
751 }
752
753 /*
754  * Do appropriate manipulations of a routing tree given
755  * all the bits of info needed
756  */
757 int
758 rtrequest(int req,
759         struct sockaddr *dst,
760         struct sockaddr *gateway,
761         struct sockaddr *netmask,
762         int flags,
763         struct rtentry **ret_nrt)
764 {
765
766         return (rtrequest_fib(req, dst, gateway, netmask, flags, ret_nrt,
767             RT_DEFAULT_FIB));
768 }
769
770 int
771 rtrequest_fib(int req,
772         struct sockaddr *dst,
773         struct sockaddr *gateway,
774         struct sockaddr *netmask,
775         int flags,
776         struct rtentry **ret_nrt,
777         u_int fibnum)
778 {
779         struct rt_addrinfo info;
780
781         if (dst->sa_len == 0)
782                 return(EINVAL);
783
784         bzero((caddr_t)&info, sizeof(info));
785         info.rti_flags = flags;
786         info.rti_info[RTAX_DST] = dst;
787         info.rti_info[RTAX_GATEWAY] = gateway;
788         info.rti_info[RTAX_NETMASK] = netmask;
789         return rtrequest1_fib(req, &info, ret_nrt, fibnum);
790 }
791
792 /*
793  * These (questionable) definitions of apparent local variables apply
794  * to the next two functions.  XXXXXX!!!
795  */
796 #define dst     info->rti_info[RTAX_DST]
797 #define gateway info->rti_info[RTAX_GATEWAY]
798 #define netmask info->rti_info[RTAX_NETMASK]
799 #define ifaaddr info->rti_info[RTAX_IFA]
800 #define ifpaddr info->rti_info[RTAX_IFP]
801 #define flags   info->rti_flags
802
803 int
804 rt_getifa(struct rt_addrinfo *info)
805 {
806
807         return (rt_getifa_fib(info, RT_DEFAULT_FIB));
808 }
809
810 /*
811  * Look up rt_addrinfo for a specific fib.  Note that if rti_ifa is defined,
812  * it will be referenced so the caller must free it.
813  */
814 int
815 rt_getifa_fib(struct rt_addrinfo *info, u_int fibnum)
816 {
817         struct ifaddr *ifa;
818         int error = 0;
819
820         /*
821          * ifp may be specified by sockaddr_dl
822          * when protocol address is ambiguous.
823          */
824         if (info->rti_ifp == NULL && ifpaddr != NULL &&
825             ifpaddr->sa_family == AF_LINK &&
826             (ifa = ifa_ifwithnet(ifpaddr, 0)) != NULL) {
827                 info->rti_ifp = ifa->ifa_ifp;
828                 ifa_free(ifa);
829         }
830         if (info->rti_ifa == NULL && ifaaddr != NULL)
831                 info->rti_ifa = ifa_ifwithaddr(ifaaddr);
832         if (info->rti_ifa == NULL) {
833                 struct sockaddr *sa;
834
835                 sa = ifaaddr != NULL ? ifaaddr :
836                     (gateway != NULL ? gateway : dst);
837                 if (sa != NULL && info->rti_ifp != NULL)
838                         info->rti_ifa = ifaof_ifpforaddr(sa, info->rti_ifp);
839                 else if (dst != NULL && gateway != NULL)
840                         info->rti_ifa = ifa_ifwithroute_fib(flags, dst, gateway,
841                                                         fibnum);
842                 else if (sa != NULL)
843                         info->rti_ifa = ifa_ifwithroute_fib(flags, sa, sa,
844                                                         fibnum);
845         }
846         if ((ifa = info->rti_ifa) != NULL) {
847                 if (info->rti_ifp == NULL)
848                         info->rti_ifp = ifa->ifa_ifp;
849         } else
850                 error = ENETUNREACH;
851         return (error);
852 }
853
854 /*
855  * Expunges references to a route that's about to be reclaimed.
856  * The route must be locked.
857  */
858 int
859 rtexpunge(struct rtentry *rt)
860 {
861 #if !defined(RADIX_MPATH)
862         struct radix_node *rn;
863 #else
864         struct rt_addrinfo info;
865         int fib;
866         struct rtentry *rt0;
867 #endif
868         struct radix_node_head *rnh;
869         struct ifaddr *ifa;
870         int error = 0;
871
872         /*
873          * Find the correct routing tree to use for this Address Family
874          */
875         rnh = rt_tables_get_rnh(rt->rt_fibnum, rt_key(rt)->sa_family);
876         RT_LOCK_ASSERT(rt);
877         if (rnh == NULL)
878                 return (EAFNOSUPPORT);
879         RADIX_NODE_HEAD_LOCK_ASSERT(rnh);
880
881 #ifdef RADIX_MPATH
882         fib = rt->rt_fibnum;
883         bzero(&info, sizeof(info));
884         info.rti_ifp = rt->rt_ifp;
885         info.rti_flags = RTF_RNH_LOCKED;
886         info.rti_info[RTAX_DST] = rt_key(rt);
887         info.rti_info[RTAX_GATEWAY] = rt->rt_ifa->ifa_addr;
888
889         RT_UNLOCK(rt);
890         error = rtrequest1_fib(RTM_DELETE, &info, &rt0, fib);
891
892         if (error == 0 && rt0 != NULL) {
893                 rt = rt0;
894                 RT_LOCK(rt);
895         } else if (error != 0) {
896                 RT_LOCK(rt);
897                 return (error);
898         }
899 #else
900         /*
901          * Remove the item from the tree; it should be there,
902          * but when callers invoke us blindly it may not (sigh).
903          */
904         rn = rnh->rnh_deladdr(rt_key(rt), rt_mask(rt), rnh);
905         if (rn == NULL) {
906                 error = ESRCH;
907                 goto bad;
908         }
909         KASSERT((rn->rn_flags & (RNF_ACTIVE | RNF_ROOT)) == 0,
910                 ("unexpected flags 0x%x", rn->rn_flags));
911         KASSERT(rt == RNTORT(rn),
912                 ("lookup mismatch, rt %p rn %p", rt, rn));
913 #endif /* RADIX_MPATH */
914
915         rt->rt_flags &= ~RTF_UP;
916
917         /*
918          * Give the protocol a chance to keep things in sync.
919          */
920         if ((ifa = rt->rt_ifa) && ifa->ifa_rtrequest) {
921                 struct rt_addrinfo info;
922
923                 bzero((caddr_t)&info, sizeof(info));
924                 info.rti_flags = rt->rt_flags;
925                 info.rti_info[RTAX_DST] = rt_key(rt);
926                 info.rti_info[RTAX_GATEWAY] = rt->rt_gateway;
927                 info.rti_info[RTAX_NETMASK] = rt_mask(rt);
928                 ifa->ifa_rtrequest(RTM_DELETE, rt, &info);
929         }
930
931         /*
932          * one more rtentry floating around that is not
933          * linked to the routing table.
934          */
935         V_rttrash++;
936 #if !defined(RADIX_MPATH)
937 bad:
938 #endif
939         return (error);
940 }
941
942 #if 0
943 int p_sockaddr(char *buf, int buflen, struct sockaddr *s);
944 int rt_print(char *buf, int buflen, struct rtentry *rt);
945
946 int
947 p_sockaddr(char *buf, int buflen, struct sockaddr *s)
948 {
949         void *paddr = NULL;
950
951         switch (s->sa_family) {
952         case AF_INET:
953                 paddr = &((struct sockaddr_in *)s)->sin_addr;
954                 break;
955         case AF_INET6:
956                 paddr = &((struct sockaddr_in6 *)s)->sin6_addr;
957                 break;
958         }
959
960         if (paddr == NULL)
961                 return (0);
962
963         if (inet_ntop(s->sa_family, paddr, buf, buflen) == NULL)
964                 return (0);
965         
966         return (strlen(buf));
967 }
968
969 int
970 rt_print(char *buf, int buflen, struct rtentry *rt)
971 {
972         struct sockaddr *addr, *mask;
973         int i = 0;
974
975         addr = rt_key(rt);
976         mask = rt_mask(rt);
977
978         i = p_sockaddr(buf, buflen, addr);
979         if (!(rt->rt_flags & RTF_HOST)) {
980                 buf[i++] = '/';
981                 i += p_sockaddr(buf + i, buflen - i, mask);
982         }
983
984         if (rt->rt_flags & RTF_GATEWAY) {
985                 buf[i++] = '>';
986                 i += p_sockaddr(buf + i, buflen - i, rt->rt_gateway);
987         }
988
989         return (i);
990 }
991 #endif
992
993 #ifdef RADIX_MPATH
994 static int
995 rn_mpath_update(int req, struct rt_addrinfo *info,
996     struct radix_node_head *rnh, struct rtentry **ret_nrt)
997 {
998         /*
999          * if we got multipath routes, we require users to specify
1000          * a matching RTAX_GATEWAY.
1001          */
1002         struct rtentry *rt, *rto = NULL;
1003         struct radix_node *rn;
1004         int error = 0;
1005
1006         RADIX_NODE_HEAD_LOCK_ASSERT(rnh);
1007         rn = rnh->rnh_lookup(dst, netmask, rnh);
1008         if (rn == NULL)
1009                 return (ESRCH);
1010         rto = rt = RNTORT(rn);
1011
1012         rt = rt_mpath_matchgate(rt, gateway);
1013         if (rt == NULL)
1014                 return (ESRCH);
1015         /*
1016          * this is the first entry in the chain
1017          */
1018         if (rto == rt) {
1019                 rn = rn_mpath_next((struct radix_node *)rt);
1020                 /*
1021                  * there is another entry, now it's active
1022                  */
1023                 if (rn) {
1024                         rto = RNTORT(rn);
1025                         RT_LOCK(rto);
1026                         rto->rt_flags |= RTF_UP;
1027                         RT_UNLOCK(rto);
1028                 } else if (rt->rt_flags & RTF_GATEWAY) {
1029                         /*
1030                          * For gateway routes, we need to 
1031                          * make sure that we we are deleting
1032                          * the correct gateway. 
1033                          * rt_mpath_matchgate() does not 
1034                          * check the case when there is only
1035                          * one route in the chain.  
1036                          */
1037                         if (gateway &&
1038                             (rt->rt_gateway->sa_len != gateway->sa_len ||
1039                                 memcmp(rt->rt_gateway, gateway, gateway->sa_len)))
1040                                 error = ESRCH;
1041                         else {
1042                                 /*
1043                                  * remove from tree before returning it
1044                                  * to the caller
1045                                  */
1046                                 rn = rnh->rnh_deladdr(dst, netmask, rnh);
1047                                 KASSERT(rt == RNTORT(rn), ("radix node disappeared"));
1048                                 goto gwdelete;
1049                         }
1050                         
1051                 }
1052                 /*
1053                  * use the normal delete code to remove
1054                  * the first entry
1055                  */
1056                 if (req != RTM_DELETE) 
1057                         goto nondelete;
1058
1059                 error = ENOENT;
1060                 goto done;
1061         }
1062                 
1063         /*
1064          * if the entry is 2nd and on up
1065          */
1066         if ((req == RTM_DELETE) && !rt_mpath_deldup(rto, rt))
1067                 panic ("rtrequest1: rt_mpath_deldup");
1068 gwdelete:
1069         RT_LOCK(rt);
1070         RT_ADDREF(rt);
1071         if (req == RTM_DELETE) {
1072                 rt->rt_flags &= ~RTF_UP;
1073                 /*
1074                  * One more rtentry floating around that is not
1075                  * linked to the routing table. rttrash will be decremented
1076                  * when RTFREE(rt) is eventually called.
1077                  */
1078                 V_rttrash++;
1079         }
1080         
1081 nondelete:
1082         if (req != RTM_DELETE)
1083                 panic("unrecognized request %d", req);
1084         
1085
1086         /*
1087          * If the caller wants it, then it can have it,
1088          * but it's up to it to free the rtentry as we won't be
1089          * doing it.
1090          */
1091         if (ret_nrt) {
1092                 *ret_nrt = rt;
1093                 RT_UNLOCK(rt);
1094         } else
1095                 RTFREE_LOCKED(rt);
1096 done:
1097         return (error);
1098 }
1099 #endif
1100
1101 int
1102 rtrequest1_fib(int req, struct rt_addrinfo *info, struct rtentry **ret_nrt,
1103                                 u_int fibnum)
1104 {
1105         int error = 0, needlock = 0;
1106         register struct rtentry *rt;
1107 #ifdef FLOWTABLE
1108         register struct rtentry *rt0;
1109 #endif
1110         register struct radix_node *rn;
1111         register struct radix_node_head *rnh;
1112         struct ifaddr *ifa;
1113         struct sockaddr *ndst;
1114         struct sockaddr_storage mdst;
1115 #define senderr(x) { error = x ; goto bad; }
1116
1117         KASSERT((fibnum < rt_numfibs), ("rtrequest1_fib: bad fibnum"));
1118         switch (dst->sa_family) {
1119         case AF_INET6:
1120         case AF_INET:
1121                 /* We support multiple FIBs. */
1122                 break;
1123         default:
1124                 fibnum = RT_DEFAULT_FIB;
1125                 break;
1126         }
1127
1128         /*
1129          * Find the correct routing tree to use for this Address Family
1130          */
1131         rnh = rt_tables_get_rnh(fibnum, dst->sa_family);
1132         if (rnh == NULL)
1133                 return (EAFNOSUPPORT);
1134         needlock = ((flags & RTF_RNH_LOCKED) == 0);
1135         flags &= ~RTF_RNH_LOCKED;
1136         if (needlock)
1137                 RADIX_NODE_HEAD_LOCK(rnh);
1138         else
1139                 RADIX_NODE_HEAD_LOCK_ASSERT(rnh);
1140         /*
1141          * If we are adding a host route then we don't want to put
1142          * a netmask in the tree, nor do we want to clone it.
1143          */
1144         if (flags & RTF_HOST)
1145                 netmask = NULL;
1146
1147         switch (req) {
1148         case RTM_DELETE:
1149                 if (netmask) {
1150                         rt_maskedcopy(dst, (struct sockaddr *)&mdst, netmask);
1151                         dst = (struct sockaddr *)&mdst;
1152                 }
1153 #ifdef RADIX_MPATH
1154                 if (rn_mpath_capable(rnh)) {
1155                         error = rn_mpath_update(req, info, rnh, ret_nrt);
1156                         /*
1157                          * "bad" holds true for the success case
1158                          * as well
1159                          */
1160                         if (error != ENOENT)
1161                                 goto bad;
1162                         error = 0;
1163                 }
1164 #endif
1165                 if ((flags & RTF_PINNED) == 0) {
1166                         /* Check if target route can be deleted */
1167                         rt = (struct rtentry *)rnh->rnh_lookup(dst,
1168                             netmask, rnh);
1169                         if ((rt != NULL) && (rt->rt_flags & RTF_PINNED))
1170                                 senderr(EADDRINUSE);
1171                 }
1172
1173                 /*
1174                  * Remove the item from the tree and return it.
1175                  * Complain if it is not there and do no more processing.
1176                  */
1177                 rn = rnh->rnh_deladdr(dst, netmask, rnh);
1178                 if (rn == NULL)
1179                         senderr(ESRCH);
1180                 if (rn->rn_flags & (RNF_ACTIVE | RNF_ROOT))
1181                         panic ("rtrequest delete");
1182                 rt = RNTORT(rn);
1183                 RT_LOCK(rt);
1184                 RT_ADDREF(rt);
1185                 rt->rt_flags &= ~RTF_UP;
1186
1187                 /*
1188                  * give the protocol a chance to keep things in sync.
1189                  */
1190                 if ((ifa = rt->rt_ifa) && ifa->ifa_rtrequest)
1191                         ifa->ifa_rtrequest(RTM_DELETE, rt, info);
1192
1193                 /*
1194                  * One more rtentry floating around that is not
1195                  * linked to the routing table. rttrash will be decremented
1196                  * when RTFREE(rt) is eventually called.
1197                  */
1198                 V_rttrash++;
1199
1200                 /*
1201                  * If the caller wants it, then it can have it,
1202                  * but it's up to it to free the rtentry as we won't be
1203                  * doing it.
1204                  */
1205                 if (ret_nrt) {
1206                         *ret_nrt = rt;
1207                         RT_UNLOCK(rt);
1208                 } else
1209                         RTFREE_LOCKED(rt);
1210                 break;
1211         case RTM_RESOLVE:
1212                 /*
1213                  * resolve was only used for route cloning
1214                  * here for compat
1215                  */
1216                 break;
1217         case RTM_ADD:
1218                 if ((flags & RTF_GATEWAY) && !gateway)
1219                         senderr(EINVAL);
1220                 if (dst && gateway && (dst->sa_family != gateway->sa_family) && 
1221                     (gateway->sa_family != AF_UNSPEC) && (gateway->sa_family != AF_LINK))
1222                         senderr(EINVAL);
1223
1224                 if (info->rti_ifa == NULL) {
1225                         error = rt_getifa_fib(info, fibnum);
1226                         if (error)
1227                                 senderr(error);
1228                 } else
1229                         ifa_ref(info->rti_ifa);
1230                 ifa = info->rti_ifa;
1231                 rt = uma_zalloc(V_rtzone, M_NOWAIT | M_ZERO);
1232                 if (rt == NULL) {
1233                         ifa_free(ifa);
1234                         senderr(ENOBUFS);
1235                 }
1236                 RT_LOCK_INIT(rt);
1237                 rt->rt_flags = RTF_UP | flags;
1238                 rt->rt_fibnum = fibnum;
1239                 /*
1240                  * Add the gateway. Possibly re-malloc-ing the storage for it.
1241                  */
1242                 RT_LOCK(rt);
1243                 if ((error = rt_setgate(rt, dst, gateway)) != 0) {
1244                         RT_LOCK_DESTROY(rt);
1245                         ifa_free(ifa);
1246                         uma_zfree(V_rtzone, rt);
1247                         senderr(error);
1248                 }
1249
1250                 /*
1251                  * point to the (possibly newly malloc'd) dest address.
1252                  */
1253                 ndst = (struct sockaddr *)rt_key(rt);
1254
1255                 /*
1256                  * make sure it contains the value we want (masked if needed).
1257                  */
1258                 if (netmask) {
1259                         rt_maskedcopy(dst, ndst, netmask);
1260                 } else
1261                         bcopy(dst, ndst, dst->sa_len);
1262
1263                 /*
1264                  * We use the ifa reference returned by rt_getifa_fib().
1265                  * This moved from below so that rnh->rnh_addaddr() can
1266                  * examine the ifa and  ifa->ifa_ifp if it so desires.
1267                  */
1268                 rt->rt_ifa = ifa;
1269                 rt->rt_ifp = ifa->ifa_ifp;
1270                 rt->rt_rmx.rmx_weight = 1;
1271
1272 #ifdef RADIX_MPATH
1273                 /* do not permit exactly the same dst/mask/gw pair */
1274                 if (rn_mpath_capable(rnh) &&
1275                         rt_mpath_conflict(rnh, rt, netmask)) {
1276                         ifa_free(rt->rt_ifa);
1277                         Free(rt_key(rt));
1278                         RT_LOCK_DESTROY(rt);
1279                         uma_zfree(V_rtzone, rt);
1280                         senderr(EEXIST);
1281                 }
1282 #endif
1283
1284 #ifdef FLOWTABLE
1285                 rt0 = NULL;
1286                 /* "flow-table" only supports IPv6 and IPv4 at the moment. */
1287                 switch (dst->sa_family) {
1288 #ifdef INET6
1289                 case AF_INET6:
1290 #endif
1291 #ifdef INET
1292                 case AF_INET:
1293 #endif
1294 #if defined(INET6) || defined(INET)
1295                         rn = rnh->rnh_matchaddr(dst, rnh);
1296                         if (rn && ((rn->rn_flags & RNF_ROOT) == 0)) {
1297                                 struct sockaddr *mask;
1298                                 u_char *m, *n;
1299                                 int len;
1300                                 
1301                                 /*
1302                                  * compare mask to see if the new route is
1303                                  * more specific than the existing one
1304                                  */
1305                                 rt0 = RNTORT(rn);
1306                                 RT_LOCK(rt0);
1307                                 RT_ADDREF(rt0);
1308                                 RT_UNLOCK(rt0);
1309                                 /*
1310                                  * A host route is already present, so 
1311                                  * leave the flow-table entries as is.
1312                                  */
1313                                 if (rt0->rt_flags & RTF_HOST) {
1314                                         RTFREE(rt0);
1315                                         rt0 = NULL;
1316                                 } else if (!(flags & RTF_HOST) && netmask) {
1317                                         mask = rt_mask(rt0);
1318                                         len = mask->sa_len;
1319                                         m = (u_char *)mask;
1320                                         n = (u_char *)netmask;
1321                                         while (len-- > 0) {
1322                                                 if (*n != *m)
1323                                                         break;
1324                                                 n++;
1325                                                 m++;
1326                                         }
1327                                         if (len == 0 || (*n < *m)) {
1328                                                 RTFREE(rt0);
1329                                                 rt0 = NULL;
1330                                         }
1331                                 }
1332                         }
1333 #endif/* INET6 || INET */
1334                 }
1335 #endif /* FLOWTABLE */
1336
1337                 /* XXX mtu manipulation will be done in rnh_addaddr -- itojun */
1338                 rn = rnh->rnh_addaddr(ndst, netmask, rnh, rt->rt_nodes);
1339                 /*
1340                  * If it still failed to go into the tree,
1341                  * then un-make it (this should be a function)
1342                  */
1343                 if (rn == NULL) {
1344                         ifa_free(rt->rt_ifa);
1345                         Free(rt_key(rt));
1346                         RT_LOCK_DESTROY(rt);
1347                         uma_zfree(V_rtzone, rt);
1348 #ifdef FLOWTABLE
1349                         if (rt0 != NULL)
1350                                 RTFREE(rt0);
1351 #endif
1352                         senderr(EEXIST);
1353                 } 
1354 #ifdef FLOWTABLE
1355                 else if (rt0 != NULL) {
1356                         flowtable_route_flush(dst->sa_family, rt0);
1357                         RTFREE(rt0);
1358                 }
1359 #endif
1360
1361                 /*
1362                  * If this protocol has something to add to this then
1363                  * allow it to do that as well.
1364                  */
1365                 if (ifa->ifa_rtrequest)
1366                         ifa->ifa_rtrequest(req, rt, info);
1367
1368                 /*
1369                  * actually return a resultant rtentry and
1370                  * give the caller a single reference.
1371                  */
1372                 if (ret_nrt) {
1373                         *ret_nrt = rt;
1374                         RT_ADDREF(rt);
1375                 }
1376                 RT_UNLOCK(rt);
1377                 break;
1378         default:
1379                 error = EOPNOTSUPP;
1380         }
1381 bad:
1382         if (needlock)
1383                 RADIX_NODE_HEAD_UNLOCK(rnh);
1384         return (error);
1385 #undef senderr
1386 }
1387
1388 #undef dst
1389 #undef gateway
1390 #undef netmask
1391 #undef ifaaddr
1392 #undef ifpaddr
1393 #undef flags
1394
1395 int
1396 rt_setgate(struct rtentry *rt, struct sockaddr *dst, struct sockaddr *gate)
1397 {
1398         /* XXX dst may be overwritten, can we move this to below */
1399         int dlen = SA_SIZE(dst), glen = SA_SIZE(gate);
1400 #ifdef INVARIANTS
1401         struct radix_node_head *rnh;
1402
1403         rnh = rt_tables_get_rnh(rt->rt_fibnum, dst->sa_family);
1404 #endif
1405
1406         RT_LOCK_ASSERT(rt);
1407         RADIX_NODE_HEAD_LOCK_ASSERT(rnh);
1408         
1409         /*
1410          * Prepare to store the gateway in rt->rt_gateway.
1411          * Both dst and gateway are stored one after the other in the same
1412          * malloc'd chunk. If we have room, we can reuse the old buffer,
1413          * rt_gateway already points to the right place.
1414          * Otherwise, malloc a new block and update the 'dst' address.
1415          */
1416         if (rt->rt_gateway == NULL || glen > SA_SIZE(rt->rt_gateway)) {
1417                 caddr_t new;
1418
1419                 R_Malloc(new, caddr_t, dlen + glen);
1420                 if (new == NULL)
1421                         return ENOBUFS;
1422                 /*
1423                  * XXX note, we copy from *dst and not *rt_key(rt) because
1424                  * rt_setgate() can be called to initialize a newly
1425                  * allocated route entry, in which case rt_key(rt) == NULL
1426                  * (and also rt->rt_gateway == NULL).
1427                  * Free()/free() handle a NULL argument just fine.
1428                  */
1429                 bcopy(dst, new, dlen);
1430                 Free(rt_key(rt));       /* free old block, if any */
1431                 rt_key(rt) = (struct sockaddr *)new;
1432                 rt->rt_gateway = (struct sockaddr *)(new + dlen);
1433         }
1434
1435         /*
1436          * Copy the new gateway value into the memory chunk.
1437          */
1438         bcopy(gate, rt->rt_gateway, glen);
1439
1440         return (0);
1441 }
1442
1443 void
1444 rt_maskedcopy(struct sockaddr *src, struct sockaddr *dst, struct sockaddr *netmask)
1445 {
1446         register u_char *cp1 = (u_char *)src;
1447         register u_char *cp2 = (u_char *)dst;
1448         register u_char *cp3 = (u_char *)netmask;
1449         u_char *cplim = cp2 + *cp3;
1450         u_char *cplim2 = cp2 + *cp1;
1451
1452         *cp2++ = *cp1++; *cp2++ = *cp1++; /* copies sa_len & sa_family */
1453         cp3 += 2;
1454         if (cplim > cplim2)
1455                 cplim = cplim2;
1456         while (cp2 < cplim)
1457                 *cp2++ = *cp1++ & *cp3++;
1458         if (cp2 < cplim2)
1459                 bzero((caddr_t)cp2, (unsigned)(cplim2 - cp2));
1460 }
1461
1462 /*
1463  * Set up a routing table entry, normally
1464  * for an interface.
1465  */
1466 #define _SOCKADDR_TMPSIZE 128 /* Not too big.. kernel stack size is limited */
1467 static inline  int
1468 rtinit1(struct ifaddr *ifa, int cmd, int flags, int fibnum)
1469 {
1470         struct sockaddr *dst;
1471         struct sockaddr *netmask;
1472         struct rtentry *rt = NULL;
1473         struct rt_addrinfo info;
1474         int error = 0;
1475         int startfib, endfib;
1476         char tempbuf[_SOCKADDR_TMPSIZE];
1477         int didwork = 0;
1478         int a_failure = 0;
1479         static struct sockaddr_dl null_sdl = {sizeof(null_sdl), AF_LINK};
1480         struct radix_node_head *rnh;
1481
1482         if (flags & RTF_HOST) {
1483                 dst = ifa->ifa_dstaddr;
1484                 netmask = NULL;
1485         } else {
1486                 dst = ifa->ifa_addr;
1487                 netmask = ifa->ifa_netmask;
1488         }
1489         if (dst->sa_len == 0)
1490                 return(EINVAL);
1491         switch (dst->sa_family) {
1492         case AF_INET6:
1493         case AF_INET:
1494                 /* We support multiple FIBs. */
1495                 break;
1496         default:
1497                 fibnum = RT_DEFAULT_FIB;
1498                 break;
1499         }
1500         if (fibnum == RT_ALL_FIBS) {
1501                 if (rt_add_addr_allfibs == 0 && cmd == (int)RTM_ADD) {
1502                         startfib = endfib = curthread->td_proc->p_fibnum;
1503                 } else {
1504                         startfib = 0;
1505                         endfib = rt_numfibs - 1;
1506                 }
1507         } else {
1508                 KASSERT((fibnum < rt_numfibs), ("rtinit1: bad fibnum"));
1509                 startfib = fibnum;
1510                 endfib = fibnum;
1511         }
1512
1513         /*
1514          * If it's a delete, check that if it exists,
1515          * it's on the correct interface or we might scrub
1516          * a route to another ifa which would
1517          * be confusing at best and possibly worse.
1518          */
1519         if (cmd == RTM_DELETE) {
1520                 /*
1521                  * It's a delete, so it should already exist..
1522                  * If it's a net, mask off the host bits
1523                  * (Assuming we have a mask)
1524                  * XXX this is kinda inet specific..
1525                  */
1526                 if (netmask != NULL) {
1527                         rt_maskedcopy(dst, (struct sockaddr *)tempbuf, netmask);
1528                         dst = (struct sockaddr *)tempbuf;
1529                 }
1530         }
1531         /*
1532          * Now go through all the requested tables (fibs) and do the
1533          * requested action. Realistically, this will either be fib 0
1534          * for protocols that don't do multiple tables or all the
1535          * tables for those that do.
1536          */
1537         for ( fibnum = startfib; fibnum <= endfib; fibnum++) {
1538                 if (cmd == RTM_DELETE) {
1539                         struct radix_node *rn;
1540                         /*
1541                          * Look up an rtentry that is in the routing tree and
1542                          * contains the correct info.
1543                          */
1544                         rnh = rt_tables_get_rnh(fibnum, dst->sa_family);
1545                         if (rnh == NULL)
1546                                 /* this table doesn't exist but others might */
1547                                 continue;
1548                         RADIX_NODE_HEAD_RLOCK(rnh);
1549                         rn = rnh->rnh_lookup(dst, netmask, rnh);
1550 #ifdef RADIX_MPATH
1551                         if (rn_mpath_capable(rnh)) {
1552
1553                                 if (rn == NULL) 
1554                                         error = ESRCH;
1555                                 else {
1556                                         rt = RNTORT(rn);
1557                                         /*
1558                                          * for interface route the
1559                                          * rt->rt_gateway is sockaddr_intf
1560                                          * for cloning ARP entries, so
1561                                          * rt_mpath_matchgate must use the
1562                                          * interface address
1563                                          */
1564                                         rt = rt_mpath_matchgate(rt,
1565                                             ifa->ifa_addr);
1566                                         if (rt == NULL) 
1567                                                 error = ESRCH;
1568                                 }
1569                         }
1570 #endif
1571                         error = (rn == NULL ||
1572                             (rn->rn_flags & RNF_ROOT) ||
1573                             RNTORT(rn)->rt_ifa != ifa);
1574                         RADIX_NODE_HEAD_RUNLOCK(rnh);
1575                         if (error) {
1576                                 /* this is only an error if bad on ALL tables */
1577                                 continue;
1578                         }
1579                 }
1580                 /*
1581                  * Do the actual request
1582                  */
1583                 bzero((caddr_t)&info, sizeof(info));
1584                 info.rti_ifa = ifa;
1585                 info.rti_flags = flags |
1586                     (ifa->ifa_flags & ~IFA_RTSELF) | RTF_PINNED;
1587                 info.rti_info[RTAX_DST] = dst;
1588                 /* 
1589                  * doing this for compatibility reasons
1590                  */
1591                 if (cmd == RTM_ADD)
1592                         info.rti_info[RTAX_GATEWAY] =
1593                             (struct sockaddr *)&null_sdl;
1594                 else
1595                         info.rti_info[RTAX_GATEWAY] = ifa->ifa_addr;
1596                 info.rti_info[RTAX_NETMASK] = netmask;
1597                 error = rtrequest1_fib(cmd, &info, &rt, fibnum);
1598
1599                 if ((error == EEXIST) && (cmd == RTM_ADD)) {
1600                         /*
1601                          * Interface route addition failed.
1602                          * Atomically delete current prefix generating
1603                          * RTM_DELETE message, and retry adding
1604                          * interface prefix.
1605                          */
1606                         rnh = rt_tables_get_rnh(fibnum, dst->sa_family);
1607                         RADIX_NODE_HEAD_LOCK(rnh);
1608
1609                         /* Delete old prefix */
1610                         info.rti_ifa = NULL;
1611                         info.rti_flags = RTF_RNH_LOCKED;
1612
1613                         error = rtrequest1_fib(RTM_DELETE, &info, NULL, fibnum);
1614                         if (error == 0) {
1615                                 info.rti_ifa = ifa;
1616                                 info.rti_flags = flags | RTF_RNH_LOCKED |
1617                                     (ifa->ifa_flags & ~IFA_RTSELF) | RTF_PINNED;
1618                                 error = rtrequest1_fib(cmd, &info, &rt, fibnum);
1619                         }
1620
1621                         RADIX_NODE_HEAD_UNLOCK(rnh);
1622                 }
1623
1624
1625                 if (error == 0 && rt != NULL) {
1626                         /*
1627                          * notify any listening routing agents of the change
1628                          */
1629                         RT_LOCK(rt);
1630 #ifdef RADIX_MPATH
1631                         /*
1632                          * in case address alias finds the first address
1633                          * e.g. ifconfig bge0 192.0.2.246/24
1634                          * e.g. ifconfig bge0 192.0.2.247/24
1635                          * the address set in the route is 192.0.2.246
1636                          * so we need to replace it with 192.0.2.247
1637                          */
1638                         if (memcmp(rt->rt_ifa->ifa_addr,
1639                             ifa->ifa_addr, ifa->ifa_addr->sa_len)) {
1640                                 ifa_free(rt->rt_ifa);
1641                                 ifa_ref(ifa);
1642                                 rt->rt_ifp = ifa->ifa_ifp;
1643                                 rt->rt_ifa = ifa;
1644                         }
1645 #endif
1646                         /* 
1647                          * doing this for compatibility reasons
1648                          */
1649                         if (cmd == RTM_ADD) {
1650                             ((struct sockaddr_dl *)rt->rt_gateway)->sdl_type  =
1651                                 rt->rt_ifp->if_type;
1652                             ((struct sockaddr_dl *)rt->rt_gateway)->sdl_index =
1653                                 rt->rt_ifp->if_index;
1654                         }
1655                         RT_ADDREF(rt);
1656                         RT_UNLOCK(rt);
1657                         rt_newaddrmsg_fib(cmd, ifa, error, rt, fibnum);
1658                         RT_LOCK(rt);
1659                         RT_REMREF(rt);
1660                         if (cmd == RTM_DELETE) {
1661                                 /*
1662                                  * If we are deleting, and we found an entry,
1663                                  * then it's been removed from the tree..
1664                                  * now throw it away.
1665                                  */
1666                                 RTFREE_LOCKED(rt);
1667                         } else {
1668                                 if (cmd == RTM_ADD) {
1669                                         /*
1670                                          * We just wanted to add it..
1671                                          * we don't actually need a reference.
1672                                          */
1673                                         RT_REMREF(rt);
1674                                 }
1675                                 RT_UNLOCK(rt);
1676                         }
1677                         didwork = 1;
1678                 }
1679                 if (error)
1680                         a_failure = error;
1681         }
1682         if (cmd == RTM_DELETE) {
1683                 if (didwork) {
1684                         error = 0;
1685                 } else {
1686                         /* we only give an error if it wasn't in any table */
1687                         error = ((flags & RTF_HOST) ?
1688                             EHOSTUNREACH : ENETUNREACH);
1689                 }
1690         } else {
1691                 if (a_failure) {
1692                         /* return an error if any of them failed */
1693                         error = a_failure;
1694                 }
1695         }
1696         return (error);
1697 }
1698
1699 #ifndef BURN_BRIDGES
1700 /* special one for inet internal use. may not use. */
1701 int
1702 rtinit_fib(struct ifaddr *ifa, int cmd, int flags)
1703 {
1704         return (rtinit1(ifa, cmd, flags, RT_ALL_FIBS));
1705 }
1706 #endif
1707
1708 /*
1709  * Set up a routing table entry, normally
1710  * for an interface.
1711  */
1712 int
1713 rtinit(struct ifaddr *ifa, int cmd, int flags)
1714 {
1715         struct sockaddr *dst;
1716         int fib = RT_DEFAULT_FIB;
1717
1718         if (flags & RTF_HOST) {
1719                 dst = ifa->ifa_dstaddr;
1720         } else {
1721                 dst = ifa->ifa_addr;
1722         }
1723
1724         switch (dst->sa_family) {
1725         case AF_INET6:
1726         case AF_INET:
1727                 /* We do support multiple FIBs. */
1728                 fib = RT_ALL_FIBS;
1729                 break;
1730         }
1731         return (rtinit1(ifa, cmd, flags, fib));
1732 }
1733
1734 /*
1735  * Announce interface address arrival/withdraw
1736  * Returns 0 on success.
1737  */
1738 int
1739 rt_addrmsg(int cmd, struct ifaddr *ifa, int fibnum)
1740 {
1741
1742         KASSERT(cmd == RTM_ADD || cmd == RTM_DELETE,
1743             ("unexpected cmd %d", cmd));
1744         
1745         KASSERT(fibnum == RT_ALL_FIBS || (fibnum >= 0 && fibnum < rt_numfibs),
1746             ("%s: fib out of range 0 <=%d<%d", __func__, fibnum, rt_numfibs));
1747
1748         return (rtsock_addrmsg(cmd, ifa, fibnum));
1749 }
1750
1751 /*
1752  * Announce route addition/removal.
1753  * Users of this function MUST validate input data BEFORE calling.
1754  * However we have to be able to handle invalid data:
1755  * if some userland app sends us "invalid" route message (invalid mask,
1756  * no dst, wrong address families, etc...) we need to pass it back
1757  * to app (and any other rtsock consumers) with rtm_errno field set to
1758  * non-zero value.
1759  * Returns 0 on success.
1760  */
1761 int
1762 rt_routemsg(int cmd, struct ifnet *ifp, int error, struct rtentry *rt,
1763     int fibnum)
1764 {
1765
1766         KASSERT(cmd == RTM_ADD || cmd == RTM_DELETE,
1767             ("unexpected cmd %d", cmd));
1768         
1769         KASSERT(fibnum == RT_ALL_FIBS || (fibnum >= 0 && fibnum < rt_numfibs),
1770             ("%s: fib out of range 0 <=%d<%d", __func__, fibnum, rt_numfibs));
1771
1772         KASSERT(rt_key(rt) != NULL, (":%s: rt_key must be supplied", __func__));
1773
1774         return (rtsock_routemsg(cmd, ifp, error, rt, fibnum));
1775 }
1776
1777 void
1778 rt_newaddrmsg(int cmd, struct ifaddr *ifa, int error, struct rtentry *rt)
1779 {
1780
1781         rt_newaddrmsg_fib(cmd, ifa, error, rt, RT_ALL_FIBS);
1782 }
1783
1784 /*
1785  * This is called to generate messages from the routing socket
1786  * indicating a network interface has had addresses associated with it.
1787  */
1788 void
1789 rt_newaddrmsg_fib(int cmd, struct ifaddr *ifa, int error, struct rtentry *rt,
1790     int fibnum)
1791 {
1792
1793         KASSERT(cmd == RTM_ADD || cmd == RTM_DELETE,
1794                 ("unexpected cmd %u", cmd));
1795         KASSERT(fibnum == RT_ALL_FIBS || (fibnum >= 0 && fibnum < rt_numfibs),
1796             ("%s: fib out of range 0 <=%d<%d", __func__, fibnum, rt_numfibs));
1797
1798 #if defined(INET) || defined(INET6)
1799 #ifdef SCTP
1800         /*
1801          * notify the SCTP stack
1802          * this will only get called when an address is added/deleted
1803          * XXX pass the ifaddr struct instead if ifa->ifa_addr...
1804          */
1805         sctp_addr_change(ifa, cmd);
1806 #endif /* SCTP */
1807 #endif
1808         if (cmd == RTM_ADD) {
1809                 rt_addrmsg(cmd, ifa, fibnum);
1810                 if (rt != NULL)
1811                         rt_routemsg(cmd, ifa->ifa_ifp, error, rt, fibnum);
1812         } else {
1813                 if (rt != NULL)
1814                         rt_routemsg(cmd, ifa->ifa_ifp, error, rt, fibnum);
1815                 rt_addrmsg(cmd, ifa, fibnum);
1816         }
1817 }
1818