xref: /openbsd/sys/netinet6/in6.c (revision 7186e918)
1 /*	$OpenBSD: in6.c,v 1.265 2024/04/21 17:32:10 florian Exp $	*/
2 /*	$KAME: in6.c,v 1.372 2004/06/14 08:14:21 itojun Exp $	*/
3 
4 /*
5  * Copyright (C) 1995, 1996, 1997, and 1998 WIDE Project.
6  * All rights reserved.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  * 3. Neither the name of the project nor the names of its contributors
17  *    may be used to endorse or promote products derived from this software
18  *    without specific prior written permission.
19  *
20  * THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND
21  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23  * ARE DISCLAIMED.  IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE
24  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
26  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
29  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
30  * SUCH DAMAGE.
31  */
32 
33 /*
34  * Copyright (c) 1982, 1986, 1991, 1993
35  *	The Regents of the University of California.  All rights reserved.
36  *
37  * Redistribution and use in source and binary forms, with or without
38  * modification, are permitted provided that the following conditions
39  * are met:
40  * 1. Redistributions of source code must retain the above copyright
41  *    notice, this list of conditions and the following disclaimer.
42  * 2. Redistributions in binary form must reproduce the above copyright
43  *    notice, this list of conditions and the following disclaimer in the
44  *    documentation and/or other materials provided with the distribution.
45  * 3. Neither the name of the University nor the names of its contributors
46  *    may be used to endorse or promote products derived from this software
47  *    without specific prior written permission.
48  *
49  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
50  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
51  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
52  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
53  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
54  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
55  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
56  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
57  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
58  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
59  * SUCH DAMAGE.
60  *
61  *	@(#)in.c	8.2 (Berkeley) 11/15/93
62  */
63 
64 #include "carp.h"
65 
66 #include <sys/param.h>
67 #include <sys/ioctl.h>
68 #include <sys/errno.h>
69 #include <sys/malloc.h>
70 #include <sys/socket.h>
71 #include <sys/socketvar.h>
72 #include <sys/sockio.h>
73 #include <sys/mbuf.h>
74 #include <sys/systm.h>
75 #include <sys/time.h>
76 #include <sys/kernel.h>
77 #include <sys/syslog.h>
78 
79 #include <net/if.h>
80 #include <net/if_dl.h>
81 #include <net/if_types.h>
82 #include <net/route.h>
83 
84 #include <netinet/in.h>
85 #include <netinet/if_ether.h>
86 
87 #include <netinet6/in6_var.h>
88 #include <netinet/ip6.h>
89 #include <netinet6/ip6_var.h>
90 #include <netinet6/nd6.h>
91 #include <netinet6/mld6_var.h>
92 #ifdef MROUTING
93 #include <netinet6/ip6_mroute.h>
94 #endif
95 #include <netinet6/in6_ifattach.h>
96 #if NCARP > 0
97 #include <netinet/ip_carp.h>
98 #endif
99 
100 /*
101  * Definitions of some constant IP6 addresses.
102  */
103 const struct in6_addr in6addr_any = IN6ADDR_ANY_INIT;
104 const struct in6_addr in6addr_loopback = IN6ADDR_LOOPBACK_INIT;
105 const struct in6_addr in6addr_intfacelocal_allnodes =
106 	IN6ADDR_INTFACELOCAL_ALLNODES_INIT;
107 const struct in6_addr in6addr_linklocal_allnodes =
108 	IN6ADDR_LINKLOCAL_ALLNODES_INIT;
109 const struct in6_addr in6addr_linklocal_allrouters =
110 	IN6ADDR_LINKLOCAL_ALLROUTERS_INIT;
111 
112 const struct in6_addr in6mask0 = IN6MASK0;
113 const struct in6_addr in6mask32 = IN6MASK32;
114 const struct in6_addr in6mask64 = IN6MASK64;
115 const struct in6_addr in6mask96 = IN6MASK96;
116 const struct in6_addr in6mask128 = IN6MASK128;
117 
118 int in6_ioctl(u_long, caddr_t, struct ifnet *, int);
119 int in6_ioctl_change_ifaddr(u_long, caddr_t, struct ifnet *);
120 int in6_ioctl_get(u_long, caddr_t, struct ifnet *);
121 int in6_check_embed_scope(struct sockaddr_in6 *, unsigned int);
122 int in6_clear_scope_id(struct sockaddr_in6 *, unsigned int);
123 int in6_ifinit(struct ifnet *, struct in6_ifaddr *, int);
124 void in6_unlink_ifa(struct in6_ifaddr *, struct ifnet *);
125 
126 const struct sockaddr_in6 sa6_any = {
127 	sizeof(sa6_any), AF_INET6, 0, 0, IN6ADDR_ANY_INIT, 0
128 };
129 
130 int
in6_mask2len(struct in6_addr * mask,u_char * lim0)131 in6_mask2len(struct in6_addr *mask, u_char *lim0)
132 {
133 	int x = 0, y;
134 	u_char *lim = lim0, *p;
135 
136 	/* ignore the scope_id part */
137 	if (lim0 == NULL || lim0 - (u_char *)mask > sizeof(*mask))
138 		lim = (u_char *)mask + sizeof(*mask);
139 	for (p = (u_char *)mask; p < lim; x++, p++) {
140 		if (*p != 0xff)
141 			break;
142 	}
143 	y = 0;
144 	if (p < lim) {
145 		for (y = 0; y < 8; y++) {
146 			if ((*p & (0x80 >> y)) == 0)
147 				break;
148 		}
149 	}
150 
151 	/*
152 	 * when the limit pointer is given, do a stricter check on the
153 	 * remaining bits.
154 	 */
155 	if (p < lim) {
156 		if (y != 0 && (*p & (0x00ff >> y)) != 0)
157 			return (-1);
158 		for (p = p + 1; p < lim; p++)
159 			if (*p != 0)
160 				return (-1);
161 	}
162 
163 	return x * 8 + y;
164 }
165 
166 int
in6_nam2sin6(const struct mbuf * nam,struct sockaddr_in6 ** sin6)167 in6_nam2sin6(const struct mbuf *nam, struct sockaddr_in6 **sin6)
168 {
169 	struct sockaddr *sa = mtod(nam, struct sockaddr *);
170 
171 	if (nam->m_len < offsetof(struct sockaddr, sa_data))
172 		return EINVAL;
173 	if (sa->sa_family != AF_INET6)
174 		return EAFNOSUPPORT;
175 	if (sa->sa_len != nam->m_len)
176 		return EINVAL;
177 	if (sa->sa_len != sizeof(struct sockaddr_in6))
178 		return EINVAL;
179 	*sin6 = satosin6(sa);
180 
181 	return 0;
182 }
183 
184 int
in6_sa2sin6(struct sockaddr * sa,struct sockaddr_in6 ** sin6)185 in6_sa2sin6(struct sockaddr *sa, struct sockaddr_in6 **sin6)
186 {
187 	if (sa->sa_family != AF_INET6)
188 		return EAFNOSUPPORT;
189 	if (sa->sa_len != sizeof(struct sockaddr_in6))
190 		return EINVAL;
191 	*sin6 = satosin6(sa);
192 
193 	return 0;
194 }
195 
196 int
in6_control(struct socket * so,u_long cmd,caddr_t data,struct ifnet * ifp)197 in6_control(struct socket *so, u_long cmd, caddr_t data, struct ifnet *ifp)
198 {
199 	int privileged;
200 
201 	privileged = 0;
202 	if ((so->so_state & SS_PRIV) != 0)
203 		privileged++;
204 
205 	switch (cmd) {
206 #ifdef MROUTING
207 	case SIOCGETSGCNT_IN6:
208 	case SIOCGETMIFCNT_IN6:
209 		return mrt6_ioctl(so, cmd, data);
210 #endif /* MROUTING */
211 	default:
212 		return in6_ioctl(cmd, data, ifp, privileged);
213 	}
214 }
215 
216 int
in6_ioctl(u_long cmd,caddr_t data,struct ifnet * ifp,int privileged)217 in6_ioctl(u_long cmd, caddr_t data, struct ifnet *ifp, int privileged)
218 {
219 	if (ifp == NULL)
220 		return (ENXIO);
221 
222 	switch (cmd) {
223 	case SIOCGIFINFO_IN6:
224 	case SIOCGNBRINFO_IN6:
225 		return (nd6_ioctl(cmd, data, ifp));
226 	case SIOCGIFDSTADDR_IN6:
227 	case SIOCGIFNETMASK_IN6:
228 	case SIOCGIFAFLAG_IN6:
229 	case SIOCGIFALIFETIME_IN6:
230 		return (in6_ioctl_get(cmd, data, ifp));
231 	case SIOCAIFADDR_IN6:
232 	case SIOCDIFADDR_IN6:
233 		if (!privileged)
234 			return (EPERM);
235 		return (in6_ioctl_change_ifaddr(cmd, data, ifp));
236 	case SIOCSIFADDR:
237 	case SIOCSIFDSTADDR:
238 	case SIOCSIFBRDADDR:
239 	case SIOCSIFNETMASK:
240 		/*
241 		 * Do not pass those ioctl to driver handler since they are not
242 		 * properly set up. Instead just error out.
243 		 */
244 		return (EINVAL);
245 	default:
246 		return (EOPNOTSUPP);
247 	}
248 }
249 
250 int
in6_ioctl_change_ifaddr(u_long cmd,caddr_t data,struct ifnet * ifp)251 in6_ioctl_change_ifaddr(u_long cmd, caddr_t data, struct ifnet *ifp)
252 {
253 	struct	in6_ifaddr *ia6 = NULL;
254 	struct	in6_aliasreq *ifra = (struct in6_aliasreq *)data;
255 	struct	sockaddr *sa;
256 	struct	sockaddr_in6 *sa6 = NULL;
257 	int	error = 0, newifaddr = 0, plen;
258 
259 	/*
260 	 * Find address for this interface, if it exists.
261 	 *
262 	 * In netinet code, we have checked ifra_addr in SIOCSIF*ADDR operation
263 	 * only, and used the first interface address as the target of other
264 	 * operations (without checking ifra_addr).  This was because netinet
265 	 * code/API assumed at most 1 interface address per interface.
266 	 * Since IPv6 allows a node to assign multiple addresses
267 	 * on a single interface, we almost always look and check the
268 	 * presence of ifra_addr, and reject invalid ones here.
269 	 * It also decreases duplicated code among SIOC*_IN6 operations.
270 	 *
271 	 * We always require users to specify a valid IPv6 address for
272 	 * the corresponding operation.
273 	 */
274 	switch (cmd) {
275 	case SIOCAIFADDR_IN6:
276 		sa = sin6tosa(&ifra->ifra_addr);
277 		break;
278 	case SIOCDIFADDR_IN6:
279 		sa = sin6tosa(&((struct in6_ifreq *)data)->ifr_addr);
280 		break;
281 	default:
282 		panic("%s: invalid ioctl %lu", __func__, cmd);
283 	}
284 	if (sa->sa_family == AF_INET6) {
285 		error = in6_sa2sin6(sa, &sa6);
286 		if (error)
287 			return (error);
288 	}
289 
290 	KERNEL_LOCK();
291 	NET_LOCK();
292 
293 	if (sa6 != NULL) {
294 		error = in6_check_embed_scope(sa6, ifp->if_index);
295 		if (error)
296 			goto err;
297 		error = in6_clear_scope_id(sa6, ifp->if_index);
298 		if (error)
299 			goto err;
300 		ia6 = in6ifa_ifpwithaddr(ifp, &sa6->sin6_addr);
301 	}
302 
303 	switch (cmd) {
304 	case SIOCDIFADDR_IN6:
305 		/*
306 		 * for IPv4, we look for existing in_ifaddr here to allow
307 		 * "ifconfig if0 delete" to remove the first IPv4 address on
308 		 * the interface.  For IPv6, as the spec allows multiple
309 		 * interface address from the day one, we consider "remove the
310 		 * first one" semantics to be not preferable.
311 		 */
312 		if (ia6 == NULL) {
313 			error = EADDRNOTAVAIL;
314 			break;
315 		}
316 		in6_purgeaddr(&ia6->ia_ifa);
317 		if_addrhooks_run(ifp);
318 		break;
319 
320 	case SIOCAIFADDR_IN6:
321 		if (ifra->ifra_addr.sin6_family != AF_INET6 ||
322 		    ifra->ifra_addr.sin6_len != sizeof(struct sockaddr_in6)) {
323 			error = EAFNOSUPPORT;
324 			break;
325 		}
326 
327 		/* reject read-only flags */
328 		if ((ifra->ifra_flags & IN6_IFF_DUPLICATED) != 0 ||
329 		    (ifra->ifra_flags & IN6_IFF_DETACHED) != 0 ||
330 		    (ifra->ifra_flags & IN6_IFF_DEPRECATED) != 0) {
331 			error = EINVAL;
332 			break;
333 		}
334 
335 		if (ia6 == NULL)
336 			newifaddr = 1;
337 
338 		/*
339 		 * Make the address tentative before joining multicast
340 		 * addresses, so that corresponding MLD responses would
341 		 * not have a tentative source address.
342 		 */
343 		if (newifaddr && in6if_do_dad(ifp))
344 			ifra->ifra_flags |= IN6_IFF_TENTATIVE;
345 
346 		/*
347 		 * first, make or update the interface address structure,
348 		 * and link it to the list. try to enable inet6 if there
349 		 * is no link-local yet.
350 		 */
351 		error = in6_ifattach(ifp);
352 		if (error)
353 			break;
354 		error = in6_update_ifa(ifp, ifra, ia6);
355 		if (error)
356 			break;
357 
358 		ia6 = NULL;
359 		if (sa6 != NULL)
360 			ia6 = in6ifa_ifpwithaddr(ifp, &sa6->sin6_addr);
361 		if (ia6 == NULL) {
362 			/*
363 			 * this can happen when the user specify the 0 valid
364 			 * lifetime.
365 			 */
366 			break;
367 		}
368 
369 		/* Perform DAD, if needed. */
370 		if (ia6->ia6_flags & IN6_IFF_TENTATIVE)
371 			nd6_dad_start(&ia6->ia_ifa);
372 
373 		if (!newifaddr) {
374 			if_addrhooks_run(ifp);
375 			break;
376 		}
377 
378 		plen = in6_mask2len(&ia6->ia_prefixmask.sin6_addr, NULL);
379 		if ((ifp->if_flags & IFF_LOOPBACK) || plen == 128) {
380 			if_addrhooks_run(ifp);
381 			break;	/* No need to install a connected route. */
382 		}
383 
384 		error = rt_ifa_add(&ia6->ia_ifa,
385 		    RTF_CLONING | RTF_CONNECTED | RTF_MPATH,
386 		    ia6->ia_ifa.ifa_addr, ifp->if_rdomain);
387 		if (error) {
388 			in6_purgeaddr(&ia6->ia_ifa);
389 			break;
390 		}
391 		if_addrhooks_run(ifp);
392 		break;
393 	}
394 
395 err:
396 	NET_UNLOCK();
397 	KERNEL_UNLOCK();
398 	return (error);
399 }
400 
401 int
in6_ioctl_get(u_long cmd,caddr_t data,struct ifnet * ifp)402 in6_ioctl_get(u_long cmd, caddr_t data, struct ifnet *ifp)
403 {
404 	struct	in6_ifreq *ifr = (struct in6_ifreq *)data;
405 	struct	in6_ifaddr *ia6 = NULL;
406 	struct	sockaddr *sa;
407 	struct	sockaddr_in6 *sa6 = NULL;
408 	int	error = 0;
409 
410 	sa = sin6tosa(&ifr->ifr_addr);
411 	if (sa->sa_family == AF_INET6) {
412 		sa->sa_len = sizeof(struct sockaddr_in6);
413 		error = in6_sa2sin6(sa, &sa6);
414 		if (error)
415 			return (error);
416 	}
417 
418 	NET_LOCK_SHARED();
419 
420 	if (sa6 != NULL) {
421 		error = in6_check_embed_scope(sa6, ifp->if_index);
422 		if (error)
423 			goto err;
424 		error = in6_clear_scope_id(sa6, ifp->if_index);
425 		if (error)
426 			goto err;
427 		ia6 = in6ifa_ifpwithaddr(ifp, &sa6->sin6_addr);
428 	}
429 
430 	/* must think again about its semantics */
431 	if (ia6 == NULL) {
432 		error = EADDRNOTAVAIL;
433 		goto err;
434 	}
435 
436 	switch (cmd) {
437 	case SIOCGIFDSTADDR_IN6:
438 		if ((ifp->if_flags & IFF_POINTOPOINT) == 0) {
439 			error = EINVAL;
440 			break;
441 		}
442 		/*
443 		 * XXX: should we check if ifa_dstaddr is NULL and return
444 		 * an error?
445 		 */
446 		ifr->ifr_dstaddr = ia6->ia_dstaddr;
447 		break;
448 
449 	case SIOCGIFNETMASK_IN6:
450 		ifr->ifr_addr = ia6->ia_prefixmask;
451 		break;
452 
453 	case SIOCGIFAFLAG_IN6:
454 		ifr->ifr_ifru.ifru_flags6 = ia6->ia6_flags;
455 		break;
456 
457 	case SIOCGIFALIFETIME_IN6:
458 		ifr->ifr_ifru.ifru_lifetime = ia6->ia6_lifetime;
459 		if (ia6->ia6_lifetime.ia6t_vltime != ND6_INFINITE_LIFETIME) {
460 			time_t expire, maxexpire;
461 			struct in6_addrlifetime *retlt =
462 			    &ifr->ifr_ifru.ifru_lifetime;
463 
464 			/*
465 			 * XXX: adjust expiration time assuming time_t is
466 			 * signed.
467 			 */
468 			maxexpire =
469 			    (time_t)~(1ULL << ((sizeof(maxexpire) * 8) - 1));
470 			if (ia6->ia6_lifetime.ia6t_vltime <
471 			    maxexpire - ia6->ia6_updatetime) {
472 				expire = ia6->ia6_updatetime +
473 				    ia6->ia6_lifetime.ia6t_vltime;
474 				if (expire != 0) {
475 					expire -= getuptime();
476 					expire += gettime();
477 				}
478 				retlt->ia6t_expire = expire;
479 			} else
480 				retlt->ia6t_expire = maxexpire;
481 		}
482 		if (ia6->ia6_lifetime.ia6t_pltime != ND6_INFINITE_LIFETIME) {
483 			time_t expire, maxexpire;
484 			struct in6_addrlifetime *retlt =
485 			    &ifr->ifr_ifru.ifru_lifetime;
486 
487 			/*
488 			 * XXX: adjust expiration time assuming time_t is
489 			 * signed.
490 			 */
491 			maxexpire =
492 			    (time_t)~(1ULL << ((sizeof(maxexpire) * 8) - 1));
493 			if (ia6->ia6_lifetime.ia6t_pltime <
494 			    maxexpire - ia6->ia6_updatetime) {
495 				expire = ia6->ia6_updatetime +
496 				    ia6->ia6_lifetime.ia6t_pltime;
497 				if (expire != 0) {
498 					expire -= getuptime();
499 					expire += gettime();
500 				}
501 				retlt->ia6t_preferred = expire;
502 			} else
503 				retlt->ia6t_preferred = maxexpire;
504 		}
505 		break;
506 
507 	default:
508 		panic("%s: invalid ioctl %lu", __func__, cmd);
509 	}
510 
511 err:
512 	NET_UNLOCK_SHARED();
513 	return (error);
514 }
515 
516 int
in6_check_embed_scope(struct sockaddr_in6 * sa6,unsigned int ifidx)517 in6_check_embed_scope(struct sockaddr_in6 *sa6, unsigned int ifidx)
518 {
519 	if (IN6_IS_ADDR_LINKLOCAL(&sa6->sin6_addr)) {
520 		if (sa6->sin6_addr.s6_addr16[1] == 0) {
521 			/* link ID is not embedded by the user */
522 			sa6->sin6_addr.s6_addr16[1] = htons(ifidx);
523 		} else if (sa6->sin6_addr.s6_addr16[1] != htons(ifidx))
524 			return EINVAL;	/* link ID contradicts */
525 	}
526 	return 0;
527 }
528 
529 int
in6_clear_scope_id(struct sockaddr_in6 * sa6,unsigned int ifidx)530 in6_clear_scope_id(struct sockaddr_in6 *sa6, unsigned int ifidx)
531 {
532 	if (IN6_IS_ADDR_LINKLOCAL(&sa6->sin6_addr)) {
533 		if (sa6->sin6_scope_id) {
534 			if (sa6->sin6_scope_id != (u_int32_t)ifidx)
535 				return EINVAL;
536 			sa6->sin6_scope_id = 0; /* XXX: good way? */
537 		}
538 	}
539 	return 0;
540 }
541 
542 /*
543  * Update parameters of an IPv6 interface address.
544  * If necessary, a new entry is created and linked into address chains.
545  * This function is separated from in6_control().
546  */
547 int
in6_update_ifa(struct ifnet * ifp,struct in6_aliasreq * ifra,struct in6_ifaddr * ia6)548 in6_update_ifa(struct ifnet *ifp, struct in6_aliasreq *ifra,
549     struct in6_ifaddr *ia6)
550 {
551 	int error = 0, hostIsNew = 0, plen = -1;
552 	struct sockaddr_in6 dst6;
553 	struct in6_addrlifetime *lt;
554 	struct in6_multi_mship *imm;
555 	struct rtentry *rt;
556 	char addr[INET6_ADDRSTRLEN];
557 
558 	NET_ASSERT_LOCKED();
559 
560 	/* Validate parameters */
561 	if (ifp == NULL || ifra == NULL) /* this maybe redundant */
562 		return (EINVAL);
563 
564 	/*
565 	 * The destination address for a p2p link or the address of the
566 	 * announcing router for an autoconf address must have a family of
567 	 * AF_UNSPEC or AF_INET6.
568 	 */
569 	if ((ifp->if_flags & IFF_POINTOPOINT) ||
570 	    (ifp->if_flags & IFF_LOOPBACK) ||
571 	    (ifra->ifra_flags & IN6_IFF_AUTOCONF)) {
572 		if (ifra->ifra_dstaddr.sin6_family != AF_INET6 &&
573 		    ifra->ifra_dstaddr.sin6_family != AF_UNSPEC)
574 			return (EAFNOSUPPORT);
575 
576 	} else if (ifra->ifra_dstaddr.sin6_family != AF_UNSPEC)
577 			return (EINVAL);
578 
579 	/*
580 	 * validate ifra_prefixmask.  don't check sin6_family, netmask
581 	 * does not carry fields other than sin6_len.
582 	 */
583 	if (ifra->ifra_prefixmask.sin6_len > sizeof(struct sockaddr_in6))
584 		return (EINVAL);
585 	/*
586 	 * Because the IPv6 address architecture is classless, we require
587 	 * users to specify a (non 0) prefix length (mask) for a new address.
588 	 * We also require the prefix (when specified) mask is valid, and thus
589 	 * reject a non-consecutive mask.
590 	 */
591 	if (ia6 == NULL && ifra->ifra_prefixmask.sin6_len == 0)
592 		return (EINVAL);
593 	if (ifra->ifra_prefixmask.sin6_len != 0) {
594 		plen = in6_mask2len(&ifra->ifra_prefixmask.sin6_addr,
595 		    (u_char *)&ifra->ifra_prefixmask +
596 		    ifra->ifra_prefixmask.sin6_len);
597 		if (plen <= 0)
598 			return (EINVAL);
599 	} else {
600 		/*
601 		 * In this case, ia6 must not be NULL.  We just use its prefix
602 		 * length.
603 		 */
604 		plen = in6_mask2len(&ia6->ia_prefixmask.sin6_addr, NULL);
605 	}
606 
607 	dst6 = ifra->ifra_dstaddr;
608 	if (dst6.sin6_family == AF_INET6) {
609 		error = in6_check_embed_scope(&dst6, ifp->if_index);
610 		if (error)
611 			return error;
612 
613 		if (((ifp->if_flags & IFF_POINTOPOINT) ||
614 		    (ifp->if_flags & IFF_LOOPBACK)) && plen != 128)
615 			return (EINVAL);
616 	}
617 	/* lifetime consistency check */
618 	lt = &ifra->ifra_lifetime;
619 	if (lt->ia6t_pltime > lt->ia6t_vltime)
620 		return (EINVAL);
621 	if (lt->ia6t_vltime == 0) {
622 		/*
623 		 * the following log might be noisy, but this is a typical
624 		 * configuration mistake or a tool's bug.
625 		 */
626 		nd6log((LOG_INFO, "%s: valid lifetime is 0 for %s\n", __func__,
627 		    inet_ntop(AF_INET6, &ifra->ifra_addr.sin6_addr,
628 		    addr, sizeof(addr))));
629 
630 		if (ia6 == NULL)
631 			return (0); /* there's nothing to do */
632 	}
633 
634 	/*
635 	 * If this is a new address, allocate a new ifaddr and link it
636 	 * into chains.
637 	 */
638 	if (ia6 == NULL) {
639 		hostIsNew = 1;
640 		ia6 = malloc(sizeof(*ia6), M_IFADDR, M_WAITOK | M_ZERO);
641 		refcnt_init_trace(&ia6->ia_ifa.ifa_refcnt,
642 		    DT_REFCNT_IDX_IFADDR);
643 		LIST_INIT(&ia6->ia6_memberships);
644 		/* Initialize the address and masks, and put time stamp */
645 		ia6->ia_ifa.ifa_addr = sin6tosa(&ia6->ia_addr);
646 		ia6->ia_addr.sin6_family = AF_INET6;
647 		ia6->ia_addr.sin6_len = sizeof(ia6->ia_addr);
648 		ia6->ia6_updatetime = getuptime();
649 		if ((ifp->if_flags & IFF_POINTOPOINT) ||
650 		    (ifp->if_flags & IFF_LOOPBACK)) {
651 			/*
652 			 * XXX: some functions expect that ifa_dstaddr is not
653 			 * NULL for p2p interfaces.
654 			 */
655 			ia6->ia_ifa.ifa_dstaddr = sin6tosa(&ia6->ia_dstaddr);
656 		} else {
657 			ia6->ia_ifa.ifa_dstaddr = NULL;
658 		}
659 		ia6->ia_ifa.ifa_netmask = sin6tosa(&ia6->ia_prefixmask);
660 
661 		ia6->ia_ifp = ifp;
662 		ia6->ia_addr = ifra->ifra_addr;
663 		ifa_add(ifp, &ia6->ia_ifa);
664 	}
665 
666 	/* set prefix mask */
667 	if (ifra->ifra_prefixmask.sin6_len) {
668 		/*
669 		 * We prohibit changing the prefix length of an existing
670 		 * address, because
671 		 * + such an operation should be rare in IPv6, and
672 		 * + the operation would confuse prefix management.
673 		 */
674 		if (ia6->ia_prefixmask.sin6_len &&
675 		    in6_mask2len(&ia6->ia_prefixmask.sin6_addr, NULL) != plen) {
676 			error = EINVAL;
677 			goto unlink;
678 		}
679 		ia6->ia_prefixmask = ifra->ifra_prefixmask;
680 	}
681 
682 	/*
683 	 * If a new destination address is specified, scrub the old one and
684 	 * install the new destination.
685 	 */
686 	if (((ifp->if_flags & IFF_POINTOPOINT)  ||
687 	    (ifp->if_flags & IFF_LOOPBACK)) && dst6.sin6_family == AF_INET6 &&
688 	    !IN6_ARE_ADDR_EQUAL(&dst6.sin6_addr, &ia6->ia_dstaddr.sin6_addr)) {
689 		struct ifaddr *ifa = &ia6->ia_ifa;
690 
691 		if ((ia6->ia_flags & IFA_ROUTE) != 0 &&
692 		    rt_ifa_del(ifa, RTF_HOST, ifa->ifa_dstaddr,
693 		     ifp->if_rdomain) != 0) {
694 			nd6log((LOG_ERR, "%s: failed to remove a route "
695 			    "to the old destination: %s\n", __func__,
696 			    inet_ntop(AF_INET6, &ia6->ia_addr.sin6_addr,
697 			    addr, sizeof(addr))));
698 			/* proceed anyway... */
699 		} else
700 			ia6->ia_flags &= ~IFA_ROUTE;
701 		ia6->ia_dstaddr = dst6;
702 	}
703 
704 	if ((ifra->ifra_flags & IN6_IFF_AUTOCONF) &&
705 	    dst6.sin6_family == AF_INET6 &&
706 	    !IN6_ARE_ADDR_EQUAL(&dst6.sin6_addr, &ia6->ia_gwaddr.sin6_addr)) {
707 		/* Set or update announcing router */
708 		ia6->ia_gwaddr = dst6;
709 	}
710 
711 	/*
712 	 * Set lifetimes.  We do not refer to ia6t_expire and ia6t_preferred
713 	 * to see if the address is deprecated or invalidated, but initialize
714 	 * these members for applications.
715 	 */
716 	ia6->ia6_updatetime = getuptime();
717 	ia6->ia6_lifetime = ifra->ifra_lifetime;
718 	if (ia6->ia6_lifetime.ia6t_vltime != ND6_INFINITE_LIFETIME) {
719 		ia6->ia6_lifetime.ia6t_expire =
720 		    getuptime() + ia6->ia6_lifetime.ia6t_vltime;
721 	} else
722 		ia6->ia6_lifetime.ia6t_expire = 0;
723 	if (ia6->ia6_lifetime.ia6t_pltime != ND6_INFINITE_LIFETIME) {
724 		ia6->ia6_lifetime.ia6t_preferred =
725 		    getuptime() + ia6->ia6_lifetime.ia6t_pltime;
726 	} else
727 		ia6->ia6_lifetime.ia6t_preferred = 0;
728 
729 	/* reset the interface and routing table appropriately. */
730 	if ((error = in6_ifinit(ifp, ia6, hostIsNew)) != 0)
731 		goto unlink;
732 
733 	/* re-run DAD */
734 	if (ia6->ia6_flags & (IN6_IFF_TENTATIVE|IN6_IFF_DUPLICATED))
735 		ifra->ifra_flags |= IN6_IFF_TENTATIVE;
736 	/*
737 	 * configure address flags.
738 	 */
739 	ia6->ia6_flags = ifra->ifra_flags;
740 
741 	nd6_expire_timer_update(ia6);
742 
743 	/*
744 	 * We are done if we have simply modified an existing address.
745 	 */
746 	if (!hostIsNew)
747 		return (error);
748 
749 	/*
750 	 * Beyond this point, we should call in6_purgeaddr upon an error,
751 	 * not just go to unlink.
752 	 */
753 
754 	/* join necessary multiast groups */
755 	if ((ifp->if_flags & IFF_MULTICAST) != 0) {
756 		struct sockaddr_in6 mltaddr, mltmask;
757 
758 		/* join solicited multicast addr for new host id */
759 		struct sockaddr_in6 llsol;
760 
761 		bzero(&llsol, sizeof(llsol));
762 		llsol.sin6_family = AF_INET6;
763 		llsol.sin6_len = sizeof(llsol);
764 		llsol.sin6_addr.s6_addr16[0] = htons(0xff02);
765 		llsol.sin6_addr.s6_addr16[1] = htons(ifp->if_index);
766 		llsol.sin6_addr.s6_addr32[1] = 0;
767 		llsol.sin6_addr.s6_addr32[2] = htonl(1);
768 		llsol.sin6_addr.s6_addr32[3] =
769 		    ifra->ifra_addr.sin6_addr.s6_addr32[3];
770 		llsol.sin6_addr.s6_addr8[12] = 0xff;
771 		imm = in6_joingroup(ifp, &llsol.sin6_addr, &error);
772 		if (!imm)
773 			goto cleanup;
774 		LIST_INSERT_HEAD(&ia6->ia6_memberships, imm, i6mm_chain);
775 
776 		bzero(&mltmask, sizeof(mltmask));
777 		mltmask.sin6_len = sizeof(struct sockaddr_in6);
778 		mltmask.sin6_family = AF_INET6;
779 		mltmask.sin6_addr = in6mask32;
780 
781 		/*
782 		 * join link-local all-nodes address
783 		 */
784 		bzero(&mltaddr, sizeof(mltaddr));
785 		mltaddr.sin6_len = sizeof(struct sockaddr_in6);
786 		mltaddr.sin6_family = AF_INET6;
787 		mltaddr.sin6_addr = in6addr_linklocal_allnodes;
788 		mltaddr.sin6_addr.s6_addr16[1] = htons(ifp->if_index);
789 		mltaddr.sin6_scope_id = 0;
790 
791 		/*
792 		 * XXX: do we really need this automatic routes?
793 		 * We should probably reconsider this stuff.  Most applications
794 		 * actually do not need the routes, since they usually specify
795 		 * the outgoing interface.
796 		 */
797 		rt = rtalloc(sin6tosa(&mltaddr), 0, ifp->if_rdomain);
798 		if (rt) {
799 			/* 32bit came from "mltmask" */
800 			if (memcmp(&mltaddr.sin6_addr,
801 			    &satosin6(rt_key(rt))->sin6_addr,
802 			    32 / 8)) {
803 				rtfree(rt);
804 				rt = NULL;
805 			}
806 		}
807 		if (!rt) {
808 			struct rt_addrinfo info;
809 
810 			bzero(&info, sizeof(info));
811 			info.rti_ifa = &ia6->ia_ifa;
812 			info.rti_info[RTAX_DST] = sin6tosa(&mltaddr);
813 			info.rti_info[RTAX_GATEWAY] = sin6tosa(&ia6->ia_addr);
814 			info.rti_info[RTAX_NETMASK] = sin6tosa(&mltmask);
815 			info.rti_info[RTAX_IFA] = sin6tosa(&ia6->ia_addr);
816 			info.rti_flags = RTF_MULTICAST;
817 			error = rtrequest(RTM_ADD, &info, RTP_CONNECTED, NULL,
818 			    ifp->if_rdomain);
819 			if (error)
820 				goto cleanup;
821 		} else {
822 			rtfree(rt);
823 		}
824 		imm = in6_joingroup(ifp, &mltaddr.sin6_addr, &error);
825 		if (!imm)
826 			goto cleanup;
827 		LIST_INSERT_HEAD(&ia6->ia6_memberships, imm, i6mm_chain);
828 
829 		/*
830 		 * join interface-local all-nodes address.
831 		 * (ff01::1%ifN, and ff01::%ifN/32)
832 		 */
833 		bzero(&mltaddr, sizeof(mltaddr));
834 		mltaddr.sin6_len = sizeof(struct sockaddr_in6);
835 		mltaddr.sin6_family = AF_INET6;
836 		mltaddr.sin6_addr = in6addr_intfacelocal_allnodes;
837 		mltaddr.sin6_addr.s6_addr16[1] = htons(ifp->if_index);
838 		mltaddr.sin6_scope_id = 0;
839 
840 		/* XXX: again, do we really need the route? */
841 		rt = rtalloc(sin6tosa(&mltaddr), 0, ifp->if_rdomain);
842 		if (rt) {
843 			/* 32bit came from "mltmask" */
844 			if (memcmp(&mltaddr.sin6_addr,
845 			    &satosin6(rt_key(rt))->sin6_addr,
846 			    32 / 8)) {
847 				rtfree(rt);
848 				rt = NULL;
849 			}
850 		}
851 		if (!rt) {
852 			struct rt_addrinfo info;
853 
854 			bzero(&info, sizeof(info));
855 			info.rti_ifa = &ia6->ia_ifa;
856 			info.rti_info[RTAX_DST] = sin6tosa(&mltaddr);
857 			info.rti_info[RTAX_GATEWAY] = sin6tosa(&ia6->ia_addr);
858 			info.rti_info[RTAX_NETMASK] = sin6tosa(&mltmask);
859 			info.rti_info[RTAX_IFA] = sin6tosa(&ia6->ia_addr);
860 			info.rti_flags = RTF_MULTICAST;
861 			error = rtrequest(RTM_ADD, &info, RTP_CONNECTED, NULL,
862 			    ifp->if_rdomain);
863 			if (error)
864 				goto cleanup;
865 		} else {
866 			rtfree(rt);
867 		}
868 		imm = in6_joingroup(ifp, &mltaddr.sin6_addr, &error);
869 		if (!imm)
870 			goto cleanup;
871 		LIST_INSERT_HEAD(&ia6->ia6_memberships, imm, i6mm_chain);
872 	}
873 
874 	return (error);
875 
876   unlink:
877 	/*
878 	 * XXX: if a change of an existing address failed, keep the entry
879 	 * anyway.
880 	 */
881 	if (hostIsNew)
882 		in6_unlink_ifa(ia6, ifp);
883 	return (error);
884 
885   cleanup:
886 	in6_purgeaddr(&ia6->ia_ifa);
887 	return error;
888 }
889 
890 void
in6_purgeaddr(struct ifaddr * ifa)891 in6_purgeaddr(struct ifaddr *ifa)
892 {
893 	struct ifnet *ifp = ifa->ifa_ifp;
894 	struct in6_ifaddr *ia6 = ifatoia6(ifa);
895 	struct in6_multi_mship *imm;
896 
897 	/* stop DAD processing */
898 	nd6_dad_stop(ifa);
899 
900 	/*
901 	 * delete route to the destination of the address being purged.
902 	 * The interface must be p2p or loopback in this case.
903 	 */
904 	if ((ifp->if_flags & IFF_POINTOPOINT) && (ia6->ia_flags & IFA_ROUTE) &&
905 	    ia6->ia_dstaddr.sin6_len != 0) {
906 		int e;
907 
908 		e = rt_ifa_del(ifa, RTF_HOST, ifa->ifa_dstaddr,
909 		    ifp->if_rdomain);
910 		if (e != 0) {
911 			char addr[INET6_ADDRSTRLEN];
912 			log(LOG_ERR, "in6_purgeaddr: failed to remove "
913 			    "a route to the p2p destination: %s on %s, "
914 			    "errno=%d\n",
915 			    inet_ntop(AF_INET6, &ia6->ia_addr.sin6_addr,
916 				addr, sizeof(addr)),
917 			    ifp->if_xname, e);
918 			/* proceed anyway... */
919 		} else
920 			ia6->ia_flags &= ~IFA_ROUTE;
921 	}
922 
923 	/* Remove ownaddr's loopback rtentry, if it exists. */
924 	rt_ifa_dellocal(&(ia6->ia_ifa));
925 
926 	/*
927 	 * leave from multicast groups we have joined for the interface
928 	 */
929 	while (!LIST_EMPTY(&ia6->ia6_memberships)) {
930 		imm = LIST_FIRST(&ia6->ia6_memberships);
931 		LIST_REMOVE(imm, i6mm_chain);
932 		in6_leavegroup(imm);
933 	}
934 
935 	in6_unlink_ifa(ia6, ifp);
936 }
937 
938 void
in6_unlink_ifa(struct in6_ifaddr * ia6,struct ifnet * ifp)939 in6_unlink_ifa(struct in6_ifaddr *ia6, struct ifnet *ifp)
940 {
941 	struct ifaddr *ifa = &ia6->ia_ifa;
942 	int plen;
943 
944 	NET_ASSERT_LOCKED();
945 
946 	/* Release the reference to the base prefix. */
947 	plen = in6_mask2len(&ia6->ia_prefixmask.sin6_addr, NULL);
948 	if ((ifp->if_flags & IFF_LOOPBACK) == 0 && plen != 128) {
949 		rt_ifa_del(ifa, RTF_CLONING | RTF_CONNECTED,
950 		    ifa->ifa_addr, ifp->if_rdomain);
951 	}
952 
953 	rt_ifa_purge(ifa);
954 	ifa_del(ifp, ifa);
955 
956 	ia6->ia_ifp = NULL;
957 	ifafree(ifa);
958 }
959 
960 /*
961  * Initialize an interface's inet6 address
962  * and routing table entry.
963  */
964 int
in6_ifinit(struct ifnet * ifp,struct in6_ifaddr * ia6,int newhost)965 in6_ifinit(struct ifnet *ifp, struct in6_ifaddr *ia6, int newhost)
966 {
967 	int	error = 0, plen, ifacount = 0;
968 	struct ifaddr *ifa;
969 
970 	NET_ASSERT_LOCKED();
971 
972 	/*
973 	 * Give the interface a chance to initialize
974 	 * if this is its first address (or it is a CARP interface)
975 	 * and to validate the address if necessary.
976 	 */
977 	TAILQ_FOREACH(ifa, &ifp->if_addrlist, ifa_list) {
978 		if (ifa->ifa_addr->sa_family != AF_INET6)
979 			continue;
980 		ifacount++;
981 	}
982 
983 	if ((ifacount <= 1 || ifp->if_type == IFT_CARP ||
984 	    (ifp->if_flags & (IFF_LOOPBACK|IFF_POINTOPOINT))) &&
985 	    (error = (*ifp->if_ioctl)(ifp, SIOCSIFADDR, (caddr_t)ia6))) {
986 		return (error);
987 	}
988 
989 	ia6->ia_ifa.ifa_metric = ifp->if_metric;
990 
991 	/* we could do in(6)_socktrim here, but just omit it at this moment. */
992 
993 	/*
994 	 * Special case:
995 	 * If the destination address is specified for a point-to-point
996 	 * interface, install a route to the destination as an interface
997 	 * direct route.
998 	 */
999 	plen = in6_mask2len(&ia6->ia_prefixmask.sin6_addr, NULL); /* XXX */
1000 	if ((ifp->if_flags & IFF_POINTOPOINT) && plen == 128 &&
1001 	    ia6->ia_dstaddr.sin6_family == AF_INET6) {
1002 		ifa = &ia6->ia_ifa;
1003 		error = rt_ifa_add(ifa, RTF_HOST | RTF_MPATH,
1004 		    ifa->ifa_dstaddr, ifp->if_rdomain);
1005 		if (error != 0)
1006 			return (error);
1007 		ia6->ia_flags |= IFA_ROUTE;
1008 	}
1009 
1010 	if (newhost)
1011 		error = rt_ifa_addlocal(&(ia6->ia_ifa));
1012 
1013 	return (error);
1014 }
1015 
1016 /*
1017  * Add an address to the list of IP6 multicast addresses for a
1018  * given interface.
1019  */
1020 struct in6_multi *
in6_addmulti(struct in6_addr * maddr6,struct ifnet * ifp,int * errorp)1021 in6_addmulti(struct in6_addr *maddr6, struct ifnet *ifp, int *errorp)
1022 {
1023 	struct	in6_ifreq ifr;
1024 	struct	in6_multi *in6m;
1025 
1026 	NET_ASSERT_LOCKED();
1027 
1028 	*errorp = 0;
1029 	/*
1030 	 * See if address already in list.
1031 	 */
1032 	IN6_LOOKUP_MULTI(*maddr6, ifp, in6m);
1033 	if (in6m != NULL) {
1034 		/*
1035 		 * Found it; just increment the reference count.
1036 		 */
1037 		refcnt_take(&in6m->in6m_refcnt);
1038 	} else {
1039 		/*
1040 		 * New address; allocate a new multicast record
1041 		 * and link it into the interface's multicast list.
1042 		 */
1043 		in6m = malloc(sizeof(*in6m), M_IPMADDR, M_NOWAIT | M_ZERO);
1044 		if (in6m == NULL) {
1045 			*errorp = ENOBUFS;
1046 			return (NULL);
1047 		}
1048 
1049 		in6m->in6m_sin.sin6_len = sizeof(struct sockaddr_in6);
1050 		in6m->in6m_sin.sin6_family = AF_INET6;
1051 		in6m->in6m_sin.sin6_addr = *maddr6;
1052 		refcnt_init_trace(&in6m->in6m_refcnt, DT_REFCNT_IDX_IFMADDR);
1053 		in6m->in6m_ifidx = ifp->if_index;
1054 		in6m->in6m_ifma.ifma_addr = sin6tosa(&in6m->in6m_sin);
1055 
1056 		/*
1057 		 * Ask the network driver to update its multicast reception
1058 		 * filter appropriately for the new address.
1059 		 */
1060 		memcpy(&ifr.ifr_addr, &in6m->in6m_sin, sizeof(in6m->in6m_sin));
1061 		KERNEL_LOCK();
1062 		*errorp = (*ifp->if_ioctl)(ifp, SIOCADDMULTI, (caddr_t)&ifr);
1063 		KERNEL_UNLOCK();
1064 		if (*errorp) {
1065 			free(in6m, M_IPMADDR, sizeof(*in6m));
1066 			return (NULL);
1067 		}
1068 
1069 		TAILQ_INSERT_HEAD(&ifp->if_maddrlist, &in6m->in6m_ifma,
1070 		    ifma_list);
1071 
1072 		/*
1073 		 * Let MLD6 know that we have joined a new IP6 multicast
1074 		 * group.
1075 		 */
1076 		mld6_start_listening(in6m);
1077 	}
1078 
1079 	return (in6m);
1080 }
1081 
1082 /*
1083  * Delete a multicast address record.
1084  */
1085 void
in6_delmulti(struct in6_multi * in6m)1086 in6_delmulti(struct in6_multi *in6m)
1087 {
1088 	struct	in6_ifreq ifr;
1089 	struct	ifnet *ifp;
1090 
1091 	NET_ASSERT_LOCKED();
1092 
1093 	if (refcnt_rele(&in6m->in6m_refcnt) != 0) {
1094 		/*
1095 		 * No remaining claims to this record; let MLD6 know
1096 		 * that we are leaving the multicast group.
1097 		 */
1098 		mld6_stop_listening(in6m);
1099 		ifp = if_get(in6m->in6m_ifidx);
1100 
1101 		/*
1102 		 * Notify the network driver to update its multicast
1103 		 * reception filter.
1104 		 */
1105 		if (ifp != NULL) {
1106 			bzero(&ifr.ifr_addr, sizeof(struct sockaddr_in6));
1107 			ifr.ifr_addr.sin6_len = sizeof(struct sockaddr_in6);
1108 			ifr.ifr_addr.sin6_family = AF_INET6;
1109 			ifr.ifr_addr.sin6_addr = in6m->in6m_addr;
1110 			KERNEL_LOCK();
1111 			(*ifp->if_ioctl)(ifp, SIOCDELMULTI, (caddr_t)&ifr);
1112 			KERNEL_UNLOCK();
1113 
1114 			TAILQ_REMOVE(&ifp->if_maddrlist, &in6m->in6m_ifma,
1115 			    ifma_list);
1116 		}
1117 		if_put(ifp);
1118 
1119 		free(in6m, M_IPMADDR, sizeof(*in6m));
1120 	}
1121 }
1122 
1123 /*
1124  * Return 1 if the multicast group represented by ``maddr6'' has been
1125  * joined by interface ``ifp'', 0 otherwise.
1126  */
1127 int
in6_hasmulti(struct in6_addr * maddr6,struct ifnet * ifp)1128 in6_hasmulti(struct in6_addr *maddr6, struct ifnet *ifp)
1129 {
1130 	struct in6_multi *in6m;
1131 	int joined;
1132 
1133 	IN6_LOOKUP_MULTI(*maddr6, ifp, in6m);
1134 	joined = (in6m != NULL);
1135 
1136 	return (joined);
1137 }
1138 
1139 struct in6_multi_mship *
in6_joingroup(struct ifnet * ifp,struct in6_addr * addr,int * errorp)1140 in6_joingroup(struct ifnet *ifp, struct in6_addr *addr, int *errorp)
1141 {
1142 	struct in6_multi_mship *imm;
1143 
1144 	imm = malloc(sizeof(*imm), M_IPMADDR, M_NOWAIT);
1145 	if (!imm) {
1146 		*errorp = ENOBUFS;
1147 		return NULL;
1148 	}
1149 	imm->i6mm_maddr = in6_addmulti(addr, ifp, errorp);
1150 	if (!imm->i6mm_maddr) {
1151 		/* *errorp is already set */
1152 		free(imm, M_IPMADDR, sizeof(*imm));
1153 		return NULL;
1154 	}
1155 	return imm;
1156 }
1157 
1158 void
in6_leavegroup(struct in6_multi_mship * imm)1159 in6_leavegroup(struct in6_multi_mship *imm)
1160 {
1161 
1162 	if (imm->i6mm_maddr)
1163 		in6_delmulti(imm->i6mm_maddr);
1164 	free(imm,  M_IPMADDR, sizeof(*imm));
1165 }
1166 
1167 /*
1168  * Find an IPv6 interface link-local address specific to an interface.
1169  */
1170 struct in6_ifaddr *
in6ifa_ifpforlinklocal(struct ifnet * ifp,int ignoreflags)1171 in6ifa_ifpforlinklocal(struct ifnet *ifp, int ignoreflags)
1172 {
1173 	struct ifaddr *ifa;
1174 
1175 	TAILQ_FOREACH(ifa, &ifp->if_addrlist, ifa_list) {
1176 		if (ifa->ifa_addr->sa_family != AF_INET6)
1177 			continue;
1178 		if (IN6_IS_ADDR_LINKLOCAL(IFA_IN6(ifa))) {
1179 			if ((ifatoia6(ifa)->ia6_flags & ignoreflags) != 0)
1180 				continue;
1181 			break;
1182 		}
1183 	}
1184 
1185 	return (ifatoia6(ifa));
1186 }
1187 
1188 
1189 /*
1190  * find the internet address corresponding to a given interface and address.
1191  */
1192 struct in6_ifaddr *
in6ifa_ifpwithaddr(struct ifnet * ifp,struct in6_addr * addr)1193 in6ifa_ifpwithaddr(struct ifnet *ifp, struct in6_addr *addr)
1194 {
1195 	struct ifaddr *ifa;
1196 
1197 	TAILQ_FOREACH(ifa, &ifp->if_addrlist, ifa_list) {
1198 		if (ifa->ifa_addr->sa_family != AF_INET6)
1199 			continue;
1200 		if (IN6_ARE_ADDR_EQUAL(addr, IFA_IN6(ifa)))
1201 			break;
1202 	}
1203 
1204 	return (ifatoia6(ifa));
1205 }
1206 
1207 /*
1208  * Get a scope of the address. Node-local, link-local, site-local or global.
1209  */
1210 int
in6_addrscope(struct in6_addr * addr)1211 in6_addrscope(struct in6_addr *addr)
1212 {
1213 	int scope;
1214 
1215 	if (addr->s6_addr8[0] == 0xfe) {
1216 		scope = addr->s6_addr8[1] & 0xc0;
1217 
1218 		switch (scope) {
1219 		case 0x80:
1220 			return __IPV6_ADDR_SCOPE_LINKLOCAL;
1221 			break;
1222 		case 0xc0:
1223 			return __IPV6_ADDR_SCOPE_SITELOCAL;
1224 			break;
1225 		default:
1226 			return __IPV6_ADDR_SCOPE_GLOBAL; /* just in case */
1227 			break;
1228 		}
1229 	}
1230 
1231 
1232 	if (addr->s6_addr8[0] == 0xff) {
1233 		scope = addr->s6_addr8[1] & 0x0f;
1234 
1235 		/*
1236 		 * due to other scope such as reserved,
1237 		 * return scope doesn't work.
1238 		 */
1239 		switch (scope) {
1240 		case __IPV6_ADDR_SCOPE_INTFACELOCAL:
1241 			return __IPV6_ADDR_SCOPE_INTFACELOCAL;
1242 			break;
1243 		case __IPV6_ADDR_SCOPE_LINKLOCAL:
1244 			return __IPV6_ADDR_SCOPE_LINKLOCAL;
1245 			break;
1246 		case __IPV6_ADDR_SCOPE_SITELOCAL:
1247 			return __IPV6_ADDR_SCOPE_SITELOCAL;
1248 			break;
1249 		default:
1250 			return __IPV6_ADDR_SCOPE_GLOBAL;
1251 			break;
1252 		}
1253 	}
1254 
1255 	if (bcmp(&in6addr_loopback, addr, sizeof(*addr) - 1) == 0) {
1256 		if (addr->s6_addr8[15] == 1) /* loopback */
1257 			return __IPV6_ADDR_SCOPE_INTFACELOCAL;
1258 		if (addr->s6_addr8[15] == 0) /* unspecified */
1259 			return __IPV6_ADDR_SCOPE_LINKLOCAL;
1260 	}
1261 
1262 	return __IPV6_ADDR_SCOPE_GLOBAL;
1263 }
1264 
1265 int
in6_addr2scopeid(unsigned int ifidx,struct in6_addr * addr)1266 in6_addr2scopeid(unsigned int ifidx, struct in6_addr *addr)
1267 {
1268 	int scope = in6_addrscope(addr);
1269 
1270 	switch(scope) {
1271 	case __IPV6_ADDR_SCOPE_INTFACELOCAL:
1272 	case __IPV6_ADDR_SCOPE_LINKLOCAL:
1273 		/* XXX: we do not distinguish between a link and an I/F. */
1274 		return (ifidx);
1275 
1276 	case __IPV6_ADDR_SCOPE_SITELOCAL:
1277 		return (0);	/* XXX: invalid. */
1278 
1279 	default:
1280 		return (0);	/* XXX: treat as global. */
1281 	}
1282 }
1283 
1284 /*
1285  * return length of part which dst and src are equal
1286  * hard coding...
1287  */
1288 int
in6_matchlen(struct in6_addr * src,struct in6_addr * dst)1289 in6_matchlen(struct in6_addr *src, struct in6_addr *dst)
1290 {
1291 	int match = 0;
1292 	u_char *s = (u_char *)src, *d = (u_char *)dst;
1293 	u_char *lim = s + 16, r;
1294 
1295 	while (s < lim)
1296 		if ((r = (*d++ ^ *s++)) != 0) {
1297 			while (r < 128) {
1298 				match++;
1299 				r <<= 1;
1300 			}
1301 			break;
1302 		} else
1303 			match += 8;
1304 	return match;
1305 }
1306 
1307 void
in6_prefixlen2mask(struct in6_addr * maskp,int len)1308 in6_prefixlen2mask(struct in6_addr *maskp, int len)
1309 {
1310 	u_char maskarray[8] = {0x80, 0xc0, 0xe0, 0xf0, 0xf8, 0xfc, 0xfe, 0xff};
1311 	int bytelen, bitlen, i;
1312 
1313 	/* sanity check */
1314 	if (0 > len || len > 128) {
1315 		log(LOG_ERR, "in6_prefixlen2mask: invalid prefix length(%d)\n",
1316 		    len);
1317 		return;
1318 	}
1319 
1320 	bzero(maskp, sizeof(*maskp));
1321 	bytelen = len / 8;
1322 	bitlen = len % 8;
1323 	for (i = 0; i < bytelen; i++)
1324 		maskp->s6_addr[i] = 0xff;
1325 	/* len == 128 is ok because bitlen == 0 then */
1326 	if (bitlen)
1327 		maskp->s6_addr[bytelen] = maskarray[bitlen - 1];
1328 }
1329 
1330 /*
1331  * return the best address out of the same scope
1332  */
1333 struct in6_ifaddr *
in6_ifawithscope(struct ifnet * oifp,struct in6_addr * dst,u_int rdomain,struct rtentry * rt)1334 in6_ifawithscope(struct ifnet *oifp, struct in6_addr *dst, u_int rdomain,
1335     struct rtentry *rt)
1336 {
1337 	int dst_scope =	in6_addrscope(dst), src_scope, best_scope = 0;
1338 	int blen = -1;
1339 	struct ifaddr *ifa;
1340 	struct ifnet *ifp;
1341 	struct in6_ifaddr *ia6_best = NULL;
1342 	struct in6_addr *gw6 = NULL;
1343 
1344 	if (rt) {
1345 		if (rt->rt_gateway != NULL &&
1346 		    rt->rt_gateway->sa_family == AF_INET6)
1347 			gw6 = &(satosin6(rt->rt_gateway)->sin6_addr);
1348 	}
1349 
1350 	if (oifp == NULL) {
1351 		printf("%s: output interface is not specified\n", __func__);
1352 		return (NULL);
1353 	}
1354 
1355 	/* We search for all addresses on all interfaces from the beginning. */
1356 	TAILQ_FOREACH(ifp, &ifnetlist, if_list) {
1357 		if (ifp->if_rdomain != rdomain)
1358 			continue;
1359 #if NCARP > 0
1360 		/*
1361 		 * Never use a carp address of an interface which is not
1362 		 * the master.
1363 		 */
1364 		if (ifp->if_type == IFT_CARP && !carp_iamatch(ifp))
1365 			continue;
1366 #endif
1367 
1368 		/*
1369 		 * We can never take an address that breaks the scope zone
1370 		 * of the destination.
1371 		 */
1372 		if (in6_addr2scopeid(ifp->if_index, dst) !=
1373 		    in6_addr2scopeid(oifp->if_index, dst))
1374 			continue;
1375 
1376 		TAILQ_FOREACH(ifa, &ifp->if_addrlist, ifa_list) {
1377 			int tlen = -1;
1378 
1379 			if (ifa->ifa_addr->sa_family != AF_INET6)
1380 				continue;
1381 
1382 			src_scope = in6_addrscope(IFA_IN6(ifa));
1383 
1384 			/*
1385 			 * Don't use an address before completing DAD
1386 			 * nor a duplicated address.
1387 			 */
1388 			if (ifatoia6(ifa)->ia6_flags &
1389 			    (IN6_IFF_TENTATIVE|IN6_IFF_DUPLICATED))
1390 				continue;
1391 
1392 			/*
1393 			 * RFC 6724 allows anycast addresses as source address
1394 			 * because the restriction was removed in RFC 4291.
1395 			 * However RFC 4443 states that ICMPv6 responses
1396 			 * MUST use a unicast source address.
1397 			 *
1398 			 * XXX Skip anycast addresses for now since
1399 			 * icmp6_reflect() uses this function for source
1400 			 * address selection.
1401 			 */
1402 			if (ifatoia6(ifa)->ia6_flags & IN6_IFF_ANYCAST)
1403 				continue;
1404 
1405 			if (ifatoia6(ifa)->ia6_flags & IN6_IFF_DETACHED)
1406 				continue;
1407 
1408 			/*
1409 			 * If this is the first address we find,
1410 			 * keep it anyway.
1411 			 */
1412 			if (ia6_best == NULL)
1413 				goto replace;
1414 
1415 			/*
1416 			 * ia6_best is never NULL beyond this line except
1417 			 * within the block labeled "replace".
1418 			 */
1419 
1420 			/*
1421 			 * Rule 2: Prefer appropriate scope.
1422 			 * Find the address with the smallest scope that is
1423 			 * bigger (or equal) to the scope of the destination
1424 			 * address.
1425 			 * Accept an address with smaller scope than the
1426 			 * destination if non exists with bigger scope.
1427 			 */
1428 			if (best_scope < src_scope) {
1429 				if (best_scope < dst_scope)
1430 					goto replace;
1431 				else
1432 					continue;
1433 			} else if (src_scope < best_scope) {
1434 				if (src_scope < dst_scope)
1435 					continue;
1436 				else
1437 					goto replace;
1438 			}
1439 
1440 			/* Rule 3: Avoid deprecated addresses. */
1441 			if (ifatoia6(ifa)->ia6_flags & IN6_IFF_DEPRECATED) {
1442 				/*
1443 				 * Ignore any deprecated addresses if
1444 				 * specified by configuration.
1445 				 */
1446 				if (!ip6_use_deprecated)
1447 					continue;
1448 
1449 				/*
1450 				 * If we have already found a non-deprecated
1451 				 * candidate, just ignore deprecated addresses.
1452 				 */
1453 				if ((ia6_best->ia6_flags & IN6_IFF_DEPRECATED)
1454 				    == 0)
1455 					continue;
1456 			} else if ((ia6_best->ia6_flags & IN6_IFF_DEPRECATED))
1457 				goto replace;
1458 
1459 			/*
1460 			 * Rule 4: Prefer home addresses.
1461 			 * We do not support home addresses.
1462 			 */
1463 
1464 			/* Rule 5: Prefer outgoing interface */
1465 			if (ia6_best->ia_ifp == oifp && ifp != oifp)
1466 				continue;
1467 			if (ia6_best->ia_ifp != oifp && ifp == oifp)
1468 				goto replace;
1469 
1470 			/*
1471 			 * Rule 5.5: Prefer addresses in a prefix advertised
1472 			 * by the next-hop.
1473 			 */
1474 			if (gw6) {
1475 				struct in6_addr *in6_bestgw, *in6_newgw;
1476 
1477 				in6_bestgw = &ia6_best->ia_gwaddr.sin6_addr;
1478 				in6_newgw = &ifatoia6(ifa)->ia_gwaddr.sin6_addr;
1479 				if (!IN6_ARE_ADDR_EQUAL(in6_bestgw, gw6) &&
1480 				    IN6_ARE_ADDR_EQUAL(in6_newgw, gw6))
1481 					goto replace;
1482 			}
1483 
1484 			/*
1485 			 * Rule 6: Prefer matching label.
1486 			 * We do not implement policy tables.
1487 			 */
1488 
1489 			/* Rule 7: Prefer temporary addresses. */
1490 			if ((ia6_best->ia6_flags & IN6_IFF_TEMPORARY) &&
1491 			    !(ifatoia6(ifa)->ia6_flags & IN6_IFF_TEMPORARY))
1492 				continue;
1493 			if (!(ia6_best->ia6_flags & IN6_IFF_TEMPORARY) &&
1494 			    (ifatoia6(ifa)->ia6_flags & IN6_IFF_TEMPORARY))
1495 				goto replace;
1496 
1497 			/* Rule 8: Use longest matching prefix. */
1498 			tlen = in6_matchlen(IFA_IN6(ifa), dst);
1499 			if (tlen > blen) {
1500 #if NCARP > 0
1501 				/*
1502 				 * Don't let carp interfaces win a tie against
1503 				 * the output interface based on matchlen.
1504 				 * We should only use a carp address if no
1505 				 * other interface has a usable address.
1506 				 * Otherwise, when communicating from a carp
1507 				 * master to a carp backup, the backup system
1508 				 * won't respond since the carp address is also
1509 				 * configured as a local address on the backup.
1510 				 * Note that carp interfaces in backup state
1511 				 * were already skipped above.
1512 				 */
1513 				if (ifp->if_type == IFT_CARP &&
1514 				    oifp->if_type != IFT_CARP)
1515 					continue;
1516 #endif
1517 				goto replace;
1518 			} else if (tlen < blen)
1519 				continue;
1520 
1521 			/*
1522 			 * If the eight rules fail to choose a single address,
1523 			 * the tiebreaker is implementation-specific.
1524 			 */
1525 
1526 			 /* Prefer address with highest pltime. */
1527 			if (ia6_best->ia6_updatetime +
1528 			    ia6_best->ia6_lifetime.ia6t_pltime <
1529 			    ifatoia6(ifa)->ia6_updatetime +
1530 			    ifatoia6(ifa)->ia6_lifetime.ia6t_pltime)
1531 				goto replace;
1532 			else if (ia6_best->ia6_updatetime +
1533 			    ia6_best->ia6_lifetime.ia6t_pltime >
1534 			    ifatoia6(ifa)->ia6_updatetime +
1535 			    ifatoia6(ifa)->ia6_lifetime.ia6t_pltime)
1536 				continue;
1537 
1538 			/* Prefer address with highest vltime. */
1539 			if (ia6_best->ia6_updatetime +
1540 			    ia6_best->ia6_lifetime.ia6t_vltime <
1541 			    ifatoia6(ifa)->ia6_updatetime +
1542 			    ifatoia6(ifa)->ia6_lifetime.ia6t_vltime)
1543 				goto replace;
1544 			else if (ia6_best->ia6_updatetime +
1545 			    ia6_best->ia6_lifetime.ia6t_vltime >
1546 			    ifatoia6(ifa)->ia6_updatetime +
1547 			    ifatoia6(ifa)->ia6_lifetime.ia6t_vltime)
1548 				continue;
1549 
1550 			continue;
1551 		  replace:
1552 			ia6_best = ifatoia6(ifa);
1553 			blen = tlen >= 0 ? tlen :
1554 			    in6_matchlen(IFA_IN6(ifa), dst);
1555 			best_scope =
1556 			    in6_addrscope(&ia6_best->ia_addr.sin6_addr);
1557 		}
1558 	}
1559 
1560 	/* count statistics for future improvements */
1561 	if (ia6_best == NULL)
1562 		ip6stat_inc(ip6s_sources_none);
1563 	else {
1564 		if (oifp == ia6_best->ia_ifp)
1565 			ip6stat_inc(ip6s_sources_sameif + best_scope);
1566 		else
1567 			ip6stat_inc(ip6s_sources_otherif + best_scope);
1568 
1569 		if (best_scope == dst_scope)
1570 			ip6stat_inc(ip6s_sources_samescope + best_scope);
1571 		else
1572 			ip6stat_inc(ip6s_sources_otherscope + best_scope);
1573 
1574 		if ((ia6_best->ia6_flags & IN6_IFF_DEPRECATED) != 0)
1575 			ip6stat_inc(ip6s_sources_deprecated + best_scope);
1576 	}
1577 
1578 	return (ia6_best);
1579 }
1580 
1581 int
in6if_do_dad(struct ifnet * ifp)1582 in6if_do_dad(struct ifnet *ifp)
1583 {
1584 	if ((ifp->if_flags & IFF_LOOPBACK) != 0)
1585 		return (0);
1586 
1587 	switch (ifp->if_type) {
1588 #if NCARP > 0
1589 	case IFT_CARP:
1590 		/*
1591 		 * XXX: DAD does not work currently on carp(4)
1592 		 * so disable it for now.
1593 		 */
1594 		return (0);
1595 #endif
1596 	default:
1597 		/*
1598 		 * Our DAD routine requires the interface up and running.
1599 		 * However, some interfaces can be up before the RUNNING
1600 		 * status.  Additionally, users may try to assign addresses
1601 		 * before the interface becomes up (or running).
1602 		 * We simply skip DAD in such a case as a work around.
1603 		 * XXX: we should rather mark "tentative" on such addresses,
1604 		 * and do DAD after the interface becomes ready.
1605 		 */
1606 		if ((ifp->if_flags & (IFF_UP|IFF_RUNNING)) !=
1607 		    (IFF_UP|IFF_RUNNING))
1608 			return (0);
1609 
1610 		return (1);
1611 	}
1612 }
1613