xref: /netbsd-src/sys/netinet6/in6.c (revision 6a493d6bc668897c91594964a732d38505b70cbb)
1 /*	$NetBSD: in6.c,v 1.167 2013/09/11 23:15:47 christos 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. 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.c	8.2 (Berkeley) 11/15/93
62  */
63 
64 #include <sys/cdefs.h>
65 __KERNEL_RCSID(0, "$NetBSD: in6.c,v 1.167 2013/09/11 23:15:47 christos Exp $");
66 
67 #include "opt_inet.h"
68 #include "opt_compat_netbsd.h"
69 
70 #include <sys/param.h>
71 #include <sys/ioctl.h>
72 #include <sys/errno.h>
73 #include <sys/malloc.h>
74 #include <sys/socket.h>
75 #include <sys/socketvar.h>
76 #include <sys/sockio.h>
77 #include <sys/systm.h>
78 #include <sys/proc.h>
79 #include <sys/time.h>
80 #include <sys/kernel.h>
81 #include <sys/syslog.h>
82 #include <sys/kauth.h>
83 #include <sys/cprng.h>
84 
85 #include <net/if.h>
86 #include <net/if_types.h>
87 #include <net/route.h>
88 #include <net/if_dl.h>
89 #include <net/pfil.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 #include <netinet6/scope6_var.h>
102 
103 #include <net/net_osdep.h>
104 
105 #ifdef COMPAT_50
106 #include <compat/netinet6/in6_var.h>
107 #endif
108 
109 MALLOC_DEFINE(M_IP6OPT, "ip6_options", "IPv6 options");
110 
111 /* enable backward compatibility code for obsoleted ioctls */
112 #define COMPAT_IN6IFIOCTL
113 
114 #ifdef	IN6_DEBUG
115 #define	IN6_DPRINTF(__fmt, ...)	printf(__fmt, __VA_ARGS__)
116 #else
117 #define	IN6_DPRINTF(__fmt, ...)	do { } while (/*CONSTCOND*/0)
118 #endif /* IN6_DEBUG */
119 
120 /*
121  * Definitions of some constant IP6 addresses.
122  */
123 const struct in6_addr in6addr_any = IN6ADDR_ANY_INIT;
124 const struct in6_addr in6addr_loopback = IN6ADDR_LOOPBACK_INIT;
125 const struct in6_addr in6addr_nodelocal_allnodes =
126 	IN6ADDR_NODELOCAL_ALLNODES_INIT;
127 const struct in6_addr in6addr_linklocal_allnodes =
128 	IN6ADDR_LINKLOCAL_ALLNODES_INIT;
129 const struct in6_addr in6addr_linklocal_allrouters =
130 	IN6ADDR_LINKLOCAL_ALLROUTERS_INIT;
131 
132 const struct in6_addr in6mask0 = IN6MASK0;
133 const struct in6_addr in6mask32 = IN6MASK32;
134 const struct in6_addr in6mask64 = IN6MASK64;
135 const struct in6_addr in6mask96 = IN6MASK96;
136 const struct in6_addr in6mask128 = IN6MASK128;
137 
138 const struct sockaddr_in6 sa6_any = {sizeof(sa6_any), AF_INET6,
139 				     0, 0, IN6ADDR_ANY_INIT, 0};
140 
141 static int in6_lifaddr_ioctl(struct socket *, u_long, void *,
142 	struct ifnet *, struct lwp *);
143 static int in6_ifinit(struct ifnet *, struct in6_ifaddr *,
144 	const struct sockaddr_in6 *, int);
145 static void in6_unlink_ifa(struct in6_ifaddr *, struct ifnet *);
146 
147 /*
148  * Subroutine for in6_ifaddloop() and in6_ifremloop().
149  * This routine does actual work.
150  */
151 static void
152 in6_ifloop_request(int cmd, struct ifaddr *ifa)
153 {
154 	struct sockaddr_in6 lo_sa;
155 	struct sockaddr_in6 all1_sa;
156 	struct rtentry *nrt = NULL;
157 	int e;
158 
159 	sockaddr_in6_init(&all1_sa, &in6mask128, 0, 0, 0);
160 	sockaddr_in6_init(&lo_sa, &in6addr_loopback, 0, 0, 0);
161 
162 	/*
163 	 * We specify the address itself as the gateway, and set the
164 	 * RTF_LLINFO flag, so that the corresponding host route would have
165 	 * the flag, and thus applications that assume traditional behavior
166 	 * would be happy.  Note that we assume the caller of the function
167 	 * (probably implicitly) set nd6_rtrequest() to ifa->ifa_rtrequest,
168 	 * which changes the outgoing interface to the loopback interface.
169 	 */
170 	e = rtrequest(cmd, ifa->ifa_addr, ifa->ifa_addr,
171 	    (struct sockaddr *)&all1_sa, RTF_UP|RTF_HOST|RTF_LLINFO, &nrt);
172 	if (e != 0) {
173 		log(LOG_ERR, "in6_ifloop_request: "
174 		    "%s operation failed for %s (errno=%d)\n",
175 		    cmd == RTM_ADD ? "ADD" : "DELETE",
176 		    ip6_sprintf(&((struct in6_ifaddr *)ifa)->ia_addr.sin6_addr),
177 		    e);
178 	}
179 
180 	/*
181 	 * Make sure rt_ifa be equal to IFA, the second argument of the
182 	 * function.
183 	 * We need this because when we refer to rt_ifa->ia6_flags in
184 	 * ip6_input, we assume that the rt_ifa points to the address instead
185 	 * of the loopback address.
186 	 */
187 	if (cmd == RTM_ADD && nrt && ifa != nrt->rt_ifa)
188 		rt_replace_ifa(nrt, ifa);
189 
190 	/*
191 	 * Report the addition/removal of the address to the routing socket
192 	 * unless the address is marked tentative, where it will be reported
193 	 * once DAD completes.
194 	 * XXX: since we called rtinit for a p2p interface with a destination,
195 	 *      we end up reporting twice in such a case.  Should we rather
196 	 *      omit the second report?
197 	 */
198 	if (nrt) {
199 		if (cmd != RTM_ADD ||
200 		    !(((struct in6_ifaddr *)ifa)->ia6_flags &IN6_IFF_TENTATIVE))
201 		{
202 #if 0
203 			struct in6_ifaddr *ia;
204 
205 			ia = (struct in6_ifaddr *)ifa;
206 			log(LOG_DEBUG,
207 			    "in6_ifloop_request: announced %s (%s %d)\n",
208 			    ip6_sprintf(&ia->ia_addr.sin6_addr),
209 			    cmd == RTM_ADD ? "RTM_ADD" : "RTM_DELETE",
210 			    ia->ia6_flags);
211 #endif
212 			rt_newaddrmsg(cmd, ifa, e, nrt);
213 		}
214 		if (cmd == RTM_DELETE) {
215 			if (nrt->rt_refcnt <= 0) {
216 				/* XXX: we should free the entry ourselves. */
217 				nrt->rt_refcnt++;
218 				rtfree(nrt);
219 			}
220 		} else {
221 			/* the cmd must be RTM_ADD here */
222 			nrt->rt_refcnt--;
223 		}
224 	}
225 }
226 
227 /*
228  * Add ownaddr as loopback rtentry.  We previously add the route only if
229  * necessary (ex. on a p2p link).  However, since we now manage addresses
230  * separately from prefixes, we should always add the route.  We can't
231  * rely on the cloning mechanism from the corresponding interface route
232  * any more.
233  */
234 void
235 in6_ifaddloop(struct ifaddr *ifa)
236 {
237 	struct rtentry *rt;
238 
239 	/* If there is no loopback entry, allocate one. */
240 	rt = rtalloc1(ifa->ifa_addr, 0);
241 	if (rt == NULL || (rt->rt_flags & RTF_HOST) == 0 ||
242 	    (rt->rt_ifp->if_flags & IFF_LOOPBACK) == 0)
243 		in6_ifloop_request(RTM_ADD, ifa);
244 	if (rt != NULL)
245 		rt->rt_refcnt--;
246 }
247 
248 /*
249  * Remove loopback rtentry of ownaddr generated by in6_ifaddloop(),
250  * if it exists.
251  */
252 void
253 in6_ifremloop(struct ifaddr *ifa)
254 {
255 	struct in6_ifaddr *alt_ia = NULL, *ia;
256 	struct rtentry *rt;
257 	int ia_count = 0;
258 
259 	/*
260 	 * Some of BSD variants do not remove cloned routes
261 	 * from an interface direct route, when removing the direct route
262 	 * (see comments in net/net_osdep.h).  Even for variants that do remove
263 	 * cloned routes, they could fail to remove the cloned routes when
264 	 * we handle multple addresses that share a common prefix.
265 	 * So, we should remove the route corresponding to the deleted address.
266 	 */
267 
268 	/*
269 	 * Delete the entry only if exactly one ifaddr matches the
270 	 * address, ifa->ifa_addr.
271 	 *
272 	 * If more than one ifaddr matches, replace the ifaddr in
273 	 * the routing table, rt_ifa, with a different ifaddr than
274 	 * the one we are purging, ifa.  It is important to do
275 	 * this, or else the routing table can accumulate dangling
276 	 * pointers rt->rt_ifa->ifa_ifp to destroyed interfaces,
277 	 * which will lead to crashes, later.  (More than one ifaddr
278 	 * can match if we assign the same address to multiple---probably
279 	 * p2p---interfaces.)
280 	 *
281 	 * XXX An old comment at this place said, "we should avoid
282 	 * XXX such a configuration [i.e., interfaces with the same
283 	 * XXX addressed assigned --ed.] in IPv6...".  I do not
284 	 * XXX agree, especially now that I have fixed the dangling
285 	 * XXX ifp-pointers bug.
286 	 */
287 	for (ia = in6_ifaddr; ia; ia = ia->ia_next) {
288 		if (!IN6_ARE_ADDR_EQUAL(IFA_IN6(ifa), &ia->ia_addr.sin6_addr))
289 			continue;
290 		if (ia->ia_ifp != ifa->ifa_ifp)
291 			alt_ia = ia;
292 		if (++ia_count > 1 && alt_ia != NULL)
293 			break;
294 	}
295 
296 	if (ia_count == 0)
297 		return;
298 
299 	if ((rt = rtalloc1(ifa->ifa_addr, 0)) == NULL)
300 		return;
301 	rt->rt_refcnt--;
302 
303 	/*
304 	 * Before deleting, check if a corresponding loopbacked
305 	 * host route surely exists.  With this check, we can avoid
306 	 * deleting an interface direct route whose destination is
307 	 * the same as the address being removed.  This can happen
308 	 * when removing a subnet-router anycast address on an
309 	 * interface attached to a shared medium.
310 	 */
311 	if ((rt->rt_flags & RTF_HOST) == 0 ||
312 	    (rt->rt_ifp->if_flags & IFF_LOOPBACK) == 0)
313 		return;
314 
315 	/* If we cannot replace the route's ifaddr with the equivalent
316 	 * ifaddr of another interface, I believe it is safest to
317 	 * delete the route.
318 	 */
319 	if (ia_count == 1 || alt_ia == NULL)
320 		in6_ifloop_request(RTM_DELETE, ifa);
321 	else
322 		rt_replace_ifa(rt, &alt_ia->ia_ifa);
323 }
324 
325 int
326 in6_mask2len(struct in6_addr *mask, u_char *lim0)
327 {
328 	int x = 0, y;
329 	u_char *lim = lim0, *p;
330 
331 	/* ignore the scope_id part */
332 	if (lim0 == NULL || lim0 - (u_char *)mask > sizeof(*mask))
333 		lim = (u_char *)mask + sizeof(*mask);
334 	for (p = (u_char *)mask; p < lim; x++, p++) {
335 		if (*p != 0xff)
336 			break;
337 	}
338 	y = 0;
339 	if (p < lim) {
340 		for (y = 0; y < NBBY; y++) {
341 			if ((*p & (0x80 >> y)) == 0)
342 				break;
343 		}
344 	}
345 
346 	/*
347 	 * when the limit pointer is given, do a stricter check on the
348 	 * remaining bits.
349 	 */
350 	if (p < lim) {
351 		if (y != 0 && (*p & (0x00ff >> y)) != 0)
352 			return -1;
353 		for (p = p + 1; p < lim; p++)
354 			if (*p != 0)
355 				return -1;
356 	}
357 
358 	return x * NBBY + y;
359 }
360 
361 #define ifa2ia6(ifa)	((struct in6_ifaddr *)(ifa))
362 #define ia62ifa(ia6)	(&((ia6)->ia_ifa))
363 
364 static int
365 in6_control1(struct socket *so, u_long cmd, void *data, struct ifnet *ifp,
366     lwp_t *l)
367 {
368 	struct	in6_ifreq *ifr = (struct in6_ifreq *)data;
369 	struct	in6_ifaddr *ia = NULL;
370 	struct	in6_aliasreq *ifra = (struct in6_aliasreq *)data;
371 	struct sockaddr_in6 *sa6;
372 	int error;
373 
374 	switch (cmd) {
375 	/*
376 	 * XXX: Fix me, once we fix SIOCSIFADDR, SIOCIFDSTADDR, etc.
377 	 */
378 	case SIOCSIFADDR:
379 	case SIOCSIFDSTADDR:
380 	case SIOCSIFBRDADDR:
381 	case SIOCSIFNETMASK:
382 		return EOPNOTSUPP;
383 	case SIOCGETSGCNT_IN6:
384 	case SIOCGETMIFCNT_IN6:
385 		return mrt6_ioctl(cmd, data);
386 	case SIOCGIFADDRPREF:
387 	case SIOCSIFADDRPREF:
388 		if (ifp == NULL)
389 			return EINVAL;
390 		return ifaddrpref_ioctl(so, cmd, data, ifp, l);
391 	}
392 
393 	if (ifp == NULL)
394 		return EOPNOTSUPP;
395 
396 	switch (cmd) {
397 	case SIOCSNDFLUSH_IN6:
398 	case SIOCSPFXFLUSH_IN6:
399 	case SIOCSRTRFLUSH_IN6:
400 	case SIOCSDEFIFACE_IN6:
401 	case SIOCSIFINFO_FLAGS:
402 	case SIOCSIFINFO_IN6:
403 		/* Privileged. */
404 		/* FALLTHROUGH */
405 	case OSIOCGIFINFO_IN6:
406 	case SIOCGIFINFO_IN6:
407 	case SIOCGDRLST_IN6:
408 	case SIOCGPRLST_IN6:
409 	case SIOCGNBRINFO_IN6:
410 	case SIOCGDEFIFACE_IN6:
411 		return nd6_ioctl(cmd, data, ifp);
412 	}
413 
414 	switch (cmd) {
415 	case SIOCSIFPREFIX_IN6:
416 	case SIOCDIFPREFIX_IN6:
417 	case SIOCAIFPREFIX_IN6:
418 	case SIOCCIFPREFIX_IN6:
419 	case SIOCSGIFPREFIX_IN6:
420 	case SIOCGIFPREFIX_IN6:
421 		log(LOG_NOTICE,
422 		    "prefix ioctls are now invalidated. "
423 		    "please use ifconfig.\n");
424 		return EOPNOTSUPP;
425 	}
426 
427 	switch (cmd) {
428 	case SIOCALIFADDR:
429 	case SIOCDLIFADDR:
430 		/* Privileged. */
431 		/* FALLTHROUGH */
432 	case SIOCGLIFADDR:
433 		return in6_lifaddr_ioctl(so, cmd, data, ifp, l);
434 	}
435 
436 	/*
437 	 * Find address for this interface, if it exists.
438 	 *
439 	 * In netinet code, we have checked ifra_addr in SIOCSIF*ADDR operation
440 	 * only, and used the first interface address as the target of other
441 	 * operations (without checking ifra_addr).  This was because netinet
442 	 * code/API assumed at most 1 interface address per interface.
443 	 * Since IPv6 allows a node to assign multiple addresses
444 	 * on a single interface, we almost always look and check the
445 	 * presence of ifra_addr, and reject invalid ones here.
446 	 * It also decreases duplicated code among SIOC*_IN6 operations.
447 	 */
448 	switch (cmd) {
449 	case SIOCAIFADDR_IN6:
450 #ifdef OSIOCAIFADDR_IN6
451 	case OSIOCAIFADDR_IN6:
452 #endif
453 #ifdef OSIOCSIFPHYADDR_IN6
454 	case OSIOCSIFPHYADDR_IN6:
455 #endif
456 	case SIOCSIFPHYADDR_IN6:
457 		sa6 = &ifra->ifra_addr;
458 		break;
459 	case SIOCSIFADDR_IN6:
460 	case SIOCGIFADDR_IN6:
461 	case SIOCSIFDSTADDR_IN6:
462 	case SIOCSIFNETMASK_IN6:
463 	case SIOCGIFDSTADDR_IN6:
464 	case SIOCGIFNETMASK_IN6:
465 	case SIOCDIFADDR_IN6:
466 	case SIOCGIFPSRCADDR_IN6:
467 	case SIOCGIFPDSTADDR_IN6:
468 	case SIOCGIFAFLAG_IN6:
469 	case SIOCSNDFLUSH_IN6:
470 	case SIOCSPFXFLUSH_IN6:
471 	case SIOCSRTRFLUSH_IN6:
472 	case SIOCGIFALIFETIME_IN6:
473 #ifdef OSIOCGIFALIFETIME_IN6
474 	case OSIOCGIFALIFETIME_IN6:
475 #endif
476 	case SIOCGIFSTAT_IN6:
477 	case SIOCGIFSTAT_ICMP6:
478 		sa6 = &ifr->ifr_addr;
479 		break;
480 	default:
481 		sa6 = NULL;
482 		break;
483 	}
484 	if (sa6 && sa6->sin6_family == AF_INET6) {
485 		if (sa6->sin6_scope_id != 0)
486 			error = sa6_embedscope(sa6, 0);
487 		else
488 			error = in6_setscope(&sa6->sin6_addr, ifp, NULL);
489 		if (error != 0)
490 			return error;
491 		ia = in6ifa_ifpwithaddr(ifp, &sa6->sin6_addr);
492 	} else
493 		ia = NULL;
494 
495 	switch (cmd) {
496 	case SIOCSIFADDR_IN6:
497 	case SIOCSIFDSTADDR_IN6:
498 	case SIOCSIFNETMASK_IN6:
499 		/*
500 		 * Since IPv6 allows a node to assign multiple addresses
501 		 * on a single interface, SIOCSIFxxx ioctls are deprecated.
502 		 */
503 		return EINVAL;
504 
505 	case SIOCDIFADDR_IN6:
506 		/*
507 		 * for IPv4, we look for existing in_ifaddr here to allow
508 		 * "ifconfig if0 delete" to remove the first IPv4 address on
509 		 * the interface.  For IPv6, as the spec allows multiple
510 		 * interface address from the day one, we consider "remove the
511 		 * first one" semantics to be not preferable.
512 		 */
513 		if (ia == NULL)
514 			return EADDRNOTAVAIL;
515 		/* FALLTHROUGH */
516 #ifdef OSIOCAIFADDR_IN6
517 	case OSIOCAIFADDR_IN6:
518 #endif
519 	case SIOCAIFADDR_IN6:
520 		/*
521 		 * We always require users to specify a valid IPv6 address for
522 		 * the corresponding operation.
523 		 */
524 		if (ifra->ifra_addr.sin6_family != AF_INET6 ||
525 		    ifra->ifra_addr.sin6_len != sizeof(struct sockaddr_in6))
526 			return EAFNOSUPPORT;
527 		/* Privileged. */
528 
529 		break;
530 
531 	case SIOCGIFADDR_IN6:
532 		/* This interface is basically deprecated. use SIOCGIFCONF. */
533 		/* FALLTHROUGH */
534 	case SIOCGIFAFLAG_IN6:
535 	case SIOCGIFNETMASK_IN6:
536 	case SIOCGIFDSTADDR_IN6:
537 	case SIOCGIFALIFETIME_IN6:
538 #ifdef OSIOCGIFALIFETIME_IN6
539 	case OSIOCGIFALIFETIME_IN6:
540 #endif
541 		/* must think again about its semantics */
542 		if (ia == NULL)
543 			return EADDRNOTAVAIL;
544 		break;
545 	}
546 
547 	switch (cmd) {
548 
549 	case SIOCGIFADDR_IN6:
550 		ifr->ifr_addr = ia->ia_addr;
551 		if ((error = sa6_recoverscope(&ifr->ifr_addr)) != 0)
552 			return error;
553 		break;
554 
555 	case SIOCGIFDSTADDR_IN6:
556 		if ((ifp->if_flags & IFF_POINTOPOINT) == 0)
557 			return EINVAL;
558 		/*
559 		 * XXX: should we check if ifa_dstaddr is NULL and return
560 		 * an error?
561 		 */
562 		ifr->ifr_dstaddr = ia->ia_dstaddr;
563 		if ((error = sa6_recoverscope(&ifr->ifr_dstaddr)) != 0)
564 			return error;
565 		break;
566 
567 	case SIOCGIFNETMASK_IN6:
568 		ifr->ifr_addr = ia->ia_prefixmask;
569 		break;
570 
571 	case SIOCGIFAFLAG_IN6:
572 		ifr->ifr_ifru.ifru_flags6 = ia->ia6_flags;
573 		break;
574 
575 	case SIOCGIFSTAT_IN6:
576 		if (ifp == NULL)
577 			return EINVAL;
578 		memset(&ifr->ifr_ifru.ifru_stat, 0,
579 		    sizeof(ifr->ifr_ifru.ifru_stat));
580 		ifr->ifr_ifru.ifru_stat =
581 		    *((struct in6_ifextra *)ifp->if_afdata[AF_INET6])->in6_ifstat;
582 		break;
583 
584 	case SIOCGIFSTAT_ICMP6:
585 		if (ifp == NULL)
586 			return EINVAL;
587 		memset(&ifr->ifr_ifru.ifru_icmp6stat, 0,
588 		    sizeof(ifr->ifr_ifru.ifru_icmp6stat));
589 		ifr->ifr_ifru.ifru_icmp6stat =
590 		    *((struct in6_ifextra *)ifp->if_afdata[AF_INET6])->icmp6_ifstat;
591 		break;
592 
593 #ifdef OSIOCGIFALIFETIME_IN6
594 	case OSIOCGIFALIFETIME_IN6:
595 #endif
596 	case SIOCGIFALIFETIME_IN6:
597 		ifr->ifr_ifru.ifru_lifetime = ia->ia6_lifetime;
598 		if (ia->ia6_lifetime.ia6t_vltime != ND6_INFINITE_LIFETIME) {
599 			time_t maxexpire;
600 			struct in6_addrlifetime *retlt =
601 			    &ifr->ifr_ifru.ifru_lifetime;
602 
603 			/*
604 			 * XXX: adjust expiration time assuming time_t is
605 			 * signed.
606 			 */
607 			maxexpire = ((time_t)~0) &
608 			    ~((time_t)1 << ((sizeof(maxexpire) * NBBY) - 1));
609 			if (ia->ia6_lifetime.ia6t_vltime <
610 			    maxexpire - ia->ia6_updatetime) {
611 				retlt->ia6t_expire = ia->ia6_updatetime +
612 				    ia->ia6_lifetime.ia6t_vltime;
613 			} else
614 				retlt->ia6t_expire = maxexpire;
615 		}
616 		if (ia->ia6_lifetime.ia6t_pltime != ND6_INFINITE_LIFETIME) {
617 			time_t maxexpire;
618 			struct in6_addrlifetime *retlt =
619 			    &ifr->ifr_ifru.ifru_lifetime;
620 
621 			/*
622 			 * XXX: adjust expiration time assuming time_t is
623 			 * signed.
624 			 */
625 			maxexpire = ((time_t)~0) &
626 			    ~((time_t)1 << ((sizeof(maxexpire) * NBBY) - 1));
627 			if (ia->ia6_lifetime.ia6t_pltime <
628 			    maxexpire - ia->ia6_updatetime) {
629 				retlt->ia6t_preferred = ia->ia6_updatetime +
630 				    ia->ia6_lifetime.ia6t_pltime;
631 			} else
632 				retlt->ia6t_preferred = maxexpire;
633 		}
634 #ifdef OSIOCFIFALIFETIME_IN6
635 		if (cmd == OSIOCFIFALIFETIME_IN6)
636 			in6_addrlifetime_to_in6_addrlifetime50(
637 			    &ifr->ifru.ifru_lifetime);
638 #endif
639 		break;
640 
641 #ifdef OSIOCAIFADDR_IN6
642 	case OSIOCAIFADDR_IN6:
643 		in6_aliasreq50_to_in6_aliasreq(ifra);
644 		/*FALLTHROUGH*/
645 #endif
646 	case SIOCAIFADDR_IN6:
647 	{
648 		int i;
649 		struct nd_prefixctl pr0;
650 		struct nd_prefix *pr;
651 
652 		/* reject read-only flags */
653 		if ((ifra->ifra_flags & IN6_IFF_DUPLICATED) != 0 ||
654 		    (ifra->ifra_flags & IN6_IFF_DETACHED) != 0 ||
655 		    (ifra->ifra_flags & IN6_IFF_NODAD) != 0 ||
656 		    (ifra->ifra_flags & IN6_IFF_AUTOCONF) != 0) {
657 			return EINVAL;
658 		}
659 		/*
660 		 * first, make or update the interface address structure,
661 		 * and link it to the list.
662 		 */
663 		if ((error = in6_update_ifa(ifp, ifra, ia, 0)) != 0)
664 			return error;
665 		if ((ia = in6ifa_ifpwithaddr(ifp, &ifra->ifra_addr.sin6_addr))
666 		    == NULL) {
667 		    	/*
668 			 * this can happen when the user specify the 0 valid
669 			 * lifetime.
670 			 */
671 			break;
672 		}
673 
674 		/*
675 		 * then, make the prefix on-link on the interface.
676 		 * XXX: we'd rather create the prefix before the address, but
677 		 * we need at least one address to install the corresponding
678 		 * interface route, so we configure the address first.
679 		 */
680 
681 		/*
682 		 * convert mask to prefix length (prefixmask has already
683 		 * been validated in in6_update_ifa().
684 		 */
685 		memset(&pr0, 0, sizeof(pr0));
686 		pr0.ndpr_ifp = ifp;
687 		pr0.ndpr_plen = in6_mask2len(&ifra->ifra_prefixmask.sin6_addr,
688 		    NULL);
689 		if (pr0.ndpr_plen == 128) {
690 			break;	/* we don't need to install a host route. */
691 		}
692 		pr0.ndpr_prefix = ifra->ifra_addr;
693 		/* apply the mask for safety. */
694 		for (i = 0; i < 4; i++) {
695 			pr0.ndpr_prefix.sin6_addr.s6_addr32[i] &=
696 			    ifra->ifra_prefixmask.sin6_addr.s6_addr32[i];
697 		}
698 		/*
699 		 * XXX: since we don't have an API to set prefix (not address)
700 		 * lifetimes, we just use the same lifetimes as addresses.
701 		 * The (temporarily) installed lifetimes can be overridden by
702 		 * later advertised RAs (when accept_rtadv is non 0), which is
703 		 * an intended behavior.
704 		 */
705 		pr0.ndpr_raf_onlink = 1; /* should be configurable? */
706 		pr0.ndpr_raf_auto =
707 		    ((ifra->ifra_flags & IN6_IFF_AUTOCONF) != 0);
708 		pr0.ndpr_vltime = ifra->ifra_lifetime.ia6t_vltime;
709 		pr0.ndpr_pltime = ifra->ifra_lifetime.ia6t_pltime;
710 
711 		/* add the prefix if not yet. */
712 		if ((pr = nd6_prefix_lookup(&pr0)) == NULL) {
713 			/*
714 			 * nd6_prelist_add will install the corresponding
715 			 * interface route.
716 			 */
717 			if ((error = nd6_prelist_add(&pr0, NULL, &pr)) != 0)
718 				return error;
719 			if (pr == NULL) {
720 				log(LOG_ERR, "nd6_prelist_add succeeded but "
721 				    "no prefix\n");
722 				return EINVAL; /* XXX panic here? */
723 			}
724 		}
725 
726 		/* relate the address to the prefix */
727 		if (ia->ia6_ndpr == NULL) {
728 			ia->ia6_ndpr = pr;
729 			pr->ndpr_refcnt++;
730 
731 			/*
732 			 * If this is the first autoconf address from the
733 			 * prefix, create a temporary address as well
734 			 * (when required).
735 			 */
736 			if ((ia->ia6_flags & IN6_IFF_AUTOCONF) &&
737 			    ip6_use_tempaddr && pr->ndpr_refcnt == 1) {
738 				int e;
739 				if ((e = in6_tmpifadd(ia, 1, 0)) != 0) {
740 					log(LOG_NOTICE, "in6_control: failed "
741 					    "to create a temporary address, "
742 					    "errno=%d\n", e);
743 				}
744 			}
745 		}
746 
747 		/*
748 		 * this might affect the status of autoconfigured addresses,
749 		 * that is, this address might make other addresses detached.
750 		 */
751 		pfxlist_onlink_check();
752 
753 		(void)pfil_run_hooks(if_pfil, (struct mbuf **)SIOCAIFADDR_IN6,
754 		    ifp, PFIL_IFADDR);
755 		break;
756 	}
757 
758 	case SIOCDIFADDR_IN6:
759 	{
760 		struct nd_prefix *pr;
761 
762 		/*
763 		 * If the address being deleted is the only one that owns
764 		 * the corresponding prefix, expire the prefix as well.
765 		 * XXX: theoretically, we don't have to worry about such
766 		 * relationship, since we separate the address management
767 		 * and the prefix management.  We do this, however, to provide
768 		 * as much backward compatibility as possible in terms of
769 		 * the ioctl operation.
770 		 * Note that in6_purgeaddr() will decrement ndpr_refcnt.
771 		 */
772 		pr = ia->ia6_ndpr;
773 		in6_purgeaddr(&ia->ia_ifa);
774 		if (pr && pr->ndpr_refcnt == 0)
775 			prelist_remove(pr);
776 		(void)pfil_run_hooks(if_pfil, (struct mbuf **)SIOCDIFADDR_IN6,
777 		    ifp, PFIL_IFADDR);
778 		break;
779 	}
780 
781 	default:
782 		return ENOTTY;
783 	}
784 
785 	return 0;
786 }
787 
788 int
789 in6_control(struct socket *so, u_long cmd, void *data, struct ifnet *ifp,
790     struct lwp *l)
791 {
792 	int error, s;
793 
794 	switch (cmd) {
795 	case SIOCSNDFLUSH_IN6:
796 	case SIOCSPFXFLUSH_IN6:
797 	case SIOCSRTRFLUSH_IN6:
798 	case SIOCSDEFIFACE_IN6:
799 	case SIOCSIFINFO_FLAGS:
800 	case SIOCSIFINFO_IN6:
801 
802 	case SIOCALIFADDR:
803 	case SIOCDLIFADDR:
804 
805 	case SIOCDIFADDR_IN6:
806 #ifdef OSIOCAIFADDR_IN6
807 	case OSIOCAIFADDR_IN6:
808 #endif
809 	case SIOCAIFADDR_IN6:
810 		if (kauth_authorize_network(l->l_cred,
811 		    KAUTH_NETWORK_SOCKET,
812 		    KAUTH_REQ_NETWORK_SOCKET_SETPRIV,
813 		    so, NULL, NULL))
814 			return EPERM;
815 		break;
816 	}
817 
818 	s = splnet();
819 	error = in6_control1(so , cmd, data, ifp, l);
820 	splx(s);
821 	return error;
822 }
823 
824 /*
825  * Update parameters of an IPv6 interface address.
826  * If necessary, a new entry is created and linked into address chains.
827  * This function is separated from in6_control().
828  * XXX: should this be performed under splnet()?
829  */
830 static int
831 in6_update_ifa1(struct ifnet *ifp, struct in6_aliasreq *ifra,
832     struct in6_ifaddr *ia, int flags)
833 {
834 	int error = 0, hostIsNew = 0, plen = -1;
835 	struct in6_ifaddr *oia;
836 	struct sockaddr_in6 dst6;
837 	struct in6_addrlifetime *lt;
838 	struct in6_multi_mship *imm;
839 	struct in6_multi *in6m_sol;
840 	struct rtentry *rt;
841 	int dad_delay;
842 
843 	in6m_sol = NULL;
844 
845 	/* Validate parameters */
846 	if (ifp == NULL || ifra == NULL) /* this maybe redundant */
847 		return EINVAL;
848 
849 	/*
850 	 * The destination address for a p2p link must have a family
851 	 * of AF_UNSPEC or AF_INET6.
852 	 */
853 	if ((ifp->if_flags & IFF_POINTOPOINT) != 0 &&
854 	    ifra->ifra_dstaddr.sin6_family != AF_INET6 &&
855 	    ifra->ifra_dstaddr.sin6_family != AF_UNSPEC)
856 		return EAFNOSUPPORT;
857 	/*
858 	 * validate ifra_prefixmask.  don't check sin6_family, netmask
859 	 * does not carry fields other than sin6_len.
860 	 */
861 	if (ifra->ifra_prefixmask.sin6_len > sizeof(struct sockaddr_in6))
862 		return EINVAL;
863 	/*
864 	 * Because the IPv6 address architecture is classless, we require
865 	 * users to specify a (non 0) prefix length (mask) for a new address.
866 	 * We also require the prefix (when specified) mask is valid, and thus
867 	 * reject a non-consecutive mask.
868 	 */
869 	if (ia == NULL && ifra->ifra_prefixmask.sin6_len == 0)
870 		return EINVAL;
871 	if (ifra->ifra_prefixmask.sin6_len != 0) {
872 		plen = in6_mask2len(&ifra->ifra_prefixmask.sin6_addr,
873 		    (u_char *)&ifra->ifra_prefixmask +
874 		    ifra->ifra_prefixmask.sin6_len);
875 		if (plen <= 0)
876 			return EINVAL;
877 	} else {
878 		/*
879 		 * In this case, ia must not be NULL.  We just use its prefix
880 		 * length.
881 		 */
882 		plen = in6_mask2len(&ia->ia_prefixmask.sin6_addr, NULL);
883 	}
884 	/*
885 	 * If the destination address on a p2p interface is specified,
886 	 * and the address is a scoped one, validate/set the scope
887 	 * zone identifier.
888 	 */
889 	dst6 = ifra->ifra_dstaddr;
890 	if ((ifp->if_flags & (IFF_POINTOPOINT|IFF_LOOPBACK)) != 0 &&
891 	    (dst6.sin6_family == AF_INET6)) {
892 		struct in6_addr in6_tmp;
893 		u_int32_t zoneid;
894 
895 		in6_tmp = dst6.sin6_addr;
896 		if (in6_setscope(&in6_tmp, ifp, &zoneid))
897 			return EINVAL; /* XXX: should be impossible */
898 
899 		if (dst6.sin6_scope_id != 0) {
900 			if (dst6.sin6_scope_id != zoneid)
901 				return EINVAL;
902 		} else		/* user omit to specify the ID. */
903 			dst6.sin6_scope_id = zoneid;
904 
905 		/* convert into the internal form */
906 		if (sa6_embedscope(&dst6, 0))
907 			return EINVAL; /* XXX: should be impossible */
908 	}
909 	/*
910 	 * The destination address can be specified only for a p2p or a
911 	 * loopback interface.  If specified, the corresponding prefix length
912 	 * must be 128.
913 	 */
914 	if (ifra->ifra_dstaddr.sin6_family == AF_INET6) {
915 #ifdef FORCE_P2PPLEN
916 		int i;
917 #endif
918 
919 		if ((ifp->if_flags & (IFF_POINTOPOINT|IFF_LOOPBACK)) == 0) {
920 			/* XXX: noisy message */
921 			nd6log((LOG_INFO, "in6_update_ifa: a destination can "
922 			    "be specified for a p2p or a loopback IF only\n"));
923 			return EINVAL;
924 		}
925 		if (plen != 128) {
926 			nd6log((LOG_INFO, "in6_update_ifa: prefixlen should "
927 			    "be 128 when dstaddr is specified\n"));
928 #ifdef FORCE_P2PPLEN
929 			/*
930 			 * To be compatible with old configurations,
931 			 * such as ifconfig gif0 inet6 2001::1 2001::2
932 			 * prefixlen 126, we override the specified
933 			 * prefixmask as if the prefix length was 128.
934 			 */
935 			ifra->ifra_prefixmask.sin6_len =
936 			    sizeof(struct sockaddr_in6);
937 			for (i = 0; i < 4; i++)
938 				ifra->ifra_prefixmask.sin6_addr.s6_addr32[i] =
939 				    0xffffffff;
940 			plen = 128;
941 #else
942 			return EINVAL;
943 #endif
944 		}
945 	}
946 	/* lifetime consistency check */
947 	lt = &ifra->ifra_lifetime;
948 	if (lt->ia6t_pltime > lt->ia6t_vltime)
949 		return EINVAL;
950 	if (lt->ia6t_vltime == 0) {
951 		/*
952 		 * the following log might be noisy, but this is a typical
953 		 * configuration mistake or a tool's bug.
954 		 */
955 		nd6log((LOG_INFO,
956 		    "in6_update_ifa: valid lifetime is 0 for %s\n",
957 		    ip6_sprintf(&ifra->ifra_addr.sin6_addr)));
958 
959 		if (ia == NULL)
960 			return 0; /* there's nothing to do */
961 	}
962 
963 	/*
964 	 * If this is a new address, allocate a new ifaddr and link it
965 	 * into chains.
966 	 */
967 	if (ia == NULL) {
968 		hostIsNew = 1;
969 		/*
970 		 * When in6_update_ifa() is called in a process of a received
971 		 * RA, it is called under an interrupt context.  So, we should
972 		 * call malloc with M_NOWAIT.
973 		 */
974 		ia = (struct in6_ifaddr *) malloc(sizeof(*ia), M_IFADDR,
975 		    M_NOWAIT);
976 		if (ia == NULL)
977 			return ENOBUFS;
978 		memset(ia, 0, sizeof(*ia));
979 		LIST_INIT(&ia->ia6_memberships);
980 		/* Initialize the address and masks, and put time stamp */
981 		ia->ia_ifa.ifa_addr = (struct sockaddr *)&ia->ia_addr;
982 		ia->ia_addr.sin6_family = AF_INET6;
983 		ia->ia_addr.sin6_len = sizeof(ia->ia_addr);
984 		ia->ia6_createtime = time_second;
985 		if ((ifp->if_flags & (IFF_POINTOPOINT | IFF_LOOPBACK)) != 0) {
986 			/*
987 			 * XXX: some functions expect that ifa_dstaddr is not
988 			 * NULL for p2p interfaces.
989 			 */
990 			ia->ia_ifa.ifa_dstaddr =
991 			    (struct sockaddr *)&ia->ia_dstaddr;
992 		} else {
993 			ia->ia_ifa.ifa_dstaddr = NULL;
994 		}
995 		ia->ia_ifa.ifa_netmask =
996 		    (struct sockaddr *)&ia->ia_prefixmask;
997 
998 		ia->ia_ifp = ifp;
999 		if ((oia = in6_ifaddr) != NULL) {
1000 			for ( ; oia->ia_next; oia = oia->ia_next)
1001 				continue;
1002 			oia->ia_next = ia;
1003 		} else
1004 			in6_ifaddr = ia;
1005 		/* gain a refcnt for the link from in6_ifaddr */
1006 		IFAREF(&ia->ia_ifa);
1007 
1008 		ifa_insert(ifp, &ia->ia_ifa);
1009 	}
1010 
1011 	/* update timestamp */
1012 	ia->ia6_updatetime = time_second;
1013 
1014 	/* set prefix mask */
1015 	if (ifra->ifra_prefixmask.sin6_len) {
1016 		/*
1017 		 * We prohibit changing the prefix length of an existing
1018 		 * address, because
1019 		 * + such an operation should be rare in IPv6, and
1020 		 * + the operation would confuse prefix management.
1021 		 */
1022 		if (ia->ia_prefixmask.sin6_len &&
1023 		    in6_mask2len(&ia->ia_prefixmask.sin6_addr, NULL) != plen) {
1024 			nd6log((LOG_INFO, "in6_update_ifa: the prefix length of an"
1025 			    " existing (%s) address should not be changed\n",
1026 			    ip6_sprintf(&ia->ia_addr.sin6_addr)));
1027 			error = EINVAL;
1028 			goto unlink;
1029 		}
1030 		ia->ia_prefixmask = ifra->ifra_prefixmask;
1031 	}
1032 
1033 	/*
1034 	 * If a new destination address is specified, scrub the old one and
1035 	 * install the new destination.  Note that the interface must be
1036 	 * p2p or loopback (see the check above.)
1037 	 */
1038 	if (dst6.sin6_family == AF_INET6 &&
1039 	    !IN6_ARE_ADDR_EQUAL(&dst6.sin6_addr, &ia->ia_dstaddr.sin6_addr)) {
1040 		if ((ia->ia_flags & IFA_ROUTE) != 0 &&
1041 		    rtinit(&(ia->ia_ifa), (int)RTM_DELETE, RTF_HOST) != 0) {
1042 			nd6log((LOG_ERR, "in6_update_ifa: failed to remove "
1043 			    "a route to the old destination: %s\n",
1044 			    ip6_sprintf(&ia->ia_addr.sin6_addr)));
1045 			/* proceed anyway... */
1046 		} else
1047 			ia->ia_flags &= ~IFA_ROUTE;
1048 		ia->ia_dstaddr = dst6;
1049 	}
1050 
1051 	/*
1052 	 * Set lifetimes.  We do not refer to ia6t_expire and ia6t_preferred
1053 	 * to see if the address is deprecated or invalidated, but initialize
1054 	 * these members for applications.
1055 	 */
1056 	ia->ia6_lifetime = ifra->ifra_lifetime;
1057 	if (ia->ia6_lifetime.ia6t_vltime != ND6_INFINITE_LIFETIME) {
1058 		ia->ia6_lifetime.ia6t_expire =
1059 		    time_second + ia->ia6_lifetime.ia6t_vltime;
1060 	} else
1061 		ia->ia6_lifetime.ia6t_expire = 0;
1062 	if (ia->ia6_lifetime.ia6t_pltime != ND6_INFINITE_LIFETIME) {
1063 		ia->ia6_lifetime.ia6t_preferred =
1064 		    time_second + ia->ia6_lifetime.ia6t_pltime;
1065 	} else
1066 		ia->ia6_lifetime.ia6t_preferred = 0;
1067 
1068 	/*
1069 	 * configure address flags.
1070 	 */
1071 	ia->ia6_flags = ifra->ifra_flags;
1072 
1073 	/*
1074 	 * Make the address tentative before joining multicast addresses,
1075 	 * so that corresponding MLD responses would not have a tentative
1076 	 * source address.
1077 	 */
1078 	ia->ia6_flags &= ~IN6_IFF_DUPLICATED;	/* safety */
1079 	if (ifp->if_link_state == LINK_STATE_DOWN) {
1080 		ia->ia6_flags |= IN6_IFF_DETACHED;
1081 		ia->ia6_flags &= ~IN6_IFF_TENTATIVE;
1082 	} else if (hostIsNew && in6if_do_dad(ifp))
1083 		ia->ia6_flags |= IN6_IFF_TENTATIVE;
1084 
1085 	/*
1086 	 * backward compatibility - if IN6_IFF_DEPRECATED is set from the
1087 	 * userland, make it deprecated.
1088 	 */
1089 	if ((ifra->ifra_flags & IN6_IFF_DEPRECATED) != 0) {
1090 		ia->ia6_lifetime.ia6t_pltime = 0;
1091 		ia->ia6_lifetime.ia6t_preferred = time_second;
1092 	}
1093 
1094 	/* reset the interface and routing table appropriately. */
1095 	if ((error = in6_ifinit(ifp, ia, &ifra->ifra_addr, hostIsNew)) != 0)
1096 		goto unlink;
1097 	/*
1098 	 * We are done if we have simply modified an existing address.
1099 	 */
1100 	if (!hostIsNew)
1101 		return error;
1102 
1103 	/*
1104 	 * Beyond this point, we should call in6_purgeaddr upon an error,
1105 	 * not just go to unlink.
1106 	 */
1107 
1108 	/* join necessary multicast groups */
1109 	if ((ifp->if_flags & IFF_MULTICAST) != 0) {
1110 		struct sockaddr_in6 mltaddr, mltmask;
1111 		struct in6_addr llsol;
1112 
1113 		/* join solicited multicast addr for new host id */
1114 		memset(&llsol, 0, sizeof(struct in6_addr));
1115 		llsol.s6_addr16[0] = htons(0xff02);
1116 		llsol.s6_addr32[1] = 0;
1117 		llsol.s6_addr32[2] = htonl(1);
1118 		llsol.s6_addr32[3] = ifra->ifra_addr.sin6_addr.s6_addr32[3];
1119 		llsol.s6_addr8[12] = 0xff;
1120 		if ((error = in6_setscope(&llsol, ifp, NULL)) != 0) {
1121 			/* XXX: should not happen */
1122 			log(LOG_ERR, "in6_update_ifa: "
1123 			    "in6_setscope failed\n");
1124 			goto cleanup;
1125 		}
1126 		dad_delay = 0;
1127 		if ((flags & IN6_IFAUPDATE_DADDELAY)) {
1128 			/*
1129 			 * We need a random delay for DAD on the address
1130 			 * being configured.  It also means delaying
1131 			 * transmission of the corresponding MLD report to
1132 			 * avoid report collision.
1133 			 * [draft-ietf-ipv6-rfc2462bis-02.txt]
1134 			 */
1135 			dad_delay = cprng_fast32() %
1136 			    (MAX_RTR_SOLICITATION_DELAY * hz);
1137 		}
1138 
1139 #define	MLTMASK_LEN  4	/* mltmask's masklen (=32bit=4octet) */
1140 		/* join solicited multicast addr for new host id */
1141 		imm = in6_joingroup(ifp, &llsol, &error, dad_delay);
1142 		if (!imm) {
1143 			nd6log((LOG_ERR,
1144 			    "in6_update_ifa: addmulti "
1145 			    "failed for %s on %s (errno=%d)\n",
1146 			    ip6_sprintf(&llsol), if_name(ifp), error));
1147 			goto cleanup;
1148 		}
1149 		LIST_INSERT_HEAD(&ia->ia6_memberships, imm, i6mm_chain);
1150 		in6m_sol = imm->i6mm_maddr;
1151 
1152 		sockaddr_in6_init(&mltmask, &in6mask32, 0, 0, 0);
1153 
1154 		/*
1155 		 * join link-local all-nodes address
1156 		 */
1157 		sockaddr_in6_init(&mltaddr, &in6addr_linklocal_allnodes,
1158 		    0, 0, 0);
1159 		if ((error = in6_setscope(&mltaddr.sin6_addr, ifp, NULL)) != 0)
1160 			goto cleanup; /* XXX: should not fail */
1161 
1162 		/*
1163 		 * XXX: do we really need this automatic routes?
1164 		 * We should probably reconsider this stuff.  Most applications
1165 		 * actually do not need the routes, since they usually specify
1166 		 * the outgoing interface.
1167 		 */
1168 		rt = rtalloc1((struct sockaddr *)&mltaddr, 0);
1169 		if (rt) {
1170 			if (memcmp(&mltaddr.sin6_addr,
1171 			    &satocsin6(rt_getkey(rt))->sin6_addr,
1172 			    MLTMASK_LEN)) {
1173 				RTFREE(rt);
1174 				rt = NULL;
1175 			} else if (rt->rt_ifp != ifp) {
1176 				IN6_DPRINTF("%s: rt_ifp %p -> %p (%s) "
1177 				    "network %04x:%04x::/32 = %04x:%04x::/32\n",
1178 				    __func__, rt->rt_ifp, ifp, ifp->if_xname,
1179 				    ntohs(mltaddr.sin6_addr.s6_addr16[0]),
1180 				    ntohs(mltaddr.sin6_addr.s6_addr16[1]),
1181 				    satocsin6(rt_getkey(rt))->sin6_addr.s6_addr16[0],
1182 				    satocsin6(rt_getkey(rt))->sin6_addr.s6_addr16[1]);
1183 				rt_replace_ifa(rt, &ia->ia_ifa);
1184 				rt->rt_ifp = ifp;
1185 			}
1186 		}
1187 		if (!rt) {
1188 			struct rt_addrinfo info;
1189 
1190 			memset(&info, 0, sizeof(info));
1191 			info.rti_info[RTAX_DST] = (struct sockaddr *)&mltaddr;
1192 			info.rti_info[RTAX_GATEWAY] =
1193 			    (struct sockaddr *)&ia->ia_addr;
1194 			info.rti_info[RTAX_NETMASK] =
1195 			    (struct sockaddr *)&mltmask;
1196 			info.rti_info[RTAX_IFA] =
1197 			    (struct sockaddr *)&ia->ia_addr;
1198 			/* XXX: we need RTF_CLONING to fake nd6_rtrequest */
1199 			info.rti_flags = RTF_UP | RTF_CLONING;
1200 			error = rtrequest1(RTM_ADD, &info, NULL);
1201 			if (error)
1202 				goto cleanup;
1203 		} else {
1204 			RTFREE(rt);
1205 		}
1206 		imm = in6_joingroup(ifp, &mltaddr.sin6_addr, &error, 0);
1207 		if (!imm) {
1208 			nd6log((LOG_WARNING,
1209 			    "in6_update_ifa: addmulti failed for "
1210 			    "%s on %s (errno=%d)\n",
1211 			    ip6_sprintf(&mltaddr.sin6_addr),
1212 			    if_name(ifp), error));
1213 			goto cleanup;
1214 		}
1215 		LIST_INSERT_HEAD(&ia->ia6_memberships, imm, i6mm_chain);
1216 
1217 		/*
1218 		 * join node information group address
1219 		 */
1220 		dad_delay = 0;
1221 		if ((flags & IN6_IFAUPDATE_DADDELAY)) {
1222 			/*
1223 			 * The spec doesn't say anything about delay for this
1224 			 * group, but the same logic should apply.
1225 			 */
1226 			dad_delay = cprng_fast32() %
1227 			    (MAX_RTR_SOLICITATION_DELAY * hz);
1228 		}
1229 		if (in6_nigroup(ifp, hostname, hostnamelen, &mltaddr) != 0)
1230 			;
1231 		else if ((imm = in6_joingroup(ifp, &mltaddr.sin6_addr, &error,
1232 		          dad_delay)) == NULL) { /* XXX jinmei */
1233 			nd6log((LOG_WARNING, "in6_update_ifa: "
1234 			    "addmulti failed for %s on %s (errno=%d)\n",
1235 			    ip6_sprintf(&mltaddr.sin6_addr),
1236 			    if_name(ifp), error));
1237 			/* XXX not very fatal, go on... */
1238 		} else {
1239 			LIST_INSERT_HEAD(&ia->ia6_memberships, imm, i6mm_chain);
1240 		}
1241 
1242 
1243 		/*
1244 		 * join interface-local all-nodes address.
1245 		 * (ff01::1%ifN, and ff01::%ifN/32)
1246 		 */
1247 		mltaddr.sin6_addr = in6addr_nodelocal_allnodes;
1248 		if ((error = in6_setscope(&mltaddr.sin6_addr, ifp, NULL)) != 0)
1249 			goto cleanup; /* XXX: should not fail */
1250 
1251 		/* XXX: again, do we really need the route? */
1252 		rt = rtalloc1((struct sockaddr *)&mltaddr, 0);
1253 		if (rt) {
1254 			/* 32bit came from "mltmask" */
1255 			if (memcmp(&mltaddr.sin6_addr,
1256 			    &satocsin6(rt_getkey(rt))->sin6_addr,
1257 			    32 / NBBY)) {
1258 				RTFREE(rt);
1259 				rt = NULL;
1260 			} else if (rt->rt_ifp != ifp) {
1261 				IN6_DPRINTF("%s: rt_ifp %p -> %p (%s) "
1262 				    "network %04x:%04x::/32 = %04x:%04x::/32\n",
1263 				    __func__, rt->rt_ifp, ifp, ifp->if_xname,
1264 				    ntohs(mltaddr.sin6_addr.s6_addr16[0]),
1265 				    ntohs(mltaddr.sin6_addr.s6_addr16[1]),
1266 				    satocsin6(rt_getkey(rt))->sin6_addr.s6_addr16[0],
1267 				    satocsin6(rt_getkey(rt))->sin6_addr.s6_addr16[1]);
1268 				rt_replace_ifa(rt, &ia->ia_ifa);
1269 				rt->rt_ifp = ifp;
1270 			}
1271 		}
1272 		if (!rt) {
1273 			struct rt_addrinfo info;
1274 
1275 			memset(&info, 0, sizeof(info));
1276 			info.rti_info[RTAX_DST] = (struct sockaddr *)&mltaddr;
1277 			info.rti_info[RTAX_GATEWAY] =
1278 			    (struct sockaddr *)&ia->ia_addr;
1279 			info.rti_info[RTAX_NETMASK] =
1280 			    (struct sockaddr *)&mltmask;
1281 			info.rti_info[RTAX_IFA] =
1282 			    (struct sockaddr *)&ia->ia_addr;
1283 			info.rti_flags = RTF_UP | RTF_CLONING;
1284 			error = rtrequest1(RTM_ADD, &info, NULL);
1285 			if (error)
1286 				goto cleanup;
1287 #undef	MLTMASK_LEN
1288 		} else {
1289 			RTFREE(rt);
1290 		}
1291 		imm = in6_joingroup(ifp, &mltaddr.sin6_addr, &error, 0);
1292 		if (!imm) {
1293 			nd6log((LOG_WARNING, "in6_update_ifa: "
1294 			    "addmulti failed for %s on %s (errno=%d)\n",
1295 			    ip6_sprintf(&mltaddr.sin6_addr),
1296 			    if_name(ifp), error));
1297 			goto cleanup;
1298 		} else {
1299 			LIST_INSERT_HEAD(&ia->ia6_memberships, imm, i6mm_chain);
1300 		}
1301 	}
1302 
1303 	/*
1304 	 * Perform DAD, if needed.
1305 	 * XXX It may be of use, if we can administratively
1306 	 * disable DAD.
1307 	 */
1308 	if (hostIsNew && in6if_do_dad(ifp) &&
1309 	    ((ifra->ifra_flags & IN6_IFF_NODAD) == 0) &&
1310 	    (ia->ia6_flags & IN6_IFF_TENTATIVE))
1311 	{
1312 		int mindelay, maxdelay;
1313 
1314 		dad_delay = 0;
1315 		if ((flags & IN6_IFAUPDATE_DADDELAY)) {
1316 			/*
1317 			 * We need to impose a delay before sending an NS
1318 			 * for DAD.  Check if we also needed a delay for the
1319 			 * corresponding MLD message.  If we did, the delay
1320 			 * should be larger than the MLD delay (this could be
1321 			 * relaxed a bit, but this simple logic is at least
1322 			 * safe).
1323 			 */
1324 			mindelay = 0;
1325 			if (in6m_sol != NULL &&
1326 			    in6m_sol->in6m_state == MLD_REPORTPENDING) {
1327 				mindelay = in6m_sol->in6m_timer;
1328 			}
1329 			maxdelay = MAX_RTR_SOLICITATION_DELAY * hz;
1330 			if (maxdelay - mindelay == 0)
1331 				dad_delay = 0;
1332 			else {
1333 				dad_delay =
1334 				    (cprng_fast32() % (maxdelay - mindelay)) +
1335 				    mindelay;
1336 			}
1337 		}
1338 		nd6_dad_start(&ia->ia_ifa, dad_delay);
1339 	}
1340 
1341 	return error;
1342 
1343   unlink:
1344 	/*
1345 	 * XXX: if a change of an existing address failed, keep the entry
1346 	 * anyway.
1347 	 */
1348 	if (hostIsNew)
1349 		in6_unlink_ifa(ia, ifp);
1350 	return error;
1351 
1352   cleanup:
1353 	in6_purgeaddr(&ia->ia_ifa);
1354 	return error;
1355 }
1356 
1357 int
1358 in6_update_ifa(struct ifnet *ifp, struct in6_aliasreq *ifra,
1359     struct in6_ifaddr *ia, int flags)
1360 {
1361 	int rc, s;
1362 
1363 	s = splnet();
1364 	rc = in6_update_ifa1(ifp, ifra, ia, flags);
1365 	splx(s);
1366 	return rc;
1367 }
1368 
1369 void
1370 in6_purgeaddr(struct ifaddr *ifa)
1371 {
1372 	struct ifnet *ifp = ifa->ifa_ifp;
1373 	struct in6_ifaddr *ia = (struct in6_ifaddr *) ifa;
1374 	struct in6_multi_mship *imm;
1375 
1376 	/* stop DAD processing */
1377 	nd6_dad_stop(ifa);
1378 
1379 	/*
1380 	 * delete route to the destination of the address being purged.
1381 	 * The interface must be p2p or loopback in this case.
1382 	 */
1383 	if ((ia->ia_flags & IFA_ROUTE) != 0 && ia->ia_dstaddr.sin6_len != 0) {
1384 		int e;
1385 
1386 		if ((e = rtinit(&(ia->ia_ifa), (int)RTM_DELETE, RTF_HOST))
1387 		    != 0) {
1388 			log(LOG_ERR, "in6_purgeaddr: failed to remove "
1389 			    "a route to the p2p destination: %s on %s, "
1390 			    "errno=%d\n",
1391 			    ip6_sprintf(&ia->ia_addr.sin6_addr), if_name(ifp),
1392 			    e);
1393 			/* proceed anyway... */
1394 		} else
1395 			ia->ia_flags &= ~IFA_ROUTE;
1396 	}
1397 
1398 	/* Remove ownaddr's loopback rtentry, if it exists. */
1399 	in6_ifremloop(&(ia->ia_ifa));
1400 
1401 	/*
1402 	 * leave from multicast groups we have joined for the interface
1403 	 */
1404 	while ((imm = LIST_FIRST(&ia->ia6_memberships)) != NULL) {
1405 		LIST_REMOVE(imm, i6mm_chain);
1406 		in6_leavegroup(imm);
1407 	}
1408 
1409 	in6_unlink_ifa(ia, ifp);
1410 }
1411 
1412 static void
1413 in6_unlink_ifa(struct in6_ifaddr *ia, struct ifnet *ifp)
1414 {
1415 	struct in6_ifaddr *oia;
1416 	int	s = splnet();
1417 
1418 	ifa_remove(ifp, &ia->ia_ifa);
1419 
1420 	oia = ia;
1421 	if (oia == (ia = in6_ifaddr))
1422 		in6_ifaddr = ia->ia_next;
1423 	else {
1424 		while (ia->ia_next && (ia->ia_next != oia))
1425 			ia = ia->ia_next;
1426 		if (ia->ia_next)
1427 			ia->ia_next = oia->ia_next;
1428 		else {
1429 			/* search failed */
1430 			printf("Couldn't unlink in6_ifaddr from in6_ifaddr\n");
1431 		}
1432 	}
1433 
1434 	/*
1435 	 * XXX thorpej@NetBSD.org -- if the interface is going
1436 	 * XXX away, don't save the multicast entries, delete them!
1437 	 */
1438 	if (LIST_EMPTY(&oia->ia6_multiaddrs))
1439 		;
1440 	else if (oia->ia_ifa.ifa_ifp->if_output == if_nulloutput) {
1441 		struct in6_multi *in6m, *next;
1442 
1443 		for (in6m = LIST_FIRST(&oia->ia6_multiaddrs); in6m != NULL;
1444 		     in6m = next) {
1445 			next = LIST_NEXT(in6m, in6m_entry);
1446 			in6_delmulti(in6m);
1447 		}
1448 	} else
1449 		in6_savemkludge(oia);
1450 
1451 	/*
1452 	 * Release the reference to the base prefix.  There should be a
1453 	 * positive reference.
1454 	 */
1455 	if (oia->ia6_ndpr == NULL) {
1456 		nd6log((LOG_NOTICE, "in6_unlink_ifa: autoconf'ed address "
1457 		    "%p has no prefix\n", oia));
1458 	} else {
1459 		oia->ia6_ndpr->ndpr_refcnt--;
1460 		oia->ia6_ndpr = NULL;
1461 	}
1462 
1463 	/*
1464 	 * Also, if the address being removed is autoconf'ed, call
1465 	 * pfxlist_onlink_check() since the release might affect the status of
1466 	 * other (detached) addresses.
1467 	 */
1468 	if ((oia->ia6_flags & IN6_IFF_AUTOCONF) != 0)
1469 		pfxlist_onlink_check();
1470 
1471 	/*
1472 	 * release another refcnt for the link from in6_ifaddr.
1473 	 * Note that we should decrement the refcnt at least once for all *BSD.
1474 	 */
1475 	IFAFREE(&oia->ia_ifa);
1476 
1477 	splx(s);
1478 }
1479 
1480 void
1481 in6_purgeif(struct ifnet *ifp)
1482 {
1483 	if_purgeaddrs(ifp, AF_INET6, in6_purgeaddr);
1484 
1485 	in6_ifdetach(ifp);
1486 }
1487 
1488 /*
1489  * SIOC[GAD]LIFADDR.
1490  *	SIOCGLIFADDR: get first address. (?)
1491  *	SIOCGLIFADDR with IFLR_PREFIX:
1492  *		get first address that matches the specified prefix.
1493  *	SIOCALIFADDR: add the specified address.
1494  *	SIOCALIFADDR with IFLR_PREFIX:
1495  *		add the specified prefix, filling hostid part from
1496  *		the first link-local address.  prefixlen must be <= 64.
1497  *	SIOCDLIFADDR: delete the specified address.
1498  *	SIOCDLIFADDR with IFLR_PREFIX:
1499  *		delete the first address that matches the specified prefix.
1500  * return values:
1501  *	EINVAL on invalid parameters
1502  *	EADDRNOTAVAIL on prefix match failed/specified address not found
1503  *	other values may be returned from in6_ioctl()
1504  *
1505  * NOTE: SIOCALIFADDR(with IFLR_PREFIX set) allows prefixlen less than 64.
1506  * this is to accommodate address naming scheme other than RFC2374,
1507  * in the future.
1508  * RFC2373 defines interface id to be 64bit, but it allows non-RFC2374
1509  * address encoding scheme. (see figure on page 8)
1510  */
1511 static int
1512 in6_lifaddr_ioctl(struct socket *so, u_long cmd, void *data,
1513 	struct ifnet *ifp, struct lwp *l)
1514 {
1515 	struct in6_ifaddr *ia;
1516 	struct if_laddrreq *iflr = (struct if_laddrreq *)data;
1517 	struct ifaddr *ifa;
1518 	struct sockaddr *sa;
1519 
1520 	/* sanity checks */
1521 	if (!data || !ifp) {
1522 		panic("invalid argument to in6_lifaddr_ioctl");
1523 		/* NOTREACHED */
1524 	}
1525 
1526 	switch (cmd) {
1527 	case SIOCGLIFADDR:
1528 		/* address must be specified on GET with IFLR_PREFIX */
1529 		if ((iflr->flags & IFLR_PREFIX) == 0)
1530 			break;
1531 		/* FALLTHROUGH */
1532 	case SIOCALIFADDR:
1533 	case SIOCDLIFADDR:
1534 		/* address must be specified on ADD and DELETE */
1535 		sa = (struct sockaddr *)&iflr->addr;
1536 		if (sa->sa_family != AF_INET6)
1537 			return EINVAL;
1538 		if (sa->sa_len != sizeof(struct sockaddr_in6))
1539 			return EINVAL;
1540 		/* XXX need improvement */
1541 		sa = (struct sockaddr *)&iflr->dstaddr;
1542 		if (sa->sa_family && sa->sa_family != AF_INET6)
1543 			return EINVAL;
1544 		if (sa->sa_len && sa->sa_len != sizeof(struct sockaddr_in6))
1545 			return EINVAL;
1546 		break;
1547 	default: /* shouldn't happen */
1548 #if 0
1549 		panic("invalid cmd to in6_lifaddr_ioctl");
1550 		/* NOTREACHED */
1551 #else
1552 		return EOPNOTSUPP;
1553 #endif
1554 	}
1555 	if (sizeof(struct in6_addr) * NBBY < iflr->prefixlen)
1556 		return EINVAL;
1557 
1558 	switch (cmd) {
1559 	case SIOCALIFADDR:
1560 	    {
1561 		struct in6_aliasreq ifra;
1562 		struct in6_addr *xhostid = NULL;
1563 		int prefixlen;
1564 
1565 		if ((iflr->flags & IFLR_PREFIX) != 0) {
1566 			struct sockaddr_in6 *sin6;
1567 
1568 			/*
1569 			 * xhostid is to fill in the hostid part of the
1570 			 * address.  xhostid points to the first link-local
1571 			 * address attached to the interface.
1572 			 */
1573 			ia = in6ifa_ifpforlinklocal(ifp, 0);
1574 			if (ia == NULL)
1575 				return EADDRNOTAVAIL;
1576 			xhostid = IFA_IN6(&ia->ia_ifa);
1577 
1578 		 	/* prefixlen must be <= 64. */
1579 			if (64 < iflr->prefixlen)
1580 				return EINVAL;
1581 			prefixlen = iflr->prefixlen;
1582 
1583 			/* hostid part must be zero. */
1584 			sin6 = (struct sockaddr_in6 *)&iflr->addr;
1585 			if (sin6->sin6_addr.s6_addr32[2] != 0
1586 			 || sin6->sin6_addr.s6_addr32[3] != 0) {
1587 				return EINVAL;
1588 			}
1589 		} else
1590 			prefixlen = iflr->prefixlen;
1591 
1592 		/* copy args to in6_aliasreq, perform ioctl(SIOCAIFADDR_IN6). */
1593 		memset(&ifra, 0, sizeof(ifra));
1594 		memcpy(ifra.ifra_name, iflr->iflr_name, sizeof(ifra.ifra_name));
1595 
1596 		memcpy(&ifra.ifra_addr, &iflr->addr,
1597 		    ((struct sockaddr *)&iflr->addr)->sa_len);
1598 		if (xhostid) {
1599 			/* fill in hostid part */
1600 			ifra.ifra_addr.sin6_addr.s6_addr32[2] =
1601 			    xhostid->s6_addr32[2];
1602 			ifra.ifra_addr.sin6_addr.s6_addr32[3] =
1603 			    xhostid->s6_addr32[3];
1604 		}
1605 
1606 		if (((struct sockaddr *)&iflr->dstaddr)->sa_family) { /* XXX */
1607 			memcpy(&ifra.ifra_dstaddr, &iflr->dstaddr,
1608 			    ((struct sockaddr *)&iflr->dstaddr)->sa_len);
1609 			if (xhostid) {
1610 				ifra.ifra_dstaddr.sin6_addr.s6_addr32[2] =
1611 				    xhostid->s6_addr32[2];
1612 				ifra.ifra_dstaddr.sin6_addr.s6_addr32[3] =
1613 				    xhostid->s6_addr32[3];
1614 			}
1615 		}
1616 
1617 		ifra.ifra_prefixmask.sin6_len = sizeof(struct sockaddr_in6);
1618 		in6_prefixlen2mask(&ifra.ifra_prefixmask.sin6_addr, prefixlen);
1619 
1620 		ifra.ifra_lifetime.ia6t_vltime = ND6_INFINITE_LIFETIME;
1621 		ifra.ifra_lifetime.ia6t_pltime = ND6_INFINITE_LIFETIME;
1622 		ifra.ifra_flags = iflr->flags & ~IFLR_PREFIX;
1623 		return in6_control(so, SIOCAIFADDR_IN6, &ifra, ifp, l);
1624 	    }
1625 	case SIOCGLIFADDR:
1626 	case SIOCDLIFADDR:
1627 	    {
1628 		struct in6_addr mask, candidate, match;
1629 		struct sockaddr_in6 *sin6;
1630 		int cmp;
1631 
1632 		memset(&mask, 0, sizeof(mask));
1633 		if (iflr->flags & IFLR_PREFIX) {
1634 			/* lookup a prefix rather than address. */
1635 			in6_prefixlen2mask(&mask, iflr->prefixlen);
1636 
1637 			sin6 = (struct sockaddr_in6 *)&iflr->addr;
1638 			memcpy(&match, &sin6->sin6_addr, sizeof(match));
1639 			match.s6_addr32[0] &= mask.s6_addr32[0];
1640 			match.s6_addr32[1] &= mask.s6_addr32[1];
1641 			match.s6_addr32[2] &= mask.s6_addr32[2];
1642 			match.s6_addr32[3] &= mask.s6_addr32[3];
1643 
1644 			/* if you set extra bits, that's wrong */
1645 			if (memcmp(&match, &sin6->sin6_addr, sizeof(match)))
1646 				return EINVAL;
1647 
1648 			cmp = 1;
1649 		} else {
1650 			if (cmd == SIOCGLIFADDR) {
1651 				/* on getting an address, take the 1st match */
1652 				cmp = 0;	/* XXX */
1653 			} else {
1654 				/* on deleting an address, do exact match */
1655 				in6_prefixlen2mask(&mask, 128);
1656 				sin6 = (struct sockaddr_in6 *)&iflr->addr;
1657 				memcpy(&match, &sin6->sin6_addr, sizeof(match));
1658 
1659 				cmp = 1;
1660 			}
1661 		}
1662 
1663 		IFADDR_FOREACH(ifa, ifp) {
1664 			if (ifa->ifa_addr->sa_family != AF_INET6)
1665 				continue;
1666 			if (!cmp)
1667 				break;
1668 
1669 			/*
1670 			 * XXX: this is adhoc, but is necessary to allow
1671 			 * a user to specify fe80::/64 (not /10) for a
1672 			 * link-local address.
1673 			 */
1674 			memcpy(&candidate, IFA_IN6(ifa), sizeof(candidate));
1675 			in6_clearscope(&candidate);
1676 			candidate.s6_addr32[0] &= mask.s6_addr32[0];
1677 			candidate.s6_addr32[1] &= mask.s6_addr32[1];
1678 			candidate.s6_addr32[2] &= mask.s6_addr32[2];
1679 			candidate.s6_addr32[3] &= mask.s6_addr32[3];
1680 			if (IN6_ARE_ADDR_EQUAL(&candidate, &match))
1681 				break;
1682 		}
1683 		if (!ifa)
1684 			return EADDRNOTAVAIL;
1685 		ia = ifa2ia6(ifa);
1686 
1687 		if (cmd == SIOCGLIFADDR) {
1688 			int error;
1689 
1690 			/* fill in the if_laddrreq structure */
1691 			memcpy(&iflr->addr, &ia->ia_addr, ia->ia_addr.sin6_len);
1692 			error = sa6_recoverscope(
1693 			    (struct sockaddr_in6 *)&iflr->addr);
1694 			if (error != 0)
1695 				return error;
1696 
1697 			if ((ifp->if_flags & IFF_POINTOPOINT) != 0) {
1698 				memcpy(&iflr->dstaddr, &ia->ia_dstaddr,
1699 				    ia->ia_dstaddr.sin6_len);
1700 				error = sa6_recoverscope(
1701 				    (struct sockaddr_in6 *)&iflr->dstaddr);
1702 				if (error != 0)
1703 					return error;
1704 			} else
1705 				memset(&iflr->dstaddr, 0, sizeof(iflr->dstaddr));
1706 
1707 			iflr->prefixlen =
1708 			    in6_mask2len(&ia->ia_prefixmask.sin6_addr, NULL);
1709 
1710 			iflr->flags = ia->ia6_flags;	/* XXX */
1711 
1712 			return 0;
1713 		} else {
1714 			struct in6_aliasreq ifra;
1715 
1716 			/* fill in6_aliasreq and do ioctl(SIOCDIFADDR_IN6) */
1717 			memset(&ifra, 0, sizeof(ifra));
1718 			memcpy(ifra.ifra_name, iflr->iflr_name,
1719 			    sizeof(ifra.ifra_name));
1720 
1721 			memcpy(&ifra.ifra_addr, &ia->ia_addr,
1722 			    ia->ia_addr.sin6_len);
1723 			if ((ifp->if_flags & IFF_POINTOPOINT) != 0) {
1724 				memcpy(&ifra.ifra_dstaddr, &ia->ia_dstaddr,
1725 				    ia->ia_dstaddr.sin6_len);
1726 			} else {
1727 				memset(&ifra.ifra_dstaddr, 0,
1728 				    sizeof(ifra.ifra_dstaddr));
1729 			}
1730 			memcpy(&ifra.ifra_dstaddr, &ia->ia_prefixmask,
1731 			    ia->ia_prefixmask.sin6_len);
1732 
1733 			ifra.ifra_flags = ia->ia6_flags;
1734 			return in6_control(so, SIOCDIFADDR_IN6, &ifra, ifp, l);
1735 		}
1736 	    }
1737 	}
1738 
1739 	return EOPNOTSUPP;	/* just for safety */
1740 }
1741 
1742 /*
1743  * Initialize an interface's internet6 address
1744  * and routing table entry.
1745  */
1746 static int
1747 in6_ifinit(struct ifnet *ifp, struct in6_ifaddr *ia,
1748 	const struct sockaddr_in6 *sin6, int newhost)
1749 {
1750 	int	error = 0, plen, ifacount = 0;
1751 	int	s = splnet();
1752 	struct ifaddr *ifa;
1753 
1754 	/*
1755 	 * Give the interface a chance to initialize
1756 	 * if this is its first address,
1757 	 * and to validate the address if necessary.
1758 	 */
1759 	IFADDR_FOREACH(ifa, ifp) {
1760 		if (ifa->ifa_addr == NULL)
1761 			continue;	/* just for safety */
1762 		if (ifa->ifa_addr->sa_family != AF_INET6)
1763 			continue;
1764 		ifacount++;
1765 	}
1766 
1767 	ia->ia_addr = *sin6;
1768 
1769 	if (ifacount <= 1 &&
1770 	    (error = if_addr_init(ifp, &ia->ia_ifa, true)) != 0) {
1771 		splx(s);
1772 		return error;
1773 	}
1774 	splx(s);
1775 
1776 	ia->ia_ifa.ifa_metric = ifp->if_metric;
1777 
1778 	/* we could do in(6)_socktrim here, but just omit it at this moment. */
1779 
1780 	/*
1781 	 * Special case:
1782 	 * If the destination address is specified for a point-to-point
1783 	 * interface, install a route to the destination as an interface
1784 	 * direct route.
1785 	 */
1786 	plen = in6_mask2len(&ia->ia_prefixmask.sin6_addr, NULL); /* XXX */
1787 	if (plen == 128 && ia->ia_dstaddr.sin6_family == AF_INET6) {
1788 		if ((error = rtinit(&ia->ia_ifa, RTM_ADD,
1789 				    RTF_UP | RTF_HOST)) != 0)
1790 			return error;
1791 		ia->ia_flags |= IFA_ROUTE;
1792 	}
1793 
1794 	/* Add ownaddr as loopback rtentry, if necessary (ex. on p2p link). */
1795 	if (newhost) {
1796 		/* set the rtrequest function to create llinfo */
1797 		ia->ia_ifa.ifa_rtrequest = nd6_rtrequest;
1798 		in6_ifaddloop(&ia->ia_ifa);
1799 	} else {
1800 		/* Inform the routing socket of new flags/timings */
1801 		nd6_newaddrmsg(&ia->ia_ifa);
1802 	}
1803 
1804 	if (ifp->if_flags & IFF_MULTICAST)
1805 		in6_restoremkludge(ia, ifp);
1806 
1807 	return error;
1808 }
1809 
1810 static struct ifaddr *
1811 bestifa(struct ifaddr *best_ifa, struct ifaddr *ifa)
1812 {
1813 	if (best_ifa == NULL || best_ifa->ifa_preference < ifa->ifa_preference)
1814 		return ifa;
1815 	return best_ifa;
1816 }
1817 
1818 /*
1819  * Find an IPv6 interface link-local address specific to an interface.
1820  */
1821 struct in6_ifaddr *
1822 in6ifa_ifpforlinklocal(const struct ifnet *ifp, const int ignoreflags)
1823 {
1824 	struct ifaddr *best_ifa = NULL, *ifa;
1825 
1826 	IFADDR_FOREACH(ifa, ifp) {
1827 		if (ifa->ifa_addr == NULL)
1828 			continue;	/* just for safety */
1829 		if (ifa->ifa_addr->sa_family != AF_INET6)
1830 			continue;
1831 		if (!IN6_IS_ADDR_LINKLOCAL(IFA_IN6(ifa)))
1832 			continue;
1833 		if ((((struct in6_ifaddr *)ifa)->ia6_flags & ignoreflags) != 0)
1834 			continue;
1835 		best_ifa = bestifa(best_ifa, ifa);
1836 	}
1837 
1838 	return (struct in6_ifaddr *)best_ifa;
1839 }
1840 
1841 
1842 /*
1843  * find the internet address corresponding to a given interface and address.
1844  */
1845 struct in6_ifaddr *
1846 in6ifa_ifpwithaddr(const struct ifnet *ifp, const struct in6_addr *addr)
1847 {
1848 	struct ifaddr *best_ifa = NULL, *ifa;
1849 
1850 	IFADDR_FOREACH(ifa, ifp) {
1851 		if (ifa->ifa_addr == NULL)
1852 			continue;	/* just for safety */
1853 		if (ifa->ifa_addr->sa_family != AF_INET6)
1854 			continue;
1855 		if (!IN6_ARE_ADDR_EQUAL(addr, IFA_IN6(ifa)))
1856 			continue;
1857 		best_ifa = bestifa(best_ifa, ifa);
1858 	}
1859 
1860 	return (struct in6_ifaddr *)best_ifa;
1861 }
1862 
1863 static struct in6_ifaddr *
1864 bestia(struct in6_ifaddr *best_ia, struct in6_ifaddr *ia)
1865 {
1866 	if (best_ia == NULL ||
1867 	    best_ia->ia_ifa.ifa_preference < ia->ia_ifa.ifa_preference)
1868 		return ia;
1869 	return best_ia;
1870 }
1871 
1872 /*
1873  * find the internet address on a given interface corresponding to a neighbor's
1874  * address.
1875  */
1876 struct in6_ifaddr *
1877 in6ifa_ifplocaladdr(const struct ifnet *ifp, const struct in6_addr *addr)
1878 {
1879 	struct ifaddr *ifa;
1880 	struct in6_ifaddr *best_ia = NULL, *ia;
1881 
1882 	IFADDR_FOREACH(ifa, ifp) {
1883 		if (ifa->ifa_addr == NULL)
1884 			continue;	/* just for safety */
1885 		if (ifa->ifa_addr->sa_family != AF_INET6)
1886 			continue;
1887 		ia = (struct in6_ifaddr *)ifa;
1888 		if (!IN6_ARE_MASKED_ADDR_EQUAL(addr,
1889 				&ia->ia_addr.sin6_addr,
1890 				&ia->ia_prefixmask.sin6_addr))
1891 			continue;
1892 		best_ia = bestia(best_ia, ia);
1893 	}
1894 
1895 	return best_ia;
1896 }
1897 
1898 /*
1899  * Convert IP6 address to printable (loggable) representation.
1900  */
1901 static int ip6round = 0;
1902 char *
1903 ip6_sprintf(const struct in6_addr *addr)
1904 {
1905 	static char ip6buf[8][48];
1906 	int i;
1907 	char *bp;
1908 	char *cp;
1909 	const u_int16_t *a = (const u_int16_t *)addr;
1910 	const u_int8_t *d;
1911 	int dcolon = 0;
1912 
1913 	ip6round = (ip6round + 1) & 7;
1914 	cp = ip6buf[ip6round];
1915 
1916 	for (i = 0; i < 8; i++) {
1917 		if (dcolon == 1) {
1918 			if (*a == 0) {
1919 				if (i == 7)
1920 					*cp++ = ':';
1921 				a++;
1922 				continue;
1923 			} else
1924 				dcolon = 2;
1925 		}
1926 		if (*a == 0) {
1927 			if (dcolon == 0 && *(a + 1) == 0) {
1928 				if (i == 0)
1929 					*cp++ = ':';
1930 				*cp++ = ':';
1931 				dcolon = 1;
1932 			} else {
1933 				*cp++ = '0';
1934 				*cp++ = ':';
1935 			}
1936 			a++;
1937 			continue;
1938 		}
1939 		d = (const u_char *)a;
1940 		bp = cp;
1941 		*cp = hexdigits[*d >> 4];
1942 		if (*cp != '0')
1943 			cp++;
1944 		*cp = hexdigits[*d++ & 0xf];
1945 		if (cp != bp || *cp != '0')
1946 			cp++;
1947 		*cp = hexdigits[*d >> 4];
1948 		if (cp != bp || *cp != '0')
1949 			cp++;
1950 		*cp++ = hexdigits[*d & 0xf];
1951 		*cp++ = ':';
1952 		a++;
1953 	}
1954 	*--cp = 0;
1955 	return ip6buf[ip6round];
1956 }
1957 
1958 /*
1959  * Determine if an address is on a local network.
1960  */
1961 int
1962 in6_localaddr(const struct in6_addr *in6)
1963 {
1964 	struct in6_ifaddr *ia;
1965 
1966 	if (IN6_IS_ADDR_LOOPBACK(in6) || IN6_IS_ADDR_LINKLOCAL(in6))
1967 		return 1;
1968 
1969 	for (ia = in6_ifaddr; ia; ia = ia->ia_next)
1970 		if (IN6_ARE_MASKED_ADDR_EQUAL(in6, &ia->ia_addr.sin6_addr,
1971 					      &ia->ia_prefixmask.sin6_addr))
1972 			return 1;
1973 
1974 	return 0;
1975 }
1976 
1977 int
1978 in6_is_addr_deprecated(struct sockaddr_in6 *sa6)
1979 {
1980 	struct in6_ifaddr *ia;
1981 
1982 	for (ia = in6_ifaddr; ia; ia = ia->ia_next) {
1983 		if (IN6_ARE_ADDR_EQUAL(&ia->ia_addr.sin6_addr,
1984 		    &sa6->sin6_addr) &&
1985 #ifdef SCOPEDROUTING
1986 		    ia->ia_addr.sin6_scope_id == sa6->sin6_scope_id &&
1987 #endif
1988 		    (ia->ia6_flags & IN6_IFF_DEPRECATED) != 0)
1989 			return 1; /* true */
1990 
1991 		/* XXX: do we still have to go thru the rest of the list? */
1992 	}
1993 
1994 	return 0;		/* false */
1995 }
1996 
1997 /*
1998  * return length of part which dst and src are equal
1999  * hard coding...
2000  */
2001 int
2002 in6_matchlen(struct in6_addr *src, struct in6_addr *dst)
2003 {
2004 	int match = 0;
2005 	u_char *s = (u_char *)src, *d = (u_char *)dst;
2006 	u_char *lim = s + 16, r;
2007 
2008 	while (s < lim)
2009 		if ((r = (*d++ ^ *s++)) != 0) {
2010 			while (r < 128) {
2011 				match++;
2012 				r <<= 1;
2013 			}
2014 			break;
2015 		} else
2016 			match += NBBY;
2017 	return match;
2018 }
2019 
2020 /* XXX: to be scope conscious */
2021 int
2022 in6_are_prefix_equal(struct in6_addr *p1, struct in6_addr *p2, int len)
2023 {
2024 	int bytelen, bitlen;
2025 
2026 	/* sanity check */
2027 	if (len < 0 || len > 128) {
2028 		log(LOG_ERR, "in6_are_prefix_equal: invalid prefix length(%d)\n",
2029 		    len);
2030 		return 0;
2031 	}
2032 
2033 	bytelen = len / NBBY;
2034 	bitlen = len % NBBY;
2035 
2036 	if (memcmp(&p1->s6_addr, &p2->s6_addr, bytelen))
2037 		return 0;
2038 	if (bitlen != 0 &&
2039 	    p1->s6_addr[bytelen] >> (NBBY - bitlen) !=
2040 	    p2->s6_addr[bytelen] >> (NBBY - bitlen))
2041 		return 0;
2042 
2043 	return 1;
2044 }
2045 
2046 void
2047 in6_prefixlen2mask(struct in6_addr *maskp, int len)
2048 {
2049 	static const u_char maskarray[NBBY] = {0x80, 0xc0, 0xe0, 0xf0, 0xf8, 0xfc, 0xfe, 0xff};
2050 	int bytelen, bitlen, i;
2051 
2052 	/* sanity check */
2053 	if (len < 0 || len > 128) {
2054 		log(LOG_ERR, "in6_prefixlen2mask: invalid prefix length(%d)\n",
2055 		    len);
2056 		return;
2057 	}
2058 
2059 	memset(maskp, 0, sizeof(*maskp));
2060 	bytelen = len / NBBY;
2061 	bitlen = len % NBBY;
2062 	for (i = 0; i < bytelen; i++)
2063 		maskp->s6_addr[i] = 0xff;
2064 	if (bitlen)
2065 		maskp->s6_addr[bytelen] = maskarray[bitlen - 1];
2066 }
2067 
2068 /*
2069  * return the best address out of the same scope. if no address was
2070  * found, return the first valid address from designated IF.
2071  */
2072 struct in6_ifaddr *
2073 in6_ifawithifp(struct ifnet *ifp, struct in6_addr *dst)
2074 {
2075 	int dst_scope =	in6_addrscope(dst), blen = -1, tlen;
2076 	struct ifaddr *ifa;
2077 	struct in6_ifaddr *best_ia = NULL, *ia;
2078 	struct in6_ifaddr *dep[2];	/* last-resort: deprecated */
2079 
2080 	dep[0] = dep[1] = NULL;
2081 
2082 	/*
2083 	 * We first look for addresses in the same scope.
2084 	 * If there is one, return it.
2085 	 * If two or more, return one which matches the dst longest.
2086 	 * If none, return one of global addresses assigned other ifs.
2087 	 */
2088 	IFADDR_FOREACH(ifa, ifp) {
2089 		if (ifa->ifa_addr->sa_family != AF_INET6)
2090 			continue;
2091 		ia = (struct in6_ifaddr *)ifa;
2092 		if (ia->ia6_flags & IN6_IFF_ANYCAST)
2093 			continue; /* XXX: is there any case to allow anycast? */
2094 		if (ia->ia6_flags & IN6_IFF_NOTREADY)
2095 			continue; /* don't use this interface */
2096 		if (ia->ia6_flags & IN6_IFF_DETACHED)
2097 			continue;
2098 		if (ia->ia6_flags & IN6_IFF_DEPRECATED) {
2099 			if (ip6_use_deprecated)
2100 				dep[0] = ia;
2101 			continue;
2102 		}
2103 
2104 		if (dst_scope != in6_addrscope(IFA_IN6(ifa)))
2105 			continue;
2106 		/*
2107 		 * call in6_matchlen() as few as possible
2108 		 */
2109 		if (best_ia == NULL) {
2110 			best_ia = ia;
2111 			continue;
2112 		}
2113 		if (blen == -1)
2114 			blen = in6_matchlen(&best_ia->ia_addr.sin6_addr, dst);
2115 		tlen = in6_matchlen(IFA_IN6(ifa), dst);
2116 		if (tlen > blen) {
2117 			blen = tlen;
2118 			best_ia = ia;
2119 		} else if (tlen == blen)
2120 			best_ia = bestia(best_ia, ia);
2121 	}
2122 	if (best_ia != NULL)
2123 		return best_ia;
2124 
2125 	IFADDR_FOREACH(ifa, ifp) {
2126 		if (ifa->ifa_addr->sa_family != AF_INET6)
2127 			continue;
2128 		ia = (struct in6_ifaddr *)ifa;
2129 		if (ia->ia6_flags & IN6_IFF_ANYCAST)
2130 			continue; /* XXX: is there any case to allow anycast? */
2131 		if (ia->ia6_flags & IN6_IFF_NOTREADY)
2132 			continue; /* don't use this interface */
2133 		if (ia->ia6_flags & IN6_IFF_DETACHED)
2134 			continue;
2135 		if (ia->ia6_flags & IN6_IFF_DEPRECATED) {
2136 			if (ip6_use_deprecated)
2137 				dep[1] = (struct in6_ifaddr *)ifa;
2138 			continue;
2139 		}
2140 
2141 		best_ia = bestia(best_ia, ia);
2142 	}
2143 	if (best_ia != NULL)
2144 		return best_ia;
2145 
2146 	/* use the last-resort values, that are, deprecated addresses */
2147 	if (dep[0])
2148 		return dep[0];
2149 	if (dep[1])
2150 		return dep[1];
2151 
2152 	return NULL;
2153 }
2154 
2155 /*
2156  * perform DAD when interface becomes IFF_UP.
2157  */
2158 void
2159 in6_if_link_up(struct ifnet *ifp)
2160 {
2161 	struct ifaddr *ifa;
2162 	struct in6_ifaddr *ia;
2163 
2164 	/* Ensure it's sane to run DAD */
2165 	if (ifp->if_link_state == LINK_STATE_DOWN)
2166 		return;
2167 	if ((ifp->if_flags & (IFF_UP|IFF_RUNNING)) != (IFF_UP|IFF_RUNNING))
2168 		return;
2169 
2170 	IFADDR_FOREACH(ifa, ifp) {
2171 		if (ifa->ifa_addr->sa_family != AF_INET6)
2172 			continue;
2173 		ia = (struct in6_ifaddr *)ifa;
2174 
2175 		/* If detached then mark as tentative */
2176 		if (ia->ia6_flags & IN6_IFF_DETACHED) {
2177 			ia->ia6_flags &= ~IN6_IFF_DETACHED;
2178 			if (in6if_do_dad(ifp)) {
2179 				ia->ia6_flags |= IN6_IFF_TENTATIVE;
2180 				nd6log((LOG_ERR, "in6_if_up: "
2181 				    "%s marked tentative\n",
2182 				    ip6_sprintf(&ia->ia_addr.sin6_addr)));
2183 			} else if ((ia->ia6_flags & IN6_IFF_TENTATIVE) == 0)
2184 				nd6_newaddrmsg(ifa);
2185 		}
2186 
2187 		if (ia->ia6_flags & IN6_IFF_TENTATIVE) {
2188 			/*
2189 			 * The TENTATIVE flag was likely set by hand
2190 			 * beforehand, implicitly indicating the need for DAD.
2191 			 * We may be able to skip the random delay in this
2192 			 * case, but we impose delays just in case.
2193 			 */
2194 			nd6_dad_start(ifa,
2195 			    cprng_fast32() %
2196 				(MAX_RTR_SOLICITATION_DELAY * hz));
2197 		}
2198 	}
2199 
2200 	/* Restore any detached prefixes */
2201 	pfxlist_onlink_check();
2202 }
2203 
2204 void
2205 in6_if_up(struct ifnet *ifp)
2206 {
2207 
2208 	/*
2209 	 * special cases, like 6to4, are handled in in6_ifattach
2210 	 */
2211 	in6_ifattach(ifp, NULL);
2212 
2213 	/* interface may not support link state, so bring it up also */
2214 	in6_if_link_up(ifp);
2215 }
2216 /*
2217  * Mark all addresses as detached.
2218  */
2219 void
2220 in6_if_link_down(struct ifnet *ifp)
2221 {
2222 	struct ifaddr *ifa;
2223 	struct in6_ifaddr *ia;
2224 
2225 	/* Any prefixes on this interface should be detached as well */
2226 	pfxlist_onlink_check();
2227 
2228 	IFADDR_FOREACH(ifa, ifp) {
2229 		if (ifa->ifa_addr->sa_family != AF_INET6)
2230 			continue;
2231 		ia = (struct in6_ifaddr *)ifa;
2232 
2233 		/* Stop DAD processing */
2234 		nd6_dad_stop(ifa);
2235 
2236 		/*
2237 		 * Mark the address as detached.
2238 		 * This satisfies RFC4862 Section 5.3, but we should apply
2239 		 * this logic to all addresses to be a good citizen and
2240 		 * avoid potential duplicated addresses.
2241 		 * When the interface comes up again, detached addresses
2242 		 * are marked tentative and DAD commences.
2243 		 */
2244 		if (!(ia->ia6_flags & IN6_IFF_DETACHED)) {
2245 			nd6log((LOG_DEBUG, "in6_if_down: "
2246 			    "%s marked detached\n",
2247 			    ip6_sprintf(&ia->ia_addr.sin6_addr)));
2248 			ia->ia6_flags |= IN6_IFF_DETACHED;
2249 			ia->ia6_flags &= ~IN6_IFF_TENTATIVE;
2250 			nd6_newaddrmsg(ifa);
2251 		}
2252 	}
2253 }
2254 
2255 void
2256 in6_if_down(struct ifnet *ifp)
2257 {
2258 
2259 	in6_if_link_down(ifp);
2260 }
2261 
2262 int
2263 in6if_do_dad(struct ifnet *ifp)
2264 {
2265 	if ((ifp->if_flags & IFF_LOOPBACK) != 0)
2266 		return 0;
2267 
2268 	switch (ifp->if_type) {
2269 	case IFT_FAITH:
2270 		/*
2271 		 * These interfaces do not have the IFF_LOOPBACK flag,
2272 		 * but loop packets back.  We do not have to do DAD on such
2273 		 * interfaces.  We should even omit it, because loop-backed
2274 		 * NS would confuse the DAD procedure.
2275 		 */
2276 		return 0;
2277 	default:
2278 		/*
2279 		 * Our DAD routine requires the interface up and running.
2280 		 * However, some interfaces can be up before the RUNNING
2281 		 * status.  Additionaly, users may try to assign addresses
2282 		 * before the interface becomes up (or running).
2283 		 * We simply skip DAD in such a case as a work around.
2284 		 * XXX: we should rather mark "tentative" on such addresses,
2285 		 * and do DAD after the interface becomes ready.
2286 		 */
2287 		if ((ifp->if_flags & (IFF_UP|IFF_RUNNING)) !=
2288 		    (IFF_UP|IFF_RUNNING))
2289 			return 0;
2290 
2291 		return 1;
2292 	}
2293 }
2294 
2295 /*
2296  * Calculate max IPv6 MTU through all the interfaces and store it
2297  * to in6_maxmtu.
2298  */
2299 void
2300 in6_setmaxmtu(void)
2301 {
2302 	unsigned long maxmtu = 0;
2303 	struct ifnet *ifp;
2304 
2305 	TAILQ_FOREACH(ifp, &ifnet, if_list) {
2306 		/* this function can be called during ifnet initialization */
2307 		if (!ifp->if_afdata[AF_INET6])
2308 			continue;
2309 		if ((ifp->if_flags & IFF_LOOPBACK) == 0 &&
2310 		    IN6_LINKMTU(ifp) > maxmtu)
2311 			maxmtu = IN6_LINKMTU(ifp);
2312 	}
2313 	if (maxmtu)	     /* update only when maxmtu is positive */
2314 		in6_maxmtu = maxmtu;
2315 }
2316 
2317 /*
2318  * Provide the length of interface identifiers to be used for the link attached
2319  * to the given interface.  The length should be defined in "IPv6 over
2320  * xxx-link" document.  Note that address architecture might also define
2321  * the length for a particular set of address prefixes, regardless of the
2322  * link type.  As clarified in rfc2462bis, those two definitions should be
2323  * consistent, and those really are as of August 2004.
2324  */
2325 int
2326 in6_if2idlen(struct ifnet *ifp)
2327 {
2328 	switch (ifp->if_type) {
2329 	case IFT_ETHER:		/* RFC2464 */
2330 	case IFT_PROPVIRTUAL:	/* XXX: no RFC. treat it as ether */
2331 	case IFT_L2VLAN:	/* ditto */
2332 	case IFT_IEEE80211:	/* ditto */
2333 	case IFT_FDDI:		/* RFC2467 */
2334 	case IFT_ISO88025:	/* RFC2470 (IPv6 over Token Ring) */
2335 	case IFT_PPP:		/* RFC2472 */
2336 	case IFT_ARCNET:	/* RFC2497 */
2337 	case IFT_FRELAY:	/* RFC2590 */
2338 	case IFT_IEEE1394:	/* RFC3146 */
2339 	case IFT_GIF:		/* draft-ietf-v6ops-mech-v2-07 */
2340 	case IFT_LOOP:		/* XXX: is this really correct? */
2341 		return 64;
2342 	default:
2343 		/*
2344 		 * Unknown link type:
2345 		 * It might be controversial to use the today's common constant
2346 		 * of 64 for these cases unconditionally.  For full compliance,
2347 		 * we should return an error in this case.  On the other hand,
2348 		 * if we simply miss the standard for the link type or a new
2349 		 * standard is defined for a new link type, the IFID length
2350 		 * is very likely to be the common constant.  As a compromise,
2351 		 * we always use the constant, but make an explicit notice
2352 		 * indicating the "unknown" case.
2353 		 */
2354 		printf("in6_if2idlen: unknown link type (%d)\n", ifp->if_type);
2355 		return 64;
2356 	}
2357 }
2358 
2359 void *
2360 in6_domifattach(struct ifnet *ifp)
2361 {
2362 	struct in6_ifextra *ext;
2363 
2364 	ext = malloc(sizeof(*ext), M_IFADDR, M_WAITOK|M_ZERO);
2365 
2366 	ext->in6_ifstat = malloc(sizeof(struct in6_ifstat),
2367 	    M_IFADDR, M_WAITOK|M_ZERO);
2368 
2369 	ext->icmp6_ifstat = malloc(sizeof(struct icmp6_ifstat),
2370 	    M_IFADDR, M_WAITOK|M_ZERO);
2371 
2372 	ext->nd_ifinfo = nd6_ifattach(ifp);
2373 	ext->scope6_id = scope6_ifattach(ifp);
2374 	ext->nprefixes = 0;
2375 	ext->ndefrouters = 0;
2376 	return ext;
2377 }
2378 
2379 void
2380 in6_domifdetach(struct ifnet *ifp, void *aux)
2381 {
2382 	struct in6_ifextra *ext = (struct in6_ifextra *)aux;
2383 
2384 	nd6_ifdetach(ext->nd_ifinfo);
2385 	free(ext->in6_ifstat, M_IFADDR);
2386 	free(ext->icmp6_ifstat, M_IFADDR);
2387 	scope6_ifdetach(ext->scope6_id);
2388 	free(ext, M_IFADDR);
2389 }
2390 
2391 /*
2392  * Convert sockaddr_in6 to sockaddr_in.  Original sockaddr_in6 must be
2393  * v4 mapped addr or v4 compat addr
2394  */
2395 void
2396 in6_sin6_2_sin(struct sockaddr_in *sin, struct sockaddr_in6 *sin6)
2397 {
2398 	memset(sin, 0, sizeof(*sin));
2399 	sin->sin_len = sizeof(struct sockaddr_in);
2400 	sin->sin_family = AF_INET;
2401 	sin->sin_port = sin6->sin6_port;
2402 	sin->sin_addr.s_addr = sin6->sin6_addr.s6_addr32[3];
2403 }
2404 
2405 /* Convert sockaddr_in to sockaddr_in6 in v4 mapped addr format. */
2406 void
2407 in6_sin_2_v4mapsin6(struct sockaddr_in *sin, struct sockaddr_in6 *sin6)
2408 {
2409 	memset(sin6, 0, sizeof(*sin6));
2410 	sin6->sin6_len = sizeof(struct sockaddr_in6);
2411 	sin6->sin6_family = AF_INET6;
2412 	sin6->sin6_port = sin->sin_port;
2413 	sin6->sin6_addr.s6_addr32[0] = 0;
2414 	sin6->sin6_addr.s6_addr32[1] = 0;
2415 	sin6->sin6_addr.s6_addr32[2] = IPV6_ADDR_INT32_SMP;
2416 	sin6->sin6_addr.s6_addr32[3] = sin->sin_addr.s_addr;
2417 }
2418 
2419 /* Convert sockaddr_in6 into sockaddr_in. */
2420 void
2421 in6_sin6_2_sin_in_sock(struct sockaddr *nam)
2422 {
2423 	struct sockaddr_in *sin_p;
2424 	struct sockaddr_in6 sin6;
2425 
2426 	/*
2427 	 * Save original sockaddr_in6 addr and convert it
2428 	 * to sockaddr_in.
2429 	 */
2430 	sin6 = *(struct sockaddr_in6 *)nam;
2431 	sin_p = (struct sockaddr_in *)nam;
2432 	in6_sin6_2_sin(sin_p, &sin6);
2433 }
2434 
2435 /* Convert sockaddr_in into sockaddr_in6 in v4 mapped addr format. */
2436 void
2437 in6_sin_2_v4mapsin6_in_sock(struct sockaddr **nam)
2438 {
2439 	struct sockaddr_in *sin_p;
2440 	struct sockaddr_in6 *sin6_p;
2441 
2442 	sin6_p = malloc(sizeof(*sin6_p), M_SONAME, M_WAITOK);
2443 	sin_p = (struct sockaddr_in *)*nam;
2444 	in6_sin_2_v4mapsin6(sin_p, sin6_p);
2445 	free(*nam, M_SONAME);
2446 	*nam = (struct sockaddr *)sin6_p;
2447 }
2448