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