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