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