1/*
2 * Copyright (c) 2003-2007 Apple Inc. All rights reserved.
3 *
4 * @APPLE_OSREFERENCE_LICENSE_HEADER_START@
5 *
6 * This file contains Original Code and/or Modifications of Original Code
7 * as defined in and that are subject to the Apple Public Source License
8 * Version 2.0 (the 'License'). You may not use this file except in
9 * compliance with the License. The rights granted to you under the License
10 * may not be used to create, or enable the creation or redistribution of,
11 * unlawful or unlicensed copies of an Apple operating system, or to
12 * circumvent, violate, or enable the circumvention or violation of, any
13 * terms of an Apple operating system software license agreement.
14 *
15 * Please obtain a copy of the License at
16 * http://www.opensource.apple.com/apsl/ and read it before using this file.
17 *
18 * The Original Code and all software distributed under the License are
19 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
20 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
21 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
22 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
23 * Please see the License for the specific language governing rights and
24 * limitations under the License.
25 *
26 * @APPLE_OSREFERENCE_LICENSE_HEADER_END@
27 */
28
29/*	$FreeBSD: src/sys/netinet6/in6.c,v 1.7.2.7 2001/08/06 20:26:22 ume Exp $	*/
30/*	$KAME: in6.c,v 1.187 2001/05/24 07:43:59 itojun Exp $	*/
31
32/*
33 * Copyright (C) 1995, 1996, 1997, and 1998 WIDE Project.
34 * 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 * 3. Neither the name of the project 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 PROJECT 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 PROJECT 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
61/*
62 * Copyright (c) 1982, 1986, 1991, 1993
63 *	The Regents of the University of California.  All rights reserved.
64 *
65 * Redistribution and use in source and binary forms, with or without
66 * modification, are permitted provided that the following conditions
67 * are met:
68 * 1. Redistributions of source code must retain the above copyright
69 *    notice, this list of conditions and the following disclaimer.
70 * 2. Redistributions in binary form must reproduce the above copyright
71 *    notice, this list of conditions and the following disclaimer in the
72 *    documentation and/or other materials provided with the distribution.
73 * 3. All advertising materials mentioning features or use of this software
74 *    must display the following acknowledgement:
75 *	This product includes software developed by the University of
76 *	California, Berkeley and its contributors.
77 * 4. Neither the name of the University nor the names of its contributors
78 *    may be used to endorse or promote products derived from this software
79 *    without specific prior written permission.
80 *
81 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
82 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
83 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
84 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
85 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
86 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
87 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
88 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
89 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
90 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
91 * SUCH DAMAGE.
92 *
93 *	@(#)in.c	8.2 (Berkeley) 11/15/93
94 */
95
96
97#include <sys/param.h>
98#include <sys/ioctl.h>
99#include <sys/errno.h>
100#include <sys/malloc.h>
101#include <sys/socket.h>
102#include <sys/socketvar.h>
103#include <sys/sockio.h>
104#include <sys/systm.h>
105#include <sys/time.h>
106#include <sys/kernel.h>
107#include <sys/syslog.h>
108#include <sys/kern_event.h>
109#include <kern/locks.h>
110
111#include <net/if.h>
112#include <net/if_types.h>
113#include <net/if_var.h>
114#include <net/route.h>
115#include <net/if_dl.h>
116#include <net/kpi_protocol.h>
117
118#include <netinet/in.h>
119#include <netinet/in_var.h>
120#include <netinet/if_ether.h>
121#ifndef SCOPEDROUTING
122#include <netinet/in_systm.h>
123#include <netinet/ip.h>
124#include <netinet/in_pcb.h>
125#endif
126
127#include <netinet6/nd6.h>
128#include <netinet/ip6.h>
129#include <netinet6/ip6_var.h>
130#include <netinet6/mld6_var.h>
131#include <netinet6/ip6_mroute.h>
132#include <netinet6/in6_ifattach.h>
133#include <netinet6/scope6_var.h>
134#ifndef SCOPEDROUTING
135#include <netinet6/in6_pcb.h>
136#endif
137
138#include <net/net_osdep.h>
139
140#ifndef __APPLE__
141MALLOC_DEFINE(M_IPMADDR, "in6_multi", "internet multicast address");
142#endif
143 /*
144 * Definitions of some costant IP6 addresses.
145 */
146const struct in6_addr in6addr_any = IN6ADDR_ANY_INIT;
147const struct in6_addr in6addr_loopback = IN6ADDR_LOOPBACK_INIT;
148const struct in6_addr in6addr_nodelocal_allnodes =
149	IN6ADDR_NODELOCAL_ALLNODES_INIT;
150const struct in6_addr in6addr_linklocal_allnodes =
151	IN6ADDR_LINKLOCAL_ALLNODES_INIT;
152const struct in6_addr in6addr_linklocal_allrouters =
153	IN6ADDR_LINKLOCAL_ALLROUTERS_INIT;
154
155const struct in6_addr in6mask0 = IN6MASK0;
156const struct in6_addr in6mask32 = IN6MASK32;
157const struct in6_addr in6mask64 = IN6MASK64;
158const struct in6_addr in6mask96 = IN6MASK96;
159const struct in6_addr in6mask128 = IN6MASK128;
160
161const struct sockaddr_in6 sa6_any = {sizeof(sa6_any), AF_INET6,
162				     0, 0, IN6ADDR_ANY_INIT, 0};
163
164static int in6_lifaddr_ioctl(struct socket *, u_long, caddr_t,
165	struct ifnet *, struct proc *);
166static int in6_ifinit(struct ifnet *, struct in6_ifaddr *,
167			   struct sockaddr_in6 *, int);
168static void in6_unlink_ifa(struct in6_ifaddr *, struct ifnet *, int);
169
170struct in6_multihead in6_multihead;	/* XXX BSS initialization */
171extern lck_mtx_t *nd6_mutex;
172extern int in6_init2done;
173
174/*
175 * Subroutine for in6_ifaddloop() and in6_ifremloop().
176 * This routine does actual work.
177 */
178static void
179in6_ifloop_request(int cmd, struct ifaddr *ifa)
180{
181	struct sockaddr_in6 all1_sa;
182	struct rtentry *nrt = NULL;
183	int e;
184
185	bzero(&all1_sa, sizeof(all1_sa));
186	all1_sa.sin6_family = AF_INET6;
187	all1_sa.sin6_len = sizeof(struct sockaddr_in6);
188	all1_sa.sin6_addr = in6mask128;
189
190	/*
191	 * We specify the address itself as the gateway, and set the
192	 * RTF_LLINFO flag, so that the corresponding host route would have
193	 * the flag, and thus applications that assume traditional behavior
194	 * would be happy.  Note that we assume the caller of the function
195	 * (probably implicitly) set nd6_rtrequest() to ifa->ifa_rtrequest,
196	 * which changes the outgoing interface to the loopback interface.
197	 */
198	e = rtrequest_locked(cmd, ifa->ifa_addr, ifa->ifa_addr,
199		      (struct sockaddr *)&all1_sa,
200		      RTF_UP|RTF_HOST|RTF_LLINFO, &nrt);
201	if (e != 0) {
202		log(LOG_ERR, "in6_ifloop_request: "
203		    "%s operation failed for %s (errno=%d)\n",
204		    cmd == RTM_ADD ? "ADD" : "DELETE",
205		    ip6_sprintf(&((struct in6_ifaddr *)ifa)->ia_addr.sin6_addr),
206		    e);
207	}
208
209	/*
210	 * Make sure rt_ifa be equal to IFA, the second argument of the
211	 * function.
212	 * We need this because when we refer to rt_ifa->ia6_flags in
213	 * ip6_input, we assume that the rt_ifa points to the address instead
214	 * of the loopback address.
215	 */
216	if (cmd == RTM_ADD && nrt && ifa != nrt->rt_ifa) {
217		rtsetifa(nrt, ifa);
218	}
219
220	/*
221	 * Report the addition/removal of the address to the routing socket.
222	 * XXX: since we called rtinit for a p2p interface with a destination,
223	 *      we end up reporting twice in such a case.  Should we rather
224	 *      omit the second report?
225	 */
226	if (nrt) {
227		rt_newaddrmsg(cmd, ifa, e, nrt);
228		if (cmd == RTM_DELETE) {
229			rtfree_locked(nrt);
230		} else {
231			/* the cmd must be RTM_ADD here */
232			rtunref(nrt);
233		}
234	}
235}
236
237/*
238 * Add ownaddr as loopback rtentry.  We previously add the route only if
239 * necessary (ex. on a p2p link).  However, since we now manage addresses
240 * separately from prefixes, we should always add the route.  We can't
241 * rely on the cloning mechanism from the corresponding interface route
242 * any more.
243 */
244static void
245in6_ifaddloop(struct ifaddr *ifa)
246{
247	struct rtentry *rt;
248
249	lck_mtx_lock(rt_mtx);
250	/* If there is no loopback entry, allocate one. */
251	rt = rtalloc1_locked(ifa->ifa_addr, 0, 0UL);
252	if (rt == NULL || (rt->rt_flags & RTF_HOST) == 0 ||
253	    (rt->rt_ifp->if_flags & IFF_LOOPBACK) == 0)
254		in6_ifloop_request(RTM_ADD, ifa);
255	if (rt)
256		rtunref(rt);
257	lck_mtx_unlock(rt_mtx);
258}
259
260/*
261 * Remove loopback rtentry of ownaddr generated by in6_ifaddloop(),
262 * if it exists.
263 */
264static void
265in6_ifremloop(struct ifaddr *ifa, int locked)
266{
267	struct in6_ifaddr *ia;
268	struct rtentry *rt;
269	int ia_count = 0;
270
271	/*
272	 * Some of BSD variants do not remove cloned routes
273	 * from an interface direct route, when removing the direct route
274	 * (see comments in net/net_osdep.h).  Even for variants that do remove
275	 * cloned routes, they could fail to remove the cloned routes when
276	 * we handle multple addresses that share a common prefix.
277	 * So, we should remove the route corresponding to the deleted address
278	 * regardless of the result of in6_is_ifloop_auto().
279	 */
280
281	/*
282	 * Delete the entry only if exact one ifa exists.  More than one ifa
283	 * can exist if we assign a same single address to multiple
284	 * (probably p2p) interfaces.
285	 * XXX: we should avoid such a configuration in IPv6...
286	 */
287	if (!locked)
288		lck_mtx_lock(nd6_mutex);
289	for (ia = in6_ifaddrs; ia; ia = ia->ia_next) {
290		if (IN6_ARE_ADDR_EQUAL(IFA_IN6(ifa), &ia->ia_addr.sin6_addr)) {
291			ia_count++;
292			if (ia_count > 1)
293				break;
294		}
295	}
296	if (!locked)
297		lck_mtx_unlock(nd6_mutex);
298
299	if (ia_count == 1) {
300		/*
301		 * Before deleting, check if a corresponding loopbacked host
302		 * route surely exists.  With this check, we can avoid to
303		 * delete an interface direct route whose destination is same
304		 * as the address being removed.  This can happen when remofing
305		 * a subnet-router anycast address on an interface attahced
306		 * to a shared medium.
307		 */
308		lck_mtx_lock(rt_mtx);
309		rt = rtalloc1_locked(ifa->ifa_addr, 0, 0UL);
310		if (rt != NULL && (rt->rt_flags & RTF_HOST) != 0 &&
311		    (rt->rt_ifp->if_flags & IFF_LOOPBACK) != 0) {
312			rtunref(rt);
313			in6_ifloop_request(RTM_DELETE, ifa);
314		}
315		lck_mtx_unlock(rt_mtx);
316	}
317}
318
319int
320in6_ifindex2scopeid(idx)
321	int idx;
322{
323	struct ifnet *ifp;
324	struct ifaddr *ifa;
325	struct sockaddr_in6 *sin6;
326
327	if (idx < 0 || if_index < idx)
328		return -1;
329
330	ifnet_head_lock_shared();
331	ifp = ifindex2ifnet[idx];
332	ifnet_head_done();
333
334	ifnet_lock_shared(ifp);
335	TAILQ_FOREACH(ifa, &ifp->if_addrlist, ifa_list)
336	{
337		if (ifa->ifa_addr->sa_family != AF_INET6)
338			continue;
339		sin6 = (struct sockaddr_in6 *)ifa->ifa_addr;
340		if (IN6_IS_ADDR_SITELOCAL(&sin6->sin6_addr)) {
341			ifnet_lock_done(ifp);
342			return sin6->sin6_scope_id & 0xffff;
343		}
344	}
345	ifnet_lock_done(ifp);
346
347	return -1;
348}
349
350int
351in6_mask2len(mask, lim0)
352	struct in6_addr *mask;
353	u_char *lim0;
354{
355	int x = 0, y;
356	u_char *lim = lim0, *p;
357
358	if (lim0 == NULL ||
359	    lim0 - (u_char *)mask > sizeof(*mask)) /* ignore the scope_id part */
360		lim = (u_char *)mask + sizeof(*mask);
361	for (p = (u_char *)mask; p < lim; x++, p++) {
362		if (*p != 0xff)
363			break;
364	}
365	y = 0;
366	if (p < lim) {
367		for (y = 0; y < 8; y++) {
368			if ((*p & (0x80 >> y)) == 0)
369				break;
370		}
371	}
372
373	/*
374	 * when the limit pointer is given, do a stricter check on the
375	 * remaining bits.
376	 */
377	if (p < lim) {
378		if (y != 0 && (*p & (0x00ff >> y)) != 0)
379			return(-1);
380		for (p = p + 1; p < lim; p++)
381			if (*p != 0)
382				return(-1);
383	}
384
385	return x * 8 + y;
386}
387
388void
389in6_len2mask(mask, len)
390	struct in6_addr *mask;
391	int len;
392{
393	int i;
394
395	bzero(mask, sizeof(*mask));
396	for (i = 0; i < len / 8; i++)
397		mask->s6_addr8[i] = 0xff;
398	if (len % 8)
399		mask->s6_addr8[i] = (0xff00 >> (len % 8)) & 0xff;
400}
401
402#define ifa2ia6(ifa)	((struct in6_ifaddr *)(ifa))
403#define ia62ifa(ia6)	(&((ia6)->ia_ifa))
404
405int
406in6_control(so, cmd, data, ifp, p)
407	struct	socket *so;
408	u_long cmd;
409	caddr_t	data;
410	struct ifnet *ifp;
411	struct proc *p;
412{
413	struct	in6_ifreq *ifr = (struct in6_ifreq *)data;
414	struct	in6_ifaddr *ia = NULL;
415	struct	in6_aliasreq *ifra = (struct in6_aliasreq *)data;
416	int privileged, error = 0;
417	int index;
418	struct timeval timenow;
419
420	getmicrotime(&timenow);
421
422	privileged = 0;
423#ifdef __APPLE__
424	if (p == NULL || !proc_suser(p))
425#else
426	if (p == NULL || !suser(p))
427#endif
428		privileged++;
429
430	switch (cmd) {
431	case SIOCGETSGCNT_IN6:
432	case SIOCGETMIFCNT_IN6:
433		return (mrt6_ioctl(cmd, data));
434	}
435
436	if (ifp == NULL)
437		return(EOPNOTSUPP);
438
439	switch (cmd) {
440	case SIOCAUTOCONF_START:
441	case SIOCAUTOCONF_STOP:
442	case SIOCLL_START:
443	case SIOCLL_STOP:
444	case SIOCPROTOATTACH_IN6:
445	case SIOCPROTODETACH_IN6:
446                if (!privileged)
447                        return(EPERM);
448		break;
449	case SIOCSNDFLUSH_IN6:
450	case SIOCSPFXFLUSH_IN6:
451	case SIOCSRTRFLUSH_IN6:
452	case SIOCSDEFIFACE_IN6:
453	case SIOCSIFINFO_FLAGS:
454		if (!privileged)
455			return(EPERM);
456		/* fall through */
457	case OSIOCGIFINFO_IN6:
458	case SIOCGIFINFO_IN6:
459	case SIOCGDRLST_IN6:
460	case SIOCGPRLST_IN6:
461	case SIOCGNBRINFO_IN6:
462	case SIOCGDEFIFACE_IN6:
463		return(nd6_ioctl(cmd, data, ifp));
464	}
465
466	switch (cmd) {
467	case SIOCSIFPREFIX_IN6:
468	case SIOCDIFPREFIX_IN6:
469	case SIOCAIFPREFIX_IN6:
470	case SIOCCIFPREFIX_IN6:
471	case SIOCSGIFPREFIX_IN6:
472	case SIOCGIFPREFIX_IN6:
473		log(LOG_NOTICE,
474		    "prefix ioctls are now invalidated. "
475		    "please use ifconfig.\n");
476		return(EOPNOTSUPP);
477	}
478
479	switch (cmd) {
480	case SIOCSSCOPE6:
481		if (!privileged)
482			return(EPERM);
483		return(scope6_set(ifp, ifr->ifr_ifru.ifru_scope_id));
484		break;
485	case SIOCGSCOPE6:
486		return(scope6_get(ifp, ifr->ifr_ifru.ifru_scope_id));
487		break;
488	case SIOCGSCOPE6DEF:
489		return(scope6_get_default(ifr->ifr_ifru.ifru_scope_id));
490		break;
491	}
492
493	switch (cmd) {
494	case SIOCALIFADDR:
495	case SIOCDLIFADDR:
496		if (!privileged)
497			return(EPERM);
498		/* fall through */
499	case SIOCGLIFADDR:
500		return in6_lifaddr_ioctl(so, cmd, data, ifp, p);
501	}
502
503#ifdef __APPLE__
504
505	switch (cmd) {
506
507	case SIOCAUTOCONF_START:
508		ifnet_lock_exclusive(ifp);
509		ifp->if_eflags |= IFEF_ACCEPT_RTADVD;
510		ifnet_lock_done(ifp);
511		return (0);
512
513	case SIOCAUTOCONF_STOP:
514		{
515			struct in6_ifaddr *nia = NULL;
516
517			ifnet_lock_exclusive(ifp);
518			ifp->if_eflags &= ~IFEF_ACCEPT_RTADVD;
519			ifnet_lock_done(ifp);
520
521			/* nuke prefix list.  this may try to remove some ifaddrs as well */
522			in6_purgeprefix(ifp);
523
524			/* removed autoconfigured address from interface */
525			lck_mtx_lock(nd6_mutex);
526			for (ia = in6_ifaddrs; ia != NULL; ia = nia) {
527				nia = ia->ia_next;
528				if (ia->ia_ifa.ifa_ifp != ifp)
529					continue;
530				if (ia->ia6_flags & IN6_IFF_AUTOCONF)
531					in6_purgeaddr(&ia->ia_ifa, 1);
532			}
533			lck_mtx_unlock(nd6_mutex);
534			return (0);
535		}
536
537
538	case SIOCLL_START:
539
540		/* NOTE: All the interface specific DLIL attachements should be done here
541		 * 	They are currently done in in6_ifattach() for the interfaces that need it
542		 */
543
544		if (ifp->if_type == IFT_PPP && ifra->ifra_addr.sin6_family == AF_INET6 &&
545		     ifra->ifra_dstaddr.sin6_family == AF_INET6)
546			in6_if_up(ifp, ifra); /* PPP may provide LinkLocal addresses */
547		else
548			in6_if_up(ifp, 0);
549
550		return(0);
551
552	case SIOCLL_STOP:
553		{
554			struct in6_ifaddr *nia = NULL;
555
556			/* removed link local addresses from interface */
557
558			lck_mtx_lock(nd6_mutex);
559			for (ia = in6_ifaddrs; ia != NULL; ia = nia) {
560				nia = ia->ia_next;
561				if (ia->ia_ifa.ifa_ifp != ifp)
562					continue;
563				if (IN6_IS_ADDR_LINKLOCAL(&ia->ia_addr.sin6_addr))
564					in6_purgeaddr(&ia->ia_ifa, 1);
565			}
566			lck_mtx_unlock(nd6_mutex);
567			return (0);
568		}
569
570
571	case SIOCPROTOATTACH_IN6:
572
573		switch (ifp->if_type) {
574#if IFT_BRIDGE	/*OpenBSD 2.8*/
575	/* some of the interfaces are inherently not IPv6 capable */
576			case IFT_BRIDGE:
577				return;
578#endif
579			default:
580
581				if ((error = proto_plumb(PF_INET6, ifp)))
582					printf("SIOCPROTOATTACH_IN6: %s error=%d\n",
583						if_name(ifp), error);
584				break;
585
586		}
587		return (error);
588
589
590	case SIOCPROTODETACH_IN6:
591
592		in6_purgeif(ifp);	/* Cleanup interface routes and addresses */
593
594		if ((error = proto_unplumb(PF_INET6, ifp)))
595			 printf("SIOCPROTODETACH_IN6: %s error=%d\n",
596			 	if_name(ifp), error);
597		return(error);
598
599	}
600#endif
601	/*
602	 * Find address for this interface, if it exists.
603	 */
604	if (ifra->ifra_addr.sin6_family == AF_INET6) { /* XXX */
605		struct sockaddr_in6 *sa6 =
606			(struct sockaddr_in6 *)&ifra->ifra_addr;
607
608		if (IN6_IS_ADDR_LINKLOCAL(&sa6->sin6_addr)) {
609			if (sa6->sin6_addr.s6_addr16[1] == 0) {
610				/* link ID is not embedded by the user */
611				sa6->sin6_addr.s6_addr16[1] =
612					htons(ifp->if_index);
613			} else if (sa6->sin6_addr.s6_addr16[1] !=
614				    htons(ifp->if_index)) {
615				return(EINVAL);	/* link ID contradicts */
616			}
617			if (sa6->sin6_scope_id) {
618				if (sa6->sin6_scope_id !=
619				    (u_int32_t)ifp->if_index)
620					return(EINVAL);
621				sa6->sin6_scope_id = 0; /* XXX: good way? */
622			}
623		}
624		ia = in6ifa_ifpwithaddr(ifp, &ifra->ifra_addr.sin6_addr);
625	}
626
627	switch (cmd) {
628	case SIOCSIFADDR_IN6:
629	case SIOCSIFDSTADDR_IN6:
630	case SIOCSIFNETMASK_IN6:
631		/*
632		 * Since IPv6 allows a node to assign multiple addresses
633		 * on a single interface, SIOCSIFxxx ioctls are not suitable
634		 * and should be unused.
635		 */
636		/* we decided to obsolete this command (20000704) */
637		error = EINVAL;
638		goto ioctl_cleanup;
639
640	case SIOCDIFADDR_IN6:
641		/*
642		 * for IPv4, we look for existing in_ifaddr here to allow
643		 * "ifconfig if0 delete" to remove first IPv4 address on the
644		 * interface.  For IPv6, as the spec allow multiple interface
645		 * address from the day one, we consider "remove the first one"
646		 * semantics to be not preferable.
647		 */
648		if (ia == NULL) {
649			error = EADDRNOTAVAIL;
650			goto ioctl_cleanup;
651		}
652
653		/* FALLTHROUGH */
654	case SIOCAIFADDR_IN6:
655		/*
656		 * We always require users to specify a valid IPv6 address for
657		 * the corresponding operation.
658		 */
659		if (ifra->ifra_addr.sin6_family != AF_INET6 ||
660		    ifra->ifra_addr.sin6_len != sizeof(struct sockaddr_in6)) {
661			error = EAFNOSUPPORT;
662			goto ioctl_cleanup;
663		}
664		if (!privileged) {
665			error = EPERM;
666			goto ioctl_cleanup;
667		}
668
669		break;
670
671	case SIOCGIFADDR_IN6:
672		/* This interface is basically deprecated. use SIOCGIFCONF. */
673		/* fall through */
674	case SIOCGIFAFLAG_IN6:
675	case SIOCGIFNETMASK_IN6:
676	case SIOCGIFDSTADDR_IN6:
677	case SIOCGIFALIFETIME_IN6:
678		/* must think again about its semantics */
679		if (ia == NULL) {
680			error = EADDRNOTAVAIL;
681			goto ioctl_cleanup;
682		}
683		break;
684	case SIOCSIFALIFETIME_IN6:
685	    {
686		struct in6_addrlifetime *lt;
687
688		if (!privileged) {
689			error = EPERM;
690			goto ioctl_cleanup;
691		}
692		if (ia == NULL) {
693			error = EADDRNOTAVAIL;
694			goto ioctl_cleanup;
695		}
696		/* sanity for overflow - beware unsigned */
697		lt = &ifr->ifr_ifru.ifru_lifetime;
698		if (lt->ia6t_vltime != ND6_INFINITE_LIFETIME
699		 && lt->ia6t_vltime + timenow.tv_sec < timenow.tv_sec) {
700			error = EINVAL;
701			goto ioctl_cleanup;
702		}
703		if (lt->ia6t_pltime != ND6_INFINITE_LIFETIME
704		 && lt->ia6t_pltime + timenow.tv_sec < timenow.tv_sec) {
705			error = EINVAL;
706			goto ioctl_cleanup;
707		}
708		break;
709	    }
710	}
711
712	switch (cmd) {
713
714	case SIOCGIFADDR_IN6:
715		ifr->ifr_addr = ia->ia_addr;
716		break;
717
718	case SIOCGIFDSTADDR_IN6:
719		if ((ifp->if_flags & IFF_POINTOPOINT) == 0) {
720			error = EINVAL;
721			goto ioctl_cleanup;
722		}
723		/*
724		 * XXX: should we check if ifa_dstaddr is NULL and return
725		 * an error?
726		 */
727		ifr->ifr_dstaddr = ia->ia_dstaddr;
728		break;
729
730	case SIOCGIFNETMASK_IN6:
731		ifr->ifr_addr = ia->ia_prefixmask;
732		break;
733
734	case SIOCGIFAFLAG_IN6:
735		ifr->ifr_ifru.ifru_flags6 = ia->ia6_flags;
736		break;
737
738	case SIOCGIFSTAT_IN6:
739		if (ifp == NULL) {
740			error = EINVAL;
741			goto ioctl_cleanup;
742		}
743		index = ifp->if_index;
744		if (in6_ifstat == NULL || index >= in6_ifstatmax
745		 || in6_ifstat[index] == NULL) {
746			/* return EAFNOSUPPORT? */
747			bzero(&ifr->ifr_ifru.ifru_stat,
748				sizeof(ifr->ifr_ifru.ifru_stat));
749		} else
750			ifr->ifr_ifru.ifru_stat = *in6_ifstat[index];
751		break;
752
753	case SIOCGIFSTAT_ICMP6:
754		if (ifp == NULL) {
755			error = EINVAL;
756			goto ioctl_cleanup;
757		}
758		index = ifp->if_index;
759		if (icmp6_ifstat == NULL || index >= icmp6_ifstatmax ||
760		    icmp6_ifstat[index] == NULL) {
761			/* return EAFNOSUPPORT? */
762			bzero(&ifr->ifr_ifru.ifru_stat,
763				sizeof(ifr->ifr_ifru.ifru_icmp6stat));
764		} else
765			ifr->ifr_ifru.ifru_icmp6stat =
766				*icmp6_ifstat[index];
767		break;
768
769	case SIOCGIFALIFETIME_IN6:
770		ifr->ifr_ifru.ifru_lifetime = ia->ia6_lifetime;
771		break;
772
773	case SIOCSIFALIFETIME_IN6:
774		ia->ia6_lifetime = ifr->ifr_ifru.ifru_lifetime;
775		/* for sanity */
776		if (ia->ia6_lifetime.ia6t_vltime != ND6_INFINITE_LIFETIME) {
777			ia->ia6_lifetime.ia6t_expire =
778				timenow.tv_sec + ia->ia6_lifetime.ia6t_vltime;
779		} else
780			ia->ia6_lifetime.ia6t_expire = 0;
781		if (ia->ia6_lifetime.ia6t_pltime != ND6_INFINITE_LIFETIME) {
782			ia->ia6_lifetime.ia6t_preferred =
783				timenow.tv_sec + ia->ia6_lifetime.ia6t_pltime;
784		} else
785			ia->ia6_lifetime.ia6t_preferred = 0;
786		break;
787
788	case SIOCAIFADDR_IN6:
789	{
790		int i;
791		struct nd_prefix pr0, *pr;
792
793		/* Attempt to attache the protocol, in case it isn't attached */
794		error = proto_plumb(PF_INET6, ifp);
795		if (error) {
796			if (error != EEXIST) {
797				printf("SIOCAIFADDR_IN6: %s can't plumb protocol error=%d\n",
798					if_name(ifp), error);
799				goto ioctl_cleanup;
800			}
801
802			/* Ignore, EEXIST */
803			error = 0;
804		}
805		else {
806			/* PF_INET6 wasn't previously attached */
807			in6_if_up(ifp, NULL);
808		}
809
810		/*
811		 * first, make or update the interface address structure,
812		 * and link it to the list.
813		 */
814		if ((error = in6_update_ifa(ifp, ifra, ia)) != 0)
815			goto ioctl_cleanup;
816
817		/*
818		 * then, make the prefix on-link on the interface.
819		 * XXX: we'd rather create the prefix before the address, but
820		 * we need at least one address to install the corresponding
821		 * interface route, so we configure the address first.
822		 */
823
824		/*
825		 * convert mask to prefix length (prefixmask has already
826		 * been validated in in6_update_ifa().
827		 */
828		bzero(&pr0, sizeof(pr0));
829		pr0.ndpr_ifp = ifp;
830		pr0.ndpr_plen = in6_mask2len(&ifra->ifra_prefixmask.sin6_addr,
831					     NULL);
832		if (pr0.ndpr_plen == 128)
833			break;	/* we don't need to install a host route. */
834		pr0.ndpr_prefix = ifra->ifra_addr;
835		pr0.ndpr_mask = ifra->ifra_prefixmask.sin6_addr;
836		/* apply the mask for safety. */
837		for (i = 0; i < 4; i++) {
838			pr0.ndpr_prefix.sin6_addr.s6_addr32[i] &=
839				ifra->ifra_prefixmask.sin6_addr.s6_addr32[i];
840		}
841		/*
842		 * XXX: since we don't have an API to set prefix (not address)
843		 * lifetimes, we just use the same lifetimes as addresses.
844		 * The (temporarily) installed lifetimes can be overridden by
845		 * later advertised RAs (when accept_rtadv is non 0), which is
846		 * an intended behavior.
847		 */
848		pr0.ndpr_raf_onlink = 1; /* should be configurable? */
849		pr0.ndpr_raf_auto =
850			((ifra->ifra_flags & IN6_IFF_AUTOCONF) != 0);
851		pr0.ndpr_vltime = ifra->ifra_lifetime.ia6t_vltime;
852		pr0.ndpr_pltime = ifra->ifra_lifetime.ia6t_pltime;
853
854		/* add the prefix if there's one. */
855		if ((pr = nd6_prefix_lookup(&pr0)) == NULL) {
856			/*
857			 * nd6_prelist_add will install the corresponding
858			 * interface route.
859			 */
860			if ((error = nd6_prelist_add(&pr0, NULL, &pr)) != 0)
861				goto ioctl_cleanup;
862			if (pr == NULL) {
863				log(LOG_ERR, "nd6_prelist_add succedded but "
864				    "no prefix\n");
865				error = EINVAL;
866				goto ioctl_cleanup;
867			}
868		}
869		if ((ia = in6ifa_ifpwithaddr(ifp, &ifra->ifra_addr.sin6_addr))
870		    == NULL) {
871		    	/* XXX: this should not happen! */
872			log(LOG_ERR, "in6_control: addition succeeded, but"
873			    " no ifaddr\n");
874		} else {
875			if ((ia->ia6_flags & IN6_IFF_AUTOCONF) != 0 &&
876			    ia->ia6_ndpr == NULL) { /* new autoconfed addr */
877				lck_mtx_lock(nd6_mutex);
878				pr->ndpr_refcnt++;
879				lck_mtx_unlock(nd6_mutex);
880				ia->ia6_ndpr = pr;
881
882				/*
883				 * If this is the first autoconf address from
884				 * the prefix, create a temporary address
885				 * as well (when specified).
886				 */
887				if (ip6_use_tempaddr &&
888				    pr->ndpr_refcnt == 1) {
889					int e;
890					if ((e = in6_tmpifadd(ia, 1)) != 0) {
891						log(LOG_NOTICE, "in6_control: "
892						    "failed to create a "
893						    "temporary address, "
894						    "errno=%d\n",
895						    e);
896					}
897				}
898			}
899
900			/*
901			 * this might affect the status of autoconfigured
902			 * addresses, that is, this address might make
903			 * other addresses detached.
904			 */
905			pfxlist_onlink_check(0);
906		}
907
908		/* Drop use count held above during lookup/add */
909		ndpr_rele(pr, FALSE);
910
911		break;
912	}
913
914	case SIOCDIFADDR_IN6:
915	{
916		int i = 0;
917		struct nd_prefix pr0, *pr;
918
919		/*
920		 * If the address being deleted is the only one that owns
921		 * the corresponding prefix, expire the prefix as well.
922		 * XXX: theoretically, we don't have to warry about such
923		 * relationship, since we separate the address management
924		 * and the prefix management.  We do this, however, to provide
925		 * as much backward compatibility as possible in terms of
926		 * the ioctl operation.
927		 */
928		bzero(&pr0, sizeof(pr0));
929		pr0.ndpr_ifp = ifp;
930		pr0.ndpr_plen = in6_mask2len(&ia->ia_prefixmask.sin6_addr,
931					     NULL);
932		if (pr0.ndpr_plen == 128)
933			goto purgeaddr;
934		pr0.ndpr_prefix = ia->ia_addr;
935		pr0.ndpr_mask = ia->ia_prefixmask.sin6_addr;
936		for (i = 0; i < 4; i++) {
937			pr0.ndpr_prefix.sin6_addr.s6_addr32[i] &=
938				ia->ia_prefixmask.sin6_addr.s6_addr32[i];
939		}
940		/*
941		 * The logic of the following condition is a bit complicated.
942		 * We expire the prefix when
943		 * 1. the address obeys autoconfiguration and it is the
944		 *    only owner of the associated prefix, or
945		 * 2. the address does not obey autoconf and there is no
946		 *    other owner of the prefix.
947		 */
948		if ((pr = nd6_prefix_lookup(&pr0)) != NULL &&
949		    (((ia->ia6_flags & IN6_IFF_AUTOCONF) != 0 &&
950		      pr->ndpr_refcnt == 1) ||
951		     ((ia->ia6_flags & IN6_IFF_AUTOCONF) == 0 &&
952		      pr->ndpr_refcnt == 0))) {
953			pr->ndpr_expire = 1; /* XXX: just for expiration */
954		}
955
956		/* Drop use count held above during lookup */
957		if (pr != NULL)
958			ndpr_rele(pr, FALSE);
959
960	  purgeaddr:
961		in6_purgeaddr(&ia->ia_ifa, 0);
962		break;
963	}
964
965	default:
966		error = ifnet_ioctl(ifp, PF_INET6, cmd, data);
967		goto ioctl_cleanup;
968	}
969ioctl_cleanup:
970	return error;
971}
972
973/*
974 * Update parameters of an IPv6 interface address.
975 * If necessary, a new entry is created and linked into address chains.
976 * This function is separated from in6_control().
977 * XXX: should this be performed under splnet()?
978 */
979int
980in6_update_ifa(ifp, ifra, ia)
981	struct ifnet *ifp;
982	struct in6_aliasreq *ifra;
983	struct in6_ifaddr *ia;
984{
985	int error = 0, hostIsNew = 0, plen = -1;
986	struct in6_ifaddr *oia;
987	struct sockaddr_in6 dst6;
988	struct in6_addrlifetime *lt;
989	struct timeval timenow;
990
991
992	lck_mtx_assert(nd6_mutex, LCK_MTX_ASSERT_NOTOWNED);
993	/* Validate parameters */
994	if (ifp == NULL || ifra == NULL) /* this maybe redundant */
995		return(EINVAL);
996
997	/*
998	 * The destination address for a p2p link must have a family
999	 * of AF_UNSPEC or AF_INET6.
1000	 */
1001	if ((ifp->if_flags & IFF_POINTOPOINT) != 0 &&
1002	    ifra->ifra_dstaddr.sin6_family != AF_INET6 &&
1003	    ifra->ifra_dstaddr.sin6_family != AF_UNSPEC)
1004		return(EAFNOSUPPORT);
1005	/*
1006	 * validate ifra_prefixmask.  don't check sin6_family, netmask
1007	 * does not carry fields other than sin6_len.
1008	 */
1009	if (ifra->ifra_prefixmask.sin6_len > sizeof(struct sockaddr_in6))
1010		return(EINVAL);
1011	/*
1012	 * Set the address family value for the mask if it was not set.
1013	 * Radar 3899482.
1014	 */
1015	if (ifra->ifra_prefixmask.sin6_len == sizeof(struct sockaddr_in6) &&
1016		ifra->ifra_prefixmask.sin6_family == 0) {
1017		ifra->ifra_prefixmask.sin6_family = AF_INET6;
1018	}
1019	/*
1020	 * Because the IPv6 address architecture is classless, we require
1021	 * users to specify a (non 0) prefix length (mask) for a new address.
1022	 * We also require the prefix (when specified) mask is valid, and thus
1023	 * reject a non-consecutive mask.
1024	 */
1025	if (ia == NULL && ifra->ifra_prefixmask.sin6_len == 0)
1026		return(EINVAL);
1027	if (ifra->ifra_prefixmask.sin6_len != 0) {
1028		plen = in6_mask2len(&ifra->ifra_prefixmask.sin6_addr,
1029				    (u_char *)&ifra->ifra_prefixmask +
1030				    ifra->ifra_prefixmask.sin6_len);
1031		if (plen <= 0)
1032			return(EINVAL);
1033	}
1034	else {
1035		/*
1036		 * In this case, ia must not be NULL.  We just use its prefix
1037		 * length.
1038		 */
1039		plen = in6_mask2len(&ia->ia_prefixmask.sin6_addr, NULL);
1040	}
1041	/*
1042	 * If the destination address on a p2p interface is specified,
1043	 * and the address is a scoped one, validate/set the scope
1044	 * zone identifier.
1045	 */
1046	dst6 = ifra->ifra_dstaddr;
1047	if ((ifp->if_flags & (IFF_POINTOPOINT|IFF_LOOPBACK)) &&
1048	    (dst6.sin6_family == AF_INET6)) {
1049		int scopeid;
1050
1051#ifndef SCOPEDROUTING
1052		if ((error = in6_recoverscope(&dst6,
1053					      &ifra->ifra_dstaddr.sin6_addr,
1054					      ifp)) != 0)
1055			return(error);
1056#endif
1057		scopeid = in6_addr2scopeid(ifp, &dst6.sin6_addr);
1058		if (dst6.sin6_scope_id == 0) /* user omit to specify the ID. */
1059			dst6.sin6_scope_id = scopeid;
1060		else if (dst6.sin6_scope_id != scopeid)
1061			return(EINVAL); /* scope ID mismatch. */
1062#ifndef SCOPEDROUTING
1063		if ((error = in6_embedscope(&dst6.sin6_addr, &dst6, NULL, NULL))
1064		    != 0)
1065			return(error);
1066		dst6.sin6_scope_id = 0; /* XXX */
1067#endif
1068	}
1069	/*
1070	 * The destination address can be specified only for a p2p or a
1071	 * loopback interface.  If specified, the corresponding prefix length
1072	 * must be 128.
1073	 */
1074	if (ifra->ifra_dstaddr.sin6_family == AF_INET6) {
1075		if ((ifp->if_flags & (IFF_POINTOPOINT|IFF_LOOPBACK)) == 0) {
1076			/* XXX: noisy message */
1077			log(LOG_INFO, "in6_update_ifa: a destination can be "
1078			    "specified for a p2p or a loopback IF only\n");
1079			return(EINVAL);
1080		}
1081		if (plen != 128) {
1082			/*
1083			 * The following message seems noisy, but we dare to
1084			 * add it for diagnosis.
1085			 */
1086			log(LOG_INFO, "in6_update_ifa: prefixlen must be 128 "
1087			    "when dstaddr is specified\n");
1088			return(EINVAL);
1089		}
1090	}
1091	/* lifetime consistency check */
1092
1093	getmicrotime(&timenow);
1094	lt = &ifra->ifra_lifetime;
1095	if (lt->ia6t_vltime != ND6_INFINITE_LIFETIME
1096	    && lt->ia6t_vltime + timenow.tv_sec < timenow.tv_sec) {
1097		return EINVAL;
1098	}
1099	if (lt->ia6t_vltime == 0) {
1100		/*
1101		 * the following log might be noisy, but this is a typical
1102		 * configuration mistake or a tool's bug.
1103		 */
1104		log(LOG_INFO,
1105		    "in6_update_ifa: valid lifetime is 0 for %s\n",
1106		    ip6_sprintf(&ifra->ifra_addr.sin6_addr));
1107	}
1108	if (lt->ia6t_pltime != ND6_INFINITE_LIFETIME
1109	    && lt->ia6t_pltime + timenow.tv_sec < timenow.tv_sec) {
1110		return EINVAL;
1111	}
1112
1113	/*
1114	 * If this is a new address, allocate a new ifaddr and link it
1115	 * into chains.
1116	 */
1117	if (ia == NULL) {
1118		hostIsNew = 1;
1119		/*
1120		 * When in6_update_ifa() is called in a process of a received
1121		 * RA, it is called under splnet().  So, we should call malloc
1122		 * with M_NOWAIT.  The exception to this is during init time
1123		 * when we know it's okay to do M_WAITOK, hence the check
1124		 * against in6_init2done flag to see if it's not yet set.
1125		 */
1126		ia = (struct in6_ifaddr *) _MALLOC(sizeof(*ia), M_IFADDR,
1127		    in6_init2done ? M_NOWAIT : M_WAITOK);
1128		if (ia == NULL)
1129			return ENOBUFS;
1130		bzero((caddr_t)ia, sizeof(*ia));
1131		/* Initialize the address and masks */
1132		ia->ia_ifa.ifa_addr = (struct sockaddr *)&ia->ia_addr;
1133		ia->ia_addr.sin6_family = AF_INET6;
1134		ia->ia_addr.sin6_len = sizeof(ia->ia_addr);
1135		if ((ifp->if_flags & (IFF_POINTOPOINT | IFF_LOOPBACK)) != 0) {
1136			/*
1137			 * XXX: some functions expect that ifa_dstaddr is not
1138			 * NULL for p2p interfaces.
1139			 */
1140			ia->ia_ifa.ifa_dstaddr
1141				= (struct sockaddr *)&ia->ia_dstaddr;
1142		} else {
1143			ia->ia_ifa.ifa_dstaddr = NULL;
1144		}
1145		ia->ia_ifa.ifa_netmask
1146			= (struct sockaddr *)&ia->ia_prefixmask;
1147
1148		ia->ia_ifp = ifp;
1149		lck_mtx_lock(nd6_mutex);
1150		if ((oia = in6_ifaddrs) != NULL) {
1151			for ( ; oia->ia_next; oia = oia->ia_next)
1152				continue;
1153			oia->ia_next = ia;
1154		} else
1155			in6_ifaddrs = ia;
1156		lck_mtx_unlock(nd6_mutex);
1157
1158		ifnet_lock_exclusive(ifp);
1159		if_attach_ifa(ifp, &ia->ia_ifa);
1160		ifnet_lock_done(ifp);
1161	}
1162
1163	/* set prefix mask */
1164	if (ifra->ifra_prefixmask.sin6_len) {
1165		/*
1166		 * We prohibit changing the prefix length of an existing
1167		 * address, because
1168		 * + such an operation should be rare in IPv6, and
1169		 * + the operation would confuse prefix management.
1170		 */
1171		if (ia->ia_prefixmask.sin6_len &&
1172		    in6_mask2len(&ia->ia_prefixmask.sin6_addr, NULL) != plen) {
1173			log(LOG_INFO, "in6_update_ifa: the prefix length of an"
1174			    " existing (%s) address should not be changed\n",
1175			    ip6_sprintf(&ia->ia_addr.sin6_addr));
1176			error = EINVAL;
1177			goto unlink;
1178		}
1179		ia->ia_prefixmask = ifra->ifra_prefixmask;
1180	}
1181
1182	/*
1183	 * If a new destination address is specified, scrub the old one and
1184	 * install the new destination.  Note that the interface must be
1185	 * p2p or loopback (see the check above.)
1186	 */
1187	if (dst6.sin6_family == AF_INET6 &&
1188	    !IN6_ARE_ADDR_EQUAL(&dst6.sin6_addr,
1189				&ia->ia_dstaddr.sin6_addr)) {
1190		int e;
1191
1192		if ((ia->ia_flags & IFA_ROUTE) != 0 &&
1193		    (e = rtinit(&(ia->ia_ifa), (int)RTM_DELETE, RTF_HOST))
1194		    != 0) {
1195			log(LOG_ERR, "in6_update_ifa: failed to remove "
1196			    "a route to the old destination: %s\n",
1197			    ip6_sprintf(&ia->ia_addr.sin6_addr));
1198			/* proceed anyway... */
1199		}
1200		else
1201			ia->ia_flags &= ~IFA_ROUTE;
1202		ia->ia_dstaddr = dst6;
1203	}
1204
1205	/* reset the interface and routing table appropriately. */
1206	if ((error = in6_ifinit(ifp, ia, &ifra->ifra_addr, hostIsNew)) != 0)
1207		goto unlink;
1208
1209	/*
1210	 * Beyond this point, we should call in6_purgeaddr upon an error,
1211	 * not just go to unlink.
1212	 */
1213
1214#if 0				/* disable this mechanism for now */
1215	/* update prefix list */
1216	if (hostIsNew &&
1217	    (ifra->ifra_flags & IN6_IFF_NOPFX) == 0) { /* XXX */
1218		int iilen;
1219
1220		iilen = (sizeof(ia->ia_prefixmask.sin6_addr) << 3) - plen;
1221		if ((error = in6_prefix_add_ifid(iilen, ia)) != 0) {
1222			in6_purgeaddr((struct ifaddr *)ia, 0);
1223			return(error);
1224		}
1225	}
1226#endif
1227
1228	if ((ifp->if_flags & IFF_MULTICAST) != 0) {
1229		struct sockaddr_in6 mltaddr, mltmask;
1230		struct in6_multi *in6m;
1231
1232		if (hostIsNew) {
1233			/*
1234			 * join solicited multicast addr for new host id
1235			 */
1236			struct in6_addr llsol;
1237			bzero(&llsol, sizeof(struct in6_addr));
1238			llsol.s6_addr16[0] = htons(0xff02);
1239			llsol.s6_addr16[1] = htons(ifp->if_index);
1240			llsol.s6_addr32[1] = 0;
1241			llsol.s6_addr32[2] = htonl(1);
1242			llsol.s6_addr32[3] =
1243				ifra->ifra_addr.sin6_addr.s6_addr32[3];
1244			llsol.s6_addr8[12] = 0xff;
1245			(void)in6_addmulti(&llsol, ifp, &error, 0);
1246			if (error != 0) {
1247				log(LOG_WARNING,
1248				    "in6_update_ifa: addmulti failed for "
1249				    "%s on %s (errno=%d)\n",
1250				    ip6_sprintf(&llsol), if_name(ifp),
1251				    error);
1252				in6_purgeaddr((struct ifaddr *)ia, 0);
1253				return(error);
1254			}
1255		}
1256
1257		bzero(&mltmask, sizeof(mltmask));
1258		mltmask.sin6_len = sizeof(struct sockaddr_in6);
1259		mltmask.sin6_family = AF_INET6;
1260		mltmask.sin6_addr = in6mask32;
1261
1262		/*
1263		 * join link-local all-nodes address
1264		 */
1265		bzero(&mltaddr, sizeof(mltaddr));
1266		mltaddr.sin6_len = sizeof(struct sockaddr_in6);
1267		mltaddr.sin6_family = AF_INET6;
1268		mltaddr.sin6_addr = in6addr_linklocal_allnodes;
1269		mltaddr.sin6_addr.s6_addr16[1] = htons(ifp->if_index);
1270
1271		ifnet_lock_shared(ifp);
1272		IN6_LOOKUP_MULTI(mltaddr.sin6_addr, ifp, in6m);
1273		ifnet_lock_done(ifp);
1274		if (in6m == NULL) {
1275			rtrequest(RTM_ADD,
1276				  (struct sockaddr *)&mltaddr,
1277				  (struct sockaddr *)&ia->ia_addr,
1278				  (struct sockaddr *)&mltmask,
1279				  RTF_UP|RTF_CLONING,  /* xxx */
1280				  (struct rtentry **)0);
1281			(void)in6_addmulti(&mltaddr.sin6_addr, ifp, &error, 0);
1282			if (error != 0) {
1283				log(LOG_WARNING,
1284				    "in6_update_ifa: addmulti failed for "
1285				    "%s on %s (errno=%d)\n",
1286				    ip6_sprintf(&mltaddr.sin6_addr),
1287				    if_name(ifp), error);
1288			}
1289		}
1290
1291		/*
1292		 * join node information group address
1293		 */
1294#define hostnamelen	strlen(hostname)
1295		if (in6_nigroup(ifp, hostname, hostnamelen, &mltaddr.sin6_addr)
1296		    == 0) {
1297		    ifnet_lock_shared(ifp);
1298			IN6_LOOKUP_MULTI(mltaddr.sin6_addr, ifp, in6m);
1299			ifnet_lock_done(ifp);
1300			if (in6m == NULL && ia != NULL) {
1301				(void)in6_addmulti(&mltaddr.sin6_addr,
1302				    ifp, &error, 0);
1303				if (error != 0) {
1304					log(LOG_WARNING, "in6_update_ifa: "
1305					    "addmulti failed for "
1306					    "%s on %s (errno=%d)\n",
1307					    ip6_sprintf(&mltaddr.sin6_addr),
1308					    if_name(ifp), error);
1309				}
1310			}
1311		}
1312#undef hostnamelen
1313
1314		/*
1315		 * join node-local all-nodes address, on loopback.
1316		 * XXX: since "node-local" is obsoleted by interface-local,
1317		 *      we have to join the group on every interface with
1318		 *      some interface-boundary restriction.
1319		 */
1320		if (ifp->if_flags & IFF_LOOPBACK) {
1321			struct in6_ifaddr *ia_loop;
1322
1323			struct in6_addr loop6 = in6addr_loopback;
1324			ia_loop = in6ifa_ifpwithaddr(ifp, &loop6);
1325
1326			mltaddr.sin6_addr = in6addr_nodelocal_allnodes;
1327
1328			ifnet_lock_shared(ifp);
1329			IN6_LOOKUP_MULTI(mltaddr.sin6_addr, ifp, in6m);
1330			ifnet_lock_done(ifp);
1331			if (in6m == NULL && ia_loop != NULL) {
1332				rtrequest(RTM_ADD,
1333					  (struct sockaddr *)&mltaddr,
1334					  (struct sockaddr *)&ia_loop->ia_addr,
1335					  (struct sockaddr *)&mltmask,
1336					  RTF_UP,
1337					  (struct rtentry **)0);
1338				(void)in6_addmulti(&mltaddr.sin6_addr, ifp,
1339						   &error, 0);
1340				if (error != 0) {
1341					log(LOG_WARNING, "in6_update_ifa: "
1342					    "addmulti failed for %s on %s "
1343					    "(errno=%d)\n",
1344					    ip6_sprintf(&mltaddr.sin6_addr),
1345					    if_name(ifp), error);
1346				}
1347			}
1348		}
1349	}
1350
1351	ia->ia6_flags = ifra->ifra_flags;
1352	ia->ia6_flags &= ~IN6_IFF_DUPLICATED;	/*safety*/
1353	ia->ia6_flags &= ~IN6_IFF_NODAD;	/* Mobile IPv6 */
1354
1355	ia->ia6_lifetime = ifra->ifra_lifetime;
1356	/* for sanity */
1357	if (ia->ia6_lifetime.ia6t_vltime != ND6_INFINITE_LIFETIME) {
1358		ia->ia6_lifetime.ia6t_expire =
1359			timenow.tv_sec + ia->ia6_lifetime.ia6t_vltime;
1360	} else
1361		ia->ia6_lifetime.ia6t_expire = 0;
1362	if (ia->ia6_lifetime.ia6t_pltime != ND6_INFINITE_LIFETIME) {
1363		ia->ia6_lifetime.ia6t_preferred =
1364			timenow.tv_sec + ia->ia6_lifetime.ia6t_pltime;
1365	} else
1366		ia->ia6_lifetime.ia6t_preferred = 0;
1367
1368	/*
1369	 * make sure to initialize ND6 information.  this is to workaround
1370	 * issues with interfaces with IPv6 addresses, which have never brought
1371	 * up.  We are assuming that it is safe to nd6_ifattach multiple times.
1372	 */
1373	nd6_ifattach(ifp);
1374
1375	/*
1376	 * Perform DAD, if needed.
1377	 * XXX It may be of use, if we can administratively
1378	 * disable DAD.
1379	 */
1380	if (in6if_do_dad(ifp) && (ifra->ifra_flags & IN6_IFF_NODAD) == 0) {
1381		ia->ia6_flags |= IN6_IFF_TENTATIVE;
1382		nd6_dad_start((struct ifaddr *)ia, NULL);
1383	}
1384
1385	return(error);
1386
1387  unlink:
1388	/*
1389	 * XXX: if a change of an existing address failed, keep the entry
1390	 * anyway.
1391	 */
1392	if (hostIsNew)
1393		in6_unlink_ifa(ia, ifp, 0);
1394	return(error);
1395}
1396
1397void
1398in6_purgeaddr(
1399	struct ifaddr *ifa, int nd6_locked)
1400{
1401	struct ifnet *ifp = ifa->ifa_ifp;
1402	struct in6_ifaddr *ia = (struct in6_ifaddr *) ifa;
1403
1404	/* stop DAD processing */
1405	nd6_dad_stop(ifa);
1406
1407	/*
1408	 * delete route to the destination of the address being purged.
1409	 * The interface must be p2p or loopback in this case.
1410	 */
1411	if ((ia->ia_flags & IFA_ROUTE) != 0 && ia->ia_dstaddr.sin6_len != 0) {
1412		int e;
1413
1414		if ((e = rtinit(&(ia->ia_ifa), (int)RTM_DELETE, RTF_HOST))
1415		    != 0) {
1416			log(LOG_ERR, "in6_purgeaddr: failed to remove "
1417			    "a route to the p2p destination: %s on %s, "
1418			    "errno=%d\n",
1419			    ip6_sprintf(&ia->ia_addr.sin6_addr), if_name(ifp),
1420			    e);
1421			/* proceed anyway... */
1422		}
1423		else
1424			ia->ia_flags &= ~IFA_ROUTE;
1425	}
1426
1427	/* Remove ownaddr's loopback rtentry, if it exists. */
1428	in6_ifremloop(&(ia->ia_ifa), nd6_locked);
1429
1430	if (ifp->if_flags & IFF_MULTICAST) {
1431		/*
1432		 * delete solicited multicast addr for deleting host id
1433		 */
1434		struct in6_multi *in6m;
1435		struct in6_addr llsol;
1436		bzero(&llsol, sizeof(struct in6_addr));
1437		llsol.s6_addr16[0] = htons(0xff02);
1438		llsol.s6_addr16[1] = htons(ifp->if_index);
1439		llsol.s6_addr32[1] = 0;
1440		llsol.s6_addr32[2] = htonl(1);
1441		llsol.s6_addr32[3] =
1442			ia->ia_addr.sin6_addr.s6_addr32[3];
1443		llsol.s6_addr8[12] = 0xff;
1444
1445		ifnet_lock_shared(ifp);
1446		IN6_LOOKUP_MULTI(llsol, ifp, in6m);
1447		ifnet_lock_done(ifp);
1448		if (in6m)
1449			in6_delmulti(in6m, nd6_locked);
1450	}
1451
1452	in6_unlink_ifa(ia, ifp, nd6_locked);
1453	in6_post_msg(ifp, KEV_INET6_ADDR_DELETED, ia);
1454}
1455
1456static void
1457in6_unlink_ifa(ia, ifp, nd6_locked)
1458	struct in6_ifaddr *ia;
1459	struct ifnet *ifp;
1460	int nd6_locked;
1461{
1462	int plen, iilen;
1463	struct in6_ifaddr *oia;
1464
1465	ifnet_lock_exclusive(ifp);
1466	if_detach_ifa(ifp, &ia->ia_ifa);
1467	ifnet_lock_done(ifp);
1468
1469	if (!nd6_locked)
1470		lck_mtx_lock(nd6_mutex);
1471	oia = ia;
1472	if (oia == (ia = in6_ifaddrs))
1473		in6_ifaddrs = ia->ia_next;
1474	else {
1475		while (ia->ia_next && (ia->ia_next != oia))
1476			ia = ia->ia_next;
1477		if (ia->ia_next)
1478			ia->ia_next = oia->ia_next;
1479		else {
1480			/* search failed */
1481			printf("Couldn't unlink in6_ifaddr from in6_ifaddr\n");
1482		}
1483	}
1484	if (oia->ia6_ifpr) {	/* check for safety */
1485		plen = in6_mask2len(&oia->ia_prefixmask.sin6_addr, NULL);
1486		iilen = (sizeof(oia->ia_prefixmask.sin6_addr) << 3) - plen;
1487		in6_prefix_remove_ifid(iilen, oia);
1488	}
1489
1490	/*
1491	 * When an autoconfigured address is being removed, release the
1492	 * reference to the base prefix.  Also, since the release might
1493	 * affect the status of other (detached) addresses, call
1494	 * pfxlist_onlink_check().
1495	 */
1496	if ((oia->ia6_flags & IN6_IFF_AUTOCONF) != 0) {
1497		if (oia->ia6_ndpr == NULL) {
1498			log(LOG_NOTICE, "in6_unlink_ifa: autoconf'ed address "
1499			    "%p has no prefix\n", oia);
1500		} else {
1501			oia->ia6_ndpr->ndpr_refcnt--;
1502			oia->ia6_flags &= ~IN6_IFF_AUTOCONF;
1503			oia->ia6_ndpr = NULL;
1504		}
1505
1506		pfxlist_onlink_check(1);
1507	}
1508	if (!nd6_locked)
1509		lck_mtx_unlock(nd6_mutex);
1510
1511
1512	/*
1513	 * release another refcnt for the link from in6_ifaddrs.
1514	 * Note that we should decrement the refcnt at least once for all *BSD.
1515	 */
1516	ifafree(&oia->ia_ifa);
1517
1518}
1519
1520void
1521in6_purgeif(ifp)
1522	struct ifnet *ifp;
1523{
1524	struct in6_ifaddr *ia, *nia = NULL;
1525
1526	if (ifp == NULL || &ifp->if_addrlist == NULL)
1527		return;
1528
1529	lck_mtx_lock(nd6_mutex);
1530	for (ia = in6_ifaddrs; ia != NULL; ia = nia)
1531	{
1532		nia = ia->ia_next;
1533		if (ia->ia_ifa.ifa_ifp != ifp)
1534			continue;
1535		in6_purgeaddr(&ia->ia_ifa, 1);
1536	}
1537	lck_mtx_unlock(nd6_mutex);
1538
1539	in6_ifdetach(ifp);
1540}
1541
1542/*
1543 * SIOC[GAD]LIFADDR.
1544 *	SIOCGLIFADDR: get first address. (?)
1545 *	SIOCGLIFADDR with IFLR_PREFIX:
1546 *		get first address that matches the specified prefix.
1547 *	SIOCALIFADDR: add the specified address.
1548 *	SIOCALIFADDR with IFLR_PREFIX:
1549 *		add the specified prefix, filling hostaddr part from
1550 *		the first link-local address.  prefixlen must be <= 64.
1551 *	SIOCDLIFADDR: delete the specified address.
1552 *	SIOCDLIFADDR with IFLR_PREFIX:
1553 *		delete the first address that matches the specified prefix.
1554 * return values:
1555 *	EINVAL on invalid parameters
1556 *	EADDRNOTAVAIL on prefix match failed/specified address not found
1557 *	other values may be returned from in6_ioctl()
1558 *
1559 * NOTE: SIOCALIFADDR(with IFLR_PREFIX set) allows prefixlen less than 64.
1560 * this is to accomodate address naming scheme other than RFC2374,
1561 * in the future.
1562 * RFC2373 defines interface id to be 64bit, but it allows non-RFC2374
1563 * address encoding scheme. (see figure on page 8)
1564 */
1565static int
1566in6_lifaddr_ioctl(so, cmd, data, ifp, p)
1567	struct socket *so;
1568	u_long cmd;
1569	caddr_t	data;
1570	struct ifnet *ifp;
1571	struct proc *p;
1572{
1573	struct if_laddrreq *iflr = (struct if_laddrreq *)data;
1574	struct ifaddr *ifa;
1575	struct sockaddr *sa;
1576
1577	/* sanity checks */
1578	if (!data || !ifp) {
1579		panic("invalid argument to in6_lifaddr_ioctl");
1580		/*NOTRECHED*/
1581	}
1582
1583	switch (cmd) {
1584	case SIOCGLIFADDR:
1585		/* address must be specified on GET with IFLR_PREFIX */
1586		if ((iflr->flags & IFLR_PREFIX) == 0)
1587			break;
1588		/* FALLTHROUGH */
1589	case SIOCALIFADDR:
1590	case SIOCDLIFADDR:
1591		/* address must be specified on ADD and DELETE */
1592		sa = (struct sockaddr *)&iflr->addr;
1593		if (sa->sa_family != AF_INET6)
1594			return EINVAL;
1595		if (sa->sa_len != sizeof(struct sockaddr_in6))
1596			return EINVAL;
1597		/* XXX need improvement */
1598		sa = (struct sockaddr *)&iflr->dstaddr;
1599		if (sa->sa_family && sa->sa_family != AF_INET6)
1600			return EINVAL;
1601		if (sa->sa_len && sa->sa_len != sizeof(struct sockaddr_in6))
1602			return EINVAL;
1603		break;
1604	default: /* shouldn't happen */
1605#if 0
1606		panic("invalid cmd to in6_lifaddr_ioctl");
1607		/* NOTREACHED */
1608#else
1609		return EOPNOTSUPP;
1610#endif
1611	}
1612	if (sizeof(struct in6_addr) * 8 < iflr->prefixlen)
1613		return EINVAL;
1614
1615	switch (cmd) {
1616	case SIOCALIFADDR:
1617	    {
1618		struct in6_aliasreq ifra;
1619		struct in6_addr hostaddr;
1620		int prefixlen;
1621		int hostid_found = 0;
1622
1623		if ((iflr->flags & IFLR_PREFIX) != 0) {
1624			struct sockaddr_in6 *sin6;
1625
1626			/*
1627			 * hostaddr is to fill in the hostaddr part of the
1628			 * address.  hostaddr points to the first link-local
1629			 * address attached to the interface.
1630			 */
1631			ifa = (struct ifaddr *)in6ifa_ifpforlinklocal(ifp, 0);
1632			if (!ifa)
1633				return EADDRNOTAVAIL;
1634			hostaddr = *IFA_IN6(ifa);
1635			hostid_found = 1;
1636
1637		 	/* prefixlen must be <= 64. */
1638			if (64 < iflr->prefixlen)
1639				return EINVAL;
1640			prefixlen = iflr->prefixlen;
1641
1642			/* hostaddr part must be zero. */
1643			sin6 = (struct sockaddr_in6 *)&iflr->addr;
1644			if (sin6->sin6_addr.s6_addr32[2] != 0
1645			 || sin6->sin6_addr.s6_addr32[3] != 0) {
1646				return EINVAL;
1647			}
1648		} else
1649			prefixlen = iflr->prefixlen;
1650
1651		/* copy args to in6_aliasreq, perform ioctl(SIOCAIFADDR_IN6). */
1652		bzero(&ifra, sizeof(ifra));
1653		bcopy(iflr->iflr_name, ifra.ifra_name,
1654			sizeof(ifra.ifra_name));
1655
1656		bcopy(&iflr->addr, &ifra.ifra_addr,
1657			((struct sockaddr *)&iflr->addr)->sa_len);
1658		if (hostid_found) {
1659			/* fill in hostaddr part */
1660			ifra.ifra_addr.sin6_addr.s6_addr32[2] =
1661				hostaddr.s6_addr32[2];
1662			ifra.ifra_addr.sin6_addr.s6_addr32[3] =
1663				hostaddr.s6_addr32[3];
1664		}
1665
1666		if (((struct sockaddr *)&iflr->dstaddr)->sa_family) {	/*XXX*/
1667			bcopy(&iflr->dstaddr, &ifra.ifra_dstaddr,
1668				((struct sockaddr *)&iflr->dstaddr)->sa_len);
1669			if (hostid_found) {
1670				ifra.ifra_dstaddr.sin6_addr.s6_addr32[2] =
1671					hostaddr.s6_addr32[2];
1672				ifra.ifra_dstaddr.sin6_addr.s6_addr32[3] =
1673					hostaddr.s6_addr32[3];
1674			}
1675		}
1676
1677		ifra.ifra_prefixmask.sin6_len = sizeof(struct sockaddr_in6);
1678		in6_len2mask(&ifra.ifra_prefixmask.sin6_addr, prefixlen);
1679
1680		ifra.ifra_flags = iflr->flags & ~IFLR_PREFIX;
1681		return in6_control(so, SIOCAIFADDR_IN6, (caddr_t)&ifra, ifp, p);
1682	    }
1683	case SIOCGLIFADDR:
1684	case SIOCDLIFADDR:
1685	    {
1686		struct in6_ifaddr *ia;
1687		struct in6_addr mask, candidate, match;
1688		struct sockaddr_in6 *sin6;
1689		int cmp;
1690
1691		bzero(&mask, sizeof(mask));
1692		if (iflr->flags & IFLR_PREFIX) {
1693			/* lookup a prefix rather than address. */
1694			in6_len2mask(&mask, iflr->prefixlen);
1695
1696			sin6 = (struct sockaddr_in6 *)&iflr->addr;
1697			bcopy(&sin6->sin6_addr, &match, sizeof(match));
1698			match.s6_addr32[0] &= mask.s6_addr32[0];
1699			match.s6_addr32[1] &= mask.s6_addr32[1];
1700			match.s6_addr32[2] &= mask.s6_addr32[2];
1701			match.s6_addr32[3] &= mask.s6_addr32[3];
1702
1703			/* if you set extra bits, that's wrong */
1704			if (bcmp(&match, &sin6->sin6_addr, sizeof(match)))
1705				return EINVAL;
1706
1707			cmp = 1;
1708		} else {
1709			if (cmd == SIOCGLIFADDR) {
1710				/* on getting an address, take the 1st match */
1711				cmp = 0;	/* XXX */
1712			} else {
1713				/* on deleting an address, do exact match */
1714				in6_len2mask(&mask, 128);
1715				sin6 = (struct sockaddr_in6 *)&iflr->addr;
1716				bcopy(&sin6->sin6_addr, &match, sizeof(match));
1717
1718				cmp = 1;
1719			}
1720		}
1721
1722		ifnet_lock_shared(ifp);
1723		TAILQ_FOREACH(ifa, &ifp->if_addrlist, ifa_list)
1724		{
1725			if (ifa->ifa_addr->sa_family != AF_INET6)
1726				continue;
1727			if (!cmp)
1728				break;
1729
1730			bcopy(IFA_IN6(ifa), &candidate, sizeof(candidate));
1731#ifndef SCOPEDROUTING
1732			/*
1733			 * XXX: this is adhoc, but is necessary to allow
1734			 * a user to specify fe80::/64 (not /10) for a
1735			 * link-local address.
1736			 */
1737			if (IN6_IS_ADDR_LINKLOCAL(&candidate))
1738				candidate.s6_addr16[1] = 0;
1739#endif
1740			candidate.s6_addr32[0] &= mask.s6_addr32[0];
1741			candidate.s6_addr32[1] &= mask.s6_addr32[1];
1742			candidate.s6_addr32[2] &= mask.s6_addr32[2];
1743			candidate.s6_addr32[3] &= mask.s6_addr32[3];
1744			if (IN6_ARE_ADDR_EQUAL(&candidate, &match))
1745				break;
1746		}
1747		ifnet_lock_done(ifp);
1748		if (!ifa)
1749			return EADDRNOTAVAIL;
1750		ia = ifa2ia6(ifa);
1751
1752		if (cmd == SIOCGLIFADDR) {
1753#ifndef SCOPEDROUTING
1754			struct sockaddr_in6 *s6;
1755#endif
1756
1757			/* fill in the if_laddrreq structure */
1758			bcopy(&ia->ia_addr, &iflr->addr, ia->ia_addr.sin6_len);
1759#ifndef SCOPEDROUTING		/* XXX see above */
1760			s6 = (struct sockaddr_in6 *)&iflr->addr;
1761			if (IN6_IS_ADDR_LINKLOCAL(&s6->sin6_addr)) {
1762				s6->sin6_addr.s6_addr16[1] = 0;
1763				s6->sin6_scope_id =
1764					in6_addr2scopeid(ifp, &s6->sin6_addr);
1765			}
1766#endif
1767			if ((ifp->if_flags & IFF_POINTOPOINT) != 0) {
1768				bcopy(&ia->ia_dstaddr, &iflr->dstaddr,
1769					ia->ia_dstaddr.sin6_len);
1770#ifndef SCOPEDROUTING		/* XXX see above */
1771				s6 = (struct sockaddr_in6 *)&iflr->dstaddr;
1772				if (IN6_IS_ADDR_LINKLOCAL(&s6->sin6_addr)) {
1773					s6->sin6_addr.s6_addr16[1] = 0;
1774					s6->sin6_scope_id =
1775						in6_addr2scopeid(ifp,
1776								 &s6->sin6_addr);
1777				}
1778#endif
1779			} else
1780				bzero(&iflr->dstaddr, sizeof(iflr->dstaddr));
1781
1782			iflr->prefixlen =
1783				in6_mask2len(&ia->ia_prefixmask.sin6_addr,
1784					     NULL);
1785
1786			iflr->flags = ia->ia6_flags;	/* XXX */
1787
1788			return 0;
1789		} else {
1790			struct in6_aliasreq ifra;
1791
1792			/* fill in6_aliasreq and do ioctl(SIOCDIFADDR_IN6) */
1793			bzero(&ifra, sizeof(ifra));
1794			bcopy(iflr->iflr_name, ifra.ifra_name,
1795				sizeof(ifra.ifra_name));
1796
1797			bcopy(&ia->ia_addr, &ifra.ifra_addr,
1798				ia->ia_addr.sin6_len);
1799			if ((ifp->if_flags & IFF_POINTOPOINT) != 0) {
1800				bcopy(&ia->ia_dstaddr, &ifra.ifra_dstaddr,
1801					ia->ia_dstaddr.sin6_len);
1802			} else {
1803				bzero(&ifra.ifra_dstaddr,
1804				    sizeof(ifra.ifra_dstaddr));
1805			}
1806			bcopy(&ia->ia_prefixmask, &ifra.ifra_dstaddr,
1807				ia->ia_prefixmask.sin6_len);
1808
1809			ifra.ifra_flags = ia->ia6_flags;
1810			return in6_control(so, SIOCDIFADDR_IN6, (caddr_t)&ifra,
1811				ifp, p);
1812		}
1813	    }
1814	}
1815
1816	return EOPNOTSUPP;	/* just for safety */
1817}
1818
1819/*
1820 * Initialize an interface's intetnet6 address
1821 * and routing table entry.
1822 */
1823static int
1824in6_ifinit(ifp, ia, sin6, newhost)
1825	struct ifnet *ifp;
1826	struct in6_ifaddr *ia;
1827	struct sockaddr_in6 *sin6;
1828	int newhost;
1829{
1830	int	error = 0, plen, ifacount = 0;
1831	struct ifaddr *ifa;
1832
1833	/*
1834	 * Give the interface a chance to initialize
1835	 * if this is its first address,
1836	 * and to validate the address if necessary.
1837	 */
1838	ifnet_lock_shared(ifp);
1839	TAILQ_FOREACH(ifa, &ifp->if_addrlist, ifa_list)
1840	{
1841		if (ifa->ifa_addr == NULL)
1842			continue;	/* just for safety */
1843		if (ifa->ifa_addr->sa_family != AF_INET6)
1844			continue;
1845		ifacount++;
1846	}
1847	ifnet_lock_done(ifp);
1848
1849	ia->ia_addr = *sin6;
1850
1851
1852	if (ifacount <= 1 &&
1853	    (error = ifnet_ioctl(ifp, PF_INET6, SIOCSIFADDR, ia))) {
1854		if (error) {
1855			return(error);
1856		}
1857	}
1858
1859	ia->ia_ifa.ifa_metric = ifp->if_metric;
1860
1861	/* we could do in(6)_socktrim here, but just omit it at this moment. */
1862
1863	/*
1864	 * Special case:
1865	 * If the destination address is specified for a point-to-point
1866	 * interface, install a route to the destination as an interface
1867	 * direct route.
1868	 */
1869	plen = in6_mask2len(&ia->ia_prefixmask.sin6_addr, NULL); /* XXX */
1870	if (plen == 128 && ia->ia_dstaddr.sin6_family == AF_INET6) {
1871		if ((error = rtinit(&(ia->ia_ifa), (int)RTM_ADD,
1872				    RTF_UP | RTF_HOST)) != 0)
1873			return(error);
1874		ia->ia_flags |= IFA_ROUTE;
1875	}
1876	if (plen < 128) {
1877		/*
1878		 * The RTF_CLONING flag is necessary for in6_is_ifloop_auto().
1879		 */
1880		ia->ia_ifa.ifa_flags |= RTF_CLONING;
1881	}
1882
1883	/* Add ownaddr as loopback rtentry, if necessary (ex. on p2p link). */
1884	if (newhost) {
1885		/* set the rtrequest function to create llinfo */
1886		ia->ia_ifa.ifa_rtrequest = nd6_rtrequest;
1887		in6_ifaddloop(&(ia->ia_ifa));
1888	}
1889
1890	return(error);
1891}
1892
1893/*
1894 * Add an address to the list of IP6 multicast addresses for a
1895 * given interface.
1896 */
1897struct	in6_multi *
1898in6_addmulti(maddr6, ifp, errorp, nd6_locked)
1899	struct in6_addr *maddr6;
1900	struct ifnet *ifp;
1901	int *errorp;
1902	int nd6_locked;
1903{
1904	struct	in6_multi *in6m;
1905	struct sockaddr_in6 sin6;
1906	struct ifmultiaddr *ifma;
1907
1908	*errorp = 0;
1909
1910	/*
1911	 * Call generic routine to add membership or increment
1912	 * refcount.  It wants addresses in the form of a sockaddr,
1913	 * so we build one here (being careful to zero the unused bytes).
1914	 */
1915	bzero(&sin6, sizeof sin6);
1916	sin6.sin6_family = AF_INET6;
1917	sin6.sin6_len = sizeof sin6;
1918	sin6.sin6_addr = *maddr6;
1919	*errorp = if_addmulti(ifp, (struct sockaddr *)&sin6, &ifma);
1920	if (*errorp) {
1921		return 0;
1922	}
1923
1924	/*
1925	 * If ifma->ifma_protospec is null, then if_addmulti() created
1926	 * a new record.  Otherwise, we are done.
1927	 */
1928	if (ifma->ifma_protospec != 0)
1929		return ifma->ifma_protospec;
1930
1931	/* XXX - if_addmulti uses M_WAITOK.  Can this really be called
1932	   at interrupt time?  If so, need to fix if_addmulti. XXX */
1933	in6m = (struct in6_multi *)_MALLOC(sizeof(*in6m), M_IPMADDR, M_NOWAIT);
1934	if (in6m == NULL) {
1935		return (NULL);
1936	}
1937
1938	bzero(in6m, sizeof *in6m);
1939	in6m->in6m_addr = *maddr6;
1940	in6m->in6m_ifp = ifp;
1941	in6m->in6m_ifma = ifma;
1942	ifma->ifma_protospec = in6m;
1943	if (nd6_locked == 0)
1944		lck_mtx_lock(nd6_mutex);
1945	LIST_INSERT_HEAD(&in6_multihead, in6m, in6m_entry);
1946	if (nd6_locked == 0)
1947		lck_mtx_unlock(nd6_mutex);
1948
1949	/*
1950	 * Let MLD6 know that we have joined a new IP6 multicast
1951	 * group.
1952	 */
1953	mld6_start_listening(in6m);
1954	return(in6m);
1955}
1956
1957/*
1958 * Delete a multicast address record.
1959 */
1960void
1961in6_delmulti(
1962	struct in6_multi *in6m, int nd6locked)
1963{
1964	struct ifmultiaddr *ifma = in6m->in6m_ifma;
1965
1966	if (ifma && ifma->ifma_usecount == 1) {
1967		/*
1968		 * No remaining claims to this record; let MLD6 know
1969		 * that we are leaving the multicast group.
1970		 */
1971		mld6_stop_listening(in6m);
1972		ifma->ifma_protospec = 0;
1973		if (nd6locked == 0)
1974			lck_mtx_lock(nd6_mutex);
1975		LIST_REMOVE(in6m, in6m_entry);
1976		if (nd6locked == 0)
1977			lck_mtx_unlock(nd6_mutex);
1978		FREE(in6m, M_IPMADDR);
1979	}
1980	/* XXX - should be separate API for when we have an ifma? */
1981	if (ifma) {
1982		if_delmultiaddr(ifma, 0);
1983		ifma_release(ifma);
1984	}
1985}
1986
1987/*
1988 * Find an IPv6 interface link-local address specific to an interface.
1989 */
1990struct in6_ifaddr *
1991in6ifa_ifpforlinklocal(ifp, ignoreflags)
1992	struct ifnet *ifp;
1993	int ignoreflags;
1994{
1995	struct ifaddr *ifa;
1996
1997	ifnet_lock_shared(ifp);
1998	TAILQ_FOREACH(ifa, &ifp->if_addrlist, ifa_list)
1999	{
2000		if (ifa->ifa_addr == NULL)
2001			continue;	/* just for safety */
2002		if (ifa->ifa_addr->sa_family != AF_INET6)
2003			continue;
2004		if (IN6_IS_ADDR_LINKLOCAL(IFA_IN6(ifa))) {
2005			if ((((struct in6_ifaddr *)ifa)->ia6_flags &
2006			     ignoreflags) != 0)
2007				continue;
2008			break;
2009		}
2010	}
2011	ifnet_lock_done(ifp);
2012
2013	return((struct in6_ifaddr *)ifa);
2014}
2015
2016/*
2017 * find the internet address corresponding to a given interface and address.
2018 */
2019struct in6_ifaddr *
2020in6ifa_ifpwithaddr(ifp, addr)
2021	struct ifnet *ifp;
2022	struct in6_addr *addr;
2023{
2024	struct ifaddr *ifa;
2025
2026	ifnet_lock_shared(ifp);
2027	TAILQ_FOREACH(ifa, &ifp->if_addrlist, ifa_list)
2028	{
2029		if (ifa->ifa_addr == NULL)
2030			continue;	/* just for safety */
2031		if (ifa->ifa_addr->sa_family != AF_INET6)
2032			continue;
2033		if (IN6_ARE_ADDR_EQUAL(addr, IFA_IN6(ifa)))
2034			break;
2035	}
2036	ifnet_lock_done(ifp);
2037
2038	return((struct in6_ifaddr *)ifa);
2039}
2040
2041/*
2042 * Convert IP6 address to printable (loggable) representation.
2043 */
2044static char digits[] = "0123456789abcdef";
2045static int ip6round = 0;
2046char *
2047ip6_sprintf(addr)
2048	const struct in6_addr *addr;
2049{
2050	static char ip6buf[8][48];
2051	int i;
2052	char *cp;
2053	const u_short *a = (const u_short *)addr;
2054	const u_char *d;
2055	int dcolon = 0;
2056
2057	ip6round = (ip6round + 1) & 7;
2058	cp = ip6buf[ip6round];
2059
2060	for (i = 0; i < 8; i++) {
2061		if (dcolon == 1) {
2062			if (*a == 0) {
2063				if (i == 7)
2064					*cp++ = ':';
2065				a++;
2066				continue;
2067			} else
2068				dcolon = 2;
2069		}
2070		if (*a == 0) {
2071			if (dcolon == 0 && *(a + 1) == 0) {
2072				if (i == 0)
2073					*cp++ = ':';
2074				*cp++ = ':';
2075				dcolon = 1;
2076			} else {
2077				*cp++ = '0';
2078				*cp++ = ':';
2079			}
2080			a++;
2081			continue;
2082		}
2083		d = (const u_char *)a;
2084		*cp++ = digits[*d >> 4];
2085		*cp++ = digits[*d++ & 0xf];
2086		*cp++ = digits[*d >> 4];
2087		*cp++ = digits[*d & 0xf];
2088		*cp++ = ':';
2089		a++;
2090	}
2091	*--cp = 0;
2092	return(ip6buf[ip6round]);
2093}
2094
2095int
2096in6addr_local(struct in6_addr *in6)
2097{
2098	struct rtentry *rt;
2099	struct sockaddr_in6 sin6;
2100	int local = 0;
2101
2102	if (IN6_IS_ADDR_LOOPBACK(in6) || IN6_IS_ADDR_LINKLOCAL(in6))
2103		return (1);
2104
2105	sin6.sin6_family = AF_INET6;
2106	sin6.sin6_len = sizeof (sin6);
2107	bcopy(in6, &sin6.sin6_addr, sizeof (*in6));
2108	rt = rtalloc1((struct sockaddr *)&sin6, 0, 0UL);
2109
2110	if (rt != NULL) {
2111		if (rt->rt_gateway->sa_family == AF_LINK)
2112			local = 1;
2113		rtfree(rt);
2114	} else {
2115		local = in6_localaddr(in6);
2116	}
2117	return (local);
2118}
2119
2120int
2121in6_localaddr(in6)
2122	struct in6_addr *in6;
2123{
2124	struct in6_ifaddr *ia;
2125
2126	if (IN6_IS_ADDR_LOOPBACK(in6) || IN6_IS_ADDR_LINKLOCAL(in6))
2127		return 1;
2128
2129	lck_mtx_lock(nd6_mutex);
2130	for (ia = in6_ifaddrs; ia; ia = ia->ia_next)
2131		if (IN6_ARE_MASKED_ADDR_EQUAL(in6, &ia->ia_addr.sin6_addr,
2132					      &ia->ia_prefixmask.sin6_addr)) {
2133			lck_mtx_unlock(nd6_mutex);
2134			return 1;
2135		}
2136
2137	lck_mtx_unlock(nd6_mutex);
2138	return (0);
2139}
2140
2141int
2142in6_is_addr_deprecated(sa6)
2143	struct sockaddr_in6 *sa6;
2144{
2145	struct in6_ifaddr *ia;
2146
2147	lck_mtx_lock(nd6_mutex);
2148	for (ia = in6_ifaddrs; ia; ia = ia->ia_next) {
2149		if (IN6_ARE_ADDR_EQUAL(&ia->ia_addr.sin6_addr,
2150				       &sa6->sin6_addr) &&
2151#if SCOPEDROUTING
2152		    ia->ia_addr.sin6_scope_id == sa6->sin6_scope_id &&
2153#endif
2154		    (ia->ia6_flags & IN6_IFF_DEPRECATED) != 0) {
2155			lck_mtx_unlock(nd6_mutex);
2156			return(1); /* true */
2157		}
2158
2159		/* XXX: do we still have to go thru the rest of the list? */
2160	}
2161
2162	lck_mtx_unlock(nd6_mutex);
2163	return(0);		/* false */
2164}
2165
2166/*
2167 * return length of part which dst and src are equal
2168 * hard coding...
2169 */
2170int
2171in6_matchlen(src, dst)
2172struct in6_addr *src, *dst;
2173{
2174	int match = 0;
2175	u_char *s = (u_char *)src, *d = (u_char *)dst;
2176	u_char *lim = s + 16, r;
2177
2178	while (s < lim)
2179		if ((r = (*d++ ^ *s++)) != 0) {
2180			while (r < 128) {
2181				match++;
2182				r <<= 1;
2183			}
2184			break;
2185		} else
2186			match += 8;
2187	return match;
2188}
2189
2190/* XXX: to be scope conscious */
2191int
2192in6_are_prefix_equal(p1, p2, len)
2193	struct in6_addr *p1, *p2;
2194	int len;
2195{
2196	int bytelen, bitlen;
2197
2198	/* sanity check */
2199	if (0 > len || len > 128) {
2200		log(LOG_ERR, "in6_are_prefix_equal: invalid prefix length(%d)\n",
2201		    len);
2202		return(0);
2203	}
2204
2205	bytelen = len / 8;
2206	bitlen = len % 8;
2207
2208	if (bcmp(&p1->s6_addr, &p2->s6_addr, bytelen))
2209		return(0);
2210	if (bitlen != 0 &&
2211	    p1->s6_addr[bytelen] >> (8 - bitlen) !=
2212	    p2->s6_addr[bytelen] >> (8 - bitlen))
2213		return(0);
2214
2215	return(1);
2216}
2217
2218void
2219in6_prefixlen2mask(maskp, len)
2220	struct in6_addr *maskp;
2221	int len;
2222{
2223	u_char maskarray[8] = {0x80, 0xc0, 0xe0, 0xf0, 0xf8, 0xfc, 0xfe, 0xff};
2224	int bytelen, bitlen, i;
2225
2226	/* sanity check */
2227	if (0 > len || len > 128) {
2228		log(LOG_ERR, "in6_prefixlen2mask: invalid prefix length(%d)\n",
2229		    len);
2230		return;
2231	}
2232
2233	bzero(maskp, sizeof(*maskp));
2234	bytelen = len / 8;
2235	bitlen = len % 8;
2236	for (i = 0; i < bytelen; i++)
2237		maskp->s6_addr[i] = 0xff;
2238	if (bitlen)
2239		maskp->s6_addr[bytelen] = maskarray[bitlen - 1];
2240}
2241
2242/*
2243 * return the best address out of the same scope
2244 */
2245struct in6_ifaddr *
2246in6_ifawithscope(
2247	struct ifnet *oifp,
2248	struct in6_addr *dst)
2249{
2250	int dst_scope =	in6_addrscope(dst), src_scope, best_scope = 0;
2251	int blen = -1;
2252	struct ifaddr *ifa;
2253	struct ifnet *ifp;
2254	struct in6_ifaddr *ifa_best = NULL;
2255
2256	if (oifp == NULL) {
2257#if 0
2258		printf("in6_ifawithscope: output interface is not specified\n");
2259#endif
2260		return(NULL);
2261	}
2262
2263	/*
2264	 * We search for all addresses on all interfaces from the beginning.
2265	 * Comparing an interface with the outgoing interface will be done
2266	 * only at the final stage of tiebreaking.
2267	 */
2268	ifnet_head_lock_shared();
2269	TAILQ_FOREACH(ifp, &ifnet_head, if_list) {
2270		/*
2271		 * We can never take an address that breaks the scope zone
2272		 * of the destination.
2273		 */
2274		if (in6_addr2scopeid(ifp, dst) != in6_addr2scopeid(oifp, dst))
2275			continue;
2276
2277		ifnet_lock_shared(ifp);
2278		TAILQ_FOREACH(ifa, &ifp->if_addrlist, ifa_list)
2279		{
2280			int tlen = -1, dscopecmp, bscopecmp, matchcmp;
2281
2282			if (ifa->ifa_addr->sa_family != AF_INET6)
2283				continue;
2284
2285			src_scope = in6_addrscope(IFA_IN6(ifa));
2286
2287			/*
2288			 * Don't use an address before completing DAD
2289			 * nor a duplicated address.
2290			 */
2291			if (((struct in6_ifaddr *)ifa)->ia6_flags &
2292			    IN6_IFF_NOTREADY)
2293				continue;
2294
2295			/* XXX: is there any case to allow anycasts? */
2296			if (((struct in6_ifaddr *)ifa)->ia6_flags &
2297			    IN6_IFF_ANYCAST)
2298				continue;
2299
2300			if (((struct in6_ifaddr *)ifa)->ia6_flags &
2301			    IN6_IFF_DETACHED)
2302				continue;
2303
2304			/*
2305			 * If this is the first address we find,
2306			 * keep it anyway.
2307			 */
2308			if (ifa_best == NULL)
2309				goto replace;
2310
2311			/*
2312			 * ifa_best is never NULL beyond this line except
2313			 * within the block labeled "replace".
2314			 */
2315
2316			/*
2317			 * If ifa_best has a smaller scope than dst and
2318			 * the current address has a larger one than
2319			 * (or equal to) dst, always replace ifa_best.
2320			 * Also, if the current address has a smaller scope
2321			 * than dst, ignore it unless ifa_best also has a
2322			 * smaller scope.
2323			 * Consequently, after the two if-clause below,
2324			 * the followings must be satisfied:
2325			 * (scope(src) < scope(dst) &&
2326			 *  scope(best) < scope(dst))
2327			 *  OR
2328			 * (scope(best) >= scope(dst) &&
2329			 *  scope(src) >= scope(dst))
2330			 */
2331			if (IN6_ARE_SCOPE_CMP(best_scope, dst_scope) < 0 &&
2332			    IN6_ARE_SCOPE_CMP(src_scope, dst_scope) >= 0)
2333				goto replace; /* (A) */
2334			if (IN6_ARE_SCOPE_CMP(src_scope, dst_scope) < 0 &&
2335			    IN6_ARE_SCOPE_CMP(best_scope, dst_scope) >= 0)
2336				continue; /* (B) */
2337
2338			/*
2339			 * A deprecated address SHOULD NOT be used in new
2340			 * communications if an alternate (non-deprecated)
2341			 * address is available and has sufficient scope.
2342			 * RFC 2462, Section 5.5.4.
2343			 */
2344			if (((struct in6_ifaddr *)ifa)->ia6_flags &
2345			    IN6_IFF_DEPRECATED) {
2346				/*
2347				 * Ignore any deprecated addresses if
2348				 * specified by configuration.
2349				 */
2350				if (!ip6_use_deprecated)
2351					continue;
2352
2353				/*
2354				 * If we have already found a non-deprecated
2355				 * candidate, just ignore deprecated addresses.
2356				 */
2357				if ((ifa_best->ia6_flags & IN6_IFF_DEPRECATED)
2358				    == 0)
2359					continue;
2360			}
2361
2362			/*
2363			 * A non-deprecated address is always preferred
2364			 * to a deprecated one regardless of scopes and
2365			 * address matching (Note invariants ensured by the
2366			 * conditions (A) and (B) above.)
2367			 */
2368			if ((ifa_best->ia6_flags & IN6_IFF_DEPRECATED) &&
2369			    (((struct in6_ifaddr *)ifa)->ia6_flags &
2370			     IN6_IFF_DEPRECATED) == 0)
2371				goto replace;
2372
2373			/*
2374			 * When we use temporary addresses described in
2375			 * RFC 3041, we prefer temporary addresses to
2376			 * public autoconf addresses.  Again, note the
2377			 * invariants from (A) and (B).  Also note that we
2378			 * don't have any preference between static addresses
2379			 * and autoconf addresses (despite of whether or not
2380			 * the latter is temporary or public.)
2381			 */
2382			if (ip6_use_tempaddr) {
2383				struct in6_ifaddr *ifat;
2384
2385				ifat = (struct in6_ifaddr *)ifa;
2386				if ((ifa_best->ia6_flags &
2387				     (IN6_IFF_AUTOCONF|IN6_IFF_TEMPORARY))
2388				     == IN6_IFF_AUTOCONF &&
2389				    (ifat->ia6_flags &
2390				     (IN6_IFF_AUTOCONF|IN6_IFF_TEMPORARY))
2391				     == (IN6_IFF_AUTOCONF|IN6_IFF_TEMPORARY)) {
2392					goto replace;
2393				}
2394				if ((ifa_best->ia6_flags &
2395				     (IN6_IFF_AUTOCONF|IN6_IFF_TEMPORARY))
2396				    == (IN6_IFF_AUTOCONF|IN6_IFF_TEMPORARY) &&
2397				    (ifat->ia6_flags &
2398				     (IN6_IFF_AUTOCONF|IN6_IFF_TEMPORARY))
2399				     == IN6_IFF_AUTOCONF) {
2400					continue;
2401				}
2402			}
2403
2404			/*
2405			 * At this point, we have two cases:
2406			 * 1. we are looking at a non-deprecated address,
2407			 *    and ifa_best is also non-deprecated.
2408			 * 2. we are looking at a deprecated address,
2409			 *    and ifa_best is also deprecated.
2410			 * Also, we do not have to consider a case where
2411			 * the scope of if_best is larger(smaller) than dst and
2412			 * the scope of the current address is smaller(larger)
2413			 * than dst. Such a case has already been covered.
2414			 * Tiebreaking is done according to the following
2415			 * items:
2416			 * - the scope comparison between the address and
2417			 *   dst (dscopecmp)
2418			 * - the scope comparison between the address and
2419			 *   ifa_best (bscopecmp)
2420			 * - if the address match dst longer than ifa_best
2421			 *   (matchcmp)
2422			 * - if the address is on the outgoing I/F (outI/F)
2423			 *
2424			 * Roughly speaking, the selection policy is
2425			 * - the most important item is scope. The same scope
2426			 *   is best. Then search for a larger scope.
2427			 *   Smaller scopes are the last resort.
2428			 * - A deprecated address is chosen only when we have
2429			 *   no address that has an enough scope, but is
2430			 *   prefered to any addresses of smaller scopes
2431			 *   (this must be already done above.)
2432			 * - addresses on the outgoing I/F are preferred to
2433			 *   ones on other interfaces if none of above
2434			 *   tiebreaks.  In the table below, the column "bI"
2435			 *   means if the best_ifa is on the outgoing
2436			 *   interface, and the column "sI" means if the ifa
2437			 *   is on the outgoing interface.
2438			 * - If there is no other reasons to choose one,
2439			 *   longest address match against dst is considered.
2440			 *
2441			 * The precise decision table is as follows:
2442			 * dscopecmp bscopecmp    match  bI oI | replace?
2443			 *       N/A     equal      N/A   Y  N |   No (1)
2444			 *       N/A     equal      N/A   N  Y |  Yes (2)
2445			 *       N/A     equal   larger    N/A |  Yes (3)
2446			 *       N/A     equal  !larger    N/A |   No (4)
2447			 *    larger    larger      N/A    N/A |   No (5)
2448			 *    larger   smaller      N/A    N/A |  Yes (6)
2449			 *   smaller    larger      N/A    N/A |  Yes (7)
2450			 *   smaller   smaller      N/A    N/A |   No (8)
2451			 *     equal   smaller      N/A    N/A |  Yes (9)
2452			 *     equal    larger       (already done at A above)
2453			 */
2454			dscopecmp = IN6_ARE_SCOPE_CMP(src_scope, dst_scope);
2455			bscopecmp = IN6_ARE_SCOPE_CMP(src_scope, best_scope);
2456
2457			if (bscopecmp == 0) {
2458				struct ifnet *bifp = ifa_best->ia_ifp;
2459
2460				if (bifp == oifp && ifp != oifp) /* (1) */
2461					continue;
2462				if (bifp != oifp && ifp == oifp) /* (2) */
2463					goto replace;
2464
2465				/*
2466				 * Both bifp and ifp are on the outgoing
2467				 * interface, or both two are on a different
2468				 * interface from the outgoing I/F.
2469				 * now we need address matching against dst
2470				 * for tiebreaking.
2471				 */
2472				tlen = in6_matchlen(IFA_IN6(ifa), dst);
2473				matchcmp = tlen - blen;
2474				if (matchcmp > 0) /* (3) */
2475					goto replace;
2476				continue; /* (4) */
2477			}
2478			if (dscopecmp > 0) {
2479				if (bscopecmp > 0) /* (5) */
2480					continue;
2481				goto replace; /* (6) */
2482			}
2483			if (dscopecmp < 0) {
2484				if (bscopecmp > 0) /* (7) */
2485					goto replace;
2486				continue; /* (8) */
2487			}
2488
2489			/* now dscopecmp must be 0 */
2490			if (bscopecmp < 0)
2491				goto replace; /* (9) */
2492
2493		  replace:
2494		  	ifaref(ifa);
2495		  	if (ifa_best)
2496		  		ifafree(&ifa_best->ia_ifa);
2497			ifa_best = (struct in6_ifaddr *)ifa;
2498			blen = tlen >= 0 ? tlen :
2499				in6_matchlen(IFA_IN6(ifa), dst);
2500			best_scope = in6_addrscope(&ifa_best->ia_addr.sin6_addr);
2501		}
2502		ifnet_lock_done(ifp);
2503	}
2504	ifnet_head_done();
2505
2506	/* count statistics for future improvements */
2507	if (ifa_best == NULL)
2508		ip6stat.ip6s_sources_none++;
2509	else {
2510		if (oifp == ifa_best->ia_ifp)
2511			ip6stat.ip6s_sources_sameif[best_scope]++;
2512		else
2513			ip6stat.ip6s_sources_otherif[best_scope]++;
2514
2515		if (best_scope == dst_scope)
2516			ip6stat.ip6s_sources_samescope[best_scope]++;
2517		else
2518			ip6stat.ip6s_sources_otherscope[best_scope]++;
2519
2520		if ((ifa_best->ia6_flags & IN6_IFF_DEPRECATED) != 0)
2521			ip6stat.ip6s_sources_deprecated[best_scope]++;
2522	}
2523
2524	return(ifa_best);
2525}
2526
2527/*
2528 * return the best address out of the same scope. if no address was
2529 * found, return the first valid address from designated IF.
2530 */
2531struct in6_ifaddr *
2532in6_ifawithifp(
2533	struct ifnet *ifp,
2534	struct in6_addr *dst)
2535{
2536	int dst_scope =	in6_addrscope(dst), blen = -1, tlen;
2537	struct ifaddr *ifa;
2538	struct in6_ifaddr *besta = 0;
2539	struct in6_ifaddr *dep[2];	/* last-resort: deprecated */
2540
2541	dep[0] = dep[1] = NULL;
2542
2543	/*
2544	 * We first look for addresses in the same scope.
2545	 * If there is one, return it.
2546	 * If two or more, return one which matches the dst longest.
2547	 * If none, return one of global addresses assigned other ifs.
2548	 */
2549	ifnet_lock_shared(ifp);
2550	TAILQ_FOREACH(ifa, &ifp->if_addrlist, ifa_list)
2551	{
2552		if (ifa->ifa_addr->sa_family != AF_INET6)
2553			continue;
2554		if (((struct in6_ifaddr *)ifa)->ia6_flags & IN6_IFF_ANYCAST)
2555			continue; /* XXX: is there any case to allow anycast? */
2556		if (((struct in6_ifaddr *)ifa)->ia6_flags & IN6_IFF_NOTREADY)
2557			continue; /* don't use this interface */
2558		if (((struct in6_ifaddr *)ifa)->ia6_flags & IN6_IFF_DETACHED)
2559			continue;
2560		if (((struct in6_ifaddr *)ifa)->ia6_flags & IN6_IFF_DEPRECATED) {
2561			if (ip6_use_deprecated)
2562				dep[0] = (struct in6_ifaddr *)ifa;
2563			continue;
2564		}
2565
2566		if (dst_scope == in6_addrscope(IFA_IN6(ifa))) {
2567			/*
2568			 * call in6_matchlen() as few as possible
2569			 */
2570			if (besta) {
2571				if (blen == -1)
2572					blen = in6_matchlen(&besta->ia_addr.sin6_addr, dst);
2573				tlen = in6_matchlen(IFA_IN6(ifa), dst);
2574				if (tlen > blen) {
2575					blen = tlen;
2576					besta = (struct in6_ifaddr *)ifa;
2577				}
2578			} else
2579				besta = (struct in6_ifaddr *)ifa;
2580		}
2581	}
2582	if (besta) {
2583		ifnet_lock_done(ifp);
2584		return(besta);
2585	}
2586
2587	TAILQ_FOREACH(ifa, &ifp->if_addrlist, ifa_list)
2588	{
2589		if (ifa->ifa_addr->sa_family != AF_INET6)
2590			continue;
2591		if (((struct in6_ifaddr *)ifa)->ia6_flags & IN6_IFF_ANYCAST)
2592			continue; /* XXX: is there any case to allow anycast? */
2593		if (((struct in6_ifaddr *)ifa)->ia6_flags & IN6_IFF_NOTREADY)
2594			continue; /* don't use this interface */
2595		if (((struct in6_ifaddr *)ifa)->ia6_flags & IN6_IFF_DETACHED)
2596			continue;
2597		if (((struct in6_ifaddr *)ifa)->ia6_flags & IN6_IFF_DEPRECATED) {
2598			if (ip6_use_deprecated)
2599				dep[1] = (struct in6_ifaddr *)ifa;
2600			continue;
2601		}
2602
2603		ifnet_lock_done(ifp);
2604		return (struct in6_ifaddr *)ifa;
2605	}
2606	ifnet_lock_done(ifp);
2607
2608	/* use the last-resort values, that are, deprecated addresses */
2609	if (dep[0])
2610		return dep[0];
2611	if (dep[1])
2612		return dep[1];
2613
2614	return NULL;
2615}
2616
2617/*
2618 * perform DAD when interface becomes IFF_UP.
2619 */
2620void
2621in6_if_up(
2622	struct ifnet *ifp,
2623	struct in6_aliasreq *ifra)
2624{
2625	struct ifaddr *ifa;
2626	struct in6_ifaddr *ia;
2627	int dad_delay;		/* delay ticks before DAD output */
2628
2629	if (!in6_init2done)
2630		return;
2631
2632	/*
2633	 * special cases, like 6to4, are handled in in6_ifattach
2634	 */
2635	in6_ifattach(ifp, NULL, ifra);
2636
2637	dad_delay = 0;
2638	ifnet_lock_exclusive(ifp);
2639	TAILQ_FOREACH(ifa, &ifp->if_addrlist, ifa_list)
2640	{
2641		if (ifa->ifa_addr->sa_family != AF_INET6)
2642			continue;
2643		ia = (struct in6_ifaddr *)ifa;
2644		if (ia->ia6_flags & IN6_IFF_TENTATIVE)
2645			nd6_dad_start(ifa, &dad_delay);
2646	}
2647	ifnet_lock_done(ifp);
2648}
2649
2650int
2651in6if_do_dad(
2652	struct ifnet *ifp)
2653{
2654	if ((ifp->if_flags & IFF_LOOPBACK) != 0)
2655		return(0);
2656
2657	switch (ifp->if_type) {
2658#if IFT_DUMMY
2659	case IFT_DUMMY:
2660#endif
2661	case IFT_FAITH:
2662		/*
2663		 * These interfaces do not have the IFF_LOOPBACK flag,
2664		 * but loop packets back.  We do not have to do DAD on such
2665		 * interfaces.  We should even omit it, because loop-backed
2666		 * NS would confuse the DAD procedure.
2667		 */
2668		return(0);
2669	default:
2670		/*
2671		 * Our DAD routine requires the interface up and running.
2672		 * However, some interfaces can be up before the RUNNING
2673		 * status.  Additionaly, users may try to assign addresses
2674		 * before the interface becomes up (or running).
2675		 * We simply skip DAD in such a case as a work around.
2676		 * XXX: we should rather mark "tentative" on such addresses,
2677		 * and do DAD after the interface becomes ready.
2678		 */
2679		if ((ifp->if_flags & (IFF_UP|IFF_RUNNING)) !=
2680		    (IFF_UP|IFF_RUNNING))
2681			return(0);
2682
2683		return(1);
2684	}
2685}
2686
2687/*
2688 * Calculate max IPv6 MTU through all the interfaces and store it
2689 * to in6_maxmtu.
2690 */
2691void
2692in6_setmaxmtu()
2693{
2694	unsigned long maxmtu = 0;
2695	struct ifnet *ifp;
2696
2697	ifnet_head_lock_shared();
2698	TAILQ_FOREACH(ifp, &ifnet_head, if_list) {
2699		if ((ifp->if_flags & IFF_LOOPBACK) == 0 &&
2700		    IN6_LINKMTU(ifp) > maxmtu)
2701			maxmtu = IN6_LINKMTU(ifp);
2702	}
2703	ifnet_head_done();
2704	if (maxmtu)	/* update only when maxmtu is positive */
2705		in6_maxmtu = maxmtu;
2706}
2707
2708/*
2709 * Convert sockaddr_in6 to sockaddr_in.  Original sockaddr_in6 must be
2710 * v4 mapped addr or v4 compat addr
2711 */
2712void
2713in6_sin6_2_sin(struct sockaddr_in *sin, struct sockaddr_in6 *sin6)
2714{
2715	bzero(sin, sizeof(*sin));
2716	sin->sin_len = sizeof(struct sockaddr_in);
2717	sin->sin_family = AF_INET;
2718	sin->sin_port = sin6->sin6_port;
2719	sin->sin_addr.s_addr = sin6->sin6_addr.s6_addr32[3];
2720}
2721
2722/* Convert sockaddr_in to sockaddr_in6 in v4 mapped addr format. */
2723void
2724in6_sin_2_v4mapsin6(struct sockaddr_in *sin, struct sockaddr_in6 *sin6)
2725{
2726	bzero(sin6, sizeof(*sin6));
2727	sin6->sin6_len = sizeof(struct sockaddr_in6);
2728	sin6->sin6_family = AF_INET6;
2729	sin6->sin6_port = sin->sin_port;
2730	sin6->sin6_addr.s6_addr32[0] = 0;
2731	sin6->sin6_addr.s6_addr32[1] = 0;
2732	sin6->sin6_addr.s6_addr32[2] = IPV6_ADDR_INT32_SMP;
2733	sin6->sin6_addr.s6_addr32[3] = sin->sin_addr.s_addr;
2734}
2735
2736/* Convert sockaddr_in6 into sockaddr_in. */
2737void
2738in6_sin6_2_sin_in_sock(struct sockaddr *nam)
2739{
2740	struct sockaddr_in *sin_p;
2741	struct sockaddr_in6 sin6;
2742
2743	/*
2744	 * Save original sockaddr_in6 addr and convert it
2745	 * to sockaddr_in.
2746	 */
2747	sin6 = *(struct sockaddr_in6 *)nam;
2748	sin_p = (struct sockaddr_in *)nam;
2749	in6_sin6_2_sin(sin_p, &sin6);
2750}
2751
2752/* Convert sockaddr_in into sockaddr_in6 in v4 mapped addr format. */
2753void
2754in6_sin_2_v4mapsin6_in_sock(struct sockaddr **nam)
2755{
2756	struct sockaddr_in *sin_p;
2757	struct sockaddr_in6 *sin6_p;
2758
2759	MALLOC(sin6_p, struct sockaddr_in6 *, sizeof *sin6_p, M_SONAME,
2760	       M_WAITOK);
2761	sin_p = (struct sockaddr_in *)*nam;
2762	in6_sin_2_v4mapsin6(sin_p, sin6_p);
2763	FREE(*nam, M_SONAME);
2764	*nam = (struct sockaddr *)sin6_p;
2765}
2766
2767/* Posts in6_event_data message kernel events */
2768void
2769in6_post_msg(struct ifnet *ifp, u_long event_code, struct in6_ifaddr *ifa)
2770{
2771	struct kev_msg        ev_msg;
2772	struct kev_in6_data    in6_event_data;
2773
2774	ev_msg.vendor_code    = KEV_VENDOR_APPLE;
2775	ev_msg.kev_class      = KEV_NETWORK_CLASS;
2776	ev_msg.kev_subclass   = KEV_INET6_SUBCLASS;
2777	ev_msg.event_code     = event_code;
2778
2779	in6_event_data.ia_addr         = ifa->ia_addr;
2780	in6_event_data.ia_net          = ifa->ia_net;
2781	in6_event_data.ia_dstaddr      = ifa->ia_dstaddr;
2782	in6_event_data.ia_prefixmask   = ifa->ia_prefixmask;
2783	in6_event_data.ia_plen	       = ifa->ia_plen;
2784	in6_event_data.ia6_flags       = (u_int32_t)ifa->ia6_flags;
2785 	in6_event_data.ia_lifetime     = ifa->ia6_lifetime;
2786
2787	if (ifp != NULL) {
2788		strncpy(&in6_event_data.link_data.if_name[0], ifp->if_name, IFNAMSIZ);
2789		in6_event_data.link_data.if_family = ifp->if_family;
2790		in6_event_data.link_data.if_unit  = (unsigned long) ifp->if_unit;
2791	}
2792
2793	ev_msg.dv[0].data_ptr    = &in6_event_data;
2794	ev_msg.dv[0].data_length = sizeof(struct kev_in6_data);
2795	ev_msg.dv[1].data_length = 0;
2796
2797	kev_post_msg(&ev_msg);
2798}
2799