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