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