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