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