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