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