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