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