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