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