xref: /netbsd-src/sys/netinet6/in6.c (revision d710132b4b8ce7f7cccaaf660cb16aa16b4077a0)
1 /*	$NetBSD: in6.c,v 1.77 2003/06/24 07:43:44 itojun Exp $	*/
2 /*	$KAME: in6.c,v 1.198 2001/07/18 09:12:38 itojun 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  * 3. All advertising materials mentioning features or use of this software
46  *    must display the following acknowledgement:
47  *	This product includes software developed by the University of
48  *	California, Berkeley and its contributors.
49  * 4. Neither the name of the University nor the names of its contributors
50  *    may be used to endorse or promote products derived from this software
51  *    without specific prior written permission.
52  *
53  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
54  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
55  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
56  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
57  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
58  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
59  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
60  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
61  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
62  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
63  * SUCH DAMAGE.
64  *
65  *	@(#)in.c	8.2 (Berkeley) 11/15/93
66  */
67 
68 #include <sys/cdefs.h>
69 __KERNEL_RCSID(0, "$NetBSD: in6.c,v 1.77 2003/06/24 07:43:44 itojun Exp $");
70 
71 #include "opt_inet.h"
72 
73 #include <sys/param.h>
74 #include <sys/ioctl.h>
75 #include <sys/errno.h>
76 #include <sys/malloc.h>
77 #include <sys/socket.h>
78 #include <sys/socketvar.h>
79 #include <sys/sockio.h>
80 #include <sys/systm.h>
81 #include <sys/proc.h>
82 #include <sys/time.h>
83 #include <sys/kernel.h>
84 #include <sys/syslog.h>
85 
86 #include <net/if.h>
87 #include <net/if_types.h>
88 #include <net/route.h>
89 #include <net/if_dl.h>
90 
91 #include <netinet/in.h>
92 #include <netinet/in_var.h>
93 #include <net/if_ether.h>
94 
95 #include <netinet/ip6.h>
96 #include <netinet6/ip6_var.h>
97 #include <netinet6/nd6.h>
98 #include <netinet6/mld6_var.h>
99 #include <netinet6/ip6_mroute.h>
100 #include <netinet6/in6_ifattach.h>
101 
102 #include <net/net_osdep.h>
103 
104 MALLOC_DEFINE(M_IP6OPT, "ip6_options", "IPv6 options");
105 
106 /* enable backward compatibility code for obsoleted ioctls */
107 #define COMPAT_IN6IFIOCTL
108 
109 /*
110  * Definitions of some constant IP6 addresses.
111  */
112 const struct in6_addr in6addr_any = IN6ADDR_ANY_INIT;
113 const struct in6_addr in6addr_loopback = IN6ADDR_LOOPBACK_INIT;
114 const struct in6_addr in6addr_nodelocal_allnodes =
115 	IN6ADDR_NODELOCAL_ALLNODES_INIT;
116 const struct in6_addr in6addr_linklocal_allnodes =
117 	IN6ADDR_LINKLOCAL_ALLNODES_INIT;
118 const struct in6_addr in6addr_linklocal_allrouters =
119 	IN6ADDR_LINKLOCAL_ALLROUTERS_INIT;
120 
121 const struct in6_addr in6mask0 = IN6MASK0;
122 const struct in6_addr in6mask32 = IN6MASK32;
123 const struct in6_addr in6mask64 = IN6MASK64;
124 const struct in6_addr in6mask96 = IN6MASK96;
125 const struct in6_addr in6mask128 = IN6MASK128;
126 
127 const struct sockaddr_in6 sa6_any = {sizeof(sa6_any), AF_INET6,
128 				     0, 0, IN6ADDR_ANY_INIT, 0};
129 
130 static int in6_lifaddr_ioctl __P((struct socket *, u_long, caddr_t,
131 	struct ifnet *, struct proc *));
132 static int in6_ifinit __P((struct ifnet *, struct in6_ifaddr *,
133 	struct sockaddr_in6 *, int));
134 static void in6_unlink_ifa __P((struct in6_ifaddr *, struct ifnet *));
135 
136 /*
137  * This structure is used to keep track of in6_multi chains which belong to
138  * deleted interface addresses.
139  */
140 static LIST_HEAD(, multi6_kludge) in6_mk; /* XXX BSS initialization */
141 
142 struct multi6_kludge {
143 	LIST_ENTRY(multi6_kludge) mk_entry;
144 	struct ifnet *mk_ifp;
145 	struct in6_multihead mk_head;
146 };
147 
148 /*
149  * Subroutine for in6_ifaddloop() and in6_ifremloop().
150  * This routine does actual work.
151  */
152 static void
153 in6_ifloop_request(int cmd, struct ifaddr *ifa)
154 {
155 	struct sockaddr_in6 lo_sa;
156 	struct sockaddr_in6 all1_sa;
157 	struct rtentry *nrt = NULL;
158 	int e;
159 
160 	bzero(&lo_sa, sizeof(lo_sa));
161 	bzero(&all1_sa, sizeof(all1_sa));
162 	lo_sa.sin6_family = all1_sa.sin6_family = AF_INET6;
163 	lo_sa.sin6_len = all1_sa.sin6_len = sizeof(struct sockaddr_in6);
164 	lo_sa.sin6_addr = in6addr_loopback;
165 	all1_sa.sin6_addr = in6mask128;
166 
167 	/*
168 	 * We specify the address itself as the gateway, and set the
169 	 * RTF_LLINFO flag, so that the corresponding host route would have
170 	 * the flag, and thus applications that assume traditional behavior
171 	 * would be happy.  Note that we assume the caller of the function
172 	 * (probably implicitly) set nd6_rtrequest() to ifa->ifa_rtrequest,
173 	 * which changes the outgoing interface to the loopback interface.
174 	 */
175 	e = rtrequest(cmd, ifa->ifa_addr, ifa->ifa_addr,
176 	    (struct sockaddr *)&all1_sa, RTF_UP|RTF_HOST|RTF_LLINFO, &nrt);
177 	if (e != 0) {
178 		log(LOG_ERR, "in6_ifloop_request: "
179 		    "%s operation failed for %s (errno=%d)\n",
180 		    cmd == RTM_ADD ? "ADD" : "DELETE",
181 		    ip6_sprintf(&((struct in6_ifaddr *)ifa)->ia_addr.sin6_addr),
182 		    e);
183 	}
184 
185 	/*
186 	 * Make sure rt_ifa be equal to IFA, the second argument of the
187 	 * function.
188 	 * We need this because when we refer to rt_ifa->ia6_flags in
189 	 * ip6_input, we assume that the rt_ifa points to the address instead
190 	 * of the loopback address.
191 	 */
192 	if (cmd == RTM_ADD && nrt && ifa != nrt->rt_ifa) {
193 		IFAFREE(nrt->rt_ifa);
194 		IFAREF(ifa);
195 		nrt->rt_ifa = ifa;
196 	}
197 
198 	/*
199 	 * Report the addition/removal of the address to the routing socket.
200 	 * XXX: since we called rtinit for a p2p interface with a destination,
201 	 *      we end up reporting twice in such a case.  Should we rather
202 	 *      omit the second report?
203 	 */
204 	if (nrt) {
205 		rt_newaddrmsg(cmd, ifa, e, nrt);
206 		if (cmd == RTM_DELETE) {
207 			if (nrt->rt_refcnt <= 0) {
208 				/* XXX: we should free the entry ourselves. */
209 				nrt->rt_refcnt++;
210 				rtfree(nrt);
211 			}
212 		} else {
213 			/* the cmd must be RTM_ADD here */
214 			nrt->rt_refcnt--;
215 		}
216 	}
217 }
218 
219 /*
220  * Add ownaddr as loopback rtentry.  We previously add the route only if
221  * necessary (ex. on a p2p link).  However, since we now manage addresses
222  * separately from prefixes, we should always add the route.  We can't
223  * rely on the cloning mechanism from the corresponding interface route
224  * any more.
225  */
226 static void
227 in6_ifaddloop(struct ifaddr *ifa)
228 {
229 	struct rtentry *rt;
230 
231 	/* If there is no loopback entry, allocate one. */
232 	rt = rtalloc1(ifa->ifa_addr, 0);
233 	if (rt == NULL || (rt->rt_flags & RTF_HOST) == 0 ||
234 	    (rt->rt_ifp->if_flags & IFF_LOOPBACK) == 0)
235 		in6_ifloop_request(RTM_ADD, ifa);
236 	if (rt)
237 		rt->rt_refcnt--;
238 }
239 
240 /*
241  * Remove loopback rtentry of ownaddr generated by in6_ifaddloop(),
242  * if it exists.
243  */
244 static void
245 in6_ifremloop(struct ifaddr *ifa)
246 {
247 	struct in6_ifaddr *ia;
248 	struct rtentry *rt;
249 	int ia_count = 0;
250 
251 	/*
252 	 * Some of BSD variants do not remove cloned routes
253 	 * from an interface direct route, when removing the direct route
254 	 * (see comments in net/net_osdep.h).  Even for variants that do remove
255 	 * cloned routes, they could fail to remove the cloned routes when
256 	 * we handle multple addresses that share a common prefix.
257 	 * So, we should remove the route corresponding to the deleted address.
258 	 */
259 
260 	/*
261 	 * Delete the entry only if exact one ifa exists.  More than one ifa
262 	 * can exist if we assign a same single address to multiple
263 	 * (probably p2p) interfaces.
264 	 * XXX: we should avoid such a configuration in IPv6...
265 	 */
266 	for (ia = in6_ifaddr; ia; ia = ia->ia_next) {
267 		if (IN6_ARE_ADDR_EQUAL(IFA_IN6(ifa), &ia->ia_addr.sin6_addr)) {
268 			ia_count++;
269 			if (ia_count > 1)
270 				break;
271 		}
272 	}
273 
274 	if (ia_count == 1) {
275 		/*
276 		 * Before deleting, check if a corresponding loopbacked host
277 		 * route surely exists.  With this check, we can avoid to
278 		 * delete an interface direct route whose destination is same
279 		 * as the address being removed.  This can happen when removing
280 		 * a subnet-router anycast address on an interface attahced
281 		 * to a shared medium.
282 		 */
283 		rt = rtalloc1(ifa->ifa_addr, 0);
284 		if (rt != NULL && (rt->rt_flags & RTF_HOST) != 0 &&
285 		    (rt->rt_ifp->if_flags & IFF_LOOPBACK) != 0) {
286 			rt->rt_refcnt--;
287 			in6_ifloop_request(RTM_DELETE, ifa);
288 		}
289 	}
290 }
291 
292 int
293 in6_ifindex2scopeid(idx)
294 	int idx;
295 {
296 	struct ifnet *ifp;
297 	struct ifaddr *ifa;
298 	struct sockaddr_in6 *sin6;
299 
300 	if (idx < 0 || if_index < idx)
301 		return -1;
302 	ifp = ifindex2ifnet[idx];
303 	if (!ifp)
304 		return -1;
305 
306 	for (ifa = ifp->if_addrlist.tqh_first; ifa; ifa = ifa->ifa_list.tqe_next)
307 	{
308 		if (ifa->ifa_addr->sa_family != AF_INET6)
309 			continue;
310 		sin6 = (struct sockaddr_in6 *)ifa->ifa_addr;
311 		if (IN6_IS_ADDR_SITELOCAL(&sin6->sin6_addr))
312 			return sin6->sin6_scope_id & 0xffff;
313 	}
314 
315 	return -1;
316 }
317 
318 int
319 in6_mask2len(mask, lim0)
320 	struct in6_addr *mask;
321 	u_char *lim0;
322 {
323 	int x = 0, y;
324 	u_char *lim = lim0, *p;
325 
326 	/* ignore the scope_id part */
327 	if (lim0 == NULL || lim0 - (u_char *)mask > sizeof(*mask))
328 		lim = (u_char *)mask + sizeof(*mask);
329 	for (p = (u_char *)mask; p < lim; x++, p++) {
330 		if (*p != 0xff)
331 			break;
332 	}
333 	y = 0;
334 	if (p < lim) {
335 		for (y = 0; y < 8; y++) {
336 			if ((*p & (0x80 >> y)) == 0)
337 				break;
338 		}
339 	}
340 
341 	/*
342 	 * when the limit pointer is given, do a stricter check on the
343 	 * remaining bits.
344 	 */
345 	if (p < lim) {
346 		if (y != 0 && (*p & (0x00ff >> y)) != 0)
347 			return (-1);
348 		for (p = p + 1; p < lim; p++)
349 			if (*p != 0)
350 				return (-1);
351 	}
352 
353 	return x * 8 + y;
354 }
355 
356 #define ifa2ia6(ifa)	((struct in6_ifaddr *)(ifa))
357 #define ia62ifa(ia6)	(&((ia6)->ia_ifa))
358 
359 int
360 in6_control(so, cmd, data, ifp, p)
361 	struct	socket *so;
362 	u_long cmd;
363 	caddr_t	data;
364 	struct ifnet *ifp;
365 	struct proc *p;
366 {
367 	struct	in6_ifreq *ifr = (struct in6_ifreq *)data;
368 	struct	in6_ifaddr *ia = NULL;
369 	struct	in6_aliasreq *ifra = (struct in6_aliasreq *)data;
370 	struct sockaddr_in6 *sa6;
371 	int privileged;
372 
373 	privileged = 0;
374 	if (p && !suser(p->p_ucred, &p->p_acflag))
375 		privileged++;
376 
377 	switch (cmd) {
378 	case SIOCGETSGCNT_IN6:
379 	case SIOCGETMIFCNT_IN6:
380 		return (mrt6_ioctl(cmd, data));
381 	}
382 
383 	if (ifp == NULL)
384 		return (EOPNOTSUPP);
385 
386 	switch (cmd) {
387 	case SIOCSNDFLUSH_IN6:
388 	case SIOCSPFXFLUSH_IN6:
389 	case SIOCSRTRFLUSH_IN6:
390 	case SIOCSDEFIFACE_IN6:
391 	case SIOCSIFINFO_FLAGS:
392 		if (!privileged)
393 			return (EPERM);
394 		/* FALLTHROUGH */
395 	case OSIOCGIFINFO_IN6:
396 	case SIOCGIFINFO_IN6:
397 	case SIOCGDRLST_IN6:
398 	case SIOCGPRLST_IN6:
399 	case SIOCGNBRINFO_IN6:
400 	case SIOCGDEFIFACE_IN6:
401 		return (nd6_ioctl(cmd, data, ifp));
402 	}
403 
404 	switch (cmd) {
405 	case SIOCSIFPREFIX_IN6:
406 	case SIOCDIFPREFIX_IN6:
407 	case SIOCAIFPREFIX_IN6:
408 	case SIOCCIFPREFIX_IN6:
409 	case SIOCSGIFPREFIX_IN6:
410 	case SIOCGIFPREFIX_IN6:
411 		log(LOG_NOTICE,
412 		    "prefix ioctls are now invalidated. "
413 		    "please use ifconfig.\n");
414 		return (EOPNOTSUPP);
415 	}
416 
417 	switch (cmd) {
418 	case SIOCALIFADDR:
419 	case SIOCDLIFADDR:
420 		if (!privileged)
421 			return (EPERM);
422 		/* FALLTHROUGH */
423 	case SIOCGLIFADDR:
424 		return in6_lifaddr_ioctl(so, cmd, data, ifp, p);
425 	}
426 
427 	/*
428 	 * Find address for this interface, if it exists.
429 	 *
430 	 * In netinet code, we have checked ifra_addr in SIOCSIF*ADDR operation
431 	 * only, and used the first interface address as the target of other
432 	 * operations (without checking ifra_addr).  This was because netinet
433 	 * code/API assumed at most 1 interface address per interface.
434 	 * Since IPv6 allows a node to assign multiple addresses
435 	 * on a single interface, we almost always look and check the
436 	 * presence of ifra_addr, and reject invalid ones here.
437 	 * It also decreases duplicated code among SIOC*_IN6 operations.
438 	 */
439 	switch (cmd) {
440 	case SIOCAIFADDR_IN6:
441 	case SIOCSIFPHYADDR_IN6:
442 		sa6 = &ifra->ifra_addr;
443 		break;
444 	case SIOCSIFADDR_IN6:
445 	case SIOCGIFADDR_IN6:
446 	case SIOCSIFDSTADDR_IN6:
447 	case SIOCSIFNETMASK_IN6:
448 	case SIOCGIFDSTADDR_IN6:
449 	case SIOCGIFNETMASK_IN6:
450 	case SIOCDIFADDR_IN6:
451 	case SIOCGIFPSRCADDR_IN6:
452 	case SIOCGIFPDSTADDR_IN6:
453 	case SIOCGIFAFLAG_IN6:
454 	case SIOCSNDFLUSH_IN6:
455 	case SIOCSPFXFLUSH_IN6:
456 	case SIOCSRTRFLUSH_IN6:
457 	case SIOCGIFALIFETIME_IN6:
458 	case SIOCSIFALIFETIME_IN6:
459 	case SIOCGIFSTAT_IN6:
460 	case SIOCGIFSTAT_ICMP6:
461 		sa6 = &ifr->ifr_addr;
462 		break;
463 	default:
464 		sa6 = NULL;
465 		break;
466 	}
467 	if (sa6 && sa6->sin6_family == AF_INET6) {
468 		if (IN6_IS_ADDR_LINKLOCAL(&sa6->sin6_addr)) {
469 			if (sa6->sin6_addr.s6_addr16[1] == 0) {
470 				/* link ID is not embedded by the user */
471 				sa6->sin6_addr.s6_addr16[1] =
472 				    htons(ifp->if_index);
473 			} else if (sa6->sin6_addr.s6_addr16[1] !=
474 			    htons(ifp->if_index)) {
475 				return (EINVAL);	/* link ID contradicts */
476 			}
477 			if (sa6->sin6_scope_id) {
478 				if (sa6->sin6_scope_id !=
479 				    (u_int32_t)ifp->if_index)
480 					return (EINVAL);
481 				sa6->sin6_scope_id = 0; /* XXX: good way? */
482 			}
483 		}
484 		ia = in6ifa_ifpwithaddr(ifp, &sa6->sin6_addr);
485 	} else
486 		ia = NULL;
487 
488 	switch (cmd) {
489 	case SIOCSIFADDR_IN6:
490 	case SIOCSIFDSTADDR_IN6:
491 	case SIOCSIFNETMASK_IN6:
492 		/*
493 		 * Since IPv6 allows a node to assign multiple addresses
494 		 * on a single interface, SIOCSIFxxx ioctls are deprecated.
495 		 */
496 		return (EINVAL);
497 
498 	case SIOCDIFADDR_IN6:
499 		/*
500 		 * for IPv4, we look for existing in_ifaddr here to allow
501 		 * "ifconfig if0 delete" to remove the first IPv4 address on
502 		 * the interface.  For IPv6, as the spec allows multiple
503 		 * interface address from the day one, we consider "remove the
504 		 * first one" semantics to be not preferable.
505 		 */
506 		if (ia == NULL)
507 			return (EADDRNOTAVAIL);
508 		/* FALLTHROUGH */
509 	case SIOCAIFADDR_IN6:
510 		/*
511 		 * We always require users to specify a valid IPv6 address for
512 		 * the corresponding operation.
513 		 */
514 		if (ifra->ifra_addr.sin6_family != AF_INET6 ||
515 		    ifra->ifra_addr.sin6_len != sizeof(struct sockaddr_in6))
516 			return (EAFNOSUPPORT);
517 		if (!privileged)
518 			return (EPERM);
519 
520 		break;
521 
522 	case SIOCGIFADDR_IN6:
523 		/* This interface is basically deprecated. use SIOCGIFCONF. */
524 		/* FALLTHROUGH */
525 	case SIOCGIFAFLAG_IN6:
526 	case SIOCGIFNETMASK_IN6:
527 	case SIOCGIFDSTADDR_IN6:
528 	case SIOCGIFALIFETIME_IN6:
529 		/* must think again about its semantics */
530 		if (ia == NULL)
531 			return (EADDRNOTAVAIL);
532 		break;
533 	case SIOCSIFALIFETIME_IN6:
534 	    {
535 		struct in6_addrlifetime *lt;
536 
537 		if (!privileged)
538 			return (EPERM);
539 		if (ia == NULL)
540 			return (EADDRNOTAVAIL);
541 		/* sanity for overflow - beware unsigned */
542 		lt = &ifr->ifr_ifru.ifru_lifetime;
543 		if (lt->ia6t_vltime != ND6_INFINITE_LIFETIME
544 		 && lt->ia6t_vltime + time.tv_sec < time.tv_sec) {
545 			return EINVAL;
546 		}
547 		if (lt->ia6t_pltime != ND6_INFINITE_LIFETIME
548 		 && lt->ia6t_pltime + time.tv_sec < time.tv_sec) {
549 			return EINVAL;
550 		}
551 		break;
552 	    }
553 	}
554 
555 	switch (cmd) {
556 
557 	case SIOCGIFADDR_IN6:
558 		ifr->ifr_addr = ia->ia_addr;
559 		break;
560 
561 	case SIOCGIFDSTADDR_IN6:
562 		if ((ifp->if_flags & IFF_POINTOPOINT) == 0)
563 			return (EINVAL);
564 		/*
565 		 * XXX: should we check if ifa_dstaddr is NULL and return
566 		 * an error?
567 		 */
568 		ifr->ifr_dstaddr = ia->ia_dstaddr;
569 		break;
570 
571 	case SIOCGIFNETMASK_IN6:
572 		ifr->ifr_addr = ia->ia_prefixmask;
573 		break;
574 
575 	case SIOCGIFAFLAG_IN6:
576 		ifr->ifr_ifru.ifru_flags6 = ia->ia6_flags;
577 		break;
578 
579 	case SIOCGIFSTAT_IN6:
580 		if (ifp == NULL)
581 			return EINVAL;
582 		bzero(&ifr->ifr_ifru.ifru_stat,
583 		    sizeof(ifr->ifr_ifru.ifru_stat));
584 		ifr->ifr_ifru.ifru_stat =
585 		    *((struct in6_ifextra *)ifp->if_afdata[AF_INET6])->in6_ifstat;
586 		break;
587 
588 	case SIOCGIFSTAT_ICMP6:
589 		if (ifp == NULL)
590 			return EINVAL;
591 		bzero(&ifr->ifr_ifru.ifru_stat,
592 		    sizeof(ifr->ifr_ifru.ifru_icmp6stat));
593 		ifr->ifr_ifru.ifru_icmp6stat =
594 		    *((struct in6_ifextra *)ifp->if_afdata[AF_INET6])->icmp6_ifstat;
595 		break;
596 
597 	case SIOCGIFALIFETIME_IN6:
598 		ifr->ifr_ifru.ifru_lifetime = ia->ia6_lifetime;
599 		if (ia->ia6_lifetime.ia6t_vltime != ND6_INFINITE_LIFETIME) {
600 			time_t maxexpire;
601 			struct in6_addrlifetime *retlt =
602 			    &ifr->ifr_ifru.ifru_lifetime;
603 
604 			/*
605 			 * XXX: adjust expiration time assuming time_t is
606 			 * signed.
607 			 */
608 			maxexpire = (-1) &
609 			    ~(1 << ((sizeof(maxexpire) * 8) - 1));
610 			if (ia->ia6_lifetime.ia6t_vltime <
611 			    maxexpire - ia->ia6_updatetime) {
612 				retlt->ia6t_expire = ia->ia6_updatetime +
613 				    ia->ia6_lifetime.ia6t_vltime;
614 			} else
615 				retlt->ia6t_expire = maxexpire;
616 		}
617 		if (ia->ia6_lifetime.ia6t_pltime != ND6_INFINITE_LIFETIME) {
618 			time_t maxexpire;
619 			struct in6_addrlifetime *retlt =
620 			    &ifr->ifr_ifru.ifru_lifetime;
621 
622 			/*
623 			 * XXX: adjust expiration time assuming time_t is
624 			 * signed.
625 			 */
626 			maxexpire = (-1) &
627 			    ~(1 << ((sizeof(maxexpire) * 8) - 1));
628 			if (ia->ia6_lifetime.ia6t_pltime <
629 			    maxexpire - ia->ia6_updatetime) {
630 				retlt->ia6t_preferred = ia->ia6_updatetime +
631 				    ia->ia6_lifetime.ia6t_pltime;
632 			} else
633 				retlt->ia6t_preferred = maxexpire;
634 		}
635 		break;
636 
637 	case SIOCSIFALIFETIME_IN6:
638 		ia->ia6_lifetime = ifr->ifr_ifru.ifru_lifetime;
639 		/* for sanity */
640 		if (ia->ia6_lifetime.ia6t_vltime != ND6_INFINITE_LIFETIME) {
641 			ia->ia6_lifetime.ia6t_expire =
642 				time.tv_sec + ia->ia6_lifetime.ia6t_vltime;
643 		} else
644 			ia->ia6_lifetime.ia6t_expire = 0;
645 		if (ia->ia6_lifetime.ia6t_pltime != ND6_INFINITE_LIFETIME) {
646 			ia->ia6_lifetime.ia6t_preferred =
647 				time.tv_sec + ia->ia6_lifetime.ia6t_pltime;
648 		} else
649 			ia->ia6_lifetime.ia6t_preferred = 0;
650 		break;
651 
652 	case SIOCAIFADDR_IN6:
653 	{
654 		int i, error = 0;
655 		struct nd_prefix pr0, *pr;
656 
657 		/* reject read-only flags */
658 		if ((ifra->ifra_flags & IN6_IFF_DUPLICATED) != 0 ||
659 		    (ifra->ifra_flags & IN6_IFF_DETACHED) != 0 ||
660 		    (ifra->ifra_flags & IN6_IFF_NODAD) != 0 ||
661 		    (ifra->ifra_flags & IN6_IFF_AUTOCONF) != 0) {
662 			return (EINVAL);
663 		}
664 		/*
665 		 * first, make or update the interface address structure,
666 		 * and link it to the list.
667 		 */
668 		if ((error = in6_update_ifa(ifp, ifra, ia)) != 0)
669 			return (error);
670 		if ((ia = in6ifa_ifpwithaddr(ifp, &ifra->ifra_addr.sin6_addr))
671 		    == NULL) {
672 		    	/*
673 			 * this can happen when the user specify the 0 valid
674 			 * lifetime.
675 			 */
676 			break;
677 		}
678 
679 		/*
680 		 * then, make the prefix on-link on the interface.
681 		 * XXX: we'd rather create the prefix before the address, but
682 		 * we need at least one address to install the corresponding
683 		 * interface route, so we configure the address first.
684 		 */
685 
686 		/*
687 		 * convert mask to prefix length (prefixmask has already
688 		 * been validated in in6_update_ifa().
689 		 */
690 		bzero(&pr0, sizeof(pr0));
691 		pr0.ndpr_ifp = ifp;
692 		pr0.ndpr_plen = in6_mask2len(&ifra->ifra_prefixmask.sin6_addr,
693 		    NULL);
694 		if (pr0.ndpr_plen == 128) {
695 			break;	/* we don't need to install a host route. */
696 		}
697 		pr0.ndpr_prefix = ifra->ifra_addr;
698 		pr0.ndpr_mask = ifra->ifra_prefixmask.sin6_addr;
699 		/* apply the mask for safety. */
700 		for (i = 0; i < 4; i++) {
701 			pr0.ndpr_prefix.sin6_addr.s6_addr32[i] &=
702 			    ifra->ifra_prefixmask.sin6_addr.s6_addr32[i];
703 		}
704 		/*
705 		 * XXX: since we don't have an API to set prefix (not address)
706 		 * lifetimes, we just use the same lifetimes as addresses.
707 		 * The (temporarily) installed lifetimes can be overridden by
708 		 * later advertised RAs (when accept_rtadv is non 0), which is
709 		 * an intended behavior.
710 		 */
711 		pr0.ndpr_raf_onlink = 1; /* should be configurable? */
712 		pr0.ndpr_raf_auto =
713 		    ((ifra->ifra_flags & IN6_IFF_AUTOCONF) != 0);
714 		pr0.ndpr_vltime = ifra->ifra_lifetime.ia6t_vltime;
715 		pr0.ndpr_pltime = ifra->ifra_lifetime.ia6t_pltime;
716 
717 		/* add the prefix if not yet. */
718 		if ((pr = nd6_prefix_lookup(&pr0)) == NULL) {
719 			/*
720 			 * nd6_prelist_add will install the corresponding
721 			 * interface route.
722 			 */
723 			if ((error = nd6_prelist_add(&pr0, NULL, &pr)) != 0)
724 				return (error);
725 			if (pr == NULL) {
726 				log(LOG_ERR, "nd6_prelist_add succeeded but "
727 				    "no prefix\n");
728 				return (EINVAL); /* XXX panic here? */
729 			}
730 		}
731 
732 		/* relate the address to the prefix */
733 		if (ia->ia6_ndpr == NULL) {
734 			ia->ia6_ndpr = pr;
735 			pr->ndpr_refcnt++;
736 		}
737 
738 		/*
739 		 * this might affect the status of autoconfigured addresses,
740 		 * that is, this address might make other addresses detached.
741 		 */
742 		pfxlist_onlink_check();
743 
744 		break;
745 	}
746 
747 	case SIOCDIFADDR_IN6:
748 	{
749 		int i = 0, purgeprefix = 0;
750 		struct nd_prefix pr0, *pr = NULL;
751 
752 		/*
753 		 * If the address being deleted is the only one that owns
754 		 * the corresponding prefix, expire the prefix as well.
755 		 * XXX: theoretically, we don't have to worry about such
756 		 * relationship, since we separate the address management
757 		 * and the prefix management.  We do this, however, to provide
758 		 * as much backward compatibility as possible in terms of
759 		 * the ioctl operation.
760 		 */
761 		bzero(&pr0, sizeof(pr0));
762 		pr0.ndpr_ifp = ifp;
763 		pr0.ndpr_plen = in6_mask2len(&ia->ia_prefixmask.sin6_addr,
764 		    NULL);
765 		if (pr0.ndpr_plen == 128)
766 			goto purgeaddr;
767 		pr0.ndpr_prefix = ia->ia_addr;
768 		pr0.ndpr_mask = ia->ia_prefixmask.sin6_addr;
769 		for (i = 0; i < 4; i++) {
770 			pr0.ndpr_prefix.sin6_addr.s6_addr32[i] &=
771 			    ia->ia_prefixmask.sin6_addr.s6_addr32[i];
772 		}
773 		if ((pr = nd6_prefix_lookup(&pr0)) != NULL &&
774 		    pr == ia->ia6_ndpr) {
775 			pr->ndpr_refcnt--;
776 			if (pr->ndpr_refcnt == 0)
777 				purgeprefix = 1;
778 		}
779 
780 	  purgeaddr:
781 		in6_purgeaddr(&ia->ia_ifa);
782 		if (pr && purgeprefix)
783 			prelist_remove(pr);
784 		break;
785 	}
786 
787 	default:
788 		if (ifp == NULL || ifp->if_ioctl == 0)
789 			return (EOPNOTSUPP);
790 		return ((*ifp->if_ioctl)(ifp, cmd, data));
791 	}
792 
793 	return (0);
794 }
795 
796 /*
797  * Update parameters of an IPv6 interface address.
798  * If necessary, a new entry is created and linked into address chains.
799  * This function is separated from in6_control().
800  * XXX: should this be performed under splnet()?
801  */
802 int
803 in6_update_ifa(ifp, ifra, ia)
804 	struct ifnet *ifp;
805 	struct in6_aliasreq *ifra;
806 	struct in6_ifaddr *ia;
807 {
808 	int error = 0, hostIsNew = 0, plen = -1;
809 	struct in6_ifaddr *oia;
810 	struct sockaddr_in6 dst6;
811 	struct in6_addrlifetime *lt;
812 	struct in6_multi_mship *imm;
813 	struct rtentry *rt;
814 
815 	/* Validate parameters */
816 	if (ifp == NULL || ifra == NULL) /* this maybe redundant */
817 		return (EINVAL);
818 
819 	/*
820 	 * The destination address for a p2p link must have a family
821 	 * of AF_UNSPEC or AF_INET6.
822 	 */
823 	if ((ifp->if_flags & IFF_POINTOPOINT) != 0 &&
824 	    ifra->ifra_dstaddr.sin6_family != AF_INET6 &&
825 	    ifra->ifra_dstaddr.sin6_family != AF_UNSPEC)
826 		return (EAFNOSUPPORT);
827 	/*
828 	 * validate ifra_prefixmask.  don't check sin6_family, netmask
829 	 * does not carry fields other than sin6_len.
830 	 */
831 	if (ifra->ifra_prefixmask.sin6_len > sizeof(struct sockaddr_in6))
832 		return (EINVAL);
833 	/*
834 	 * Because the IPv6 address architecture is classless, we require
835 	 * users to specify a (non 0) prefix length (mask) for a new address.
836 	 * We also require the prefix (when specified) mask is valid, and thus
837 	 * reject a non-consecutive mask.
838 	 */
839 	if (ia == NULL && ifra->ifra_prefixmask.sin6_len == 0)
840 		return (EINVAL);
841 	if (ifra->ifra_prefixmask.sin6_len != 0) {
842 		plen = in6_mask2len(&ifra->ifra_prefixmask.sin6_addr,
843 		    (u_char *)&ifra->ifra_prefixmask +
844 		    ifra->ifra_prefixmask.sin6_len);
845 		if (plen <= 0)
846 			return (EINVAL);
847 	} else {
848 		/*
849 		 * In this case, ia must not be NULL.  We just use its prefix
850 		 * length.
851 		 */
852 		plen = in6_mask2len(&ia->ia_prefixmask.sin6_addr, NULL);
853 	}
854 	/*
855 	 * If the destination address on a p2p interface is specified,
856 	 * and the address is a scoped one, validate/set the scope
857 	 * zone identifier.
858 	 */
859 	dst6 = ifra->ifra_dstaddr;
860 	if ((ifp->if_flags & (IFF_POINTOPOINT|IFF_LOOPBACK)) != 0 &&
861 	    (dst6.sin6_family == AF_INET6)) {
862 		/* link-local index check: should be a separate function? */
863 		if (IN6_IS_ADDR_LINKLOCAL(&dst6.sin6_addr)) {
864 			if (dst6.sin6_addr.s6_addr16[1] == 0) {
865 				/*
866 				 * interface ID is not embedded by
867 				 * the user
868 				 */
869 				dst6.sin6_addr.s6_addr16[1] =
870 				    htons(ifp->if_index);
871 			} else if (dst6.sin6_addr.s6_addr16[1] !=
872 			    htons(ifp->if_index)) {
873 				return (EINVAL);	/* ifid contradicts */
874 			}
875 		}
876 	}
877 	/*
878 	 * The destination address can be specified only for a p2p or a
879 	 * loopback interface.  If specified, the corresponding prefix length
880 	 * must be 128.
881 	 */
882 	if (ifra->ifra_dstaddr.sin6_family == AF_INET6) {
883 #ifdef FORCE_P2PPLEN
884 		int i;
885 #endif
886 
887 		if ((ifp->if_flags & (IFF_POINTOPOINT|IFF_LOOPBACK)) == 0) {
888 			/* XXX: noisy message */
889 			nd6log((LOG_INFO, "in6_update_ifa: a destination can "
890 			    "be specified for a p2p or a loopback IF only\n"));
891 			return (EINVAL);
892 		}
893 		if (plen != 128) {
894 			nd6log((LOG_INFO, "in6_update_ifa: prefixlen should "
895 			    "be 128 when dstaddr is specified\n"));
896 #ifdef FORCE_P2PPLEN
897 			/*
898 			 * To be compatible with old configurations,
899 			 * such as ifconfig gif0 inet6 2001::1 2001::2
900 			 * prefixlen 126, we override the specified
901 			 * prefixmask as if the prefix length was 128.
902 			 */
903 			ifra->ifra_prefixmask.sin6_len =
904 			    sizeof(struct sockaddr_in6);
905 			for (i = 0; i < 4; i++)
906 				ifra->ifra_prefixmask.sin6_addr.s6_addr32[i] =
907 				    0xffffffff;
908 			plen = 128;
909 #else
910 			return (EINVAL);
911 #endif
912 		}
913 	}
914 	/* lifetime consistency check */
915 	lt = &ifra->ifra_lifetime;
916 	if (lt->ia6t_pltime > lt->ia6t_vltime)
917 		return (EINVAL);
918 	if (lt->ia6t_vltime == 0) {
919 		/*
920 		 * the following log might be noisy, but this is a typical
921 		 * configuration mistake or a tool's bug.
922 		 */
923 		nd6log((LOG_INFO,
924 		    "in6_update_ifa: valid lifetime is 0 for %s\n",
925 		    ip6_sprintf(&ifra->ifra_addr.sin6_addr)));
926 
927 		if (ia == NULL)
928 			return (0); /* there's nothing to do */
929 	}
930 
931 	/*
932 	 * If this is a new address, allocate a new ifaddr and link it
933 	 * into chains.
934 	 */
935 	if (ia == NULL) {
936 		hostIsNew = 1;
937 		/*
938 		 * When in6_update_ifa() is called in a process of a received
939 		 * RA, it is called under an interrupt context.  So, we should
940 		 * call malloc with M_NOWAIT.
941 		 */
942 		ia = (struct in6_ifaddr *) malloc(sizeof(*ia), M_IFADDR,
943 		    M_NOWAIT);
944 		if (ia == NULL)
945 			return (ENOBUFS);
946 		bzero((caddr_t)ia, sizeof(*ia));
947 		LIST_INIT(&ia->ia6_memberships);
948 		/* Initialize the address and masks, and put time stamp */
949 		ia->ia_ifa.ifa_addr = (struct sockaddr *)&ia->ia_addr;
950 		ia->ia_addr.sin6_family = AF_INET6;
951 		ia->ia_addr.sin6_len = sizeof(ia->ia_addr);
952 		ia->ia6_createtime = ia->ia6_updatetime = time.tv_sec;
953 		if ((ifp->if_flags & (IFF_POINTOPOINT | IFF_LOOPBACK)) != 0) {
954 			/*
955 			 * XXX: some functions expect that ifa_dstaddr is not
956 			 * NULL for p2p interfaces.
957 			 */
958 			ia->ia_ifa.ifa_dstaddr =
959 			    (struct sockaddr *)&ia->ia_dstaddr;
960 		} else {
961 			ia->ia_ifa.ifa_dstaddr = NULL;
962 		}
963 		ia->ia_ifa.ifa_netmask =
964 		    (struct sockaddr *)&ia->ia_prefixmask;
965 
966 		ia->ia_ifp = ifp;
967 		if ((oia = in6_ifaddr) != NULL) {
968 			for ( ; oia->ia_next; oia = oia->ia_next)
969 				continue;
970 			oia->ia_next = ia;
971 		} else
972 			in6_ifaddr = ia;
973 		/* gain a refcnt for the link from in6_ifaddr */
974 		IFAREF(&ia->ia_ifa);
975 
976 		TAILQ_INSERT_TAIL(&ifp->if_addrlist, &ia->ia_ifa,
977 				  ifa_list);
978 		/* gain another refcnt for the link from if_addrlist */
979 		IFAREF(&ia->ia_ifa);
980 	}
981 
982 	/* set prefix mask */
983 	if (ifra->ifra_prefixmask.sin6_len) {
984 		/*
985 		 * We prohibit changing the prefix length of an existing
986 		 * address, because
987 		 * + such an operation should be rare in IPv6, and
988 		 * + the operation would confuse prefix management.
989 		 */
990 		if (ia->ia_prefixmask.sin6_len &&
991 		    in6_mask2len(&ia->ia_prefixmask.sin6_addr, NULL) != plen) {
992 			nd6log((LOG_INFO, "in6_update_ifa: the prefix length of an"
993 			    " existing (%s) address should not be changed\n",
994 			    ip6_sprintf(&ia->ia_addr.sin6_addr)));
995 			error = EINVAL;
996 			goto unlink;
997 		}
998 		ia->ia_prefixmask = ifra->ifra_prefixmask;
999 	}
1000 
1001 	/*
1002 	 * If a new destination address is specified, scrub the old one and
1003 	 * install the new destination.  Note that the interface must be
1004 	 * p2p or loopback (see the check above.)
1005 	 */
1006 	if (dst6.sin6_family == AF_INET6 &&
1007 	    !IN6_ARE_ADDR_EQUAL(&dst6.sin6_addr, &ia->ia_dstaddr.sin6_addr)) {
1008 		int e;
1009 
1010 		if ((ia->ia_flags & IFA_ROUTE) != 0 &&
1011 		    (e = rtinit(&(ia->ia_ifa), (int)RTM_DELETE, RTF_HOST)) != 0) {
1012 			nd6log((LOG_ERR, "in6_update_ifa: failed to remove "
1013 			    "a route to the old destination: %s\n",
1014 			    ip6_sprintf(&ia->ia_addr.sin6_addr)));
1015 			/* proceed anyway... */
1016 		} else
1017 			ia->ia_flags &= ~IFA_ROUTE;
1018 		ia->ia_dstaddr = dst6;
1019 	}
1020 
1021 	/*
1022 	 * Set lifetimes.  We do not refer to ia6t_expire and ia6t_preferred
1023 	 * to see if the address is deprecated or invalidated, but initialize
1024 	 * these members for applications.
1025 	 */
1026 	ia->ia6_lifetime = ifra->ifra_lifetime;
1027 	if (ia->ia6_lifetime.ia6t_vltime != ND6_INFINITE_LIFETIME) {
1028 		ia->ia6_lifetime.ia6t_expire =
1029 		    time.tv_sec + ia->ia6_lifetime.ia6t_vltime;
1030 	} else
1031 		ia->ia6_lifetime.ia6t_expire = 0;
1032 	if (ia->ia6_lifetime.ia6t_pltime != ND6_INFINITE_LIFETIME) {
1033 		ia->ia6_lifetime.ia6t_preferred =
1034 		    time.tv_sec + ia->ia6_lifetime.ia6t_pltime;
1035 	} else
1036 		ia->ia6_lifetime.ia6t_preferred = 0;
1037 
1038 	/* reset the interface and routing table appropriately. */
1039 	if ((error = in6_ifinit(ifp, ia, &ifra->ifra_addr, hostIsNew)) != 0)
1040 		goto unlink;
1041 
1042 	/*
1043 	 * configure address flags.
1044 	 */
1045 	ia->ia6_flags = ifra->ifra_flags;
1046 	/*
1047 	 * backward compatibility - if IN6_IFF_DEPRECATED is set from the
1048 	 * userland, make it deprecated.
1049 	 */
1050 	if ((ifra->ifra_flags & IN6_IFF_DEPRECATED) != 0) {
1051 		ia->ia6_lifetime.ia6t_pltime = 0;
1052 		ia->ia6_lifetime.ia6t_preferred = time.tv_sec;
1053 	}
1054 	/*
1055 	 * Make the address tentative before joining multicast addresses,
1056 	 * so that corresponding MLD responses would not have a tentative
1057 	 * source address.
1058 	 */
1059 	ia->ia6_flags &= ~IN6_IFF_DUPLICATED;	/* safety */
1060 	if (hostIsNew && in6if_do_dad(ifp))
1061 		ia->ia6_flags |= IN6_IFF_TENTATIVE;
1062 
1063 	/*
1064 	 * Beyond this point, we should call in6_purgeaddr upon an error,
1065 	 * not just go to unlink.
1066 	 */
1067 
1068 	if ((ifp->if_flags & IFF_MULTICAST) != 0) {
1069 		struct sockaddr_in6 mltaddr, mltmask;
1070 #ifndef SCOPEDROUTING
1071 		u_int32_t zoneid = 0;
1072 #endif
1073 
1074 		if (hostIsNew) {
1075 			/* join solicited multicast addr for new host id */
1076 			struct sockaddr_in6 llsol;
1077 
1078 			bzero(&llsol, sizeof(llsol));
1079 			llsol.sin6_family = AF_INET6;
1080 			llsol.sin6_len = sizeof(llsol);
1081 			llsol.sin6_addr.s6_addr16[0] = htons(0xff02);
1082 			llsol.sin6_addr.s6_addr16[1] = htons(ifp->if_index);
1083 			llsol.sin6_addr.s6_addr32[1] = 0;
1084 			llsol.sin6_addr.s6_addr32[2] = htonl(1);
1085 			llsol.sin6_addr.s6_addr32[3] =
1086 			    ifra->ifra_addr.sin6_addr.s6_addr32[3];
1087 			llsol.sin6_addr.s6_addr8[12] = 0xff;
1088 			imm = in6_joingroup(ifp, &llsol.sin6_addr, &error);
1089 			if (imm) {
1090 				LIST_INSERT_HEAD(&ia->ia6_memberships, imm,
1091 				    i6mm_chain);
1092 			} else {
1093 				nd6log((LOG_ERR, "in6_update_ifa: addmulti "
1094 				    "failed for %s on %s (errno=%d)\n",
1095 				    ip6_sprintf(&llsol.sin6_addr),
1096 				    if_name(ifp), error));
1097 				goto cleanup;
1098 			}
1099 		}
1100 
1101 		bzero(&mltmask, sizeof(mltmask));
1102 		mltmask.sin6_len = sizeof(struct sockaddr_in6);
1103 		mltmask.sin6_family = AF_INET6;
1104 		mltmask.sin6_addr = in6mask32;
1105 
1106 		/*
1107 		 * join link-local all-nodes address
1108 		 */
1109 		bzero(&mltaddr, sizeof(mltaddr));
1110 		mltaddr.sin6_len = sizeof(struct sockaddr_in6);
1111 		mltaddr.sin6_family = AF_INET6;
1112 		mltaddr.sin6_addr = in6addr_linklocal_allnodes;
1113 		mltaddr.sin6_addr.s6_addr16[1] = htons(ifp->if_index);
1114 
1115 		/*
1116 		 * XXX: do we really need this automatic routes?
1117 		 * We should probably reconsider this stuff.  Most applications
1118 		 * actually do not need the routes, since they usually specify
1119 		 * the outgoing interface.
1120 		 */
1121 		rt = rtalloc1((struct sockaddr *)&mltaddr, 0);
1122 		if (rt) {
1123 			/*
1124 			 * 32bit came from "mltmask"
1125 			 * XXX: only works in !SCOPEDROUTING case.
1126 			 */
1127 			if (memcmp(&mltaddr.sin6_addr,
1128 			    &((struct sockaddr_in6 *)rt_key(rt))->sin6_addr,
1129 			    32 / 8)) {
1130 				RTFREE(rt);
1131 				rt = NULL;
1132 			}
1133 		}
1134 		if (!rt) {
1135 			struct rt_addrinfo info;
1136 
1137 			bzero(&info, sizeof(info));
1138 			info.rti_info[RTAX_DST] = (struct sockaddr *)&mltaddr;
1139 			info.rti_info[RTAX_GATEWAY] =
1140 			    (struct sockaddr *)&ia->ia_addr;
1141 			info.rti_info[RTAX_NETMASK] =
1142 			    (struct sockaddr *)&mltmask;
1143 			info.rti_info[RTAX_IFA] =
1144 			    (struct sockaddr *)&ia->ia_addr;
1145 			/* XXX: we need RTF_CLONING to fake nd6_rtrequest */
1146 			info.rti_flags = RTF_UP | RTF_CLONING;
1147 			error = rtrequest1(RTM_ADD, &info, NULL);
1148 			if (error)
1149 				goto cleanup;
1150 		} else {
1151 			RTFREE(rt);
1152 		}
1153 #ifndef SCOPEDROUTING
1154 		mltaddr.sin6_scope_id = zoneid;	/* XXX */
1155 #endif
1156 		imm = in6_joingroup(ifp, &mltaddr.sin6_addr, &error);
1157 		if (imm) {
1158 			LIST_INSERT_HEAD(&ia->ia6_memberships, imm,
1159 			    i6mm_chain);
1160 		} else {
1161 			nd6log((LOG_WARNING,
1162 			    "in6_update_ifa: addmulti failed for "
1163 			    "%s on %s (errno=%d)\n",
1164 			    ip6_sprintf(&mltaddr.sin6_addr),
1165 			    if_name(ifp), error));
1166 			goto cleanup;
1167 		}
1168 
1169 		/*
1170 		 * join node information group address
1171 		 */
1172 		if (in6_nigroup(ifp, hostname, hostnamelen, &mltaddr) == 0) {
1173 			imm = in6_joingroup(ifp, &mltaddr.sin6_addr, &error);
1174 			if (imm) {
1175 				LIST_INSERT_HEAD(&ia->ia6_memberships, imm,
1176 				    i6mm_chain);
1177 			} else {
1178 				nd6log((LOG_WARNING, "in6_update_ifa: "
1179 				    "addmulti failed for %s on %s (errno=%d)\n",
1180 				    ip6_sprintf(&mltaddr.sin6_addr),
1181 				    if_name(ifp), error));
1182 				/* XXX not very fatal, go on... */
1183 			}
1184 		}
1185 
1186 		if (ifp->if_flags & IFF_LOOPBACK) {
1187 			/*
1188 			 * join node-local all-nodes address, on loopback.
1189 			 * (ff01::1%ifN, and ff01::%ifN/32)
1190 			 */
1191 			mltaddr.sin6_addr = in6addr_nodelocal_allnodes;
1192 
1193 			/* XXX: again, do we really need the route? */
1194 			rt = rtalloc1((struct sockaddr *)&mltaddr, 0);
1195 			if (rt) {
1196 				/* 32bit came from "mltmask" */
1197 				if (memcmp(&mltaddr.sin6_addr,
1198 				    &((struct sockaddr_in6 *)rt_key(rt))->sin6_addr,
1199 				    32 / 8)) {
1200 					RTFREE(rt);
1201 					rt = NULL;
1202 				}
1203 			}
1204 			if (!rt) {
1205 				struct rt_addrinfo info;
1206 
1207 				bzero(&info, sizeof(info));
1208 				info.rti_info[RTAX_DST] = (struct sockaddr *)&mltaddr;
1209 				info.rti_info[RTAX_GATEWAY] =
1210 				    (struct sockaddr *)&ia->ia_addr;
1211 				info.rti_info[RTAX_NETMASK] =
1212 				    (struct sockaddr *)&mltmask;
1213 				info.rti_info[RTAX_IFA] =
1214 				    (struct sockaddr *)&ia->ia_addr;
1215 				info.rti_flags = RTF_UP | RTF_CLONING;
1216 				error = rtrequest1(RTM_ADD, &info, NULL);
1217 				if (error)
1218 					goto cleanup;
1219 			} else {
1220 				RTFREE(rt);
1221 			}
1222 			imm = in6_joingroup(ifp, &mltaddr.sin6_addr, &error);
1223 			if (imm) {
1224 				LIST_INSERT_HEAD(&ia->ia6_memberships, imm,
1225 				    i6mm_chain);
1226 			} else {
1227 				nd6log((LOG_WARNING, "in6_update_ifa: "
1228 				    "addmulti failed for %s on %s "
1229 				    "(errno=%d)\n",
1230 				    ip6_sprintf(&mltaddr.sin6_addr),
1231 				    if_name(ifp), error));
1232 				goto cleanup;
1233 			}
1234 		}
1235 	}
1236 
1237 	/*
1238 	 * Perform DAD, if needed.
1239 	 * XXX It may be of use, if we can administratively
1240 	 * disable DAD.
1241 	 */
1242 	if (hostIsNew && in6if_do_dad(ifp) &&
1243 	    (ifra->ifra_flags & IN6_IFF_NODAD) == 0)
1244 	{
1245 		nd6_dad_start((struct ifaddr *)ia, NULL);
1246 	}
1247 
1248 	return (error);
1249 
1250   unlink:
1251 	/*
1252 	 * XXX: if a change of an existing address failed, keep the entry
1253 	 * anyway.
1254 	 */
1255 	if (hostIsNew)
1256 		in6_unlink_ifa(ia, ifp);
1257 	return (error);
1258 
1259   cleanup:
1260 	in6_purgeaddr(&ia->ia_ifa);
1261 	return error;
1262 }
1263 
1264 void
1265 in6_purgeaddr(ifa)
1266 	struct ifaddr *ifa;
1267 {
1268 	struct ifnet *ifp = ifa->ifa_ifp;
1269 	struct in6_ifaddr *ia = (struct in6_ifaddr *) ifa;
1270 	struct in6_multi_mship *imm;
1271 
1272 	/* stop DAD processing */
1273 	nd6_dad_stop(ifa);
1274 
1275 	/*
1276 	 * delete route to the destination of the address being purged.
1277 	 * The interface must be p2p or loopback in this case.
1278 	 */
1279 	if ((ia->ia_flags & IFA_ROUTE) != 0 && ia->ia_dstaddr.sin6_len != 0) {
1280 		int e;
1281 
1282 		if ((e = rtinit(&(ia->ia_ifa), (int)RTM_DELETE, RTF_HOST))
1283 		    != 0) {
1284 			log(LOG_ERR, "in6_purgeaddr: failed to remove "
1285 			    "a route to the p2p destination: %s on %s, "
1286 			    "errno=%d\n",
1287 			    ip6_sprintf(&ia->ia_addr.sin6_addr), if_name(ifp),
1288 			    e);
1289 			/* proceed anyway... */
1290 		} else
1291 			ia->ia_flags &= ~IFA_ROUTE;
1292 	}
1293 
1294 	/* Remove ownaddr's loopback rtentry, if it exists. */
1295 	in6_ifremloop(&(ia->ia_ifa));
1296 
1297 	/*
1298 	 * leave from multicast groups we have joined for the interface
1299 	 */
1300 	while ((imm = ia->ia6_memberships.lh_first) != NULL) {
1301 		LIST_REMOVE(imm, i6mm_chain);
1302 		in6_leavegroup(imm);
1303 	}
1304 
1305 	in6_unlink_ifa(ia, ifp);
1306 }
1307 
1308 static void
1309 in6_unlink_ifa(ia, ifp)
1310 	struct in6_ifaddr *ia;
1311 	struct ifnet *ifp;
1312 {
1313 	struct in6_ifaddr *oia;
1314 	int	s = splnet();
1315 
1316 	TAILQ_REMOVE(&ifp->if_addrlist, &ia->ia_ifa, ifa_list);
1317 	/* release a refcnt for the link from if_addrlist */
1318 	IFAFREE(&ia->ia_ifa);
1319 
1320 	oia = ia;
1321 	if (oia == (ia = in6_ifaddr))
1322 		in6_ifaddr = ia->ia_next;
1323 	else {
1324 		while (ia->ia_next && (ia->ia_next != oia))
1325 			ia = ia->ia_next;
1326 		if (ia->ia_next)
1327 			ia->ia_next = oia->ia_next;
1328 		else {
1329 			/* search failed */
1330 			printf("Couldn't unlink in6_ifaddr from in6_ifaddr\n");
1331 		}
1332 	}
1333 
1334 	if (oia->ia6_multiaddrs.lh_first != NULL) {
1335 		/*
1336 		 * XXX thorpej@netbsd.org -- if the interface is going
1337 		 * XXX away, don't save the multicast entries, delete them!
1338 		 */
1339 		if (oia->ia_ifa.ifa_ifp->if_output == if_nulloutput) {
1340 			struct in6_multi *in6m;
1341 
1342 			while ((in6m =
1343 			    LIST_FIRST(&oia->ia6_multiaddrs)) != NULL)
1344 				in6_delmulti(in6m);
1345 		} else
1346 			in6_savemkludge(oia);
1347 	}
1348 
1349 	/*
1350 	 * When an autoconfigured address is being removed, release the
1351 	 * reference to the base prefix.  Also, since the release might
1352 	 * affect the status of other (detached) addresses, call
1353 	 * pfxlist_onlink_check().
1354 	 */
1355 	if ((oia->ia6_flags & IN6_IFF_AUTOCONF) != 0) {
1356 		if (oia->ia6_ndpr == NULL) {
1357 			log(LOG_NOTICE, "in6_unlink_ifa: autoconf'ed address "
1358 			    "%p has no prefix\n", oia);
1359 		} else {
1360 			oia->ia6_ndpr->ndpr_refcnt--;
1361 			oia->ia6_flags &= ~IN6_IFF_AUTOCONF;
1362 			oia->ia6_ndpr = NULL;
1363 		}
1364 
1365 		pfxlist_onlink_check();
1366 	}
1367 
1368 	/*
1369 	 * release another refcnt for the link from in6_ifaddr.
1370 	 * Note that we should decrement the refcnt at least once for all *BSD.
1371 	 */
1372 	IFAFREE(&oia->ia_ifa);
1373 
1374 	splx(s);
1375 }
1376 
1377 void
1378 in6_purgeif(ifp)
1379 	struct ifnet *ifp;
1380 {
1381 	struct ifaddr *ifa, *nifa;
1382 
1383 	for (ifa = TAILQ_FIRST(&ifp->if_addrlist); ifa != NULL; ifa = nifa)
1384 	{
1385 		nifa = TAILQ_NEXT(ifa, ifa_list);
1386 		if (ifa->ifa_addr->sa_family != AF_INET6)
1387 			continue;
1388 		in6_purgeaddr(ifa);
1389 	}
1390 
1391 	in6_ifdetach(ifp);
1392 }
1393 
1394 /*
1395  * SIOC[GAD]LIFADDR.
1396  *	SIOCGLIFADDR: get first address. (?)
1397  *	SIOCGLIFADDR with IFLR_PREFIX:
1398  *		get first address that matches the specified prefix.
1399  *	SIOCALIFADDR: add the specified address.
1400  *	SIOCALIFADDR with IFLR_PREFIX:
1401  *		add the specified prefix, filling hostid part from
1402  *		the first link-local address.  prefixlen must be <= 64.
1403  *	SIOCDLIFADDR: delete the specified address.
1404  *	SIOCDLIFADDR with IFLR_PREFIX:
1405  *		delete the first address that matches the specified prefix.
1406  * return values:
1407  *	EINVAL on invalid parameters
1408  *	EADDRNOTAVAIL on prefix match failed/specified address not found
1409  *	other values may be returned from in6_ioctl()
1410  *
1411  * NOTE: SIOCALIFADDR(with IFLR_PREFIX set) allows prefixlen less than 64.
1412  * this is to accomodate address naming scheme other than RFC2374,
1413  * in the future.
1414  * RFC2373 defines interface id to be 64bit, but it allows non-RFC2374
1415  * address encoding scheme. (see figure on page 8)
1416  */
1417 static int
1418 in6_lifaddr_ioctl(so, cmd, data, ifp, p)
1419 	struct socket *so;
1420 	u_long cmd;
1421 	caddr_t	data;
1422 	struct ifnet *ifp;
1423 	struct proc *p;
1424 {
1425 	struct if_laddrreq *iflr = (struct if_laddrreq *)data;
1426 	struct ifaddr *ifa;
1427 	struct sockaddr *sa;
1428 
1429 	/* sanity checks */
1430 	if (!data || !ifp) {
1431 		panic("invalid argument to in6_lifaddr_ioctl");
1432 		/* NOTREACHED */
1433 	}
1434 
1435 	switch (cmd) {
1436 	case SIOCGLIFADDR:
1437 		/* address must be specified on GET with IFLR_PREFIX */
1438 		if ((iflr->flags & IFLR_PREFIX) == 0)
1439 			break;
1440 		/* FALLTHROUGH */
1441 	case SIOCALIFADDR:
1442 	case SIOCDLIFADDR:
1443 		/* address must be specified on ADD and DELETE */
1444 		sa = (struct sockaddr *)&iflr->addr;
1445 		if (sa->sa_family != AF_INET6)
1446 			return EINVAL;
1447 		if (sa->sa_len != sizeof(struct sockaddr_in6))
1448 			return EINVAL;
1449 		/* XXX need improvement */
1450 		sa = (struct sockaddr *)&iflr->dstaddr;
1451 		if (sa->sa_family && sa->sa_family != AF_INET6)
1452 			return EINVAL;
1453 		if (sa->sa_len && sa->sa_len != sizeof(struct sockaddr_in6))
1454 			return EINVAL;
1455 		break;
1456 	default: /* shouldn't happen */
1457 #if 0
1458 		panic("invalid cmd to in6_lifaddr_ioctl");
1459 		/* NOTREACHED */
1460 #else
1461 		return EOPNOTSUPP;
1462 #endif
1463 	}
1464 	if (sizeof(struct in6_addr) * 8 < iflr->prefixlen)
1465 		return EINVAL;
1466 
1467 	switch (cmd) {
1468 	case SIOCALIFADDR:
1469 	    {
1470 		struct in6_aliasreq ifra;
1471 		struct in6_addr *hostid = NULL;
1472 		int prefixlen;
1473 
1474 		if ((iflr->flags & IFLR_PREFIX) != 0) {
1475 			struct sockaddr_in6 *sin6;
1476 
1477 			/*
1478 			 * hostid is to fill in the hostid part of the
1479 			 * address.  hostid points to the first link-local
1480 			 * address attached to the interface.
1481 			 */
1482 			ifa = (struct ifaddr *)in6ifa_ifpforlinklocal(ifp, 0);
1483 			if (!ifa)
1484 				return EADDRNOTAVAIL;
1485 			hostid = IFA_IN6(ifa);
1486 
1487 		 	/* prefixlen must be <= 64. */
1488 			if (64 < iflr->prefixlen)
1489 				return EINVAL;
1490 			prefixlen = iflr->prefixlen;
1491 
1492 			/* hostid part must be zero. */
1493 			sin6 = (struct sockaddr_in6 *)&iflr->addr;
1494 			if (sin6->sin6_addr.s6_addr32[2] != 0
1495 			 || sin6->sin6_addr.s6_addr32[3] != 0) {
1496 				return EINVAL;
1497 			}
1498 		} else
1499 			prefixlen = iflr->prefixlen;
1500 
1501 		/* copy args to in6_aliasreq, perform ioctl(SIOCAIFADDR_IN6). */
1502 		bzero(&ifra, sizeof(ifra));
1503 		bcopy(iflr->iflr_name, ifra.ifra_name, sizeof(ifra.ifra_name));
1504 
1505 		bcopy(&iflr->addr, &ifra.ifra_addr,
1506 		    ((struct sockaddr *)&iflr->addr)->sa_len);
1507 		if (hostid) {
1508 			/* fill in hostid part */
1509 			ifra.ifra_addr.sin6_addr.s6_addr32[2] =
1510 			    hostid->s6_addr32[2];
1511 			ifra.ifra_addr.sin6_addr.s6_addr32[3] =
1512 			    hostid->s6_addr32[3];
1513 		}
1514 
1515 		if (((struct sockaddr *)&iflr->dstaddr)->sa_family) { /* XXX */
1516 			bcopy(&iflr->dstaddr, &ifra.ifra_dstaddr,
1517 			    ((struct sockaddr *)&iflr->dstaddr)->sa_len);
1518 			if (hostid) {
1519 				ifra.ifra_dstaddr.sin6_addr.s6_addr32[2] =
1520 				    hostid->s6_addr32[2];
1521 				ifra.ifra_dstaddr.sin6_addr.s6_addr32[3] =
1522 				    hostid->s6_addr32[3];
1523 			}
1524 		}
1525 
1526 		ifra.ifra_prefixmask.sin6_len = sizeof(struct sockaddr_in6);
1527 		in6_prefixlen2mask(&ifra.ifra_prefixmask.sin6_addr, prefixlen);
1528 
1529 		ifra.ifra_flags = iflr->flags & ~IFLR_PREFIX;
1530 		return in6_control(so, SIOCAIFADDR_IN6, (caddr_t)&ifra, ifp, p);
1531 	    }
1532 	case SIOCGLIFADDR:
1533 	case SIOCDLIFADDR:
1534 	    {
1535 		struct in6_ifaddr *ia;
1536 		struct in6_addr mask, candidate, match;
1537 		struct sockaddr_in6 *sin6;
1538 		int cmp;
1539 
1540 		bzero(&mask, sizeof(mask));
1541 		if (iflr->flags & IFLR_PREFIX) {
1542 			/* lookup a prefix rather than address. */
1543 			in6_prefixlen2mask(&mask, iflr->prefixlen);
1544 
1545 			sin6 = (struct sockaddr_in6 *)&iflr->addr;
1546 			bcopy(&sin6->sin6_addr, &match, sizeof(match));
1547 			match.s6_addr32[0] &= mask.s6_addr32[0];
1548 			match.s6_addr32[1] &= mask.s6_addr32[1];
1549 			match.s6_addr32[2] &= mask.s6_addr32[2];
1550 			match.s6_addr32[3] &= mask.s6_addr32[3];
1551 
1552 			/* if you set extra bits, that's wrong */
1553 			if (bcmp(&match, &sin6->sin6_addr, sizeof(match)))
1554 				return EINVAL;
1555 
1556 			cmp = 1;
1557 		} else {
1558 			if (cmd == SIOCGLIFADDR) {
1559 				/* on getting an address, take the 1st match */
1560 				cmp = 0;	/* XXX */
1561 			} else {
1562 				/* on deleting an address, do exact match */
1563 				in6_prefixlen2mask(&mask, 128);
1564 				sin6 = (struct sockaddr_in6 *)&iflr->addr;
1565 				bcopy(&sin6->sin6_addr, &match, sizeof(match));
1566 
1567 				cmp = 1;
1568 			}
1569 		}
1570 
1571 		for (ifa = ifp->if_addrlist.tqh_first;
1572 		     ifa;
1573 		     ifa = ifa->ifa_list.tqe_next)
1574 		{
1575 			if (ifa->ifa_addr->sa_family != AF_INET6)
1576 				continue;
1577 			if (!cmp)
1578 				break;
1579 
1580 			bcopy(IFA_IN6(ifa), &candidate, sizeof(candidate));
1581 			candidate.s6_addr32[0] &= mask.s6_addr32[0];
1582 			candidate.s6_addr32[1] &= mask.s6_addr32[1];
1583 			candidate.s6_addr32[2] &= mask.s6_addr32[2];
1584 			candidate.s6_addr32[3] &= mask.s6_addr32[3];
1585 			if (IN6_ARE_ADDR_EQUAL(&candidate, &match))
1586 				break;
1587 		}
1588 		if (!ifa)
1589 			return EADDRNOTAVAIL;
1590 		ia = ifa2ia6(ifa);
1591 
1592 		if (cmd == SIOCGLIFADDR) {
1593 			/* fill in the if_laddrreq structure */
1594 			bcopy(&ia->ia_addr, &iflr->addr, ia->ia_addr.sin6_len);
1595 			if ((ifp->if_flags & IFF_POINTOPOINT) != 0) {
1596 				bcopy(&ia->ia_dstaddr, &iflr->dstaddr,
1597 				    ia->ia_dstaddr.sin6_len);
1598 			} else
1599 				bzero(&iflr->dstaddr, sizeof(iflr->dstaddr));
1600 
1601 			iflr->prefixlen =
1602 			    in6_mask2len(&ia->ia_prefixmask.sin6_addr, NULL);
1603 
1604 			iflr->flags = ia->ia6_flags;	/* XXX */
1605 
1606 			return 0;
1607 		} else {
1608 			struct in6_aliasreq ifra;
1609 
1610 			/* fill in6_aliasreq and do ioctl(SIOCDIFADDR_IN6) */
1611 			bzero(&ifra, sizeof(ifra));
1612 			bcopy(iflr->iflr_name, ifra.ifra_name,
1613 			    sizeof(ifra.ifra_name));
1614 
1615 			bcopy(&ia->ia_addr, &ifra.ifra_addr,
1616 			    ia->ia_addr.sin6_len);
1617 			if ((ifp->if_flags & IFF_POINTOPOINT) != 0) {
1618 				bcopy(&ia->ia_dstaddr, &ifra.ifra_dstaddr,
1619 				    ia->ia_dstaddr.sin6_len);
1620 			} else {
1621 				bzero(&ifra.ifra_dstaddr,
1622 				    sizeof(ifra.ifra_dstaddr));
1623 			}
1624 			bcopy(&ia->ia_prefixmask, &ifra.ifra_dstaddr,
1625 			    ia->ia_prefixmask.sin6_len);
1626 
1627 			ifra.ifra_flags = ia->ia6_flags;
1628 			return in6_control(so, SIOCDIFADDR_IN6, (caddr_t)&ifra,
1629 			    ifp, p);
1630 		}
1631 	    }
1632 	}
1633 
1634 	return EOPNOTSUPP;	/* just for safety */
1635 }
1636 
1637 /*
1638  * Initialize an interface's intetnet6 address
1639  * and routing table entry.
1640  */
1641 static int
1642 in6_ifinit(ifp, ia, sin6, newhost)
1643 	struct ifnet *ifp;
1644 	struct in6_ifaddr *ia;
1645 	struct sockaddr_in6 *sin6;
1646 	int newhost;
1647 {
1648 	int	error = 0, plen, ifacount = 0;
1649 	int	s = splnet();
1650 	struct ifaddr *ifa;
1651 
1652 	/*
1653 	 * Give the interface a chance to initialize
1654 	 * if this is its first address,
1655 	 * and to validate the address if necessary.
1656 	 */
1657 	for (ifa = ifp->if_addrlist.tqh_first; ifa;
1658 	     ifa = ifa->ifa_list.tqe_next)
1659 	{
1660 		if (ifa->ifa_addr == NULL)
1661 			continue;	/* just for safety */
1662 		if (ifa->ifa_addr->sa_family != AF_INET6)
1663 			continue;
1664 		ifacount++;
1665 	}
1666 
1667 	ia->ia_addr = *sin6;
1668 
1669 	if (ifacount <= 1 && ifp->if_ioctl &&
1670 	    (error = (*ifp->if_ioctl)(ifp, SIOCSIFADDR, (caddr_t)ia))) {
1671 		splx(s);
1672 		return (error);
1673 	}
1674 	splx(s);
1675 
1676 	ia->ia_ifa.ifa_metric = ifp->if_metric;
1677 
1678 	/* we could do in(6)_socktrim here, but just omit it at this moment. */
1679 
1680 	/*
1681 	 * Special case:
1682 	 * If the destination address is specified for a point-to-point
1683 	 * interface, install a route to the destination as an interface
1684 	 * direct route.
1685 	 */
1686 	plen = in6_mask2len(&ia->ia_prefixmask.sin6_addr, NULL); /* XXX */
1687 	if (plen == 128 && ia->ia_dstaddr.sin6_family == AF_INET6) {
1688 		if ((error = rtinit(&(ia->ia_ifa), (int)RTM_ADD,
1689 				    RTF_UP | RTF_HOST)) != 0)
1690 			return (error);
1691 		ia->ia_flags |= IFA_ROUTE;
1692 	}
1693 
1694 	/* Add ownaddr as loopback rtentry, if necessary (ex. on p2p link). */
1695 	if (newhost) {
1696 		/* set the rtrequest function to create llinfo */
1697 		ia->ia_ifa.ifa_rtrequest = nd6_rtrequest;
1698 		in6_ifaddloop(&(ia->ia_ifa));
1699 	}
1700 
1701 	if (ifp->if_flags & IFF_MULTICAST)
1702 		in6_restoremkludge(ia, ifp);
1703 
1704 	return (error);
1705 }
1706 
1707 /*
1708  * Multicast address kludge:
1709  * If there were any multicast addresses attached to this interface address,
1710  * either move them to another address on this interface, or save them until
1711  * such time as this interface is reconfigured for IPv6.
1712  */
1713 void
1714 in6_savemkludge(oia)
1715 	struct in6_ifaddr *oia;
1716 {
1717 	struct in6_ifaddr *ia;
1718 	struct in6_multi *in6m, *next;
1719 
1720 	IFP_TO_IA6(oia->ia_ifp, ia);
1721 	if (ia) {	/* there is another address */
1722 		for (in6m = oia->ia6_multiaddrs.lh_first; in6m; in6m = next){
1723 			next = in6m->in6m_entry.le_next;
1724 			IFAFREE(&in6m->in6m_ia->ia_ifa);
1725 			IFAREF(&ia->ia_ifa);
1726 			in6m->in6m_ia = ia;
1727 			LIST_INSERT_HEAD(&ia->ia6_multiaddrs, in6m, in6m_entry);
1728 		}
1729 	} else {	/* last address on this if deleted, save */
1730 		struct multi6_kludge *mk;
1731 
1732 		for (mk = in6_mk.lh_first; mk; mk = mk->mk_entry.le_next) {
1733 			if (mk->mk_ifp == oia->ia_ifp)
1734 				break;
1735 		}
1736 		if (mk == NULL) /* this should not happen! */
1737 			panic("in6_savemkludge: no kludge space");
1738 
1739 		for (in6m = oia->ia6_multiaddrs.lh_first; in6m; in6m = next){
1740 			next = in6m->in6m_entry.le_next;
1741 			IFAFREE(&in6m->in6m_ia->ia_ifa); /* release reference */
1742 			in6m->in6m_ia = NULL;
1743 			LIST_INSERT_HEAD(&mk->mk_head, in6m, in6m_entry);
1744 		}
1745 	}
1746 }
1747 
1748 /*
1749  * Continuation of multicast address hack:
1750  * If there was a multicast group list previously saved for this interface,
1751  * then we re-attach it to the first address configured on the i/f.
1752  */
1753 void
1754 in6_restoremkludge(ia, ifp)
1755 	struct in6_ifaddr *ia;
1756 	struct ifnet *ifp;
1757 {
1758 	struct multi6_kludge *mk;
1759 
1760 	for (mk = in6_mk.lh_first; mk; mk = mk->mk_entry.le_next) {
1761 		if (mk->mk_ifp == ifp) {
1762 			struct in6_multi *in6m, *next;
1763 
1764 			for (in6m = mk->mk_head.lh_first; in6m; in6m = next) {
1765 				next = in6m->in6m_entry.le_next;
1766 				in6m->in6m_ia = ia;
1767 				IFAREF(&ia->ia_ifa);
1768 				LIST_INSERT_HEAD(&ia->ia6_multiaddrs,
1769 						 in6m, in6m_entry);
1770 			}
1771 			LIST_INIT(&mk->mk_head);
1772 			break;
1773 		}
1774 	}
1775 }
1776 
1777 /*
1778  * Allocate space for the kludge at interface initialization time.
1779  * Formerly, we dynamically allocated the space in in6_savemkludge() with
1780  * malloc(M_WAITOK).  However, it was wrong since the function could be called
1781  * under an interrupt context (software timer on address lifetime expiration).
1782  * Also, we cannot just give up allocating the strucutre, since the group
1783  * membership structure is very complex and we need to keep it anyway.
1784  * Of course, this function MUST NOT be called under an interrupt context.
1785  * Specifically, it is expected to be called only from in6_ifattach(), though
1786  * it is a global function.
1787  */
1788 void
1789 in6_createmkludge(ifp)
1790 	struct ifnet *ifp;
1791 {
1792 	struct multi6_kludge *mk;
1793 
1794 	for (mk = in6_mk.lh_first; mk; mk = mk->mk_entry.le_next) {
1795 		/* If we've already had one, do not allocate. */
1796 		if (mk->mk_ifp == ifp)
1797 			return;
1798 	}
1799 
1800 	mk = malloc(sizeof(*mk), M_IPMADDR, M_WAITOK);
1801 
1802 	bzero(mk, sizeof(*mk));
1803 	LIST_INIT(&mk->mk_head);
1804 	mk->mk_ifp = ifp;
1805 	LIST_INSERT_HEAD(&in6_mk, mk, mk_entry);
1806 }
1807 
1808 void
1809 in6_purgemkludge(ifp)
1810 	struct ifnet *ifp;
1811 {
1812 	struct multi6_kludge *mk;
1813 	struct in6_multi *in6m;
1814 
1815 	for (mk = in6_mk.lh_first; mk; mk = mk->mk_entry.le_next) {
1816 		if (mk->mk_ifp != ifp)
1817 			continue;
1818 
1819 		/* leave from all multicast groups joined */
1820 		while ((in6m = LIST_FIRST(&mk->mk_head)) != NULL)
1821 			in6_delmulti(in6m);
1822 		LIST_REMOVE(mk, mk_entry);
1823 		free(mk, M_IPMADDR);
1824 		break;
1825 	}
1826 }
1827 
1828 /*
1829  * Add an address to the list of IP6 multicast addresses for a
1830  * given interface.
1831  */
1832 struct	in6_multi *
1833 in6_addmulti(maddr6, ifp, errorp)
1834 	struct in6_addr *maddr6;
1835 	struct ifnet *ifp;
1836 	int *errorp;
1837 {
1838 	struct	in6_ifaddr *ia;
1839 	struct	in6_ifreq ifr;
1840 	struct	in6_multi *in6m;
1841 	int	s = splsoftnet();
1842 
1843 	*errorp = 0;
1844 	/*
1845 	 * See if address already in list.
1846 	 */
1847 	IN6_LOOKUP_MULTI(*maddr6, ifp, in6m);
1848 	if (in6m != NULL) {
1849 		/*
1850 		 * Found it; just increment the refrence count.
1851 		 */
1852 		in6m->in6m_refcount++;
1853 	} else {
1854 		/*
1855 		 * New address; allocate a new multicast record
1856 		 * and link it into the interface's multicast list.
1857 		 */
1858 		in6m = (struct in6_multi *)
1859 			malloc(sizeof(*in6m), M_IPMADDR, M_NOWAIT);
1860 		if (in6m == NULL) {
1861 			splx(s);
1862 			*errorp = ENOBUFS;
1863 			return (NULL);
1864 		}
1865 		in6m->in6m_addr = *maddr6;
1866 		in6m->in6m_ifp = ifp;
1867 		in6m->in6m_refcount = 1;
1868 		IFP_TO_IA6(ifp, ia);
1869 		if (ia == NULL) {
1870 			free(in6m, M_IPMADDR);
1871 			splx(s);
1872 			*errorp = EADDRNOTAVAIL; /* appropriate? */
1873 			return (NULL);
1874 		}
1875 		in6m->in6m_ia = ia;
1876 		IFAREF(&ia->ia_ifa); /* gain a reference */
1877 		LIST_INSERT_HEAD(&ia->ia6_multiaddrs, in6m, in6m_entry);
1878 
1879 		/*
1880 		 * Ask the network driver to update its multicast reception
1881 		 * filter appropriately for the new address.
1882 		 */
1883 		bzero(&ifr.ifr_addr, sizeof(struct sockaddr_in6));
1884 		ifr.ifr_addr.sin6_len = sizeof(struct sockaddr_in6);
1885 		ifr.ifr_addr.sin6_family = AF_INET6;
1886 		ifr.ifr_addr.sin6_addr = *maddr6;
1887 		if (ifp->if_ioctl == NULL)
1888 			*errorp = ENXIO; /* XXX: appropriate? */
1889 		else
1890 			*errorp = (*ifp->if_ioctl)(ifp, SIOCADDMULTI,
1891 			    (caddr_t)&ifr);
1892 		if (*errorp) {
1893 			LIST_REMOVE(in6m, in6m_entry);
1894 			free(in6m, M_IPMADDR);
1895 			IFAFREE(&ia->ia_ifa);
1896 			splx(s);
1897 			return (NULL);
1898 		}
1899 		/*
1900 		 * Let MLD6 know that we have joined a new IP6 multicast
1901 		 * group.
1902 		 */
1903 		mld6_start_listening(in6m);
1904 	}
1905 	splx(s);
1906 	return (in6m);
1907 }
1908 
1909 /*
1910  * Delete a multicast address record.
1911  */
1912 void
1913 in6_delmulti(in6m)
1914 	struct in6_multi *in6m;
1915 {
1916 	struct	in6_ifreq ifr;
1917 	int	s = splsoftnet();
1918 
1919 	if (--in6m->in6m_refcount == 0) {
1920 		/*
1921 		 * No remaining claims to this record; let MLD6 know
1922 		 * that we are leaving the multicast group.
1923 		 */
1924 		mld6_stop_listening(in6m);
1925 
1926 		/*
1927 		 * Unlink from list.
1928 		 */
1929 		LIST_REMOVE(in6m, in6m_entry);
1930 		if (in6m->in6m_ia) {
1931 			IFAFREE(&in6m->in6m_ia->ia_ifa); /* release reference */
1932 		}
1933 
1934 		/*
1935 		 * Notify the network driver to update its multicast
1936 		 * reception filter.
1937 		 */
1938 		bzero(&ifr.ifr_addr, sizeof(struct sockaddr_in6));
1939 		ifr.ifr_addr.sin6_len = sizeof(struct sockaddr_in6);
1940 		ifr.ifr_addr.sin6_family = AF_INET6;
1941 		ifr.ifr_addr.sin6_addr = in6m->in6m_addr;
1942 		(*in6m->in6m_ifp->if_ioctl)(in6m->in6m_ifp,
1943 					    SIOCDELMULTI, (caddr_t)&ifr);
1944 		free(in6m, M_IPMADDR);
1945 	}
1946 	splx(s);
1947 }
1948 
1949 struct in6_multi_mship *
1950 in6_joingroup(ifp, addr, errorp)
1951 	struct ifnet *ifp;
1952 	struct in6_addr *addr;
1953 	int *errorp;
1954 {
1955 	struct in6_multi_mship *imm;
1956 
1957 	imm = malloc(sizeof(*imm), M_IPMADDR, M_NOWAIT);
1958 	if (!imm) {
1959 		*errorp = ENOBUFS;
1960 		return NULL;
1961 	}
1962 	imm->i6mm_maddr = in6_addmulti(addr, ifp, errorp);
1963 	if (!imm->i6mm_maddr) {
1964 		/* *errorp is alrady set */
1965 		free(imm, M_IPMADDR);
1966 		return NULL;
1967 	}
1968 	return imm;
1969 }
1970 
1971 int
1972 in6_leavegroup(imm)
1973 	struct in6_multi_mship *imm;
1974 {
1975 
1976 	if (imm->i6mm_maddr)
1977 		in6_delmulti(imm->i6mm_maddr);
1978 	free(imm,  M_IPMADDR);
1979 	return 0;
1980 }
1981 
1982 /*
1983  * Find an IPv6 interface link-local address specific to an interface.
1984  */
1985 struct in6_ifaddr *
1986 in6ifa_ifpforlinklocal(ifp, ignoreflags)
1987 	struct ifnet *ifp;
1988 	int ignoreflags;
1989 {
1990 	struct ifaddr *ifa;
1991 
1992 	for (ifa = ifp->if_addrlist.tqh_first; ifa; ifa = ifa->ifa_list.tqe_next)
1993 	{
1994 		if (ifa->ifa_addr == NULL)
1995 			continue;	/* just for safety */
1996 		if (ifa->ifa_addr->sa_family != AF_INET6)
1997 			continue;
1998 		if (IN6_IS_ADDR_LINKLOCAL(IFA_IN6(ifa))) {
1999 			if ((((struct in6_ifaddr *)ifa)->ia6_flags &
2000 			     ignoreflags) != 0)
2001 				continue;
2002 			break;
2003 		}
2004 	}
2005 
2006 	return ((struct in6_ifaddr *)ifa);
2007 }
2008 
2009 
2010 /*
2011  * find the internet address corresponding to a given interface and address.
2012  */
2013 struct in6_ifaddr *
2014 in6ifa_ifpwithaddr(ifp, addr)
2015 	struct ifnet *ifp;
2016 	struct in6_addr *addr;
2017 {
2018 	struct ifaddr *ifa;
2019 
2020 	for (ifa = ifp->if_addrlist.tqh_first; ifa; ifa = ifa->ifa_list.tqe_next)
2021 	{
2022 		if (ifa->ifa_addr == NULL)
2023 			continue;	/* just for safety */
2024 		if (ifa->ifa_addr->sa_family != AF_INET6)
2025 			continue;
2026 		if (IN6_ARE_ADDR_EQUAL(addr, IFA_IN6(ifa)))
2027 			break;
2028 	}
2029 
2030 	return ((struct in6_ifaddr *)ifa);
2031 }
2032 
2033 /*
2034  * Convert IP6 address to printable (loggable) representation.
2035  */
2036 static char digits[] = "0123456789abcdef";
2037 static int ip6round = 0;
2038 char *
2039 ip6_sprintf(addr)
2040 	const struct in6_addr *addr;
2041 {
2042 	static char ip6buf[8][48];
2043 	int i;
2044 	char *cp;
2045 	const u_short *a = (const u_short *)addr;
2046 	const u_char *d;
2047 	int dcolon = 0;
2048 
2049 	ip6round = (ip6round + 1) & 7;
2050 	cp = ip6buf[ip6round];
2051 
2052 	for (i = 0; i < 8; i++) {
2053 		if (dcolon == 1) {
2054 			if (*a == 0) {
2055 				if (i == 7)
2056 					*cp++ = ':';
2057 				a++;
2058 				continue;
2059 			} else
2060 				dcolon = 2;
2061 		}
2062 		if (*a == 0) {
2063 			if (dcolon == 0 && *(a + 1) == 0) {
2064 				if (i == 0)
2065 					*cp++ = ':';
2066 				*cp++ = ':';
2067 				dcolon = 1;
2068 			} else {
2069 				*cp++ = '0';
2070 				*cp++ = ':';
2071 			}
2072 			a++;
2073 			continue;
2074 		}
2075 		d = (const u_char *)a;
2076 		*cp++ = digits[*d >> 4];
2077 		*cp++ = digits[*d++ & 0xf];
2078 		*cp++ = digits[*d >> 4];
2079 		*cp++ = digits[*d & 0xf];
2080 		*cp++ = ':';
2081 		a++;
2082 	}
2083 	*--cp = 0;
2084 	return (ip6buf[ip6round]);
2085 }
2086 
2087 /*
2088  * Determine if an address is on a local network.
2089  */
2090 int
2091 in6_localaddr(in6)
2092 	struct in6_addr *in6;
2093 {
2094 	struct in6_ifaddr *ia;
2095 
2096 	if (IN6_IS_ADDR_LOOPBACK(in6) || IN6_IS_ADDR_LINKLOCAL(in6))
2097 		return (1);
2098 
2099 	for (ia = in6_ifaddr; ia; ia = ia->ia_next)
2100 		if (IN6_ARE_MASKED_ADDR_EQUAL(in6, &ia->ia_addr.sin6_addr,
2101 					      &ia->ia_prefixmask.sin6_addr))
2102 			return (1);
2103 
2104 	return (0);
2105 }
2106 
2107 /*
2108  * Get a scope of the address. Node-local, link-local, site-local or global.
2109  */
2110 int
2111 in6_addrscope (addr)
2112 struct in6_addr *addr;
2113 {
2114 	int scope;
2115 
2116 	if (addr->s6_addr8[0] == 0xfe) {
2117 		scope = addr->s6_addr8[1] & 0xc0;
2118 
2119 		switch (scope) {
2120 		case 0x80:
2121 			return IPV6_ADDR_SCOPE_LINKLOCAL;
2122 		case 0xc0:
2123 			return IPV6_ADDR_SCOPE_SITELOCAL;
2124 		default:
2125 			return IPV6_ADDR_SCOPE_GLOBAL; /* just in case */
2126 		}
2127 	}
2128 
2129 
2130 	if (addr->s6_addr8[0] == 0xff) {
2131 		scope = addr->s6_addr8[1] & 0x0f;
2132 
2133 		/*
2134 		 * due to other scope such as reserved,
2135 		 * return scope doesn't work.
2136 		 */
2137 		switch (scope) {
2138 		case IPV6_ADDR_SCOPE_NODELOCAL:
2139 			return IPV6_ADDR_SCOPE_NODELOCAL;
2140 		case IPV6_ADDR_SCOPE_LINKLOCAL:
2141 			return IPV6_ADDR_SCOPE_LINKLOCAL;
2142 		case IPV6_ADDR_SCOPE_SITELOCAL:
2143 			return IPV6_ADDR_SCOPE_SITELOCAL;
2144 		default:
2145 			return IPV6_ADDR_SCOPE_GLOBAL;
2146 		}
2147 	}
2148 
2149 	if (bcmp(&in6addr_loopback, addr, sizeof(*addr) - 1) == 0) {
2150 		if (addr->s6_addr8[15] == 1) /* loopback */
2151 			return IPV6_ADDR_SCOPE_NODELOCAL;
2152 		if (addr->s6_addr8[15] == 0) /* unspecified */
2153 			return IPV6_ADDR_SCOPE_LINKLOCAL;
2154 	}
2155 
2156 	return IPV6_ADDR_SCOPE_GLOBAL;
2157 }
2158 
2159 int
2160 in6_addr2scopeid(ifp, addr)
2161 	struct ifnet *ifp;	/* must not be NULL */
2162 	struct in6_addr *addr;	/* must not be NULL */
2163 {
2164 	int scope = in6_addrscope(addr);
2165 
2166 	switch (scope) {
2167 	case IPV6_ADDR_SCOPE_NODELOCAL:
2168 		return (-1);	/* XXX: is this an appropriate value? */
2169 
2170 	case IPV6_ADDR_SCOPE_LINKLOCAL:
2171 		/* XXX: we do not distinguish between a link and an I/F. */
2172 		return (ifp->if_index);
2173 
2174 	case IPV6_ADDR_SCOPE_SITELOCAL:
2175 		return (0);	/* XXX: invalid. */
2176 
2177 	default:
2178 		return (0);	/* XXX: treat as global. */
2179 	}
2180 }
2181 
2182 int
2183 in6_is_addr_deprecated(sa6)
2184 	struct sockaddr_in6 *sa6;
2185 {
2186 	struct in6_ifaddr *ia;
2187 
2188 	for (ia = in6_ifaddr; ia; ia = ia->ia_next) {
2189 		if (IN6_ARE_ADDR_EQUAL(&ia->ia_addr.sin6_addr,
2190 		    &sa6->sin6_addr) &&
2191 #ifdef SCOPEDROUTING
2192 		    ia->ia_addr.sin6_scope_id == sa6->sin6_scope_id &&
2193 #endif
2194 		    (ia->ia6_flags & IN6_IFF_DEPRECATED) != 0)
2195 			return (1); /* true */
2196 
2197 		/* XXX: do we still have to go thru the rest of the list? */
2198 	}
2199 
2200 	return (0);		/* false */
2201 }
2202 
2203 /*
2204  * return length of part which dst and src are equal
2205  * hard coding...
2206  */
2207 int
2208 in6_matchlen(src, dst)
2209 struct in6_addr *src, *dst;
2210 {
2211 	int match = 0;
2212 	u_char *s = (u_char *)src, *d = (u_char *)dst;
2213 	u_char *lim = s + 16, r;
2214 
2215 	while (s < lim)
2216 		if ((r = (*d++ ^ *s++)) != 0) {
2217 			while (r < 128) {
2218 				match++;
2219 				r <<= 1;
2220 			}
2221 			break;
2222 		} else
2223 			match += 8;
2224 	return match;
2225 }
2226 
2227 /* XXX: to be scope conscious */
2228 int
2229 in6_are_prefix_equal(p1, p2, len)
2230 	struct in6_addr *p1, *p2;
2231 	int len;
2232 {
2233 	int bytelen, bitlen;
2234 
2235 	/* sanity check */
2236 	if (0 > len || len > 128) {
2237 		log(LOG_ERR, "in6_are_prefix_equal: invalid prefix length(%d)\n",
2238 		    len);
2239 		return (0);
2240 	}
2241 
2242 	bytelen = len / 8;
2243 	bitlen = len % 8;
2244 
2245 	if (bcmp(&p1->s6_addr, &p2->s6_addr, bytelen))
2246 		return (0);
2247 	if (p1->s6_addr[bytelen] >> (8 - bitlen) !=
2248 	    p2->s6_addr[bytelen] >> (8 - bitlen))
2249 		return (0);
2250 
2251 	return (1);
2252 }
2253 
2254 void
2255 in6_prefixlen2mask(maskp, len)
2256 	struct in6_addr *maskp;
2257 	int len;
2258 {
2259 	static const u_char maskarray[8] = {0x80, 0xc0, 0xe0, 0xf0, 0xf8, 0xfc, 0xfe, 0xff};
2260 	int bytelen, bitlen, i;
2261 
2262 	/* sanity check */
2263 	if (0 > len || len > 128) {
2264 		log(LOG_ERR, "in6_prefixlen2mask: invalid prefix length(%d)\n",
2265 		    len);
2266 		return;
2267 	}
2268 
2269 	bzero(maskp, sizeof(*maskp));
2270 	bytelen = len / 8;
2271 	bitlen = len % 8;
2272 	for (i = 0; i < bytelen; i++)
2273 		maskp->s6_addr[i] = 0xff;
2274 	if (bitlen)
2275 		maskp->s6_addr[bytelen] = maskarray[bitlen - 1];
2276 }
2277 
2278 /*
2279  * return the best address out of the same scope
2280  */
2281 struct in6_ifaddr *
2282 in6_ifawithscope(oifp, dst)
2283 	struct ifnet *oifp;
2284 	struct in6_addr *dst;
2285 {
2286 	int dst_scope =	in6_addrscope(dst), src_scope, best_scope = 0;
2287 	int blen = -1;
2288 	struct ifaddr *ifa;
2289 	struct ifnet *ifp;
2290 	struct in6_ifaddr *ifa_best = NULL;
2291 
2292 	if (oifp == NULL) {
2293 		printf("in6_ifawithscope: output interface is not specified\n");
2294 		return (NULL);
2295 	}
2296 
2297 	/*
2298 	 * We search for all addresses on all interfaces from the beginning.
2299 	 * Comparing an interface with the outgoing interface will be done
2300 	 * only at the final stage of tiebreaking.
2301 	 */
2302 	for (ifp = TAILQ_FIRST(&ifnet); ifp; ifp = TAILQ_NEXT(ifp, if_list))
2303 	{
2304 		/*
2305 		 * We can never take an address that breaks the scope zone
2306 		 * of the destination.
2307 		 */
2308 		if (in6_addr2scopeid(ifp, dst) != in6_addr2scopeid(oifp, dst))
2309 			continue;
2310 
2311 		for (ifa = ifp->if_addrlist.tqh_first; ifa;
2312 		     ifa = ifa->ifa_list.tqe_next)
2313 		{
2314 			int tlen = -1, dscopecmp, bscopecmp, matchcmp;
2315 
2316 			if (ifa->ifa_addr->sa_family != AF_INET6)
2317 				continue;
2318 
2319 			src_scope = in6_addrscope(IFA_IN6(ifa));
2320 
2321 #ifdef ADDRSELECT_DEBUG		/* should be removed after stabilization */
2322 			dscopecmp = IN6_ARE_SCOPE_CMP(src_scope, dst_scope);
2323 			printf("in6_ifawithscope: dst=%s bestaddr=%s, "
2324 			       "newaddr=%s, scope=%x, dcmp=%d, bcmp=%d, "
2325 			       "matchlen=%d, flgs=%x\n",
2326 			       ip6_sprintf(dst),
2327 			       ifa_best ? ip6_sprintf(&ifa_best->ia_addr.sin6_addr) : "none",
2328 			       ip6_sprintf(IFA_IN6(ifa)), src_scope,
2329 			       dscopecmp,
2330 			       ifa_best ? IN6_ARE_SCOPE_CMP(src_scope, best_scope) : -1,
2331 			       in6_matchlen(IFA_IN6(ifa), dst),
2332 			       ((struct in6_ifaddr *)ifa)->ia6_flags);
2333 #endif
2334 
2335 			/*
2336 			 * Don't use an address before completing DAD
2337 			 * nor a duplicated address.
2338 			 */
2339 			if (((struct in6_ifaddr *)ifa)->ia6_flags &
2340 			    IN6_IFF_NOTREADY)
2341 				continue;
2342 
2343 			/* XXX: is there any case to allow anycasts? */
2344 			if (((struct in6_ifaddr *)ifa)->ia6_flags &
2345 			    IN6_IFF_ANYCAST)
2346 				continue;
2347 
2348 			if (((struct in6_ifaddr *)ifa)->ia6_flags &
2349 			    IN6_IFF_DETACHED)
2350 				continue;
2351 
2352 			/*
2353 			 * If this is the first address we find,
2354 			 * keep it anyway.
2355 			 */
2356 			if (ifa_best == NULL)
2357 				goto replace;
2358 
2359 			/*
2360 			 * ifa_best is never NULL beyond this line except
2361 			 * within the block labeled "replace".
2362 			 */
2363 
2364 			/*
2365 			 * If ifa_best has a smaller scope than dst and
2366 			 * the current address has a larger one than
2367 			 * (or equal to) dst, always replace ifa_best.
2368 			 * Also, if the current address has a smaller scope
2369 			 * than dst, ignore it unless ifa_best also has a
2370 			 * smaller scope.
2371 			 */
2372 			if (IN6_ARE_SCOPE_CMP(best_scope, dst_scope) < 0 &&
2373 			    IN6_ARE_SCOPE_CMP(src_scope, dst_scope) >= 0)
2374 				goto replace;
2375 			if (IN6_ARE_SCOPE_CMP(src_scope, dst_scope) < 0 &&
2376 			    IN6_ARE_SCOPE_CMP(best_scope, dst_scope) >= 0)
2377 				continue;
2378 
2379 			/*
2380 			 * A deprecated address SHOULD NOT be used in new
2381 			 * communications if an alternate (non-deprecated)
2382 			 * address is available and has sufficient scope.
2383 			 * RFC 2462, Section 5.5.4.
2384 			 */
2385 			if (((struct in6_ifaddr *)ifa)->ia6_flags &
2386 			    IN6_IFF_DEPRECATED) {
2387 				/*
2388 				 * Ignore any deprecated addresses if
2389 				 * specified by configuration.
2390 				 */
2391 				if (!ip6_use_deprecated)
2392 					continue;
2393 
2394 				/*
2395 				 * If we have already found a non-deprecated
2396 				 * candidate, just ignore deprecated addresses.
2397 				 */
2398 				if ((ifa_best->ia6_flags & IN6_IFF_DEPRECATED)
2399 				    == 0)
2400 					continue;
2401 			}
2402 
2403 			/*
2404 			 * A non-deprecated address is always preferred
2405 			 * to a deprecated one regardless of scopes and
2406 			 * address matching.
2407 			 */
2408 			if ((ifa_best->ia6_flags & IN6_IFF_DEPRECATED) &&
2409 			    (((struct in6_ifaddr *)ifa)->ia6_flags &
2410 			     IN6_IFF_DEPRECATED) == 0)
2411 				goto replace;
2412 
2413 			/*
2414 			 * At this point, we have two cases:
2415 			 * 1. we are looking at a non-deprecated address,
2416 			 *    and ifa_best is also non-deprecated.
2417 			 * 2. we are looking at a deprecated address,
2418 			 *    and ifa_best is also deprecated.
2419 			 * Also, we do not have to consider a case where
2420 			 * the scope of if_best is larger(smaller) than dst and
2421 			 * the scope of the current address is smaller(larger)
2422 			 * than dst. Such a case has already been covered.
2423 			 * Tiebreaking is done according to the following
2424 			 * items:
2425 			 * - the scope comparison between the address and
2426 			 *   dst (dscopecmp)
2427 			 * - the scope comparison between the address and
2428 			 *   ifa_best (bscopecmp)
2429 			 * - if the address match dst longer than ifa_best
2430 			 *   (matchcmp)
2431 			 * - if the address is on the outgoing I/F (outI/F)
2432 			 *
2433 			 * Roughly speaking, the selection policy is
2434 			 * - the most important item is scope. The same scope
2435 			 *   is best. Then search for a larger scope.
2436 			 *   Smaller scopes are the last resort.
2437 			 * - A deprecated address is chosen only when we have
2438 			 *   no address that has an enough scope, but is
2439 			 *   prefered to any addresses of smaller scopes.
2440 			 * - Longest address match against dst is considered
2441 			 *   only for addresses that has the same scope of dst.
2442 			 * - If there is no other reasons to choose one,
2443 			 *   addresses on the outgoing I/F are preferred.
2444 			 *
2445 			 * The precise decision table is as follows:
2446 			 * dscopecmp bscopecmp matchcmp outI/F | replace?
2447 			 *    !equal     equal      N/A    Yes |      Yes (1)
2448 			 *    !equal     equal      N/A     No |       No (2)
2449 			 *    larger    larger      N/A    N/A |       No (3)
2450 			 *    larger   smaller      N/A    N/A |      Yes (4)
2451 			 *   smaller    larger      N/A    N/A |      Yes (5)
2452 			 *   smaller   smaller      N/A    N/A |       No (6)
2453 			 *     equal   smaller      N/A    N/A |      Yes (7)
2454 			 *     equal    larger       (already done)
2455 			 *     equal     equal   larger    N/A |      Yes (8)
2456 			 *     equal     equal  smaller    N/A |       No (9)
2457 			 *     equal     equal    equal    Yes |      Yes (a)
2458 			 *     eaual     eqaul    equal     No |       No (b)
2459 			 */
2460 			dscopecmp = IN6_ARE_SCOPE_CMP(src_scope, dst_scope);
2461 			bscopecmp = IN6_ARE_SCOPE_CMP(src_scope, best_scope);
2462 
2463 			if (dscopecmp && bscopecmp == 0) {
2464 				if (oifp == ifp) /* (1) */
2465 					goto replace;
2466 				continue; /* (2) */
2467 			}
2468 			if (dscopecmp > 0) {
2469 				if (bscopecmp > 0) /* (3) */
2470 					continue;
2471 				goto replace; /* (4) */
2472 			}
2473 			if (dscopecmp < 0) {
2474 				if (bscopecmp > 0) /* (5) */
2475 					goto replace;
2476 				continue; /* (6) */
2477 			}
2478 
2479 			/* now dscopecmp must be 0 */
2480 			if (bscopecmp < 0)
2481 				goto replace; /* (7) */
2482 
2483 			/*
2484 			 * At last both dscopecmp and bscopecmp must be 0.
2485 			 * We need address matching against dst for
2486 			 * tiebreaking.
2487 			 */
2488 			tlen = in6_matchlen(IFA_IN6(ifa), dst);
2489 			matchcmp = tlen - blen;
2490 			if (matchcmp > 0) /* (8) */
2491 				goto replace;
2492 			if (matchcmp < 0) /* (9) */
2493 				continue;
2494 			if (oifp == ifp) /* (a) */
2495 				goto replace;
2496 			continue; /* (b) */
2497 
2498 		  replace:
2499 			ifa_best = (struct in6_ifaddr *)ifa;
2500 			blen = tlen >= 0 ? tlen :
2501 				in6_matchlen(IFA_IN6(ifa), dst);
2502 			best_scope = in6_addrscope(&ifa_best->ia_addr.sin6_addr);
2503 		}
2504 	}
2505 
2506 	/* count statistics for future improvements */
2507 	if (ifa_best == NULL)
2508 		ip6stat.ip6s_sources_none++;
2509 	else {
2510 		if (oifp == ifa_best->ia_ifp)
2511 			ip6stat.ip6s_sources_sameif[best_scope]++;
2512 		else
2513 			ip6stat.ip6s_sources_otherif[best_scope]++;
2514 
2515 		if (best_scope == dst_scope)
2516 			ip6stat.ip6s_sources_samescope[best_scope]++;
2517 		else
2518 			ip6stat.ip6s_sources_otherscope[best_scope]++;
2519 
2520 		if ((ifa_best->ia6_flags & IN6_IFF_DEPRECATED) != 0)
2521 			ip6stat.ip6s_sources_deprecated[best_scope]++;
2522 	}
2523 
2524 	return (ifa_best);
2525 }
2526 
2527 /*
2528  * return the best address out of the same scope. if no address was
2529  * found, return the first valid address from designated IF.
2530  */
2531 struct in6_ifaddr *
2532 in6_ifawithifp(ifp, dst)
2533 	struct ifnet *ifp;
2534 	struct in6_addr *dst;
2535 {
2536 	int dst_scope =	in6_addrscope(dst), blen = -1, tlen;
2537 	struct ifaddr *ifa;
2538 	struct in6_ifaddr *besta = 0;
2539 	struct in6_ifaddr *dep[2];	/* last-resort: deprecated */
2540 
2541 	dep[0] = dep[1] = NULL;
2542 
2543 	/*
2544 	 * We first look for addresses in the same scope.
2545 	 * If there is one, return it.
2546 	 * If two or more, return one which matches the dst longest.
2547 	 * If none, return one of global addresses assigned other ifs.
2548 	 */
2549 	for (ifa = ifp->if_addrlist.tqh_first; ifa; ifa = ifa->ifa_list.tqe_next)
2550 	{
2551 		if (ifa->ifa_addr->sa_family != AF_INET6)
2552 			continue;
2553 		if (((struct in6_ifaddr *)ifa)->ia6_flags & IN6_IFF_ANYCAST)
2554 			continue; /* XXX: is there any case to allow anycast? */
2555 		if (((struct in6_ifaddr *)ifa)->ia6_flags & IN6_IFF_NOTREADY)
2556 			continue; /* don't use this interface */
2557 		if (((struct in6_ifaddr *)ifa)->ia6_flags & IN6_IFF_DETACHED)
2558 			continue;
2559 		if (((struct in6_ifaddr *)ifa)->ia6_flags & IN6_IFF_DEPRECATED) {
2560 			if (ip6_use_deprecated)
2561 				dep[0] = (struct in6_ifaddr *)ifa;
2562 			continue;
2563 		}
2564 
2565 		if (dst_scope == in6_addrscope(IFA_IN6(ifa))) {
2566 			/*
2567 			 * call in6_matchlen() as few as possible
2568 			 */
2569 			if (besta) {
2570 				if (blen == -1)
2571 					blen = in6_matchlen(&besta->ia_addr.sin6_addr, dst);
2572 				tlen = in6_matchlen(IFA_IN6(ifa), dst);
2573 				if (tlen > blen) {
2574 					blen = tlen;
2575 					besta = (struct in6_ifaddr *)ifa;
2576 				}
2577 			} else
2578 				besta = (struct in6_ifaddr *)ifa;
2579 		}
2580 	}
2581 	if (besta)
2582 		return (besta);
2583 
2584 	for (ifa = ifp->if_addrlist.tqh_first; ifa; ifa = ifa->ifa_list.tqe_next)
2585 	{
2586 		if (ifa->ifa_addr->sa_family != AF_INET6)
2587 			continue;
2588 		if (((struct in6_ifaddr *)ifa)->ia6_flags & IN6_IFF_ANYCAST)
2589 			continue; /* XXX: is there any case to allow anycast? */
2590 		if (((struct in6_ifaddr *)ifa)->ia6_flags & IN6_IFF_NOTREADY)
2591 			continue; /* don't use this interface */
2592 		if (((struct in6_ifaddr *)ifa)->ia6_flags & IN6_IFF_DETACHED)
2593 			continue;
2594 		if (((struct in6_ifaddr *)ifa)->ia6_flags & IN6_IFF_DEPRECATED) {
2595 			if (ip6_use_deprecated)
2596 				dep[1] = (struct in6_ifaddr *)ifa;
2597 			continue;
2598 		}
2599 
2600 		return (struct in6_ifaddr *)ifa;
2601 	}
2602 
2603 	/* use the last-resort values, that are, deprecated addresses */
2604 	if (dep[0])
2605 		return dep[0];
2606 	if (dep[1])
2607 		return dep[1];
2608 
2609 	return NULL;
2610 }
2611 
2612 /*
2613  * perform DAD when interface becomes IFF_UP.
2614  */
2615 void
2616 in6_if_up(ifp)
2617 	struct ifnet *ifp;
2618 {
2619 	struct ifaddr *ifa;
2620 	struct in6_ifaddr *ia;
2621 	int dad_delay;		/* delay ticks before DAD output */
2622 
2623 	/*
2624 	 * special cases, like 6to4, are handled in in6_ifattach
2625 	 */
2626 	in6_ifattach(ifp, NULL);
2627 
2628 	dad_delay = 0;
2629 	for (ifa = ifp->if_addrlist.tqh_first; ifa; ifa = ifa->ifa_list.tqe_next)
2630 	{
2631 		if (ifa->ifa_addr->sa_family != AF_INET6)
2632 			continue;
2633 		ia = (struct in6_ifaddr *)ifa;
2634 		if (ia->ia6_flags & IN6_IFF_TENTATIVE)
2635 			nd6_dad_start(ifa, &dad_delay);
2636 	}
2637 }
2638 
2639 int
2640 in6if_do_dad(ifp)
2641 	struct ifnet *ifp;
2642 {
2643 	if ((ifp->if_flags & IFF_LOOPBACK) != 0)
2644 		return (0);
2645 
2646 	switch (ifp->if_type) {
2647 	case IFT_FAITH:
2648 		/*
2649 		 * These interfaces do not have the IFF_LOOPBACK flag,
2650 		 * but loop packets back.  We do not have to do DAD on such
2651 		 * interfaces.  We should even omit it, because loop-backed
2652 		 * NS would confuse the DAD procedure.
2653 		 */
2654 		return (0);
2655 	default:
2656 		/*
2657 		 * Our DAD routine requires the interface up and running.
2658 		 * However, some interfaces can be up before the RUNNING
2659 		 * status.  Additionaly, users may try to assign addresses
2660 		 * before the interface becomes up (or running).
2661 		 * We simply skip DAD in such a case as a work around.
2662 		 * XXX: we should rather mark "tentative" on such addresses,
2663 		 * and do DAD after the interface becomes ready.
2664 		 */
2665 		if ((ifp->if_flags & (IFF_UP|IFF_RUNNING)) !=
2666 		    (IFF_UP|IFF_RUNNING))
2667 			return (0);
2668 
2669 		return (1);
2670 	}
2671 }
2672 
2673 /*
2674  * Calculate max IPv6 MTU through all the interfaces and store it
2675  * to in6_maxmtu.
2676  */
2677 void
2678 in6_setmaxmtu()
2679 {
2680 	unsigned long maxmtu = 0;
2681 	struct ifnet *ifp;
2682 
2683 	for (ifp = TAILQ_FIRST(&ifnet); ifp; ifp = TAILQ_NEXT(ifp, if_list))
2684 	{
2685 		/* this function can be called during ifnet initialization */
2686 		if (!ifp->if_afdata[AF_INET6])
2687 			continue;
2688 		if ((ifp->if_flags & IFF_LOOPBACK) == 0 &&
2689 		    IN6_LINKMTU(ifp) > maxmtu)
2690 			maxmtu = IN6_LINKMTU(ifp);
2691 	}
2692 	if (maxmtu)	     /* update only when maxmtu is positive */
2693 		in6_maxmtu = maxmtu;
2694 }
2695 
2696 void *
2697 in6_domifattach(ifp)
2698 	struct ifnet *ifp;
2699 {
2700 	struct in6_ifextra *ext;
2701 
2702 	ext = (struct in6_ifextra *)malloc(sizeof(*ext), M_IFADDR, M_WAITOK);
2703 	bzero(ext, sizeof(*ext));
2704 
2705 	ext->in6_ifstat = (struct in6_ifstat *)malloc(sizeof(struct in6_ifstat),
2706 	    M_IFADDR, M_WAITOK);
2707 	bzero(ext->in6_ifstat, sizeof(*ext->in6_ifstat));
2708 
2709 	ext->icmp6_ifstat =
2710 	    (struct icmp6_ifstat *)malloc(sizeof(struct icmp6_ifstat),
2711 	    M_IFADDR, M_WAITOK);
2712 	bzero(ext->icmp6_ifstat, sizeof(*ext->icmp6_ifstat));
2713 
2714 	ext->nd_ifinfo = nd6_ifattach(ifp);
2715 	return ext;
2716 }
2717 
2718 void
2719 in6_domifdetach(ifp, aux)
2720 	struct ifnet *ifp;
2721 	void *aux;
2722 {
2723 	struct in6_ifextra *ext = (struct in6_ifextra *)aux;
2724 
2725 	nd6_ifdetach(ext->nd_ifinfo);
2726 	free(ext->in6_ifstat, M_IFADDR);
2727 	free(ext->icmp6_ifstat, M_IFADDR);
2728 	free(ext, M_IFADDR);
2729 }
2730