]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/netinet6/in6_src.c
MFC: r175162 & r174510: un-__P() & clean up VCS Ids.
[FreeBSD/FreeBSD.git] / sys / netinet6 / in6_src.c
1 /*-
2  * Copyright (C) 1995, 1996, 1997, and 1998 WIDE Project.
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  * 3. Neither the name of the project 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 PROJECT 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 PROJECT 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  *      $KAME: in6_src.c,v 1.132 2003/08/26 04:42:27 keiichi Exp $
30  */
31
32 /*-
33  * Copyright (c) 1982, 1986, 1991, 1993
34  *      The Regents of the University of California.  All rights reserved.
35  *
36  * Redistribution and use in source and binary forms, with or without
37  * modification, are permitted provided that the following conditions
38  * are met:
39  * 1. Redistributions of source code must retain the above copyright
40  *    notice, this list of conditions and the following disclaimer.
41  * 2. Redistributions in binary form must reproduce the above copyright
42  *    notice, this list of conditions and the following disclaimer in the
43  *    documentation and/or other materials provided with the distribution.
44  * 4. Neither the name of the University nor the names of its contributors
45  *    may be used to endorse or promote products derived from this software
46  *    without specific prior written permission.
47  *
48  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
49  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
50  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
51  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
52  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
53  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
54  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
55  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
56  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
57  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
58  * SUCH DAMAGE.
59  *
60  *      @(#)in_pcb.c    8.2 (Berkeley) 1/4/94
61  */
62
63 #include <sys/cdefs.h>
64 __FBSDID("$FreeBSD$");
65
66 #include "opt_inet.h"
67 #include "opt_inet6.h"
68
69 #include <sys/param.h>
70 #include <sys/systm.h>
71 #include <sys/malloc.h>
72 #include <sys/mbuf.h>
73 #include <sys/protosw.h>
74 #include <sys/socket.h>
75 #include <sys/socketvar.h>
76 #include <sys/sockio.h>
77 #include <sys/sysctl.h>
78 #include <sys/errno.h>
79 #include <sys/time.h>
80 #include <sys/kernel.h>
81 #include <sys/lock.h>
82 #include <sys/sx.h>
83
84 #include <net/if.h>
85 #include <net/route.h>
86
87 #include <netinet/in.h>
88 #include <netinet/in_var.h>
89 #include <netinet/in_systm.h>
90 #include <netinet/ip.h>
91 #include <netinet/in_pcb.h>
92 #include <netinet6/in6_var.h>
93 #include <netinet/ip6.h>
94 #include <netinet6/in6_pcb.h>
95 #include <netinet6/ip6_var.h>
96 #include <netinet6/scope6_var.h>
97 #include <netinet6/nd6.h>
98
99 #include <net/net_osdep.h>
100
101 static struct mtx addrsel_lock;
102 #define ADDRSEL_LOCK_INIT()     mtx_init(&addrsel_lock, "addrsel_lock", NULL, MTX_DEF)
103 #define ADDRSEL_LOCK()          mtx_lock(&addrsel_lock)
104 #define ADDRSEL_UNLOCK()        mtx_unlock(&addrsel_lock)
105 #define ADDRSEL_LOCK_ASSERT()   mtx_assert(&addrsel_lock, MA_OWNED)
106
107 static struct sx addrsel_sxlock;
108 #define ADDRSEL_SXLOCK_INIT()   sx_init(&addrsel_sxlock, "addrsel_sxlock")
109 #define ADDRSEL_SLOCK()         sx_slock(&addrsel_sxlock)
110 #define ADDRSEL_SUNLOCK()       sx_sunlock(&addrsel_sxlock)
111 #define ADDRSEL_XLOCK()         sx_xlock(&addrsel_sxlock)
112 #define ADDRSEL_XUNLOCK()       sx_xunlock(&addrsel_sxlock)
113
114 #define ADDR_LABEL_NOTAPP (-1)
115 struct in6_addrpolicy defaultaddrpolicy;
116
117 int ip6_prefer_tempaddr = 0;
118
119 static int selectroute __P((struct sockaddr_in6 *, struct ip6_pktopts *,
120         struct ip6_moptions *, struct route_in6 *, struct ifnet **,
121         struct rtentry **, int, int));
122 static int in6_selectif __P((struct sockaddr_in6 *, struct ip6_pktopts *,
123         struct ip6_moptions *, struct route_in6 *ro, struct ifnet **));
124
125 static struct in6_addrpolicy *lookup_addrsel_policy(struct sockaddr_in6 *);
126
127 static void init_policy_queue(void);
128 static int add_addrsel_policyent(struct in6_addrpolicy *);
129 static int delete_addrsel_policyent(struct in6_addrpolicy *);
130 static int walk_addrsel_policy __P((int (*)(struct in6_addrpolicy *, void *),
131                                     void *));
132 static int dump_addrsel_policyent(struct in6_addrpolicy *, void *);
133 static struct in6_addrpolicy *match_addrsel_policy(struct sockaddr_in6 *);
134
135 /*
136  * Return an IPv6 address, which is the most appropriate for a given
137  * destination and user specified options.
138  * If necessary, this function lookups the routing table and returns
139  * an entry to the caller for later use.
140  */
141 #define REPLACE(r) do {\
142         if ((r) < sizeof(ip6stat.ip6s_sources_rule) / \
143                 sizeof(ip6stat.ip6s_sources_rule[0])) /* check for safety */ \
144                 ip6stat.ip6s_sources_rule[(r)]++; \
145         /* printf("in6_selectsrc: replace %s with %s by %d\n", ia_best ? ip6_sprintf(&ia_best->ia_addr.sin6_addr) : "none", ip6_sprintf(&ia->ia_addr.sin6_addr), (r)); */ \
146         goto replace; \
147 } while(0)
148 #define NEXT(r) do {\
149         if ((r) < sizeof(ip6stat.ip6s_sources_rule) / \
150                 sizeof(ip6stat.ip6s_sources_rule[0])) /* check for safety */ \
151                 ip6stat.ip6s_sources_rule[(r)]++; \
152         /* printf("in6_selectsrc: keep %s against %s by %d\n", ia_best ? ip6_sprintf(&ia_best->ia_addr.sin6_addr) : "none", ip6_sprintf(&ia->ia_addr.sin6_addr), (r)); */ \
153         goto next;              /* XXX: we can't use 'continue' here */ \
154 } while(0)
155 #define BREAK(r) do { \
156         if ((r) < sizeof(ip6stat.ip6s_sources_rule) / \
157                 sizeof(ip6stat.ip6s_sources_rule[0])) /* check for safety */ \
158                 ip6stat.ip6s_sources_rule[(r)]++; \
159         goto out;               /* XXX: we can't use 'break' here */ \
160 } while(0)
161
162 struct in6_addr *
163 in6_selectsrc(dstsock, opts, mopts, ro, laddr, ifpp, errorp)
164         struct sockaddr_in6 *dstsock;
165         struct ip6_pktopts *opts;
166         struct ip6_moptions *mopts;
167         struct route_in6 *ro;
168         struct in6_addr *laddr;
169         struct ifnet **ifpp;
170         int *errorp;
171 {
172         struct in6_addr dst;
173         struct ifnet *ifp = NULL;
174         struct in6_ifaddr *ia = NULL, *ia_best = NULL;
175         struct in6_pktinfo *pi = NULL;
176         int dst_scope = -1, best_scope = -1, best_matchlen = -1;
177         struct in6_addrpolicy *dst_policy = NULL, *best_policy = NULL;
178         u_int32_t odstzone;
179         int prefer_tempaddr;
180
181         dst = dstsock->sin6_addr; /* make a copy for local operation */
182         *errorp = 0;
183         if (ifpp)
184                 *ifpp = NULL;
185
186         /*
187          * If the source address is explicitly specified by the caller,
188          * check if the requested source address is indeed a unicast address
189          * assigned to the node, and can be used as the packet's source
190          * address.  If everything is okay, use the address as source.
191          */
192         if (opts && (pi = opts->ip6po_pktinfo) &&
193             !IN6_IS_ADDR_UNSPECIFIED(&pi->ipi6_addr)) {
194                 struct sockaddr_in6 srcsock;
195                 struct in6_ifaddr *ia6;
196
197                 /* get the outgoing interface */
198                 if ((*errorp = in6_selectif(dstsock, opts, mopts, ro, &ifp))
199                     != 0) {
200                         return (NULL);
201                 }
202
203                 /*
204                  * determine the appropriate zone id of the source based on
205                  * the zone of the destination and the outgoing interface.
206                  * If the specified address is ambiguous wrt the scope zone,
207                  * the interface must be specified; otherwise, ifa_ifwithaddr()
208                  * will fail matching the address.
209                  */
210                 bzero(&srcsock, sizeof(srcsock));
211                 srcsock.sin6_family = AF_INET6;
212                 srcsock.sin6_len = sizeof(srcsock);
213                 srcsock.sin6_addr = pi->ipi6_addr;
214                 if (ifp) {
215                         *errorp = in6_setscope(&srcsock.sin6_addr, ifp, NULL);
216                         if (*errorp != 0)
217                                 return (NULL);
218                 }
219
220                 ia6 = (struct in6_ifaddr *)ifa_ifwithaddr((struct sockaddr *)(&srcsock));
221                 if (ia6 == NULL ||
222                     (ia6->ia6_flags & (IN6_IFF_ANYCAST | IN6_IFF_NOTREADY))) {
223                         *errorp = EADDRNOTAVAIL;
224                         return (NULL);
225                 }
226                 pi->ipi6_addr = srcsock.sin6_addr; /* XXX: this overrides pi */
227                 if (ifpp)
228                         *ifpp = ifp;
229                 return (&ia6->ia_addr.sin6_addr);
230         }
231
232         /*
233          * Otherwise, if the socket has already bound the source, just use it.
234          */
235         if (laddr && !IN6_IS_ADDR_UNSPECIFIED(laddr))
236                 return (laddr);
237
238         /*
239          * If the address is not specified, choose the best one based on
240          * the outgoing interface and the destination address.
241          */
242         /* get the outgoing interface */
243         if ((*errorp = in6_selectif(dstsock, opts, mopts, ro, &ifp)) != 0)
244                 return (NULL);
245
246 #ifdef DIAGNOSTIC
247         if (ifp == NULL)        /* this should not happen */
248                 panic("in6_selectsrc: NULL ifp");
249 #endif
250         *errorp = in6_setscope(&dst, ifp, &odstzone);
251         if (*errorp != 0)
252                 return (NULL);
253
254         for (ia = in6_ifaddr; ia; ia = ia->ia_next) {
255                 int new_scope = -1, new_matchlen = -1;
256                 struct in6_addrpolicy *new_policy = NULL;
257                 u_int32_t srczone, osrczone, dstzone;
258                 struct in6_addr src;
259                 struct ifnet *ifp1 = ia->ia_ifp;
260
261                 /*
262                  * We'll never take an address that breaks the scope zone
263                  * of the destination.  We also skip an address if its zone
264                  * does not contain the outgoing interface.
265                  * XXX: we should probably use sin6_scope_id here.
266                  */
267                 if (in6_setscope(&dst, ifp1, &dstzone) ||
268                     odstzone != dstzone) {
269                         continue;
270                 }
271                 src = ia->ia_addr.sin6_addr;
272                 if (in6_setscope(&src, ifp, &osrczone) ||
273                     in6_setscope(&src, ifp1, &srczone) ||
274                     osrczone != srczone) {
275                         continue;
276                 }
277
278                 /* avoid unusable addresses */
279                 if ((ia->ia6_flags &
280                      (IN6_IFF_NOTREADY | IN6_IFF_ANYCAST | IN6_IFF_DETACHED))) {
281                                 continue;
282                 }
283                 if (!ip6_use_deprecated && IFA6_IS_DEPRECATED(ia))
284                         continue;
285
286                 /* Rule 1: Prefer same address */
287                 if (IN6_ARE_ADDR_EQUAL(&dst, &ia->ia_addr.sin6_addr)) {
288                         ia_best = ia;
289                         BREAK(1); /* there should be no better candidate */
290                 }
291
292                 if (ia_best == NULL)
293                         REPLACE(0);
294
295                 /* Rule 2: Prefer appropriate scope */
296                 if (dst_scope < 0)
297                         dst_scope = in6_addrscope(&dst);
298                 new_scope = in6_addrscope(&ia->ia_addr.sin6_addr);
299                 if (IN6_ARE_SCOPE_CMP(best_scope, new_scope) < 0) {
300                         if (IN6_ARE_SCOPE_CMP(best_scope, dst_scope) < 0)
301                                 REPLACE(2);
302                         NEXT(2);
303                 } else if (IN6_ARE_SCOPE_CMP(new_scope, best_scope) < 0) {
304                         if (IN6_ARE_SCOPE_CMP(new_scope, dst_scope) < 0)
305                                 NEXT(2);
306                         REPLACE(2);
307                 }
308
309                 /*
310                  * Rule 3: Avoid deprecated addresses.  Note that the case of
311                  * !ip6_use_deprecated is already rejected above.
312                  */
313                 if (!IFA6_IS_DEPRECATED(ia_best) && IFA6_IS_DEPRECATED(ia))
314                         NEXT(3);
315                 if (IFA6_IS_DEPRECATED(ia_best) && !IFA6_IS_DEPRECATED(ia))
316                         REPLACE(3);
317
318                 /* Rule 4: Prefer home addresses */
319                 /*
320                  * XXX: This is a TODO.  We should probably merge the MIP6
321                  * case above.
322                  */
323
324                 /* Rule 5: Prefer outgoing interface */
325                 if (ia_best->ia_ifp == ifp && ia->ia_ifp != ifp)
326                         NEXT(5);
327                 if (ia_best->ia_ifp != ifp && ia->ia_ifp == ifp)
328                         REPLACE(5);
329
330                 /*
331                  * Rule 6: Prefer matching label
332                  * Note that best_policy should be non-NULL here.
333                  */
334                 if (dst_policy == NULL)
335                         dst_policy = lookup_addrsel_policy(dstsock);
336                 if (dst_policy->label != ADDR_LABEL_NOTAPP) {
337                         new_policy = lookup_addrsel_policy(&ia->ia_addr);
338                         if (dst_policy->label == best_policy->label &&
339                             dst_policy->label != new_policy->label)
340                                 NEXT(6);
341                         if (dst_policy->label != best_policy->label &&
342                             dst_policy->label == new_policy->label)
343                                 REPLACE(6);
344                 }
345
346                 /*
347                  * Rule 7: Prefer public addresses.
348                  * We allow users to reverse the logic by configuring
349                  * a sysctl variable, so that privacy conscious users can
350                  * always prefer temporary addresses.
351                  */
352                 if (opts == NULL ||
353                     opts->ip6po_prefer_tempaddr == IP6PO_TEMPADDR_SYSTEM) {
354                         prefer_tempaddr = ip6_prefer_tempaddr;
355                 } else if (opts->ip6po_prefer_tempaddr ==
356                     IP6PO_TEMPADDR_NOTPREFER) {
357                         prefer_tempaddr = 0;
358                 } else
359                         prefer_tempaddr = 1;
360                 if (!(ia_best->ia6_flags & IN6_IFF_TEMPORARY) &&
361                     (ia->ia6_flags & IN6_IFF_TEMPORARY)) {
362                         if (prefer_tempaddr)
363                                 REPLACE(7);
364                         else
365                                 NEXT(7);
366                 }
367                 if ((ia_best->ia6_flags & IN6_IFF_TEMPORARY) &&
368                     !(ia->ia6_flags & IN6_IFF_TEMPORARY)) {
369                         if (prefer_tempaddr)
370                                 NEXT(7);
371                         else
372                                 REPLACE(7);
373                 }
374
375                 /*
376                  * Rule 8: prefer addresses on alive interfaces.
377                  * This is a KAME specific rule.
378                  */
379                 if ((ia_best->ia_ifp->if_flags & IFF_UP) &&
380                     !(ia->ia_ifp->if_flags & IFF_UP))
381                         NEXT(8);
382                 if (!(ia_best->ia_ifp->if_flags & IFF_UP) &&
383                     (ia->ia_ifp->if_flags & IFF_UP))
384                         REPLACE(8);
385
386                 /*
387                  * Rule 14: Use longest matching prefix.
388                  * Note: in the address selection draft, this rule is
389                  * documented as "Rule 8".  However, since it is also
390                  * documented that this rule can be overridden, we assign
391                  * a large number so that it is easy to assign smaller numbers
392                  * to more preferred rules.
393                  */
394                 new_matchlen = in6_matchlen(&ia->ia_addr.sin6_addr, &dst);
395                 if (best_matchlen < new_matchlen)
396                         REPLACE(14);
397                 if (new_matchlen < best_matchlen)
398                         NEXT(14);
399
400                 /* Rule 15 is reserved. */
401
402                 /*
403                  * Last resort: just keep the current candidate.
404                  * Or, do we need more rules?
405                  */
406                 continue;
407
408           replace:
409                 ia_best = ia;
410                 best_scope = (new_scope >= 0 ? new_scope :
411                               in6_addrscope(&ia_best->ia_addr.sin6_addr));
412                 best_policy = (new_policy ? new_policy :
413                                lookup_addrsel_policy(&ia_best->ia_addr));
414                 best_matchlen = (new_matchlen >= 0 ? new_matchlen :
415                                  in6_matchlen(&ia_best->ia_addr.sin6_addr,
416                                               &dst));
417
418           next:
419                 continue;
420
421           out:
422                 break;
423         }
424
425         if ((ia = ia_best) == NULL) {
426                 *errorp = EADDRNOTAVAIL;
427                 return (NULL);
428         }
429
430         if (ifpp)
431                 *ifpp = ifp;
432
433         return (&ia->ia_addr.sin6_addr);
434 }
435
436 static int
437 selectroute(dstsock, opts, mopts, ro, retifp, retrt, clone, norouteok)
438         struct sockaddr_in6 *dstsock;
439         struct ip6_pktopts *opts;
440         struct ip6_moptions *mopts;
441         struct route_in6 *ro;
442         struct ifnet **retifp;
443         struct rtentry **retrt;
444         int clone;              /* meaningful only for bsdi and freebsd. */
445         int norouteok;
446 {
447         int error = 0;
448         struct ifnet *ifp = NULL;
449         struct rtentry *rt = NULL;
450         struct sockaddr_in6 *sin6_next;
451         struct in6_pktinfo *pi = NULL;
452         struct in6_addr *dst = &dstsock->sin6_addr;
453
454 #if 0
455         if (dstsock->sin6_addr.s6_addr32[0] == 0 &&
456             dstsock->sin6_addr.s6_addr32[1] == 0 &&
457             !IN6_IS_ADDR_LOOPBACK(&dstsock->sin6_addr)) {
458                 printf("in6_selectroute: strange destination %s\n",
459                        ip6_sprintf(&dstsock->sin6_addr));
460         } else {
461                 printf("in6_selectroute: destination = %s%%%d\n",
462                        ip6_sprintf(&dstsock->sin6_addr),
463                        dstsock->sin6_scope_id); /* for debug */
464         }
465 #endif
466
467         /* If the caller specify the outgoing interface explicitly, use it. */
468         if (opts && (pi = opts->ip6po_pktinfo) != NULL && pi->ipi6_ifindex) {
469                 /* XXX boundary check is assumed to be already done. */
470                 ifp = ifnet_byindex(pi->ipi6_ifindex);
471                 if (ifp != NULL &&
472                     (norouteok || retrt == NULL ||
473                     IN6_IS_ADDR_MULTICAST(dst))) {
474                         /*
475                          * we do not have to check or get the route for
476                          * multicast.
477                          */
478                         goto done;
479                 } else
480                         goto getroute;
481         }
482
483         /*
484          * If the destination address is a multicast address and the outgoing
485          * interface for the address is specified by the caller, use it.
486          */
487         if (IN6_IS_ADDR_MULTICAST(dst) &&
488             mopts != NULL && (ifp = mopts->im6o_multicast_ifp) != NULL) {
489                 goto done; /* we do not need a route for multicast. */
490         }
491
492   getroute:
493         /*
494          * If the next hop address for the packet is specified by the caller,
495          * use it as the gateway.
496          */
497         if (opts && opts->ip6po_nexthop) {
498                 struct route_in6 *ron;
499
500                 sin6_next = satosin6(opts->ip6po_nexthop);
501
502                 /* at this moment, we only support AF_INET6 next hops */
503                 if (sin6_next->sin6_family != AF_INET6) {
504                         error = EAFNOSUPPORT; /* or should we proceed? */
505                         goto done;
506                 }
507
508                 /*
509                  * If the next hop is an IPv6 address, then the node identified
510                  * by that address must be a neighbor of the sending host.
511                  */
512                 ron = &opts->ip6po_nextroute;
513                 if ((ron->ro_rt &&
514                      (ron->ro_rt->rt_flags & (RTF_UP | RTF_LLINFO)) !=
515                      (RTF_UP | RTF_LLINFO)) ||
516                     !IN6_ARE_ADDR_EQUAL(&satosin6(&ron->ro_dst)->sin6_addr,
517                     &sin6_next->sin6_addr)) {
518                         if (ron->ro_rt) {
519                                 RTFREE(ron->ro_rt);
520                                 ron->ro_rt = NULL;
521                         }
522                         *satosin6(&ron->ro_dst) = *sin6_next;
523                 }
524                 if (ron->ro_rt == NULL) {
525                         rtalloc((struct route *)ron); /* multi path case? */
526                         if (ron->ro_rt == NULL ||
527                             !(ron->ro_rt->rt_flags & RTF_LLINFO)) {
528                                 if (ron->ro_rt) {
529                                         RTFREE(ron->ro_rt);
530                                         ron->ro_rt = NULL;
531                                 }
532                                 error = EHOSTUNREACH;
533                                 goto done;
534                         }
535                 }
536                 rt = ron->ro_rt;
537                 ifp = rt->rt_ifp;
538
539                 /*
540                  * When cloning is required, try to allocate a route to the
541                  * destination so that the caller can store path MTU
542                  * information.
543                  */
544                 if (!clone)
545                         goto done;
546         }
547
548         /*
549          * Use a cached route if it exists and is valid, else try to allocate
550          * a new one.  Note that we should check the address family of the
551          * cached destination, in case of sharing the cache with IPv4.
552          */
553         if (ro) {
554                 if (ro->ro_rt &&
555                     (!(ro->ro_rt->rt_flags & RTF_UP) ||
556                      ((struct sockaddr *)(&ro->ro_dst))->sa_family != AF_INET6 ||
557                      !IN6_ARE_ADDR_EQUAL(&satosin6(&ro->ro_dst)->sin6_addr,
558                      dst))) {
559                         RTFREE(ro->ro_rt);
560                         ro->ro_rt = (struct rtentry *)NULL;
561                 }
562                 if (ro->ro_rt == (struct rtentry *)NULL) {
563                         struct sockaddr_in6 *sa6;
564
565                         /* No route yet, so try to acquire one */
566                         bzero(&ro->ro_dst, sizeof(struct sockaddr_in6));
567                         sa6 = (struct sockaddr_in6 *)&ro->ro_dst;
568                         *sa6 = *dstsock;
569                         sa6->sin6_scope_id = 0;
570
571                         if (clone) {
572                                 rtalloc((struct route *)ro);
573                         } else {
574                                 ro->ro_rt = rtalloc1(&((struct route *)ro)
575                                                      ->ro_dst, 0, 0UL);
576                                 if (ro->ro_rt)
577                                         RT_UNLOCK(ro->ro_rt);
578                         }
579                 }
580
581                 /*
582                  * do not care about the result if we have the nexthop
583                  * explicitly specified.
584                  */
585                 if (opts && opts->ip6po_nexthop)
586                         goto done;
587
588                 if (ro->ro_rt) {
589                         ifp = ro->ro_rt->rt_ifp;
590
591                         if (ifp == NULL) { /* can this really happen? */
592                                 RTFREE(ro->ro_rt);
593                                 ro->ro_rt = NULL;
594                         }
595                 }
596                 if (ro->ro_rt == NULL)
597                         error = EHOSTUNREACH;
598                 rt = ro->ro_rt;
599
600                 /*
601                  * Check if the outgoing interface conflicts with
602                  * the interface specified by ipi6_ifindex (if specified).
603                  * Note that loopback interface is always okay.
604                  * (this may happen when we are sending a packet to one of
605                  *  our own addresses.)
606                  */
607                 if (ifp && opts && opts->ip6po_pktinfo &&
608                     opts->ip6po_pktinfo->ipi6_ifindex) {
609                         if (!(ifp->if_flags & IFF_LOOPBACK) &&
610                             ifp->if_index !=
611                             opts->ip6po_pktinfo->ipi6_ifindex) {
612                                 error = EHOSTUNREACH;
613                                 goto done;
614                         }
615                 }
616         }
617
618   done:
619         if (ifp == NULL && rt == NULL) {
620                 /*
621                  * This can happen if the caller did not pass a cached route
622                  * nor any other hints.  We treat this case an error.
623                  */
624                 error = EHOSTUNREACH;
625         }
626         if (error == EHOSTUNREACH)
627                 ip6stat.ip6s_noroute++;
628
629         if (retifp != NULL)
630                 *retifp = ifp;
631         if (retrt != NULL)
632                 *retrt = rt;    /* rt may be NULL */
633
634         return (error);
635 }
636
637 static int
638 in6_selectif(dstsock, opts, mopts, ro, retifp)
639         struct sockaddr_in6 *dstsock;
640         struct ip6_pktopts *opts;
641         struct ip6_moptions *mopts;
642         struct route_in6 *ro;
643         struct ifnet **retifp;
644 {
645         int error;
646         struct route_in6 sro;
647         struct rtentry *rt = NULL;
648
649         if (ro == NULL) {
650                 bzero(&sro, sizeof(sro));
651                 ro = &sro;
652         }
653
654         if ((error = selectroute(dstsock, opts, mopts, ro, retifp,
655                                      &rt, 0, 1)) != 0) {
656                 if (rt && rt == sro.ro_rt)
657                         RTFREE(rt);
658                 return (error);
659         }
660
661         /*
662          * do not use a rejected or black hole route.
663          * XXX: this check should be done in the L2 output routine.
664          * However, if we skipped this check here, we'd see the following
665          * scenario:
666          * - install a rejected route for a scoped address prefix
667          *   (like fe80::/10)
668          * - send a packet to a destination that matches the scoped prefix,
669          *   with ambiguity about the scope zone.
670          * - pick the outgoing interface from the route, and disambiguate the
671          *   scope zone with the interface.
672          * - ip6_output() would try to get another route with the "new"
673          *   destination, which may be valid.
674          * - we'd see no error on output.
675          * Although this may not be very harmful, it should still be confusing.
676          * We thus reject the case here.
677          */
678         if (rt && (rt->rt_flags & (RTF_REJECT | RTF_BLACKHOLE))) {
679                 int flags = (rt->rt_flags & RTF_HOST ? EHOSTUNREACH : ENETUNREACH);
680
681                 if (rt && rt == sro.ro_rt)
682                         RTFREE(rt);
683                 return (flags);
684         }
685
686         /*
687          * Adjust the "outgoing" interface.  If we're going to loop the packet
688          * back to ourselves, the ifp would be the loopback interface.
689          * However, we'd rather know the interface associated to the
690          * destination address (which should probably be one of our own
691          * addresses.)
692          */
693         if (rt && rt->rt_ifa && rt->rt_ifa->ifa_ifp)
694                 *retifp = rt->rt_ifa->ifa_ifp;
695
696         if (rt && rt == sro.ro_rt)
697                 RTFREE(rt);
698         return (0);
699 }
700
701 int
702 in6_selectroute(dstsock, opts, mopts, ro, retifp, retrt, clone)
703         struct sockaddr_in6 *dstsock;
704         struct ip6_pktopts *opts;
705         struct ip6_moptions *mopts;
706         struct route_in6 *ro;
707         struct ifnet **retifp;
708         struct rtentry **retrt;
709         int clone;              /* meaningful only for bsdi and freebsd. */
710 {
711         return (selectroute(dstsock, opts, mopts, ro, retifp,
712             retrt, clone, 0));
713 }
714
715 /*
716  * Default hop limit selection. The precedence is as follows:
717  * 1. Hoplimit value specified via ioctl.
718  * 2. (If the outgoing interface is detected) the current
719  *     hop limit of the interface specified by router advertisement.
720  * 3. The system default hoplimit.
721  */
722 int
723 in6_selecthlim(in6p, ifp)
724         struct in6pcb *in6p;
725         struct ifnet *ifp;
726 {
727         if (in6p && in6p->in6p_hops >= 0)
728                 return (in6p->in6p_hops);
729         else if (ifp)
730                 return (ND_IFINFO(ifp)->chlim);
731         else if (in6p && !IN6_IS_ADDR_UNSPECIFIED(&in6p->in6p_faddr)) {
732                 struct route_in6 ro6;
733                 struct ifnet *lifp;
734
735                 bzero(&ro6, sizeof(ro6));
736                 ro6.ro_dst.sin6_family = AF_INET6;
737                 ro6.ro_dst.sin6_len = sizeof(struct sockaddr_in6);
738                 ro6.ro_dst.sin6_addr = in6p->in6p_faddr;
739                 rtalloc((struct route *)&ro6);
740                 if (ro6.ro_rt) {
741                         lifp = ro6.ro_rt->rt_ifp;
742                         RTFREE(ro6.ro_rt);
743                         if (lifp)
744                                 return (ND_IFINFO(lifp)->chlim);
745                 } else
746                         return (ip6_defhlim);
747         }
748         return (ip6_defhlim);
749 }
750
751 /*
752  * XXX: this is borrowed from in6_pcbbind(). If possible, we should
753  * share this function by all *bsd*...
754  */
755 int
756 in6_pcbsetport(laddr, inp, cred)
757         struct in6_addr *laddr;
758         struct inpcb *inp;
759         struct ucred *cred;
760 {
761         struct socket *so = inp->inp_socket;
762         u_int16_t lport = 0, first, last, *lastport;
763         int count, error = 0, wild = 0;
764         struct inpcbinfo *pcbinfo = inp->inp_pcbinfo;
765
766         /* XXX: this is redundant when called from in6_pcbbind */
767         if ((so->so_options & (SO_REUSEADDR|SO_REUSEPORT)) == 0)
768                 wild = INPLOOKUP_WILDCARD;
769
770         inp->inp_flags |= INP_ANONPORT;
771
772         if (inp->inp_flags & INP_HIGHPORT) {
773                 first = ipport_hifirstauto;     /* sysctl */
774                 last  = ipport_hilastauto;
775                 lastport = &pcbinfo->lasthi;
776         } else if (inp->inp_flags & INP_LOWPORT) {
777                 if ((error = suser_cred(cred, 0)))
778                         return error;
779                 first = ipport_lowfirstauto;    /* 1023 */
780                 last  = ipport_lowlastauto;     /* 600 */
781                 lastport = &pcbinfo->lastlow;
782         } else {
783                 first = ipport_firstauto;       /* sysctl */
784                 last  = ipport_lastauto;
785                 lastport = &pcbinfo->lastport;
786         }
787         /*
788          * Simple check to ensure all ports are not used up causing
789          * a deadlock here.
790          *
791          * We split the two cases (up and down) so that the direction
792          * is not being tested on each round of the loop.
793          */
794         if (first > last) {
795                 /*
796                  * counting down
797                  */
798                 count = first - last;
799
800                 do {
801                         if (count-- < 0) {      /* completely used? */
802                                 /*
803                                  * Undo any address bind that may have
804                                  * occurred above.
805                                  */
806                                 inp->in6p_laddr = in6addr_any;
807                                 return (EAGAIN);
808                         }
809                         --*lastport;
810                         if (*lastport > first || *lastport < last)
811                                 *lastport = first;
812                         lport = htons(*lastport);
813                 } while (in6_pcblookup_local(pcbinfo, &inp->in6p_laddr,
814                                              lport, wild));
815         } else {
816                 /*
817                          * counting up
818                          */
819                 count = last - first;
820
821                 do {
822                         if (count-- < 0) {      /* completely used? */
823                                 /*
824                                  * Undo any address bind that may have
825                                  * occurred above.
826                                  */
827                                 inp->in6p_laddr = in6addr_any;
828                                 return (EAGAIN);
829                         }
830                         ++*lastport;
831                         if (*lastport < first || *lastport > last)
832                                 *lastport = first;
833                         lport = htons(*lastport);
834                 } while (in6_pcblookup_local(pcbinfo,
835                                              &inp->in6p_laddr, lport, wild));
836         }
837
838         inp->inp_lport = lport;
839         if (in_pcbinshash(inp) != 0) {
840                 inp->in6p_laddr = in6addr_any;
841                 inp->inp_lport = 0;
842                 return (EAGAIN);
843         }
844
845         return (0);
846 }
847
848 void
849 addrsel_policy_init()
850 {
851         ADDRSEL_LOCK_INIT();
852         ADDRSEL_SXLOCK_INIT();
853
854         init_policy_queue();
855
856         /* initialize the "last resort" policy */
857         bzero(&defaultaddrpolicy, sizeof(defaultaddrpolicy));
858         defaultaddrpolicy.label = ADDR_LABEL_NOTAPP;
859 }
860
861 static struct in6_addrpolicy *
862 lookup_addrsel_policy(key)
863         struct sockaddr_in6 *key;
864 {
865         struct in6_addrpolicy *match = NULL;
866
867         ADDRSEL_LOCK();
868         match = match_addrsel_policy(key);
869
870         if (match == NULL)
871                 match = &defaultaddrpolicy;
872         else
873                 match->use++;
874         ADDRSEL_UNLOCK();
875
876         return (match);
877 }
878
879 /*
880  * Subroutines to manage the address selection policy table via sysctl.
881  */
882 struct walkarg {
883         struct sysctl_req *w_req;
884 };
885
886 static int in6_src_sysctl(SYSCTL_HANDLER_ARGS);
887 SYSCTL_DECL(_net_inet6_ip6);
888 SYSCTL_NODE(_net_inet6_ip6, IPV6CTL_ADDRCTLPOLICY, addrctlpolicy,
889         CTLFLAG_RD, in6_src_sysctl, "");
890
891 static int
892 in6_src_sysctl(SYSCTL_HANDLER_ARGS)
893 {
894         struct walkarg w;
895
896         if (req->newptr)
897                 return EPERM;
898
899         bzero(&w, sizeof(w));
900         w.w_req = req;
901
902         return (walk_addrsel_policy(dump_addrsel_policyent, &w));
903 }
904
905 int
906 in6_src_ioctl(cmd, data)
907         u_long cmd;
908         caddr_t data;
909 {
910         int i;
911         struct in6_addrpolicy ent0;
912
913         if (cmd != SIOCAADDRCTL_POLICY && cmd != SIOCDADDRCTL_POLICY)
914                 return (EOPNOTSUPP); /* check for safety */
915
916         ent0 = *(struct in6_addrpolicy *)data;
917
918         if (ent0.label == ADDR_LABEL_NOTAPP)
919                 return (EINVAL);
920         /* check if the prefix mask is consecutive. */
921         if (in6_mask2len(&ent0.addrmask.sin6_addr, NULL) < 0)
922                 return (EINVAL);
923         /* clear trailing garbages (if any) of the prefix address. */
924         for (i = 0; i < 4; i++) {
925                 ent0.addr.sin6_addr.s6_addr32[i] &=
926                         ent0.addrmask.sin6_addr.s6_addr32[i];
927         }
928         ent0.use = 0;
929
930         switch (cmd) {
931         case SIOCAADDRCTL_POLICY:
932                 return (add_addrsel_policyent(&ent0));
933         case SIOCDADDRCTL_POLICY:
934                 return (delete_addrsel_policyent(&ent0));
935         }
936
937         return (0);             /* XXX: compromise compilers */
938 }
939
940 /*
941  * The followings are implementation of the policy table using a
942  * simple tail queue.
943  * XXX such details should be hidden.
944  * XXX implementation using binary tree should be more efficient.
945  */
946 struct addrsel_policyent {
947         TAILQ_ENTRY(addrsel_policyent) ape_entry;
948         struct in6_addrpolicy ape_policy;
949 };
950
951 TAILQ_HEAD(addrsel_policyhead, addrsel_policyent);
952
953 struct addrsel_policyhead addrsel_policytab;
954
955 static void
956 init_policy_queue()
957 {
958         TAILQ_INIT(&addrsel_policytab);
959 }
960
961 static int
962 add_addrsel_policyent(newpolicy)
963         struct in6_addrpolicy *newpolicy;
964 {
965         struct addrsel_policyent *new, *pol;
966
967         MALLOC(new, struct addrsel_policyent *, sizeof(*new), M_IFADDR,
968                M_WAITOK);
969         ADDRSEL_XLOCK();
970         ADDRSEL_LOCK();
971
972         /* duplication check */
973         TAILQ_FOREACH(pol, &addrsel_policytab, ape_entry) {
974                 if (IN6_ARE_ADDR_EQUAL(&newpolicy->addr.sin6_addr,
975                                        &pol->ape_policy.addr.sin6_addr) &&
976                     IN6_ARE_ADDR_EQUAL(&newpolicy->addrmask.sin6_addr,
977                                        &pol->ape_policy.addrmask.sin6_addr)) {
978                         ADDRSEL_UNLOCK();
979                         ADDRSEL_XUNLOCK();
980                         FREE(new, M_IFADDR);
981                         return (EEXIST);        /* or override it? */
982                 }
983         }
984
985         bzero(new, sizeof(*new));
986
987         /* XXX: should validate entry */
988         new->ape_policy = *newpolicy;
989
990         TAILQ_INSERT_TAIL(&addrsel_policytab, new, ape_entry);
991         ADDRSEL_UNLOCK();
992         ADDRSEL_XUNLOCK();
993
994         return (0);
995 }
996
997 static int
998 delete_addrsel_policyent(key)
999         struct in6_addrpolicy *key;
1000 {
1001         struct addrsel_policyent *pol;
1002
1003         ADDRSEL_XLOCK();
1004         ADDRSEL_LOCK();
1005
1006         /* search for the entry in the table */
1007         TAILQ_FOREACH(pol, &addrsel_policytab, ape_entry) {
1008                 if (IN6_ARE_ADDR_EQUAL(&key->addr.sin6_addr,
1009                     &pol->ape_policy.addr.sin6_addr) &&
1010                     IN6_ARE_ADDR_EQUAL(&key->addrmask.sin6_addr,
1011                     &pol->ape_policy.addrmask.sin6_addr)) {
1012                         break;
1013                 }
1014         }
1015         if (pol == NULL) {
1016                 ADDRSEL_UNLOCK();
1017                 ADDRSEL_XUNLOCK();
1018                 return (ESRCH);
1019         }
1020
1021         TAILQ_REMOVE(&addrsel_policytab, pol, ape_entry);
1022         ADDRSEL_UNLOCK();
1023         ADDRSEL_XUNLOCK();
1024
1025         return (0);
1026 }
1027
1028 static int
1029 walk_addrsel_policy(int (*callback)(struct in6_addrpolicy *, void *), void *w)
1030 {
1031         struct addrsel_policyent *pol;
1032         int error = 0;
1033
1034         ADDRSEL_SLOCK();
1035         TAILQ_FOREACH(pol, &addrsel_policytab, ape_entry) {
1036                 if ((error = (*callback)(&pol->ape_policy, w)) != 0) {
1037                         ADDRSEL_SUNLOCK();
1038                         return (error);
1039                 }
1040         }
1041         ADDRSEL_SUNLOCK();
1042         return (error);
1043 }
1044
1045 static int
1046 dump_addrsel_policyent(pol, arg)
1047         struct in6_addrpolicy *pol;
1048         void *arg;
1049 {
1050         int error = 0;
1051         struct walkarg *w = arg;
1052
1053         error = SYSCTL_OUT(w->w_req, pol, sizeof(*pol));
1054
1055         return (error);
1056 }
1057
1058 static struct in6_addrpolicy *
1059 match_addrsel_policy(key)
1060         struct sockaddr_in6 *key;
1061 {
1062         struct addrsel_policyent *pent;
1063         struct in6_addrpolicy *bestpol = NULL, *pol;
1064         int matchlen, bestmatchlen = -1;
1065         u_char *mp, *ep, *k, *p, m;
1066
1067         TAILQ_FOREACH(pent, &addrsel_policytab, ape_entry) {
1068                 matchlen = 0;
1069
1070                 pol = &pent->ape_policy;
1071                 mp = (u_char *)&pol->addrmask.sin6_addr;
1072                 ep = mp + 16;   /* XXX: scope field? */
1073                 k = (u_char *)&key->sin6_addr;
1074                 p = (u_char *)&pol->addr.sin6_addr;
1075                 for (; mp < ep && *mp; mp++, k++, p++) {
1076                         m = *mp;
1077                         if ((*k & m) != *p)
1078                                 goto next; /* not match */
1079                         if (m == 0xff) /* short cut for a typical case */
1080                                 matchlen += 8;
1081                         else {
1082                                 while (m >= 0x80) {
1083                                         matchlen++;
1084                                         m <<= 1;
1085                                 }
1086                         }
1087                 }
1088
1089                 /* matched.  check if this is better than the current best. */
1090                 if (bestpol == NULL ||
1091                     matchlen > bestmatchlen) {
1092                         bestpol = pol;
1093                         bestmatchlen = matchlen;
1094                 }
1095
1096           next:
1097                 continue;
1098         }
1099
1100         return (bestpol);
1101 }