xref: /freebsd/sys/netinet6/nd6_rtr.c (revision 9e792f7ef7298080c058fbc2d36a4e60e596dae9)
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: nd6_rtr.c,v 1.111 2001/04/27 01:37:15 jinmei Exp $
32  */
33 
34 #include <sys/cdefs.h>
35 #include "opt_inet.h"
36 #include "opt_inet6.h"
37 
38 #include <sys/param.h>
39 #include <sys/systm.h>
40 #include <sys/malloc.h>
41 #include <sys/mbuf.h>
42 #include <sys/refcount.h>
43 #include <sys/socket.h>
44 #include <sys/sockio.h>
45 #include <sys/time.h>
46 #include <sys/kernel.h>
47 #include <sys/lock.h>
48 #include <sys/errno.h>
49 #include <sys/rmlock.h>
50 #include <sys/rwlock.h>
51 #include <sys/sysctl.h>
52 #include <sys/syslog.h>
53 #include <sys/queue.h>
54 #include <sys/random.h>
55 
56 #include <net/if.h>
57 #include <net/if_var.h>
58 #include <net/if_private.h>
59 #include <net/if_types.h>
60 #include <net/if_dl.h>
61 #include <net/route.h>
62 #include <net/route/nhop.h>
63 #include <net/route/route_ctl.h>
64 #include <net/radix.h>
65 #include <net/vnet.h>
66 
67 #include <netinet/in.h>
68 #include <net/if_llatbl.h>
69 #include <netinet6/in6_var.h>
70 #include <netinet6/in6_ifattach.h>
71 #include <netinet/ip6.h>
72 #include <netinet6/ip6_var.h>
73 #include <netinet6/nd6.h>
74 #include <netinet/icmp6.h>
75 #include <netinet6/scope6_var.h>
76 
77 static struct nd_defrouter *defrtrlist_update(struct nd_defrouter *);
78 static int prelist_update(struct nd_prefixctl *, struct nd_defrouter *,
79     struct mbuf *, int);
80 static int nd6_prefix_onlink(struct nd_prefix *);
81 static int in6_get_tmp_ifid(struct in6_aliasreq *);
82 
83 TAILQ_HEAD(nd6_drhead, nd_defrouter);
84 VNET_DEFINE_STATIC(struct nd6_drhead, nd6_defrouter);
85 #define	V_nd6_defrouter			VNET(nd6_defrouter)
86 
87 VNET_DECLARE(int, nd6_recalc_reachtm_interval);
88 #define	V_nd6_recalc_reachtm_interval	VNET(nd6_recalc_reachtm_interval)
89 
90 VNET_DEFINE_STATIC(struct ifnet *, nd6_defifp);
91 VNET_DEFINE(int, nd6_defifindex);
92 #define	V_nd6_defifp			VNET(nd6_defifp)
93 
94 VNET_DEFINE(int, ip6_use_tempaddr) = 0;
95 
96 VNET_DEFINE(int, ip6_desync_factor);
97 VNET_DEFINE(uint32_t, ip6_temp_max_desync_factor) = TEMP_MAX_DESYNC_FACTOR_BASE;
98 VNET_DEFINE(u_int32_t, ip6_temp_preferred_lifetime) = DEF_TEMP_PREFERRED_LIFETIME;
99 VNET_DEFINE(u_int32_t, ip6_temp_valid_lifetime) = DEF_TEMP_VALID_LIFETIME;
100 
101 VNET_DEFINE(int, ip6_temp_regen_advance) = TEMPADDR_REGEN_ADVANCE;
102 
103 #ifdef EXPERIMENTAL
104 VNET_DEFINE_STATIC(int, nd6_ignore_ipv6_only_ra) = 1;
105 #define	V_nd6_ignore_ipv6_only_ra	VNET(nd6_ignore_ipv6_only_ra)
106 SYSCTL_INT(_net_inet6_icmp6, OID_AUTO,
107     nd6_ignore_ipv6_only_ra, CTLFLAG_VNET | CTLFLAG_RW,
108     &VNET_NAME(nd6_ignore_ipv6_only_ra), 0,
109     "Ignore the 'IPv6-Only flag' in RA messages in compliance with "
110     "draft-ietf-6man-ipv6only-flag");
111 #endif
112 
113 /* RTPREF_MEDIUM has to be 0! */
114 #define RTPREF_HIGH	1
115 #define RTPREF_MEDIUM	0
116 #define RTPREF_LOW	(-1)
117 #define RTPREF_RESERVED	(-2)
118 #define RTPREF_INVALID	(-3)	/* internal */
119 
120 static void
defrouter_ref(struct nd_defrouter * dr)121 defrouter_ref(struct nd_defrouter *dr)
122 {
123 
124 	refcount_acquire(&dr->refcnt);
125 }
126 
127 void
defrouter_rele(struct nd_defrouter * dr)128 defrouter_rele(struct nd_defrouter *dr)
129 {
130 
131 	if (refcount_release(&dr->refcnt))
132 		free(dr, M_IP6NDP);
133 }
134 
135 /*
136  * Remove a router from the global list and optionally stash it in a
137  * caller-supplied queue.
138  */
139 static void
defrouter_unlink(struct nd_defrouter * dr,struct nd6_drhead * drq)140 defrouter_unlink(struct nd_defrouter *dr, struct nd6_drhead *drq)
141 {
142 
143 	ND6_WLOCK_ASSERT();
144 
145 	TAILQ_REMOVE(&V_nd6_defrouter, dr, dr_entry);
146 	V_nd6_list_genid++;
147 	if (drq != NULL)
148 		TAILQ_INSERT_TAIL(drq, dr, dr_entry);
149 }
150 
151 /*
152  * Receive Router Solicitation Message - just for routers.
153  * Router solicitation/advertisement is mostly managed by userland program
154  * (rtadvd) so here we have no function like nd6_ra_output().
155  *
156  * Based on RFC 2461
157  */
158 void
nd6_rs_input(struct mbuf * m,int off,int icmp6len)159 nd6_rs_input(struct mbuf *m, int off, int icmp6len)
160 {
161 	struct ifnet *ifp;
162 	struct ip6_hdr *ip6;
163 	struct nd_router_solicit *nd_rs;
164 	struct in6_addr saddr6;
165 	union nd_opts ndopts;
166 	char ip6bufs[INET6_ADDRSTRLEN], ip6bufd[INET6_ADDRSTRLEN];
167 	char *lladdr;
168 	int lladdrlen;
169 
170 	ifp = m->m_pkthdr.rcvif;
171 
172 	/*
173 	 * Accept RS only when V_ip6_forwarding=1 and the interface has
174 	 * no ND6_IFF_ACCEPT_RTADV.
175 	 */
176 	if (!V_ip6_forwarding || ND_IFINFO(ifp)->flags & ND6_IFF_ACCEPT_RTADV)
177 		goto freeit;
178 
179 	/* RFC 6980: Nodes MUST silently ignore fragments */
180 	if(m->m_flags & M_FRAGMENTED)
181 		goto freeit;
182 
183 	/* Sanity checks */
184 	ip6 = mtod(m, struct ip6_hdr *);
185 	if (__predict_false(ip6->ip6_hlim != 255)) {
186 		ICMP6STAT_INC(icp6s_invlhlim);
187 		nd6log((LOG_ERR,
188 		    "%s: invalid hlim (%d) from %s to %s on %s\n", __func__,
189 		    ip6->ip6_hlim, ip6_sprintf(ip6bufs, &ip6->ip6_src),
190 		    ip6_sprintf(ip6bufd, &ip6->ip6_dst), if_name(ifp)));
191 		goto bad;
192 	}
193 
194 	/*
195 	 * Don't update the neighbor cache, if src = ::.
196 	 * This indicates that the src has no IP address assigned yet.
197 	 */
198 	saddr6 = ip6->ip6_src;
199 	if (IN6_IS_ADDR_UNSPECIFIED(&saddr6))
200 		goto freeit;
201 
202 	if (m->m_len < off + icmp6len) {
203 		m = m_pullup(m, off + icmp6len);
204 		if (m == NULL) {
205 			IP6STAT_INC(ip6s_exthdrtoolong);
206 			return;
207 		}
208 	}
209 	ip6 = mtod(m, struct ip6_hdr *);
210 	nd_rs = (struct nd_router_solicit *)((caddr_t)ip6 + off);
211 
212 	icmp6len -= sizeof(*nd_rs);
213 	nd6_option_init(nd_rs + 1, icmp6len, &ndopts);
214 	if (nd6_options(&ndopts) < 0) {
215 		nd6log((LOG_INFO,
216 		    "%s: invalid ND option, ignored\n", __func__));
217 		/* nd6_options have incremented stats */
218 		goto freeit;
219 	}
220 
221 	lladdr = NULL;
222 	lladdrlen = 0;
223 	if (ndopts.nd_opts_src_lladdr) {
224 		lladdr = (char *)(ndopts.nd_opts_src_lladdr + 1);
225 		lladdrlen = ndopts.nd_opts_src_lladdr->nd_opt_len << 3;
226 	}
227 
228 	if (lladdr && ((ifp->if_addrlen + 2 + 7) & ~7) != lladdrlen) {
229 		nd6log((LOG_INFO,
230 		    "%s: lladdrlen mismatch for %s (if %d, RS packet %d)\n",
231 		    __func__, ip6_sprintf(ip6bufs, &saddr6),
232 		    ifp->if_addrlen, lladdrlen - 2));
233 		goto bad;
234 	}
235 
236 	nd6_cache_lladdr(ifp, &saddr6, lladdr, lladdrlen, ND_ROUTER_SOLICIT, 0);
237 
238  freeit:
239 	m_freem(m);
240 	return;
241 
242  bad:
243 	ICMP6STAT_INC(icp6s_badrs);
244 	m_freem(m);
245 }
246 
247 #ifdef EXPERIMENTAL
248 /*
249  * An initial update routine for draft-ietf-6man-ipv6only-flag.
250  * We need to iterate over all default routers for the given
251  * interface to see whether they are all advertising the "S"
252  * (IPv6-Only) flag.  If they do set, otherwise unset, the
253  * interface flag we later use to filter on.
254  */
255 static void
defrtr_ipv6_only_ifp(struct ifnet * ifp)256 defrtr_ipv6_only_ifp(struct ifnet *ifp)
257 {
258 	struct nd_defrouter *dr;
259 	bool ipv6_only, ipv6_only_old;
260 #ifdef INET
261 	struct epoch_tracker et;
262 	struct ifaddr *ifa;
263 	bool has_ipv4_addr;
264 #endif
265 
266 	if (V_nd6_ignore_ipv6_only_ra != 0)
267 		return;
268 
269 	ipv6_only = true;
270 	ND6_RLOCK();
271 	TAILQ_FOREACH(dr, &V_nd6_defrouter, dr_entry)
272 		if (dr->ifp == ifp &&
273 		    (dr->raflags & ND_RA_FLAG_IPV6_ONLY) == 0)
274 			ipv6_only = false;
275 	ND6_RUNLOCK();
276 
277 	IF_AFDATA_WLOCK(ifp);
278 	ipv6_only_old = ND_IFINFO(ifp)->flags & ND6_IFF_IPV6_ONLY;
279 	IF_AFDATA_WUNLOCK(ifp);
280 
281 	/* If nothing changed, we have an early exit. */
282 	if (ipv6_only == ipv6_only_old)
283 		return;
284 
285 #ifdef INET
286 	/*
287 	 * Should we want to set the IPV6-ONLY flag, check if the
288 	 * interface has a non-0/0 and non-link-local IPv4 address
289 	 * configured on it.  If it has we will assume working
290 	 * IPv4 operations and will clear the interface flag.
291 	 */
292 	has_ipv4_addr = false;
293 	if (ipv6_only) {
294 		NET_EPOCH_ENTER(et);
295 		CK_STAILQ_FOREACH(ifa, &ifp->if_addrhead, ifa_link) {
296 			if (ifa->ifa_addr->sa_family != AF_INET)
297 				continue;
298 			if (in_canforward(
299 			    satosin(ifa->ifa_addr)->sin_addr)) {
300 				has_ipv4_addr = true;
301 				break;
302 			}
303 		}
304 		NET_EPOCH_EXIT(et);
305 	}
306 	if (ipv6_only && has_ipv4_addr) {
307 		log(LOG_NOTICE, "%s rcvd RA w/ IPv6-Only flag set but has IPv4 "
308 		    "configured, ignoring IPv6-Only flag.\n", ifp->if_xname);
309 		ipv6_only = false;
310 	}
311 #endif
312 
313 	IF_AFDATA_WLOCK(ifp);
314 	if (ipv6_only)
315 		ND_IFINFO(ifp)->flags |= ND6_IFF_IPV6_ONLY;
316 	else
317 		ND_IFINFO(ifp)->flags &= ~ND6_IFF_IPV6_ONLY;
318 	IF_AFDATA_WUNLOCK(ifp);
319 
320 #ifdef notyet
321 	/* Send notification of flag change. */
322 #endif
323 }
324 
325 static void
defrtr_ipv6_only_ipf_down(struct ifnet * ifp)326 defrtr_ipv6_only_ipf_down(struct ifnet *ifp)
327 {
328 
329 	IF_AFDATA_WLOCK(ifp);
330 	ND_IFINFO(ifp)->flags &= ~ND6_IFF_IPV6_ONLY;
331 	IF_AFDATA_WUNLOCK(ifp);
332 }
333 #endif	/* EXPERIMENTAL */
334 
335 void
nd6_ifnet_link_event(void * arg __unused,struct ifnet * ifp,int linkstate)336 nd6_ifnet_link_event(void *arg __unused, struct ifnet *ifp, int linkstate)
337 {
338 
339 	/*
340 	 * XXX-BZ we might want to trigger re-evaluation of our default router
341 	 * availability. E.g., on link down the default router might be
342 	 * unreachable but a different interface might still have connectivity.
343 	 */
344 
345 #ifdef EXPERIMENTAL
346 	if (linkstate == LINK_STATE_DOWN)
347 		defrtr_ipv6_only_ipf_down(ifp);
348 #endif
349 }
350 
351 /*
352  * Receive Router Advertisement Message.
353  *
354  * Based on RFC 2461
355  * TODO: on-link bit on prefix information
356  * TODO: ND_RA_FLAG_{OTHER,MANAGED} processing
357  */
358 void
nd6_ra_input(struct mbuf * m,int off,int icmp6len)359 nd6_ra_input(struct mbuf *m, int off, int icmp6len)
360 {
361 	struct ifnet *ifp;
362 	struct nd_ifinfo *ndi;
363 	struct ip6_hdr *ip6;
364 	struct nd_router_advert *nd_ra;
365 	struct in6_addr saddr6;
366 	struct nd_defrouter *dr;
367 	union nd_opts ndopts;
368 	char ip6bufs[INET6_ADDRSTRLEN], ip6bufd[INET6_ADDRSTRLEN];
369 	int mcast;
370 
371 	/*
372 	 * We only accept RAs only when the per-interface flag
373 	 * ND6_IFF_ACCEPT_RTADV is on the receiving interface.
374 	 */
375 	ifp = m->m_pkthdr.rcvif;
376 	ndi = ND_IFINFO(ifp);
377 	if (!(ndi->flags & ND6_IFF_ACCEPT_RTADV))
378 		goto freeit;
379 
380 	/* RFC 6980: Nodes MUST silently ignore fragments */
381 	if(m->m_flags & M_FRAGMENTED)
382 		goto freeit;
383 
384 	ip6 = mtod(m, struct ip6_hdr *);
385 	if (__predict_false(ip6->ip6_hlim != 255)) {
386 		ICMP6STAT_INC(icp6s_invlhlim);
387 		nd6log((LOG_ERR,
388 		    "%s: invalid hlim (%d) from %s to %s on %s\n", __func__,
389 		    ip6->ip6_hlim, ip6_sprintf(ip6bufs, &ip6->ip6_src),
390 		    ip6_sprintf(ip6bufd, &ip6->ip6_dst), if_name(ifp)));
391 		goto bad;
392 	}
393 
394 	saddr6 = ip6->ip6_src;
395 	if (!IN6_IS_ADDR_LINKLOCAL(&saddr6)) {
396 		nd6log((LOG_ERR,
397 		    "%s: src %s is not link-local\n", __func__,
398 		    ip6_sprintf(ip6bufs, &saddr6)));
399 		goto bad;
400 	}
401 
402 	if (m->m_len < off + icmp6len) {
403 		m = m_pullup(m, off + icmp6len);
404 		if (m == NULL) {
405 			IP6STAT_INC(ip6s_exthdrtoolong);
406 			return;
407 		}
408 	}
409 	ip6 = mtod(m, struct ip6_hdr *);
410 	nd_ra = (struct nd_router_advert *)((caddr_t)ip6 + off);
411 
412 	icmp6len -= sizeof(*nd_ra);
413 	nd6_option_init(nd_ra + 1, icmp6len, &ndopts);
414 	if (nd6_options(&ndopts) < 0) {
415 		nd6log((LOG_INFO,
416 		    "%s: invalid ND option, ignored\n", __func__));
417 		/* nd6_options have incremented stats */
418 		goto freeit;
419 	}
420 
421 	mcast = 0;
422 	dr = NULL;
423     {
424 	struct nd_defrouter dr0;
425 	u_int32_t advreachable = nd_ra->nd_ra_reachable;
426 
427 	/* remember if this is a multicasted advertisement */
428 	if (IN6_IS_ADDR_MULTICAST(&ip6->ip6_dst))
429 		mcast = 1;
430 
431 	bzero(&dr0, sizeof(dr0));
432 	dr0.rtaddr = saddr6;
433 	dr0.raflags = nd_ra->nd_ra_flags_reserved;
434 	/*
435 	 * Effectively-disable routes from RA messages when
436 	 * ND6_IFF_NO_RADR enabled on the receiving interface or
437 	 * (ip6.forwarding == 1 && ip6.rfc6204w3 != 1).
438 	 */
439 	if (ndi->flags & ND6_IFF_NO_RADR)
440 		dr0.rtlifetime = 0;
441 	else if (V_ip6_forwarding && !V_ip6_rfc6204w3)
442 		dr0.rtlifetime = 0;
443 	else
444 		dr0.rtlifetime = ntohs(nd_ra->nd_ra_router_lifetime);
445 	dr0.expire = time_uptime + dr0.rtlifetime;
446 	dr0.ifp = ifp;
447 	/* unspecified or not? (RFC 2461 6.3.4) */
448 	if (advreachable) {
449 		advreachable = ntohl(advreachable);
450 		if (advreachable <= MAX_REACHABLE_TIME &&
451 		    ndi->basereachable != advreachable) {
452 			ndi->basereachable = advreachable;
453 			ndi->reachable = ND_COMPUTE_RTIME(ndi->basereachable);
454 			ndi->recalctm = V_nd6_recalc_reachtm_interval; /* reset */
455 		}
456 	}
457 	if (nd_ra->nd_ra_retransmit)
458 		ndi->retrans = ntohl(nd_ra->nd_ra_retransmit);
459 	if (nd_ra->nd_ra_curhoplimit) {
460 		if (ndi->chlim < nd_ra->nd_ra_curhoplimit)
461 			ndi->chlim = nd_ra->nd_ra_curhoplimit;
462 		else if (ndi->chlim != nd_ra->nd_ra_curhoplimit) {
463 			log(LOG_ERR, "RA with a lower CurHopLimit sent from "
464 			    "%s on %s (current = %d, received = %d). "
465 			    "Ignored.\n", ip6_sprintf(ip6bufs, &ip6->ip6_src),
466 			    if_name(ifp), ndi->chlim, nd_ra->nd_ra_curhoplimit);
467 		}
468 	}
469 	dr = defrtrlist_update(&dr0);
470 #ifdef EXPERIMENTAL
471 	defrtr_ipv6_only_ifp(ifp);
472 #endif
473     }
474 
475 	/*
476 	 * prefix
477 	 */
478 	if (ndopts.nd_opts_pi) {
479 		struct nd_opt_hdr *pt;
480 		struct nd_opt_prefix_info *pi = NULL;
481 		struct nd_prefixctl pr;
482 
483 		for (pt = (struct nd_opt_hdr *)ndopts.nd_opts_pi;
484 		     pt <= (struct nd_opt_hdr *)ndopts.nd_opts_pi_end;
485 		     pt = (struct nd_opt_hdr *)((caddr_t)pt +
486 						(pt->nd_opt_len << 3))) {
487 			if (pt->nd_opt_type != ND_OPT_PREFIX_INFORMATION)
488 				continue;
489 			pi = (struct nd_opt_prefix_info *)pt;
490 
491 			if (pi->nd_opt_pi_len != 4) {
492 				nd6log((LOG_INFO,
493 				    "%s: invalid option len %d for prefix "
494 				    "information option, ignored\n", __func__,
495 				    pi->nd_opt_pi_len));
496 				continue;
497 			}
498 
499 			if (128 < pi->nd_opt_pi_prefix_len) {
500 				nd6log((LOG_INFO,
501 				    "%s: invalid prefix len %d for prefix "
502 				    "information option, ignored\n", __func__,
503 				    pi->nd_opt_pi_prefix_len));
504 				continue;
505 			}
506 
507 			if (IN6_IS_ADDR_MULTICAST(&pi->nd_opt_pi_prefix)
508 			 || IN6_IS_ADDR_LINKLOCAL(&pi->nd_opt_pi_prefix)) {
509 				nd6log((LOG_INFO,
510 				    "%s: invalid prefix %s, ignored\n",
511 				    __func__, ip6_sprintf(ip6bufs,
512 					&pi->nd_opt_pi_prefix)));
513 				continue;
514 			}
515 
516 			bzero(&pr, sizeof(pr));
517 			pr.ndpr_prefix.sin6_family = AF_INET6;
518 			pr.ndpr_prefix.sin6_len = sizeof(pr.ndpr_prefix);
519 			pr.ndpr_prefix.sin6_addr = pi->nd_opt_pi_prefix;
520 			pr.ndpr_ifp = (struct ifnet *)m->m_pkthdr.rcvif;
521 
522 			pr.ndpr_raf_onlink = (pi->nd_opt_pi_flags_reserved &
523 			    ND_OPT_PI_FLAG_ONLINK) ? 1 : 0;
524 			pr.ndpr_raf_auto = (pi->nd_opt_pi_flags_reserved &
525 			    ND_OPT_PI_FLAG_AUTO) ? 1 : 0;
526 			pr.ndpr_plen = pi->nd_opt_pi_prefix_len;
527 			pr.ndpr_vltime = ntohl(pi->nd_opt_pi_valid_time);
528 			pr.ndpr_pltime = ntohl(pi->nd_opt_pi_preferred_time);
529 			(void)prelist_update(&pr, dr, m, mcast);
530 		}
531 	}
532 	if (dr != NULL) {
533 		defrouter_rele(dr);
534 		dr = NULL;
535 	}
536 
537 	/*
538 	 * MTU
539 	 */
540 	if (ndopts.nd_opts_mtu && ndopts.nd_opts_mtu->nd_opt_mtu_len == 1) {
541 		u_long mtu;
542 		u_long maxmtu;
543 
544 		mtu = (u_long)ntohl(ndopts.nd_opts_mtu->nd_opt_mtu_mtu);
545 
546 		/* lower bound */
547 		if (mtu < IPV6_MMTU) {
548 			nd6log((LOG_INFO, "%s: bogus mtu option mtu=%lu sent "
549 			    "from %s, ignoring\n", __func__,
550 			    mtu, ip6_sprintf(ip6bufs, &ip6->ip6_src)));
551 			goto skip;
552 		}
553 
554 		/* upper bound */
555 		maxmtu = (ndi->maxmtu && ndi->maxmtu < ifp->if_mtu)
556 		    ? ndi->maxmtu : ifp->if_mtu;
557 		if (mtu <= maxmtu) {
558 			if (ndi->linkmtu != mtu) {
559 				ndi->linkmtu = mtu;
560 				rt_updatemtu(ifp);
561 			}
562 		} else {
563 			nd6log((LOG_INFO, "%s: bogus mtu=%lu sent from %s; "
564 			    "exceeds maxmtu %lu, ignoring\n", __func__,
565 			    mtu, ip6_sprintf(ip6bufs, &ip6->ip6_src), maxmtu));
566 		}
567 	}
568 
569  skip:
570 
571 	/*
572 	 * Source link layer address
573 	 */
574     {
575 	char *lladdr = NULL;
576 	int lladdrlen = 0;
577 
578 	if (ndopts.nd_opts_src_lladdr) {
579 		lladdr = (char *)(ndopts.nd_opts_src_lladdr + 1);
580 		lladdrlen = ndopts.nd_opts_src_lladdr->nd_opt_len << 3;
581 	}
582 
583 	if (lladdr && ((ifp->if_addrlen + 2 + 7) & ~7) != lladdrlen) {
584 		nd6log((LOG_INFO,
585 		    "%s: lladdrlen mismatch for %s (if %d, RA packet %d)\n",
586 		    __func__, ip6_sprintf(ip6bufs, &saddr6),
587 		    ifp->if_addrlen, lladdrlen - 2));
588 		goto bad;
589 	}
590 
591 	nd6_cache_lladdr(ifp, &saddr6, lladdr,
592 	    lladdrlen, ND_ROUTER_ADVERT, 0);
593 
594 	/*
595 	 * Installing a link-layer address might change the state of the
596 	 * router's neighbor cache, which might also affect our on-link
597 	 * detection of adveritsed prefixes.
598 	 */
599 	pfxlist_onlink_check();
600     }
601 
602  freeit:
603 	m_freem(m);
604 	return;
605 
606  bad:
607 	ICMP6STAT_INC(icp6s_badra);
608 	m_freem(m);
609 }
610 
611 /* PFXRTR */
612 static struct nd_pfxrouter *
pfxrtr_lookup(struct nd_prefix * pr,struct nd_defrouter * dr)613 pfxrtr_lookup(struct nd_prefix *pr, struct nd_defrouter *dr)
614 {
615 	struct nd_pfxrouter *search;
616 
617 	ND6_LOCK_ASSERT();
618 
619 	LIST_FOREACH(search, &pr->ndpr_advrtrs, pfr_entry) {
620 		if (search->router == dr)
621 			break;
622 	}
623 	return (search);
624 }
625 
626 static void
pfxrtr_add(struct nd_prefix * pr,struct nd_defrouter * dr)627 pfxrtr_add(struct nd_prefix *pr, struct nd_defrouter *dr)
628 {
629 	struct nd_pfxrouter *new;
630 	bool update;
631 
632 	ND6_UNLOCK_ASSERT();
633 
634 	ND6_RLOCK();
635 	if (pfxrtr_lookup(pr, dr) != NULL) {
636 		ND6_RUNLOCK();
637 		return;
638 	}
639 	ND6_RUNLOCK();
640 
641 	new = malloc(sizeof(*new), M_IP6NDP, M_NOWAIT | M_ZERO);
642 	if (new == NULL)
643 		return;
644 	defrouter_ref(dr);
645 	new->router = dr;
646 
647 	ND6_WLOCK();
648 	if (pfxrtr_lookup(pr, dr) == NULL) {
649 		LIST_INSERT_HEAD(&pr->ndpr_advrtrs, new, pfr_entry);
650 		update = true;
651 	} else {
652 		/* We lost a race to add the reference. */
653 		defrouter_rele(dr);
654 		free(new, M_IP6NDP);
655 		update = false;
656 	}
657 	ND6_WUNLOCK();
658 
659 	if (update)
660 		pfxlist_onlink_check();
661 }
662 
663 static void
pfxrtr_del(struct nd_pfxrouter * pfr)664 pfxrtr_del(struct nd_pfxrouter *pfr)
665 {
666 
667 	ND6_WLOCK_ASSERT();
668 
669 	LIST_REMOVE(pfr, pfr_entry);
670 	defrouter_rele(pfr->router);
671 	free(pfr, M_IP6NDP);
672 }
673 
674 /* Default router list processing sub routines. */
675 static void
defrouter_addreq(struct nd_defrouter * new)676 defrouter_addreq(struct nd_defrouter *new)
677 {
678 	uint32_t fibnum = new->ifp->if_fib;
679 	struct rib_cmd_info rc = {};
680 	int error = 0;
681 
682 	NET_EPOCH_ASSERT();
683 
684 	struct sockaddr_in6 gw = {
685 		.sin6_family = AF_INET6,
686 		.sin6_len = sizeof(struct sockaddr_in6),
687 		.sin6_addr = new->rtaddr,
688 	};
689 
690 	error = rib_add_default_route(fibnum, AF_INET6, new->ifp,
691 	    (struct sockaddr *)&gw, &rc);
692 
693 	if (error == 0) {
694 		struct nhop_object *nh = nhop_select_func(rc.rc_nh_new, 0);
695 		rt_routemsg(RTM_ADD, rc.rc_rt, nh, fibnum);
696 		new->installed = 1;
697 	}
698 }
699 
700 /*
701  * Remove the default route for a given router.
702  * This is just a subroutine function for defrouter_select_fib(), and
703  * should not be called from anywhere else.
704  */
705 static void
defrouter_delreq(struct nd_defrouter * dr)706 defrouter_delreq(struct nd_defrouter *dr)
707 {
708 	uint32_t fibnum = dr->ifp->if_fib;
709 	struct epoch_tracker et;
710 	struct rib_cmd_info rc;
711 	int error;
712 
713 	struct sockaddr_in6 dst = {
714 		.sin6_family = AF_INET6,
715 		.sin6_len = sizeof(struct sockaddr_in6),
716 	};
717 
718 	struct sockaddr_in6 gw = {
719 		.sin6_family = AF_INET6,
720 		.sin6_len = sizeof(struct sockaddr_in6),
721 		.sin6_addr = dr->rtaddr,
722 	};
723 
724 	NET_EPOCH_ENTER(et);
725 	error = rib_del_route_px(fibnum, (struct sockaddr *)&dst, 0,
726 		    rib_match_gw, (struct sockaddr *)&gw, 0, &rc);
727 	if (error == 0) {
728 		struct nhop_object *nh = nhop_select_func(rc.rc_nh_old, 0);
729 		rt_routemsg(RTM_DELETE, rc.rc_rt, nh, fibnum);
730 	}
731 	NET_EPOCH_EXIT(et);
732 
733 	dr->installed = 0;
734 }
735 
736 static void
defrouter_del(struct nd_defrouter * dr)737 defrouter_del(struct nd_defrouter *dr)
738 {
739 	struct nd_defrouter *deldr = NULL;
740 	struct nd_prefix *pr;
741 	struct nd_pfxrouter *pfxrtr;
742 
743 	ND6_UNLOCK_ASSERT();
744 
745 	/*
746 	 * Flush all the routing table entries that use the router
747 	 * as a next hop.
748 	 */
749 	if (ND_IFINFO(dr->ifp)->flags & ND6_IFF_ACCEPT_RTADV)
750 		rt6_flush(&dr->rtaddr, dr->ifp);
751 
752 #ifdef EXPERIMENTAL
753 	defrtr_ipv6_only_ifp(dr->ifp);
754 #endif
755 
756 	if (dr->installed) {
757 		deldr = dr;
758 		defrouter_delreq(dr);
759 	}
760 
761 	/*
762 	 * Also delete all the pointers to the router in each prefix lists.
763 	 */
764 	ND6_WLOCK();
765 	LIST_FOREACH(pr, &V_nd_prefix, ndpr_entry) {
766 		if ((pfxrtr = pfxrtr_lookup(pr, dr)) != NULL)
767 			pfxrtr_del(pfxrtr);
768 	}
769 	ND6_WUNLOCK();
770 
771 	pfxlist_onlink_check();
772 
773 	/*
774 	 * If the router is the primary one, choose a new one.
775 	 * Note that defrouter_select_fib() will remove the current
776          * gateway from the routing table.
777 	 */
778 	if (deldr)
779 		defrouter_select_fib(deldr->ifp->if_fib);
780 
781 	/*
782 	 * Release the list reference.
783 	 */
784 	defrouter_rele(dr);
785 }
786 
787 struct nd_defrouter *
defrouter_lookup_locked(const struct in6_addr * addr,struct ifnet * ifp)788 defrouter_lookup_locked(const struct in6_addr *addr, struct ifnet *ifp)
789 {
790 	struct nd_defrouter *dr;
791 
792 	ND6_LOCK_ASSERT();
793 	TAILQ_FOREACH(dr, &V_nd6_defrouter, dr_entry)
794 		if (dr->ifp == ifp && IN6_ARE_ADDR_EQUAL(addr, &dr->rtaddr)) {
795 			defrouter_ref(dr);
796 			return (dr);
797 		}
798 	return (NULL);
799 }
800 
801 struct nd_defrouter *
defrouter_lookup(const struct in6_addr * addr,struct ifnet * ifp)802 defrouter_lookup(const struct in6_addr *addr, struct ifnet *ifp)
803 {
804 	struct nd_defrouter *dr;
805 
806 	ND6_RLOCK();
807 	dr = defrouter_lookup_locked(addr, ifp);
808 	ND6_RUNLOCK();
809 	return (dr);
810 }
811 
812 /*
813  * Remove all default routes from default router list.
814  */
815 void
defrouter_reset(void)816 defrouter_reset(void)
817 {
818 	struct nd_defrouter *dr, **dra;
819 	int count, i;
820 
821 	count = i = 0;
822 
823 	/*
824 	 * We can't delete routes with the ND lock held, so make a copy of the
825 	 * current default router list and use that when deleting routes.
826 	 */
827 	ND6_RLOCK();
828 	TAILQ_FOREACH(dr, &V_nd6_defrouter, dr_entry)
829 		count++;
830 	ND6_RUNLOCK();
831 
832 	dra = malloc(count * sizeof(*dra), M_TEMP, M_WAITOK | M_ZERO);
833 
834 	ND6_RLOCK();
835 	TAILQ_FOREACH(dr, &V_nd6_defrouter, dr_entry) {
836 		if (i == count)
837 			break;
838 		defrouter_ref(dr);
839 		dra[i++] = dr;
840 	}
841 	ND6_RUNLOCK();
842 
843 	for (i = 0; i < count && dra[i] != NULL; i++) {
844 		defrouter_delreq(dra[i]);
845 		defrouter_rele(dra[i]);
846 	}
847 	free(dra, M_TEMP);
848 
849 	/*
850 	 * XXX should we also nuke any default routers in the kernel, by
851 	 * going through them by rtalloc1()?
852 	 */
853 }
854 
855 /*
856  * Look up a matching default router list entry and remove it. Returns true if a
857  * matching entry was found, false otherwise.
858  */
859 bool
defrouter_remove(struct in6_addr * addr,struct ifnet * ifp)860 defrouter_remove(struct in6_addr *addr, struct ifnet *ifp)
861 {
862 	struct nd_defrouter *dr;
863 
864 	ND6_WLOCK();
865 	dr = defrouter_lookup_locked(addr, ifp);
866 	if (dr == NULL) {
867 		ND6_WUNLOCK();
868 		return (false);
869 	}
870 
871 	defrouter_unlink(dr, NULL);
872 	ND6_WUNLOCK();
873 	defrouter_del(dr);
874 	defrouter_rele(dr);
875 	return (true);
876 }
877 
878 /*
879  * for default router selection
880  * regards router-preference field as a 2-bit signed integer
881  */
882 static int
rtpref(struct nd_defrouter * dr)883 rtpref(struct nd_defrouter *dr)
884 {
885 	switch (dr->raflags & ND_RA_FLAG_RTPREF_MASK) {
886 	case ND_RA_FLAG_RTPREF_HIGH:
887 		return (RTPREF_HIGH);
888 	case ND_RA_FLAG_RTPREF_MEDIUM:
889 	case ND_RA_FLAG_RTPREF_RSV:
890 		return (RTPREF_MEDIUM);
891 	case ND_RA_FLAG_RTPREF_LOW:
892 		return (RTPREF_LOW);
893 	default:
894 		/*
895 		 * This case should never happen.  If it did, it would mean a
896 		 * serious bug of kernel internal.  We thus always bark here.
897 		 * Or, can we even panic?
898 		 */
899 		log(LOG_ERR, "rtpref: impossible RA flag %x\n", dr->raflags);
900 		return (RTPREF_INVALID);
901 	}
902 	/* NOTREACHED */
903 }
904 
905 static bool
is_dr_reachable(const struct nd_defrouter * dr)906 is_dr_reachable(const struct nd_defrouter *dr) {
907 	struct llentry *ln = NULL;
908 
909 	ln = nd6_lookup(&dr->rtaddr, LLE_SF(AF_INET6, 0), dr->ifp);
910 	if (ln == NULL)
911 		return (false);
912 	bool reachable = ND6_IS_LLINFO_PROBREACH(ln);
913 	LLE_RUNLOCK(ln);
914 	return reachable;
915 }
916 
917 /*
918  * Default Router Selection according to Section 6.3.6 of RFC 2461 and
919  * draft-ietf-ipngwg-router-selection:
920  * 1) Routers that are reachable or probably reachable should be preferred.
921  *    If we have more than one (probably) reachable router, prefer ones
922  *    with the highest router preference.
923  * 2) When no routers on the list are known to be reachable or
924  *    probably reachable, routers SHOULD be selected in a round-robin
925  *    fashion, regardless of router preference values.
926  * 3) If the Default Router List is empty, assume that all
927  *    destinations are on-link.
928  *
929  * We assume nd_defrouter is sorted by router preference value.
930  * Since the code below covers both with and without router preference cases,
931  * we do not need to classify the cases by ifdef.
932  *
933  * At this moment, we do not try to install more than one default router,
934  * even when the multipath routing is available, because we're not sure about
935  * the benefits for stub hosts comparing to the risk of making the code
936  * complicated and the possibility of introducing bugs.
937  *
938  * We maintain a single list of routers for multiple FIBs, only considering one
939  * at a time based on the receiving interface's FIB. If @fibnum is RT_ALL_FIBS,
940  * we do the whole thing multiple times.
941  */
942 void
defrouter_select_fib(int fibnum)943 defrouter_select_fib(int fibnum)
944 {
945 	struct epoch_tracker et;
946 	struct nd_defrouter *dr, *selected_dr, *installed_dr;
947 
948 	if (fibnum == RT_ALL_FIBS) {
949 		for (fibnum = 0; fibnum < rt_numfibs; fibnum++) {
950 			defrouter_select_fib(fibnum);
951 		}
952 		return;
953 	}
954 
955 	ND6_RLOCK();
956 	/*
957 	 * Let's handle easy case (3) first:
958 	 * If default router list is empty, there's nothing to be done.
959 	 */
960 	if (TAILQ_EMPTY(&V_nd6_defrouter)) {
961 		ND6_RUNLOCK();
962 		return;
963 	}
964 
965 	/*
966 	 * Search for a (probably) reachable router from the list.
967 	 * We just pick up the first reachable one (if any), assuming that
968 	 * the ordering rule of the list described in defrtrlist_update().
969 	 */
970 	selected_dr = installed_dr = NULL;
971 	NET_EPOCH_ENTER(et);
972 	TAILQ_FOREACH(dr, &V_nd6_defrouter, dr_entry) {
973 		if (dr->ifp->if_fib != fibnum)
974 			continue;
975 
976 		if (selected_dr == NULL && is_dr_reachable(dr)) {
977 			selected_dr = dr;
978 			defrouter_ref(selected_dr);
979 		}
980 
981 		if (dr->installed) {
982 			if (installed_dr == NULL) {
983 				installed_dr = dr;
984 				defrouter_ref(installed_dr);
985 			} else {
986 				/*
987 				 * this should not happen.
988 				 * warn for diagnosis.
989 				 */
990 				log(LOG_ERR, "defrouter_select_fib: more than "
991 				             "one router is installed\n");
992 			}
993 		}
994 	}
995 
996 	/*
997 	 * If none of the default routers was found to be reachable,
998 	 * round-robin the list regardless of preference.
999 	 * Otherwise, if we have an installed router, check if the selected
1000 	 * (reachable) router should really be preferred to the installed one.
1001 	 * We only prefer the new router when the old one is not reachable
1002 	 * or when the new one has a really higher preference value.
1003 	 */
1004 	if (selected_dr == NULL) {
1005 		if (installed_dr == NULL ||
1006 		    TAILQ_NEXT(installed_dr, dr_entry) == NULL)
1007 			dr = TAILQ_FIRST(&V_nd6_defrouter);
1008 		else
1009 			dr = TAILQ_NEXT(installed_dr, dr_entry);
1010 
1011 		/* Ensure we select a router for this FIB. */
1012 		TAILQ_FOREACH_FROM(dr, &V_nd6_defrouter, dr_entry) {
1013 			if (dr->ifp->if_fib == fibnum) {
1014 				selected_dr = dr;
1015 				defrouter_ref(selected_dr);
1016 				break;
1017 			}
1018 		}
1019 	} else if (installed_dr != NULL) {
1020 		if (is_dr_reachable(installed_dr) &&
1021 		    rtpref(selected_dr) <= rtpref(installed_dr)) {
1022 			defrouter_rele(selected_dr);
1023 			selected_dr = installed_dr;
1024 		}
1025 	}
1026 	ND6_RUNLOCK();
1027 
1028 	/*
1029 	 * If we selected a router for this FIB and it's different
1030 	 * than the installed one, remove the installed router and
1031 	 * install the selected one in its place.
1032 	 */
1033 	if (installed_dr != selected_dr) {
1034 		if (installed_dr != NULL) {
1035 			defrouter_delreq(installed_dr);
1036 			defrouter_rele(installed_dr);
1037 		}
1038 		if (selected_dr != NULL)
1039 			defrouter_addreq(selected_dr);
1040 	}
1041 	if (selected_dr != NULL)
1042 		defrouter_rele(selected_dr);
1043 	NET_EPOCH_EXIT(et);
1044 }
1045 
1046 static struct nd_defrouter *
defrtrlist_update(struct nd_defrouter * new)1047 defrtrlist_update(struct nd_defrouter *new)
1048 {
1049 	struct nd_defrouter *dr, *n;
1050 	uint64_t genid;
1051 	int oldpref;
1052 	bool writelocked;
1053 
1054 	if (new->rtlifetime == 0) {
1055 		defrouter_remove(&new->rtaddr, new->ifp);
1056 		return (NULL);
1057 	}
1058 
1059 	ND6_RLOCK();
1060 	writelocked = false;
1061 restart:
1062 	dr = defrouter_lookup_locked(&new->rtaddr, new->ifp);
1063 	if (dr != NULL) {
1064 		oldpref = rtpref(dr);
1065 
1066 		/* override */
1067 		dr->raflags = new->raflags; /* XXX flag check */
1068 		dr->rtlifetime = new->rtlifetime;
1069 		dr->expire = new->expire;
1070 
1071 		/*
1072 		 * If the preference does not change, there's no need
1073 		 * to sort the entries. Also make sure the selected
1074 		 * router is still installed in the kernel.
1075 		 */
1076 		if (dr->installed && rtpref(new) == oldpref) {
1077 			if (writelocked)
1078 				ND6_WUNLOCK();
1079 			else
1080 				ND6_RUNLOCK();
1081 			return (dr);
1082 		}
1083 	}
1084 
1085 	/*
1086 	 * The router needs to be reinserted into the default router
1087 	 * list, so upgrade to a write lock. If that fails and the list
1088 	 * has potentially changed while the lock was dropped, we'll
1089 	 * redo the lookup with the write lock held.
1090 	 */
1091 	if (!writelocked) {
1092 		writelocked = true;
1093 		if (!ND6_TRY_UPGRADE()) {
1094 			genid = V_nd6_list_genid;
1095 			ND6_RUNLOCK();
1096 			ND6_WLOCK();
1097 			if (genid != V_nd6_list_genid)
1098 				goto restart;
1099 		}
1100 	}
1101 
1102 	if (dr != NULL) {
1103 		/*
1104 		 * The preferred router may have changed, so relocate this
1105 		 * router.
1106 		 */
1107 		TAILQ_REMOVE(&V_nd6_defrouter, dr, dr_entry);
1108 		n = dr;
1109 	} else {
1110 		n = malloc(sizeof(*n), M_IP6NDP, M_NOWAIT | M_ZERO);
1111 		if (n == NULL) {
1112 			ND6_WUNLOCK();
1113 			return (NULL);
1114 		}
1115 		memcpy(n, new, sizeof(*n));
1116 		/* Initialize with an extra reference for the caller. */
1117 		refcount_init(&n->refcnt, 2);
1118 	}
1119 
1120 	/*
1121 	 * Insert the new router in the Default Router List;
1122 	 * The Default Router List should be in the descending order
1123 	 * of router-preferece.  Routers with the same preference are
1124 	 * sorted in the arriving time order.
1125 	 */
1126 
1127 	/* insert at the end of the group */
1128 	TAILQ_FOREACH(dr, &V_nd6_defrouter, dr_entry) {
1129 		if (rtpref(n) > rtpref(dr))
1130 			break;
1131 	}
1132 	if (dr != NULL)
1133 		TAILQ_INSERT_BEFORE(dr, n, dr_entry);
1134 	else
1135 		TAILQ_INSERT_TAIL(&V_nd6_defrouter, n, dr_entry);
1136 	V_nd6_list_genid++;
1137 	ND6_WUNLOCK();
1138 
1139 	defrouter_select_fib(new->ifp->if_fib);
1140 
1141 	return (n);
1142 }
1143 
1144 static int
in6_init_prefix_ltimes(struct nd_prefix * ndpr)1145 in6_init_prefix_ltimes(struct nd_prefix *ndpr)
1146 {
1147 	if (ndpr->ndpr_pltime == ND6_INFINITE_LIFETIME)
1148 		ndpr->ndpr_preferred = 0;
1149 	else
1150 		ndpr->ndpr_preferred = time_uptime + ndpr->ndpr_pltime;
1151 	if (ndpr->ndpr_vltime == ND6_INFINITE_LIFETIME)
1152 		ndpr->ndpr_expire = 0;
1153 	else
1154 		ndpr->ndpr_expire = time_uptime + ndpr->ndpr_vltime;
1155 
1156 	return 0;
1157 }
1158 
1159 static void
in6_init_address_ltimes(struct nd_prefix * new,struct in6_addrlifetime * lt6)1160 in6_init_address_ltimes(struct nd_prefix *new, struct in6_addrlifetime *lt6)
1161 {
1162 	/* init ia6t_expire */
1163 	if (lt6->ia6t_vltime == ND6_INFINITE_LIFETIME)
1164 		lt6->ia6t_expire = 0;
1165 	else {
1166 		lt6->ia6t_expire = time_uptime;
1167 		lt6->ia6t_expire += lt6->ia6t_vltime;
1168 	}
1169 
1170 	/* init ia6t_preferred */
1171 	if (lt6->ia6t_pltime == ND6_INFINITE_LIFETIME)
1172 		lt6->ia6t_preferred = 0;
1173 	else {
1174 		lt6->ia6t_preferred = time_uptime;
1175 		lt6->ia6t_preferred += lt6->ia6t_pltime;
1176 	}
1177 }
1178 
1179 static struct in6_ifaddr *
in6_ifadd(struct nd_prefixctl * pr,int mcast)1180 in6_ifadd(struct nd_prefixctl *pr, int mcast)
1181 {
1182 	struct ifnet *ifp = pr->ndpr_ifp;
1183 	struct ifaddr *ifa;
1184 	struct in6_aliasreq ifra;
1185 	struct in6_ifaddr *ia = NULL, *ib = NULL;
1186 	int error, plen0;
1187 	struct in6_addr *ifid_addr = NULL, mask;
1188 	int prefixlen = pr->ndpr_plen;
1189 	int updateflags;
1190 	char ip6buf[INET6_ADDRSTRLEN];
1191 
1192 	in6_prefixlen2mask(&mask, prefixlen);
1193 
1194 	/*
1195 	 * find a link-local address (will be interface ID).
1196 	 * Is it really mandatory? Theoretically, a global or a site-local
1197 	 * address can be configured without a link-local address, if we
1198 	 * have a unique interface identifier...
1199 	 *
1200 	 * it is not mandatory to have a link-local address, we can generate
1201 	 * interface identifier on the fly.  we do this because:
1202 	 * (1) it should be the easiest way to find interface identifier.
1203 	 * (2) RFC2462 5.4 suggesting the use of the same interface identifier
1204 	 * for multiple addresses on a single interface, and possible shortcut
1205 	 * of DAD.  we omitted DAD for this reason in the past.
1206 	 * (3) a user can prevent autoconfiguration of global address
1207 	 * by removing link-local address by hand (this is partly because we
1208 	 * don't have other way to control the use of IPv6 on an interface.
1209 	 * this has been our design choice - cf. NRL's "ifconfig auto").
1210 	 * (4) it is easier to manage when an interface has addresses
1211 	 * with the same interface identifier, than to have multiple addresses
1212 	 * with different interface identifiers.
1213 	 */
1214 	ifa = (struct ifaddr *)in6ifa_ifpforlinklocal(ifp, 0); /* 0 is OK? */
1215 	if (ifa) {
1216 		ib = (struct in6_ifaddr *)ifa;
1217 		ifid_addr = &ib->ia_addr.sin6_addr;
1218 
1219 		/* prefixlen + ifidlen must be equal to 128 */
1220 		plen0 = in6_mask2len(&ib->ia_prefixmask.sin6_addr, NULL);
1221 		if (prefixlen != plen0) {
1222 			ifa_free(ifa);
1223 			ifid_addr = NULL;
1224 			nd6log((LOG_DEBUG,
1225 			    "%s: wrong prefixlen for %s (prefix=%d ifid=%d)\n",
1226 			    __func__, if_name(ifp), prefixlen, 128 - plen0));
1227 		}
1228 	}
1229 
1230 	/* No suitable LL address, get the ifid directly */
1231 	if (ifid_addr == NULL) {
1232 		struct in6_addr taddr;
1233 		ifa = ifa_alloc(sizeof(taddr), M_WAITOK);
1234 		if (ifa) {
1235 			ib = (struct in6_ifaddr *)ifa;
1236 			ifid_addr = &ib->ia_addr.sin6_addr;
1237 			if(in6_get_ifid(ifp, NULL, ifid_addr) != 0) {
1238 				nd6log((LOG_DEBUG,
1239 				    "%s: failed to get ifid for %s\n",
1240 				    __func__, if_name(ifp)));
1241 				ifa_free(ifa);
1242 				ifid_addr = NULL;
1243 			}
1244 		}
1245 	}
1246 
1247 	if (ifid_addr == NULL) {
1248 		nd6log((LOG_INFO,
1249 		    "%s: could not determine ifid for %s\n",
1250 		    __func__, if_name(ifp)));
1251 		return NULL;
1252 	}
1253 
1254 	/* make ifaddr */
1255 	in6_prepare_ifra(&ifra, &pr->ndpr_prefix.sin6_addr, &mask);
1256 
1257 	IN6_MASK_ADDR(&ifra.ifra_addr.sin6_addr, &mask);
1258 	/* interface ID */
1259 	ifra.ifra_addr.sin6_addr.s6_addr32[0] |=
1260 	    (ifid_addr->s6_addr32[0] & ~mask.s6_addr32[0]);
1261 	ifra.ifra_addr.sin6_addr.s6_addr32[1] |=
1262 	    (ifid_addr->s6_addr32[1] & ~mask.s6_addr32[1]);
1263 	ifra.ifra_addr.sin6_addr.s6_addr32[2] |=
1264 	    (ifid_addr->s6_addr32[2] & ~mask.s6_addr32[2]);
1265 	ifra.ifra_addr.sin6_addr.s6_addr32[3] |=
1266 	    (ifid_addr->s6_addr32[3] & ~mask.s6_addr32[3]);
1267 	ifa_free(ifa);
1268 
1269 	/* lifetimes. */
1270 	ifra.ifra_lifetime.ia6t_vltime = pr->ndpr_vltime;
1271 	ifra.ifra_lifetime.ia6t_pltime = pr->ndpr_pltime;
1272 
1273 	/* XXX: scope zone ID? */
1274 
1275 	ifra.ifra_flags |= IN6_IFF_AUTOCONF; /* obey autoconf */
1276 
1277 	/*
1278 	 * Make sure that we do not have this address already.  This should
1279 	 * usually not happen, but we can still see this case, e.g., if we
1280 	 * have manually configured the exact address to be configured.
1281 	 */
1282 	ifa = (struct ifaddr *)in6ifa_ifpwithaddr(ifp,
1283 	    &ifra.ifra_addr.sin6_addr);
1284 	if (ifa != NULL) {
1285 		ifa_free(ifa);
1286 		/* this should be rare enough to make an explicit log */
1287 		log(LOG_INFO, "in6_ifadd: %s is already configured\n",
1288 		    ip6_sprintf(ip6buf, &ifra.ifra_addr.sin6_addr));
1289 		return (NULL);
1290 	}
1291 
1292 	/*
1293 	 * Allocate ifaddr structure, link into chain, etc.
1294 	 * If we are going to create a new address upon receiving a multicasted
1295 	 * RA, we need to impose a random delay before starting DAD.
1296 	 * [draft-ietf-ipv6-rfc2462bis-02.txt, Section 5.4.2]
1297 	 */
1298 	updateflags = 0;
1299 	if (mcast)
1300 		updateflags |= IN6_IFAUPDATE_DADDELAY;
1301 	if ((error = in6_update_ifa(ifp, &ifra, NULL, updateflags)) != 0) {
1302 		nd6log((LOG_ERR,
1303 		    "%s: failed to make ifaddr %s on %s (errno=%d)\n", __func__,
1304 		    ip6_sprintf(ip6buf, &ifra.ifra_addr.sin6_addr),
1305 		    if_name(ifp), error));
1306 		return (NULL);	/* ifaddr must not have been allocated. */
1307 	}
1308 
1309 	ia = in6ifa_ifpwithaddr(ifp, &ifra.ifra_addr.sin6_addr);
1310 	/*
1311 	 * XXXRW: Assumption of non-NULLness here might not be true with
1312 	 * fine-grained locking -- should we validate it?  Or just return
1313 	 * earlier ifa rather than looking it up again?
1314 	 */
1315 	return (ia);		/* this is always non-NULL  and referenced. */
1316 }
1317 
1318 static struct nd_prefix *
nd6_prefix_lookup_locked(struct nd_prefixctl * key)1319 nd6_prefix_lookup_locked(struct nd_prefixctl *key)
1320 {
1321 	struct nd_prefix *search;
1322 
1323 	ND6_LOCK_ASSERT();
1324 
1325 	LIST_FOREACH(search, &V_nd_prefix, ndpr_entry) {
1326 		if (key->ndpr_ifp == search->ndpr_ifp &&
1327 		    key->ndpr_plen == search->ndpr_plen &&
1328 		    in6_are_prefix_equal(&key->ndpr_prefix.sin6_addr,
1329 		    &search->ndpr_prefix.sin6_addr, key->ndpr_plen)) {
1330 			nd6_prefix_ref(search);
1331 			break;
1332 		}
1333 	}
1334 	return (search);
1335 }
1336 
1337 struct nd_prefix *
nd6_prefix_lookup(struct nd_prefixctl * key)1338 nd6_prefix_lookup(struct nd_prefixctl *key)
1339 {
1340 	struct nd_prefix *search;
1341 
1342 	ND6_RLOCK();
1343 	search = nd6_prefix_lookup_locked(key);
1344 	ND6_RUNLOCK();
1345 	return (search);
1346 }
1347 
1348 void
nd6_prefix_ref(struct nd_prefix * pr)1349 nd6_prefix_ref(struct nd_prefix *pr)
1350 {
1351 
1352 	refcount_acquire(&pr->ndpr_refcnt);
1353 }
1354 
1355 void
nd6_prefix_rele(struct nd_prefix * pr)1356 nd6_prefix_rele(struct nd_prefix *pr)
1357 {
1358 
1359 	if (refcount_release(&pr->ndpr_refcnt)) {
1360 		KASSERT(LIST_EMPTY(&pr->ndpr_advrtrs),
1361 		    ("prefix %p has advertising routers", pr));
1362 		free(pr, M_IP6NDP);
1363 	}
1364 }
1365 
1366 int
nd6_prelist_add(struct nd_prefixctl * pr,struct nd_defrouter * dr,struct nd_prefix ** newp)1367 nd6_prelist_add(struct nd_prefixctl *pr, struct nd_defrouter *dr,
1368     struct nd_prefix **newp)
1369 {
1370 	struct nd_prefix *new;
1371 	char ip6buf[INET6_ADDRSTRLEN];
1372 	int error;
1373 
1374 	new = malloc(sizeof(*new), M_IP6NDP, M_NOWAIT | M_ZERO);
1375 	if (new == NULL)
1376 		return (ENOMEM);
1377 	refcount_init(&new->ndpr_refcnt, newp != NULL ? 2 : 1);
1378 	new->ndpr_ifp = pr->ndpr_ifp;
1379 	new->ndpr_prefix = pr->ndpr_prefix;
1380 	new->ndpr_plen = pr->ndpr_plen;
1381 	new->ndpr_vltime = pr->ndpr_vltime;
1382 	new->ndpr_pltime = pr->ndpr_pltime;
1383 	new->ndpr_flags = pr->ndpr_flags;
1384 	if ((error = in6_init_prefix_ltimes(new)) != 0) {
1385 		free(new, M_IP6NDP);
1386 		return (error);
1387 	}
1388 	new->ndpr_lastupdate = time_uptime;
1389 
1390 	/* initialization */
1391 	LIST_INIT(&new->ndpr_advrtrs);
1392 	in6_prefixlen2mask(&new->ndpr_mask, new->ndpr_plen);
1393 	/* make prefix in the canonical form */
1394 	IN6_MASK_ADDR(&new->ndpr_prefix.sin6_addr, &new->ndpr_mask);
1395 
1396 	ND6_WLOCK();
1397 	LIST_INSERT_HEAD(&V_nd_prefix, new, ndpr_entry);
1398 	V_nd6_list_genid++;
1399 	ND6_WUNLOCK();
1400 
1401 	/* ND_OPT_PI_FLAG_ONLINK processing */
1402 	if (new->ndpr_raf_onlink) {
1403 		struct epoch_tracker et;
1404 
1405 		ND6_ONLINK_LOCK();
1406 		NET_EPOCH_ENTER(et);
1407 		if ((error = nd6_prefix_onlink(new)) != 0) {
1408 			nd6log((LOG_ERR, "%s: failed to make the prefix %s/%d "
1409 			    "on-link on %s (errno=%d)\n", __func__,
1410 			    ip6_sprintf(ip6buf, &pr->ndpr_prefix.sin6_addr),
1411 			    pr->ndpr_plen, if_name(pr->ndpr_ifp), error));
1412 			/* proceed anyway. XXX: is it correct? */
1413 		}
1414 		NET_EPOCH_EXIT(et);
1415 		ND6_ONLINK_UNLOCK();
1416 	}
1417 
1418 	if (dr != NULL)
1419 		pfxrtr_add(new, dr);
1420 	if (newp != NULL)
1421 		*newp = new;
1422 	return (0);
1423 }
1424 
1425 /*
1426  * Remove a prefix from the prefix list and optionally stash it in a
1427  * caller-provided list.
1428  *
1429  * The ND6 lock must be held.
1430  */
1431 void
nd6_prefix_unlink(struct nd_prefix * pr,struct nd_prhead * list)1432 nd6_prefix_unlink(struct nd_prefix *pr, struct nd_prhead *list)
1433 {
1434 
1435 	ND6_WLOCK_ASSERT();
1436 
1437 	LIST_REMOVE(pr, ndpr_entry);
1438 	V_nd6_list_genid++;
1439 	if (list != NULL)
1440 		LIST_INSERT_HEAD(list, pr, ndpr_entry);
1441 }
1442 
1443 /*
1444  * Free an unlinked prefix, first marking it off-link if necessary.
1445  */
1446 void
nd6_prefix_del(struct nd_prefix * pr)1447 nd6_prefix_del(struct nd_prefix *pr)
1448 {
1449 	struct nd_pfxrouter *pfr, *next;
1450 	int e;
1451 	char ip6buf[INET6_ADDRSTRLEN];
1452 
1453 	KASSERT(pr->ndpr_addrcnt == 0,
1454 	    ("prefix %p has referencing addresses", pr));
1455 	ND6_UNLOCK_ASSERT();
1456 
1457 	/*
1458 	 * Though these flags are now meaningless, we'd rather keep the value
1459 	 * of pr->ndpr_raf_onlink and pr->ndpr_raf_auto not to confuse users
1460 	 * when executing "ndp -p".
1461 	 */
1462 	if ((pr->ndpr_stateflags & NDPRF_ONLINK) != 0) {
1463 		ND6_ONLINK_LOCK();
1464 		if ((e = nd6_prefix_offlink(pr)) != 0) {
1465 			nd6log((LOG_ERR,
1466 			    "%s: failed to make the prefix %s/%d offlink on %s "
1467 			    "(errno=%d)\n", __func__,
1468 			    ip6_sprintf(ip6buf, &pr->ndpr_prefix.sin6_addr),
1469 			    pr->ndpr_plen, if_name(pr->ndpr_ifp), e));
1470 			/* what should we do? */
1471 		}
1472 		ND6_ONLINK_UNLOCK();
1473 	}
1474 
1475 	/* Release references to routers that have advertised this prefix. */
1476 	ND6_WLOCK();
1477 	LIST_FOREACH_SAFE(pfr, &pr->ndpr_advrtrs, pfr_entry, next)
1478 		pfxrtr_del(pfr);
1479 	ND6_WUNLOCK();
1480 
1481 	nd6_prefix_rele(pr);
1482 
1483 	pfxlist_onlink_check();
1484 }
1485 
1486 static int
prelist_update(struct nd_prefixctl * new,struct nd_defrouter * dr,struct mbuf * m,int mcast)1487 prelist_update(struct nd_prefixctl *new, struct nd_defrouter *dr,
1488     struct mbuf *m, int mcast)
1489 {
1490 	struct in6_ifaddr *ia6 = NULL, *ia6_match = NULL;
1491 	struct ifaddr *ifa;
1492 	struct ifnet *ifp = new->ndpr_ifp;
1493 	struct nd_prefix *pr;
1494 	int error = 0;
1495 	int auth;
1496 	struct in6_addrlifetime lt6_tmp;
1497 	char ip6buf[INET6_ADDRSTRLEN];
1498 
1499 	NET_EPOCH_ASSERT();
1500 
1501 	auth = 0;
1502 	if (m) {
1503 		/*
1504 		 * Authenticity for NA consists authentication for
1505 		 * both IP header and IP datagrams, doesn't it ?
1506 		 */
1507 #if defined(M_AUTHIPHDR) && defined(M_AUTHIPDGM)
1508 		auth = ((m->m_flags & M_AUTHIPHDR) &&
1509 		    (m->m_flags & M_AUTHIPDGM));
1510 #endif
1511 	}
1512 
1513 	if ((pr = nd6_prefix_lookup(new)) != NULL) {
1514 		/*
1515 		 * nd6_prefix_lookup() ensures that pr and new have the same
1516 		 * prefix on a same interface.
1517 		 */
1518 
1519 		/*
1520 		 * Update prefix information.  Note that the on-link (L) bit
1521 		 * and the autonomous (A) bit should NOT be changed from 1
1522 		 * to 0.
1523 		 */
1524 		if (new->ndpr_raf_onlink == 1)
1525 			pr->ndpr_raf_onlink = 1;
1526 		if (new->ndpr_raf_auto == 1)
1527 			pr->ndpr_raf_auto = 1;
1528 		if (new->ndpr_raf_onlink) {
1529 			pr->ndpr_vltime = new->ndpr_vltime;
1530 			pr->ndpr_pltime = new->ndpr_pltime;
1531 			(void)in6_init_prefix_ltimes(pr); /* XXX error case? */
1532 			pr->ndpr_lastupdate = time_uptime;
1533 		}
1534 
1535 		if (new->ndpr_raf_onlink &&
1536 		    (pr->ndpr_stateflags & NDPRF_ONLINK) == 0) {
1537 			ND6_ONLINK_LOCK();
1538 			if ((error = nd6_prefix_onlink(pr)) != 0) {
1539 				nd6log((LOG_ERR,
1540 				    "%s: failed to make the prefix %s/%d "
1541 				    "on-link on %s (errno=%d)\n", __func__,
1542 				    ip6_sprintf(ip6buf,
1543 				        &pr->ndpr_prefix.sin6_addr),
1544 				    pr->ndpr_plen, if_name(pr->ndpr_ifp),
1545 				    error));
1546 				/* proceed anyway. XXX: is it correct? */
1547 			}
1548 			ND6_ONLINK_UNLOCK();
1549 		}
1550 
1551 		if (dr != NULL)
1552 			pfxrtr_add(pr, dr);
1553 	} else {
1554 		if (new->ndpr_vltime == 0)
1555 			goto end;
1556 		if (new->ndpr_raf_onlink == 0 && new->ndpr_raf_auto == 0)
1557 			goto end;
1558 
1559 		error = nd6_prelist_add(new, dr, &pr);
1560 		if (error != 0) {
1561 			nd6log((LOG_NOTICE, "%s: nd6_prelist_add() failed for "
1562 			    "the prefix %s/%d on %s (errno=%d)\n", __func__,
1563 			    ip6_sprintf(ip6buf, &new->ndpr_prefix.sin6_addr),
1564 			    new->ndpr_plen, if_name(new->ndpr_ifp), error));
1565 			goto end; /* we should just give up in this case. */
1566 		}
1567 
1568 		/*
1569 		 * XXX: from the ND point of view, we can ignore a prefix
1570 		 * with the on-link bit being zero.  However, we need a
1571 		 * prefix structure for references from autoconfigured
1572 		 * addresses.  Thus, we explicitly make sure that the prefix
1573 		 * itself expires now.
1574 		 */
1575 		if (pr->ndpr_raf_onlink == 0) {
1576 			pr->ndpr_vltime = 0;
1577 			pr->ndpr_pltime = 0;
1578 			in6_init_prefix_ltimes(pr);
1579 		}
1580 	}
1581 
1582 	/*
1583 	 * Address autoconfiguration based on Section 5.5.3 of RFC 2462.
1584 	 * Note that pr must be non NULL at this point.
1585 	 */
1586 
1587 	/* 5.5.3 (a). Ignore the prefix without the A bit set. */
1588 	if (!new->ndpr_raf_auto)
1589 		goto end;
1590 
1591 	/*
1592 	 * 5.5.3 (b). the link-local prefix should have been ignored in
1593 	 * nd6_ra_input.
1594 	 */
1595 
1596 	/* 5.5.3 (c). Consistency check on lifetimes: pltime <= vltime. */
1597 	if (new->ndpr_pltime > new->ndpr_vltime) {
1598 		error = EINVAL;	/* XXX: won't be used */
1599 		goto end;
1600 	}
1601 
1602 	/*
1603 	 * 5.5.3 (d).  If the prefix advertised is not equal to the prefix of
1604 	 * an address configured by stateless autoconfiguration already in the
1605 	 * list of addresses associated with the interface, and the Valid
1606 	 * Lifetime is not 0, form an address.  We first check if we have
1607 	 * a matching prefix.
1608 	 * Note: we apply a clarification in rfc2462bis-02 here.  We only
1609 	 * consider autoconfigured addresses while RFC2462 simply said
1610 	 * "address".
1611 	 */
1612 	CK_STAILQ_FOREACH(ifa, &ifp->if_addrhead, ifa_link) {
1613 		struct in6_ifaddr *ifa6;
1614 		u_int32_t remaininglifetime;
1615 
1616 		if (ifa->ifa_addr->sa_family != AF_INET6)
1617 			continue;
1618 
1619 		ifa6 = (struct in6_ifaddr *)ifa;
1620 
1621 		/*
1622 		 * We only consider autoconfigured addresses as per rfc2462bis.
1623 		 */
1624 		if (!(ifa6->ia6_flags & IN6_IFF_AUTOCONF))
1625 			continue;
1626 
1627 		/*
1628 		 * Spec is not clear here, but I believe we should concentrate
1629 		 * on unicast (i.e. not anycast) addresses.
1630 		 * XXX: other ia6_flags? detached or duplicated?
1631 		 */
1632 		if ((ifa6->ia6_flags & IN6_IFF_ANYCAST) != 0)
1633 			continue;
1634 
1635 		/*
1636 		 * Ignore the address if it is not associated with a prefix
1637 		 * or is associated with a prefix that is different from this
1638 		 * one.  (pr is never NULL here)
1639 		 */
1640 		if (ifa6->ia6_ndpr != pr)
1641 			continue;
1642 
1643 		if (ia6_match == NULL) /* remember the first one */
1644 			ia6_match = ifa6;
1645 
1646 		/*
1647 		 * An already autoconfigured address matched.  Now that we
1648 		 * are sure there is at least one matched address, we can
1649 		 * proceed to 5.5.3. (e): update the lifetimes according to the
1650 		 * "two hours" rule and the privacy extension.
1651 		 * We apply some clarifications in rfc2462bis:
1652 		 * - use remaininglifetime instead of storedlifetime as a
1653 		 *   variable name
1654 		 * - remove the dead code in the "two-hour" rule
1655 		 */
1656 #define TWOHOUR		(120*60)
1657 		lt6_tmp = ifa6->ia6_lifetime;
1658 
1659 		if (lt6_tmp.ia6t_vltime == ND6_INFINITE_LIFETIME)
1660 			remaininglifetime = ND6_INFINITE_LIFETIME;
1661 		else if (time_uptime - ifa6->ia6_updatetime >
1662 			 lt6_tmp.ia6t_vltime) {
1663 			/*
1664 			 * The case of "invalid" address.  We should usually
1665 			 * not see this case.
1666 			 */
1667 			remaininglifetime = 0;
1668 		} else
1669 			remaininglifetime = lt6_tmp.ia6t_vltime -
1670 			    (time_uptime - ifa6->ia6_updatetime);
1671 
1672 		/* when not updating, keep the current stored lifetime. */
1673 		lt6_tmp.ia6t_vltime = remaininglifetime;
1674 
1675 		if (TWOHOUR < new->ndpr_vltime ||
1676 		    remaininglifetime < new->ndpr_vltime) {
1677 			lt6_tmp.ia6t_vltime = new->ndpr_vltime;
1678 		} else if (remaininglifetime <= TWOHOUR) {
1679 			if (auth) {
1680 				lt6_tmp.ia6t_vltime = new->ndpr_vltime;
1681 			}
1682 		} else {
1683 			/*
1684 			 * new->ndpr_vltime <= TWOHOUR &&
1685 			 * TWOHOUR < remaininglifetime
1686 			 */
1687 			lt6_tmp.ia6t_vltime = TWOHOUR;
1688 		}
1689 
1690 		/* The 2 hour rule is not imposed for preferred lifetime. */
1691 		lt6_tmp.ia6t_pltime = new->ndpr_pltime;
1692 
1693 		in6_init_address_ltimes(pr, &lt6_tmp);
1694 
1695 		/*
1696 		 * We need to treat lifetimes for temporary addresses
1697 		 * differently, according to
1698 		 * draft-ietf-ipv6-privacy-addrs-v2-01.txt 3.3 (1);
1699 		 * we only update the lifetimes when they are in the maximum
1700 		 * intervals.
1701 		 */
1702 		if ((ifa6->ia6_flags & IN6_IFF_TEMPORARY) != 0) {
1703 			u_int32_t maxvltime, maxpltime;
1704 
1705 			if (V_ip6_temp_valid_lifetime >
1706 			    (u_int32_t)((time_uptime - ifa6->ia6_createtime) +
1707 			    V_ip6_desync_factor)) {
1708 				maxvltime = V_ip6_temp_valid_lifetime -
1709 				    (time_uptime - ifa6->ia6_createtime) -
1710 				    V_ip6_desync_factor;
1711 			} else
1712 				maxvltime = 0;
1713 			if (V_ip6_temp_preferred_lifetime >
1714 			    (u_int32_t)((time_uptime - ifa6->ia6_createtime) +
1715 			    V_ip6_desync_factor)) {
1716 				maxpltime = V_ip6_temp_preferred_lifetime -
1717 				    (time_uptime - ifa6->ia6_createtime) -
1718 				    V_ip6_desync_factor;
1719 			} else
1720 				maxpltime = 0;
1721 
1722 			if (lt6_tmp.ia6t_vltime == ND6_INFINITE_LIFETIME ||
1723 			    lt6_tmp.ia6t_vltime > maxvltime) {
1724 				lt6_tmp.ia6t_vltime = maxvltime;
1725 			}
1726 			if (lt6_tmp.ia6t_pltime == ND6_INFINITE_LIFETIME ||
1727 			    lt6_tmp.ia6t_pltime > maxpltime) {
1728 				lt6_tmp.ia6t_pltime = maxpltime;
1729 			}
1730 		}
1731 		ifa6->ia6_lifetime = lt6_tmp;
1732 		ifa6->ia6_updatetime = time_uptime;
1733 	}
1734 	if (ia6_match == NULL && new->ndpr_vltime) {
1735 		int ifidlen;
1736 
1737 		/*
1738 		 * 5.5.3 (d) (continued)
1739 		 * No address matched and the valid lifetime is non-zero.
1740 		 * Create a new address.
1741 		 */
1742 
1743 		/*
1744 		 * Prefix Length check:
1745 		 * If the sum of the prefix length and interface identifier
1746 		 * length does not equal 128 bits, the Prefix Information
1747 		 * option MUST be ignored.  The length of the interface
1748 		 * identifier is defined in a separate link-type specific
1749 		 * document.
1750 		 */
1751 		ifidlen = in6_if2idlen(ifp);
1752 		if (ifidlen < 0) {
1753 			/* this should not happen, so we always log it. */
1754 			log(LOG_ERR, "prelist_update: IFID undefined (%s)\n",
1755 			    if_name(ifp));
1756 			goto end;
1757 		}
1758 		if (ifidlen + pr->ndpr_plen != 128) {
1759 			nd6log((LOG_INFO,
1760 			    "%s: invalid prefixlen %d for %s, ignored\n",
1761 			    __func__, pr->ndpr_plen, if_name(ifp)));
1762 			goto end;
1763 		}
1764 
1765 		if ((ia6 = in6_ifadd(new, mcast)) != NULL) {
1766 			/*
1767 			 * note that we should use pr (not new) for reference.
1768 			 */
1769 			pr->ndpr_addrcnt++;
1770 			ia6->ia6_ndpr = pr;
1771 
1772 			/*
1773 			 * RFC 3041 3.3 (2).
1774 			 * When a new public address is created as described
1775 			 * in RFC2462, also create a new temporary address.
1776 			 *
1777 			 * RFC 3041 3.5.
1778 			 * When an interface connects to a new link, a new
1779 			 * randomized interface identifier should be generated
1780 			 * immediately together with a new set of temporary
1781 			 * addresses.  Thus, we specifiy 1 as the 2nd arg of
1782 			 * in6_tmpifadd().
1783 			 */
1784 			if (V_ip6_use_tempaddr) {
1785 				int e;
1786 				if ((e = in6_tmpifadd(ia6, 1, 1)) != 0) {
1787 					nd6log((LOG_NOTICE, "%s: failed to "
1788 					    "create a temporary address "
1789 					    "(errno=%d)\n", __func__, e));
1790 				}
1791 			}
1792 			ifa_free(&ia6->ia_ifa);
1793 
1794 			/*
1795 			 * A newly added address might affect the status
1796 			 * of other addresses, so we check and update it.
1797 			 * XXX: what if address duplication happens?
1798 			 */
1799 			pfxlist_onlink_check();
1800 		} else {
1801 			/* just set an error. do not bark here. */
1802 			error = EADDRNOTAVAIL; /* XXX: might be unused. */
1803 		}
1804 	}
1805 
1806 end:
1807 	if (pr != NULL)
1808 		nd6_prefix_rele(pr);
1809 	return (error);
1810 }
1811 
1812 /*
1813  * A supplement function used in the on-link detection below;
1814  * detect if a given prefix has a (probably) reachable advertising router.
1815  * XXX: lengthy function name...
1816  */
1817 static struct nd_pfxrouter *
find_pfxlist_reachable_router(struct nd_prefix * pr)1818 find_pfxlist_reachable_router(struct nd_prefix *pr)
1819 {
1820 	struct epoch_tracker et;
1821 	struct nd_pfxrouter *pfxrtr;
1822 
1823 	ND6_LOCK_ASSERT();
1824 
1825 	NET_EPOCH_ENTER(et);
1826 	LIST_FOREACH(pfxrtr, &pr->ndpr_advrtrs, pfr_entry) {
1827 		if (is_dr_reachable(pfxrtr->router))
1828 			break;
1829 	}
1830 	NET_EPOCH_EXIT(et);
1831 	return (pfxrtr);
1832 }
1833 
1834 /*
1835  * Check if each prefix in the prefix list has at least one available router
1836  * that advertised the prefix (a router is "available" if its neighbor cache
1837  * entry is reachable or probably reachable).
1838  * If the check fails, the prefix may be off-link, because, for example,
1839  * we have moved from the network but the lifetime of the prefix has not
1840  * expired yet.  So we should not use the prefix if there is another prefix
1841  * that has an available router.
1842  * But, if there is no prefix that has an available router, we still regard
1843  * all the prefixes as on-link.  This is because we can't tell if all the
1844  * routers are simply dead or if we really moved from the network and there
1845  * is no router around us.
1846  */
1847 void
pfxlist_onlink_check(void)1848 pfxlist_onlink_check(void)
1849 {
1850 	struct nd_prefix *pr;
1851 	struct in6_ifaddr *ifa;
1852 	struct nd_defrouter *dr;
1853 	struct nd_pfxrouter *pfxrtr = NULL;
1854 	struct rm_priotracker in6_ifa_tracker;
1855 	uint64_t genid;
1856 	uint32_t flags;
1857 
1858 	ND6_ONLINK_LOCK();
1859 	ND6_RLOCK();
1860 
1861 	/*
1862 	 * Check if there is a prefix that has a reachable advertising
1863 	 * router.
1864 	 */
1865 	LIST_FOREACH(pr, &V_nd_prefix, ndpr_entry) {
1866 		if (pr->ndpr_raf_onlink && find_pfxlist_reachable_router(pr))
1867 			break;
1868 	}
1869 
1870 	/*
1871 	 * If we have no such prefix, check whether we still have a router
1872 	 * that does not advertise any prefixes.
1873 	 */
1874 	if (pr == NULL) {
1875 		TAILQ_FOREACH(dr, &V_nd6_defrouter, dr_entry) {
1876 			struct nd_prefix *pr0;
1877 
1878 			LIST_FOREACH(pr0, &V_nd_prefix, ndpr_entry) {
1879 				if ((pfxrtr = pfxrtr_lookup(pr0, dr)) != NULL)
1880 					break;
1881 			}
1882 			if (pfxrtr != NULL)
1883 				break;
1884 		}
1885 	}
1886 	if (pr != NULL || (!TAILQ_EMPTY(&V_nd6_defrouter) && pfxrtr == NULL)) {
1887 		/*
1888 		 * There is at least one prefix that has a reachable router,
1889 		 * or at least a router which probably does not advertise
1890 		 * any prefixes.  The latter would be the case when we move
1891 		 * to a new link where we have a router that does not provide
1892 		 * prefixes and we configure an address by hand.
1893 		 * Detach prefixes which have no reachable advertising
1894 		 * router, and attach other prefixes.
1895 		 */
1896 		LIST_FOREACH(pr, &V_nd_prefix, ndpr_entry) {
1897 			/* XXX: a link-local prefix should never be detached */
1898 			if (IN6_IS_ADDR_LINKLOCAL(&pr->ndpr_prefix.sin6_addr) ||
1899 			    pr->ndpr_raf_onlink == 0 ||
1900 			    pr->ndpr_raf_auto == 0)
1901 				continue;
1902 
1903 			if ((pr->ndpr_stateflags & NDPRF_DETACHED) == 0 &&
1904 			    find_pfxlist_reachable_router(pr) == NULL)
1905 				pr->ndpr_stateflags |= NDPRF_DETACHED;
1906 			else if ((pr->ndpr_stateflags & NDPRF_DETACHED) != 0 &&
1907 			    find_pfxlist_reachable_router(pr) != NULL)
1908 				pr->ndpr_stateflags &= ~NDPRF_DETACHED;
1909 		}
1910 	} else {
1911 		/* there is no prefix that has a reachable router */
1912 		LIST_FOREACH(pr, &V_nd_prefix, ndpr_entry) {
1913 			if (IN6_IS_ADDR_LINKLOCAL(&pr->ndpr_prefix.sin6_addr) ||
1914 			    pr->ndpr_raf_onlink == 0 ||
1915 			    pr->ndpr_raf_auto == 0)
1916 				continue;
1917 			pr->ndpr_stateflags &= ~NDPRF_DETACHED;
1918 		}
1919 	}
1920 
1921 	/*
1922 	 * Remove each interface route associated with a (just) detached
1923 	 * prefix, and reinstall the interface route for a (just) attached
1924 	 * prefix.  Note that all attempt of reinstallation does not
1925 	 * necessarily success, when a same prefix is shared among multiple
1926 	 * interfaces.  Such cases will be handled in nd6_prefix_onlink,
1927 	 * so we don't have to care about them.
1928 	 */
1929 restart:
1930 	LIST_FOREACH(pr, &V_nd_prefix, ndpr_entry) {
1931 		char ip6buf[INET6_ADDRSTRLEN];
1932 		int e;
1933 
1934 		if (IN6_IS_ADDR_LINKLOCAL(&pr->ndpr_prefix.sin6_addr) ||
1935 		    pr->ndpr_raf_onlink == 0 ||
1936 		    pr->ndpr_raf_auto == 0)
1937 			continue;
1938 
1939 		flags = pr->ndpr_stateflags & (NDPRF_DETACHED | NDPRF_ONLINK);
1940 		if (flags == 0 || flags == (NDPRF_DETACHED | NDPRF_ONLINK)) {
1941 			genid = V_nd6_list_genid;
1942 			ND6_RUNLOCK();
1943 			if ((flags & NDPRF_ONLINK) != 0 &&
1944 			    (e = nd6_prefix_offlink(pr)) != 0) {
1945 				nd6log((LOG_ERR,
1946 				    "%s: failed to make %s/%d offlink "
1947 				    "(errno=%d)\n", __func__,
1948 				    ip6_sprintf(ip6buf,
1949 					    &pr->ndpr_prefix.sin6_addr),
1950 					    pr->ndpr_plen, e));
1951 			} else if ((flags & NDPRF_ONLINK) == 0 &&
1952 			    (e = nd6_prefix_onlink(pr)) != 0) {
1953 				nd6log((LOG_ERR,
1954 				    "%s: failed to make %s/%d onlink "
1955 				    "(errno=%d)\n", __func__,
1956 				    ip6_sprintf(ip6buf,
1957 					    &pr->ndpr_prefix.sin6_addr),
1958 					    pr->ndpr_plen, e));
1959 			}
1960 			ND6_RLOCK();
1961 			if (genid != V_nd6_list_genid)
1962 				goto restart;
1963 		}
1964 	}
1965 
1966 	/*
1967 	 * Changes on the prefix status might affect address status as well.
1968 	 * Make sure that all addresses derived from an attached prefix are
1969 	 * attached, and that all addresses derived from a detached prefix are
1970 	 * detached.  Note, however, that a manually configured address should
1971 	 * always be attached.
1972 	 * The precise detection logic is same as the one for prefixes.
1973 	 */
1974 	IN6_IFADDR_RLOCK(&in6_ifa_tracker);
1975 	CK_STAILQ_FOREACH(ifa, &V_in6_ifaddrhead, ia_link) {
1976 		if (!(ifa->ia6_flags & IN6_IFF_AUTOCONF))
1977 			continue;
1978 
1979 		if (ifa->ia6_ndpr == NULL) {
1980 			/*
1981 			 * This can happen when we first configure the address
1982 			 * (i.e. the address exists, but the prefix does not).
1983 			 * XXX: complicated relationships...
1984 			 */
1985 			continue;
1986 		}
1987 
1988 		if (find_pfxlist_reachable_router(ifa->ia6_ndpr))
1989 			break;
1990 	}
1991 	if (ifa) {
1992 		CK_STAILQ_FOREACH(ifa, &V_in6_ifaddrhead, ia_link) {
1993 			if ((ifa->ia6_flags & IN6_IFF_AUTOCONF) == 0)
1994 				continue;
1995 
1996 			if (ifa->ia6_ndpr == NULL) /* XXX: see above. */
1997 				continue;
1998 
1999 			if (find_pfxlist_reachable_router(ifa->ia6_ndpr)) {
2000 				if (ifa->ia6_flags & IN6_IFF_DETACHED) {
2001 					ifa->ia6_flags &= ~IN6_IFF_DETACHED;
2002 					ifa->ia6_flags |= IN6_IFF_TENTATIVE;
2003 					nd6_dad_start((struct ifaddr *)ifa, 0);
2004 				}
2005 			} else {
2006 				ifa->ia6_flags |= IN6_IFF_DETACHED;
2007 			}
2008 		}
2009 	} else {
2010 		CK_STAILQ_FOREACH(ifa, &V_in6_ifaddrhead, ia_link) {
2011 			if ((ifa->ia6_flags & IN6_IFF_AUTOCONF) == 0)
2012 				continue;
2013 
2014 			if (ifa->ia6_flags & IN6_IFF_DETACHED) {
2015 				ifa->ia6_flags &= ~IN6_IFF_DETACHED;
2016 				ifa->ia6_flags |= IN6_IFF_TENTATIVE;
2017 				/* Do we need a delay in this case? */
2018 				nd6_dad_start((struct ifaddr *)ifa, 0);
2019 			}
2020 		}
2021 	}
2022 	IN6_IFADDR_RUNLOCK(&in6_ifa_tracker);
2023 	ND6_RUNLOCK();
2024 	ND6_ONLINK_UNLOCK();
2025 }
2026 
2027 /*
2028  * Add or remove interface route specified by @dst, @netmask and @ifp.
2029  * ifa can be NULL.
2030  * Returns 0 on success
2031  */
2032 static int
nd6_prefix_rtrequest(uint32_t fibnum,int cmd,struct sockaddr_in6 * dst,struct sockaddr_in6 * netmask,struct ifnet * ifp,struct ifaddr * ifa)2033 nd6_prefix_rtrequest(uint32_t fibnum, int cmd, struct sockaddr_in6 *dst,
2034     struct sockaddr_in6 *netmask, struct ifnet *ifp, struct ifaddr *ifa)
2035 {
2036 	struct epoch_tracker et;
2037 	int error;
2038 
2039 	/* Prepare gateway */
2040 	struct sockaddr_dl_short sdl = {
2041 		.sdl_family = AF_LINK,
2042 		.sdl_len = sizeof(struct sockaddr_dl_short),
2043 		.sdl_type = ifp->if_type,
2044 		.sdl_index = ifp->if_index,
2045 	};
2046 
2047 	struct rt_addrinfo info = {
2048 		.rti_ifa = ifa,
2049 		.rti_ifp = ifp,
2050 		.rti_flags = RTF_PINNED | ((netmask != NULL) ? 0 : RTF_HOST),
2051 		.rti_info = {
2052 			[RTAX_DST] = (struct sockaddr *)dst,
2053 			[RTAX_NETMASK] = (struct sockaddr *)netmask,
2054 			[RTAX_GATEWAY] = (struct sockaddr *)&sdl,
2055 		},
2056 	};
2057 	/* Don't set additional per-gw filters on removal */
2058 
2059 	NET_EPOCH_ENTER(et);
2060 	error = rib_handle_ifaddr_info(fibnum, cmd, &info);
2061 	NET_EPOCH_EXIT(et);
2062 	return (error);
2063 }
2064 
2065 static int
nd6_prefix_onlink_rtrequest(struct nd_prefix * pr,struct ifaddr * ifa)2066 nd6_prefix_onlink_rtrequest(struct nd_prefix *pr, struct ifaddr *ifa)
2067 {
2068 	int error;
2069 
2070 	struct sockaddr_in6 mask6 = {
2071 		.sin6_family = AF_INET6,
2072 		.sin6_len = sizeof(struct sockaddr_in6),
2073 		.sin6_addr = pr->ndpr_mask,
2074 	};
2075 	struct sockaddr_in6 *pmask6 = (pr->ndpr_plen != 128) ? &mask6 : NULL;
2076 
2077 	error = nd6_prefix_rtrequest(pr->ndpr_ifp->if_fib, RTM_ADD,
2078 	    &pr->ndpr_prefix, pmask6, pr->ndpr_ifp, ifa);
2079 	if (error == 0)
2080 		pr->ndpr_stateflags |= NDPRF_ONLINK;
2081 
2082 	return (error);
2083 }
2084 
2085 static int
nd6_prefix_onlink(struct nd_prefix * pr)2086 nd6_prefix_onlink(struct nd_prefix *pr)
2087 {
2088 	struct epoch_tracker et;
2089 	struct ifaddr *ifa;
2090 	struct ifnet *ifp = pr->ndpr_ifp;
2091 	struct nd_prefix *opr;
2092 	char ip6buf[INET6_ADDRSTRLEN];
2093 	int error;
2094 
2095 	ND6_ONLINK_LOCK_ASSERT();
2096 	ND6_UNLOCK_ASSERT();
2097 
2098 	if ((pr->ndpr_stateflags & NDPRF_ONLINK) != 0)
2099 		return (EEXIST);
2100 
2101 	/*
2102 	 * Add the interface route associated with the prefix.  Before
2103 	 * installing the route, check if there's the same prefix on another
2104 	 * interface, and the prefix has already installed the interface route.
2105 	 * Although such a configuration is expected to be rare, we explicitly
2106 	 * allow it.
2107 	 */
2108 	ND6_RLOCK();
2109 	LIST_FOREACH(opr, &V_nd_prefix, ndpr_entry) {
2110 		if (opr == pr)
2111 			continue;
2112 
2113 		if ((opr->ndpr_stateflags & NDPRF_ONLINK) == 0)
2114 			continue;
2115 
2116 		if (!V_rt_add_addr_allfibs &&
2117 		    opr->ndpr_ifp->if_fib != pr->ndpr_ifp->if_fib)
2118 			continue;
2119 
2120 		if (opr->ndpr_plen == pr->ndpr_plen &&
2121 		    in6_are_prefix_equal(&pr->ndpr_prefix.sin6_addr,
2122 		    &opr->ndpr_prefix.sin6_addr, pr->ndpr_plen)) {
2123 			ND6_RUNLOCK();
2124 			return (0);
2125 		}
2126 	}
2127 	ND6_RUNLOCK();
2128 
2129 	/*
2130 	 * We prefer link-local addresses as the associated interface address.
2131 	 */
2132 	/* search for a link-local addr */
2133 	NET_EPOCH_ENTER(et);
2134 	ifa = (struct ifaddr *)in6ifa_ifpforlinklocal(ifp,
2135 	    IN6_IFF_NOTREADY | IN6_IFF_ANYCAST);
2136 	if (ifa == NULL) {
2137 		/* XXX: freebsd does not have ifa_ifwithaf */
2138 		CK_STAILQ_FOREACH(ifa, &ifp->if_addrhead, ifa_link) {
2139 			if (ifa->ifa_addr->sa_family == AF_INET6) {
2140 				ifa_ref(ifa);
2141 				break;
2142 			}
2143 		}
2144 		/* should we care about ia6_flags? */
2145 	}
2146 	if (ifa == NULL) {
2147 		/*
2148 		 * This can still happen, when, for example, we receive an RA
2149 		 * containing a prefix with the L bit set and the A bit clear,
2150 		 * after removing all IPv6 addresses on the receiving
2151 		 * interface.  This should, of course, be rare though.
2152 		 */
2153 		nd6log((LOG_NOTICE,
2154 		    "%s: failed to find any ifaddr to add route for a "
2155 		    "prefix(%s/%d) on %s\n", __func__,
2156 		    ip6_sprintf(ip6buf, &pr->ndpr_prefix.sin6_addr),
2157 		    pr->ndpr_plen, if_name(ifp)));
2158 		error = 0;
2159 	} else {
2160 		error = nd6_prefix_onlink_rtrequest(pr, ifa);
2161 		ifa_free(ifa);
2162 	}
2163 	NET_EPOCH_EXIT(et);
2164 
2165 	return (error);
2166 }
2167 
2168 int
nd6_prefix_offlink(struct nd_prefix * pr)2169 nd6_prefix_offlink(struct nd_prefix *pr)
2170 {
2171 	int error = 0;
2172 	struct ifnet *ifp = pr->ndpr_ifp;
2173 	struct nd_prefix *opr;
2174 	char ip6buf[INET6_ADDRSTRLEN];
2175 	uint64_t genid;
2176 	int a_failure;
2177 
2178 	ND6_ONLINK_LOCK_ASSERT();
2179 	ND6_UNLOCK_ASSERT();
2180 
2181 	if ((pr->ndpr_stateflags & NDPRF_ONLINK) == 0)
2182 		return (EEXIST);
2183 
2184 	struct sockaddr_in6 mask6 = {
2185 		.sin6_family = AF_INET6,
2186 		.sin6_len = sizeof(struct sockaddr_in6),
2187 		.sin6_addr = pr->ndpr_mask,
2188 	};
2189 	struct sockaddr_in6 *pmask6 = (pr->ndpr_plen != 128) ? &mask6 : NULL;
2190 
2191 	error = nd6_prefix_rtrequest(ifp->if_fib, RTM_DELETE,
2192 	    &pr->ndpr_prefix, pmask6, ifp, NULL);
2193 
2194 	a_failure = 1;
2195 	if (error == 0) {
2196 		pr->ndpr_stateflags &= ~NDPRF_ONLINK;
2197 
2198 		/*
2199 		 * There might be the same prefix on another interface,
2200 		 * the prefix which could not be on-link just because we have
2201 		 * the interface route (see comments in nd6_prefix_onlink).
2202 		 * If there's one, try to make the prefix on-link on the
2203 		 * interface.
2204 		 */
2205 		ND6_RLOCK();
2206 restart:
2207 		LIST_FOREACH(opr, &V_nd_prefix, ndpr_entry) {
2208 			/*
2209 			 * KAME specific: detached prefixes should not be
2210 			 * on-link.
2211 			 */
2212 			if (opr == pr || (opr->ndpr_stateflags &
2213 			    (NDPRF_ONLINK | NDPRF_DETACHED)) != 0)
2214 				continue;
2215 
2216 			if (opr->ndpr_plen == pr->ndpr_plen &&
2217 			    in6_are_prefix_equal(&pr->ndpr_prefix.sin6_addr,
2218 			    &opr->ndpr_prefix.sin6_addr, pr->ndpr_plen)) {
2219 				int e;
2220 
2221 				genid = V_nd6_list_genid;
2222 				ND6_RUNLOCK();
2223 				if ((e = nd6_prefix_onlink(opr)) != 0) {
2224 					nd6log((LOG_ERR,
2225 					    "%s: failed to recover a prefix "
2226 					    "%s/%d from %s to %s (errno=%d)\n",
2227 					    __func__, ip6_sprintf(ip6buf,
2228 						&opr->ndpr_prefix.sin6_addr),
2229 					    opr->ndpr_plen, if_name(ifp),
2230 					    if_name(opr->ndpr_ifp), e));
2231 				} else
2232 					a_failure = 0;
2233 				ND6_RLOCK();
2234 				if (genid != V_nd6_list_genid)
2235 					goto restart;
2236 			}
2237 		}
2238 		ND6_RUNLOCK();
2239 	} else {
2240 		/* XXX: can we still set the NDPRF_ONLINK flag? */
2241 		nd6log((LOG_ERR,
2242 		    "%s: failed to delete route: %s/%d on %s (errno=%d)\n",
2243 		    __func__, ip6_sprintf(ip6buf, &pr->ndpr_prefix.sin6_addr),
2244 		    pr->ndpr_plen, if_name(ifp), error));
2245 	}
2246 
2247 	if (a_failure)
2248 		lltable_prefix_free(AF_INET6,
2249 		    (struct sockaddr *)&pr->ndpr_prefix,
2250 		    (struct sockaddr *)&mask6, LLE_STATIC);
2251 
2252 	return (error);
2253 }
2254 
2255 /*
2256  * Get a randomized interface identifier for a temporary address
2257  * Based on RFC 8981, Section 3.3.1.
2258  */
2259 static int
in6_get_tmp_ifid(struct in6_aliasreq * ifra)2260 in6_get_tmp_ifid(struct in6_aliasreq *ifra)
2261 {
2262 	struct in6_addr *addr;
2263 
2264 	if(!is_random_seeded()){
2265 		return 1;
2266 	}
2267 
2268 	addr = &(ifra->ifra_addr.sin6_addr);
2269 regen:
2270 	ifra->ifra_addr.sin6_addr.s6_addr32[2] |=
2271 	    (arc4random() & ~(ifra->ifra_prefixmask.sin6_addr.s6_addr32[2]));
2272 	ifra->ifra_addr.sin6_addr.s6_addr32[3] |=
2273 	    (arc4random() & ~(ifra->ifra_prefixmask.sin6_addr.s6_addr32[3]));
2274 
2275 	/*
2276 	 * Check if generated address is not inappropriate:
2277 	 *
2278 	 * - Reserved IPv6 Interface aIdentifers
2279 	 *   (https://www.iana.org/assignments/ipv6-interface-ids/)
2280 	 */
2281 
2282 	/* Subnet-router anycast: 0000:0000:0000:0000 */
2283 	if (!(addr->s6_addr32[2] | addr->s6_addr32[3]))
2284 		goto regen;
2285 
2286 	/*
2287 	 * IANA Ethernet block: 0200:5EFF:FE00:0000-0200:5EFF:FE00:5212
2288 	 * Proxy Mobile IPv6:   0200:5EFF:FE00:5213
2289 	 * IANA Ethernet block: 0200:5EFF:FE00:5214-0200:5EFF:FEFF:FFFF
2290 	 */
2291 	if (ntohl(addr->s6_addr32[2]) == 0x02005eff &&
2292 	    (ntohl(addr->s6_addr32[3]) & 0Xff000000) == 0xfe000000)
2293 		goto regen;
2294 
2295 	/* Reserved subnet anycast addresses */
2296 	if (ntohl(addr->s6_addr32[2]) == 0xfdffffff &&
2297 	    ntohl(addr->s6_addr32[3]) >= 0Xffffff80)
2298 		goto regen;
2299 
2300 	return 0;
2301 }
2302 
2303 /*
2304  * ia0 - corresponding public address
2305  */
2306 int
in6_tmpifadd(const struct in6_ifaddr * ia0,int forcegen,int delay)2307 in6_tmpifadd(const struct in6_ifaddr *ia0, int forcegen, int delay)
2308 {
2309 	struct ifnet *ifp = ia0->ia_ifa.ifa_ifp;
2310 	struct in6_ifaddr *newia;
2311 	struct in6_aliasreq ifra;
2312 	int error;
2313 	int trylimit = 3;	/* XXX: adhoc value */
2314 	int updateflags;
2315 	time_t vltime0, pltime0;
2316 
2317 	in6_prepare_ifra(&ifra, &ia0->ia_addr.sin6_addr,
2318 	    &ia0->ia_prefixmask.sin6_addr);
2319 
2320 	ifra.ifra_addr = ia0->ia_addr;	/* XXX: do we need this ? */
2321 	/* clear the old IFID */
2322 	IN6_MASK_ADDR(&ifra.ifra_addr.sin6_addr,
2323 	    &ifra.ifra_prefixmask.sin6_addr);
2324 
2325   again:
2326 	if (in6_get_tmp_ifid(&ifra) != 0) {
2327 		nd6log((LOG_NOTICE, "%s: failed to find a good random IFID\n",
2328 		    __func__));
2329 		return (EINVAL);
2330 	}
2331 
2332 	/*
2333 	 * in6_get_tmpifid() quite likely provided a unique interface ID.
2334 	 * However, we may still have a chance to see collision, because
2335 	 * there may be a time lag between generation of the ID and generation
2336 	 * of the address.  So, we'll do one more sanity check.
2337 	 */
2338 
2339 	if (in6_localip(&ifra.ifra_addr.sin6_addr) != 0) {
2340 		if (trylimit-- > 0) {
2341 			forcegen = 1;
2342 			goto again;
2343 		}
2344 
2345 		/* Give up.  Something strange should have happened.  */
2346 		nd6log((LOG_NOTICE, "%s: failed to find a unique random IFID\n",
2347 		    __func__));
2348 		return (EEXIST);
2349 	}
2350 
2351 	/*
2352 	 * The Valid Lifetime is the lower of the Valid Lifetime of the
2353          * public address or TEMP_VALID_LIFETIME.
2354 	 * The Preferred Lifetime is the lower of the Preferred Lifetime
2355          * of the public address or TEMP_PREFERRED_LIFETIME -
2356          * DESYNC_FACTOR.
2357 	 */
2358 	if (ia0->ia6_lifetime.ia6t_vltime != ND6_INFINITE_LIFETIME) {
2359 		vltime0 = IFA6_IS_INVALID(ia0) ? 0 :
2360 		    (ia0->ia6_lifetime.ia6t_vltime -
2361 		    (time_uptime - ia0->ia6_updatetime));
2362 		if (vltime0 > V_ip6_temp_valid_lifetime)
2363 			vltime0 = V_ip6_temp_valid_lifetime;
2364 	} else
2365 		vltime0 = V_ip6_temp_valid_lifetime;
2366 	if (ia0->ia6_lifetime.ia6t_pltime != ND6_INFINITE_LIFETIME) {
2367 		pltime0 = IFA6_IS_DEPRECATED(ia0) ? 0 :
2368 		    (ia0->ia6_lifetime.ia6t_pltime -
2369 		    (time_uptime - ia0->ia6_updatetime));
2370 		if (pltime0 > V_ip6_temp_preferred_lifetime - V_ip6_desync_factor){
2371 			pltime0 = V_ip6_temp_preferred_lifetime -
2372 			    V_ip6_desync_factor;
2373 		}
2374 	} else
2375 		pltime0 = V_ip6_temp_preferred_lifetime - V_ip6_desync_factor;
2376 	ifra.ifra_lifetime.ia6t_vltime = vltime0;
2377 	ifra.ifra_lifetime.ia6t_pltime = pltime0;
2378 
2379 	/*
2380 	 * A temporary address is created only if this calculated Preferred
2381 	 * Lifetime is greater than REGEN_ADVANCE time units.
2382 	 */
2383 	if (ifra.ifra_lifetime.ia6t_pltime <= V_ip6_temp_regen_advance)
2384 		return (0);
2385 
2386 	/* XXX: scope zone ID? */
2387 
2388 	ifra.ifra_flags |= (IN6_IFF_AUTOCONF|IN6_IFF_TEMPORARY);
2389 
2390 	/* allocate ifaddr structure, link into chain, etc. */
2391 	updateflags = 0;
2392 	if (delay)
2393 		updateflags |= IN6_IFAUPDATE_DADDELAY;
2394 	if ((error = in6_update_ifa(ifp, &ifra, NULL, updateflags)) != 0)
2395 		return (error);
2396 
2397 	newia = in6ifa_ifpwithaddr(ifp, &ifra.ifra_addr.sin6_addr);
2398 	if (newia == NULL) {	/* XXX: can it happen? */
2399 		nd6log((LOG_ERR,
2400 		    "%s: ifa update succeeded, but we got no ifaddr\n",
2401 		    __func__));
2402 		return (EINVAL); /* XXX */
2403 	}
2404 	newia->ia6_ndpr = ia0->ia6_ndpr;
2405 	newia->ia6_ndpr->ndpr_addrcnt++;
2406 	ifa_free(&newia->ia_ifa);
2407 
2408 	/*
2409 	 * A newly added address might affect the status of other addresses.
2410 	 * XXX: when the temporary address is generated with a new public
2411 	 * address, the onlink check is redundant.  However, it would be safe
2412 	 * to do the check explicitly everywhere a new address is generated,
2413 	 * and, in fact, we surely need the check when we create a new
2414 	 * temporary address due to deprecation of an old temporary address.
2415 	 */
2416 	pfxlist_onlink_check();
2417 
2418 	return (0);
2419 }
2420 
2421 static int
rt6_deleteroute(const struct rtentry * rt,const struct nhop_object * nh,void * arg)2422 rt6_deleteroute(const struct rtentry *rt, const struct nhop_object *nh,
2423     void *arg)
2424 {
2425 	struct in6_addr *gate = (struct in6_addr *)arg;
2426 	int nh_rt_flags;
2427 
2428 	if (nh->gw_sa.sa_family != AF_INET6)
2429 		return (0);
2430 
2431 	if (!IN6_ARE_ADDR_EQUAL(gate, &nh->gw6_sa.sin6_addr)) {
2432 		return (0);
2433 	}
2434 
2435 	/*
2436 	 * Do not delete a static route.
2437 	 * XXX: this seems to be a bit ad-hoc. Should we consider the
2438 	 * 'cloned' bit instead?
2439 	 */
2440 	nh_rt_flags = nhop_get_rtflags(nh);
2441 	if ((nh_rt_flags & RTF_STATIC) != 0)
2442 		return (0);
2443 
2444 	/*
2445 	 * We delete only host route. This means, in particular, we don't
2446 	 * delete default route.
2447 	 */
2448 	if ((nh_rt_flags & RTF_HOST) == 0)
2449 		return (0);
2450 
2451 	return (1);
2452 #undef SIN6
2453 }
2454 
2455 /*
2456  * Delete all the routing table entries that use the specified gateway.
2457  * XXX: this function causes search through all entries of routing table, so
2458  * it shouldn't be called when acting as a router.
2459  */
2460 void
rt6_flush(struct in6_addr * gateway,struct ifnet * ifp)2461 rt6_flush(struct in6_addr *gateway, struct ifnet *ifp)
2462 {
2463 
2464 	/* We'll care only link-local addresses */
2465 	if (!IN6_IS_ADDR_LINKLOCAL(gateway))
2466 		return;
2467 
2468 	/* XXX Do we really need to walk any but the default FIB? */
2469 	rib_foreach_table_walk_del(AF_INET6, rt6_deleteroute, (void *)gateway);
2470 }
2471 
2472 int
nd6_setdefaultiface(int ifindex)2473 nd6_setdefaultiface(int ifindex)
2474 {
2475 
2476 	if (V_nd6_defifindex != ifindex) {
2477 		V_nd6_defifindex = ifindex;
2478 		if (V_nd6_defifindex != 0) {
2479 			struct epoch_tracker et;
2480 
2481 			/*
2482 			 * XXXGL: this function should use ifnet_byindex_ref!
2483 			 */
2484 			NET_EPOCH_ENTER(et);
2485 			V_nd6_defifp = ifnet_byindex(V_nd6_defifindex);
2486 			NET_EPOCH_EXIT(et);
2487 			if (V_nd6_defifp == NULL)
2488 				return (EINVAL);
2489 		} else
2490 			V_nd6_defifp = NULL;
2491 
2492 		/*
2493 		 * Our current implementation assumes one-to-one mapping between
2494 		 * interfaces and links, so it would be natural to use the
2495 		 * default interface as the default link.
2496 		 */
2497 		scope6_setdefault(V_nd6_defifp);
2498 	}
2499 
2500 	return (0);
2501 }
2502 
2503 bool
nd6_defrouter_list_empty(void)2504 nd6_defrouter_list_empty(void)
2505 {
2506 
2507 	return (TAILQ_EMPTY(&V_nd6_defrouter));
2508 }
2509 
2510 void
nd6_defrouter_timer(void)2511 nd6_defrouter_timer(void)
2512 {
2513 	struct nd_defrouter *dr, *ndr;
2514 	struct nd6_drhead drq;
2515 
2516 	TAILQ_INIT(&drq);
2517 
2518 	ND6_WLOCK();
2519 	TAILQ_FOREACH_SAFE(dr, &V_nd6_defrouter, dr_entry, ndr)
2520 		if (dr->expire && dr->expire < time_uptime)
2521 			defrouter_unlink(dr, &drq);
2522 	ND6_WUNLOCK();
2523 
2524 	while ((dr = TAILQ_FIRST(&drq)) != NULL) {
2525 		TAILQ_REMOVE(&drq, dr, dr_entry);
2526 		defrouter_del(dr);
2527 	}
2528 }
2529 
2530 /*
2531  * Nuke default router list entries toward ifp.
2532  * We defer removal of default router list entries that is installed in the
2533  * routing table, in order to keep additional side effects as small as possible.
2534  */
2535 void
nd6_defrouter_purge(struct ifnet * ifp)2536 nd6_defrouter_purge(struct ifnet *ifp)
2537 {
2538 	struct nd_defrouter *dr, *ndr;
2539 	struct nd6_drhead drq;
2540 
2541 	TAILQ_INIT(&drq);
2542 
2543 	ND6_WLOCK();
2544 	TAILQ_FOREACH_SAFE(dr, &V_nd6_defrouter, dr_entry, ndr) {
2545 		if (dr->installed)
2546 			continue;
2547 		if (dr->ifp == ifp)
2548 			defrouter_unlink(dr, &drq);
2549 	}
2550 	TAILQ_FOREACH_SAFE(dr, &V_nd6_defrouter, dr_entry, ndr) {
2551 		if (!dr->installed)
2552 			continue;
2553 		if (dr->ifp == ifp)
2554 			defrouter_unlink(dr, &drq);
2555 	}
2556 	ND6_WUNLOCK();
2557 
2558 	/* Delete the unlinked router objects. */
2559 	while ((dr = TAILQ_FIRST(&drq)) != NULL) {
2560 		TAILQ_REMOVE(&drq, dr, dr_entry);
2561 		defrouter_del(dr);
2562 	}
2563 }
2564 
2565 void
nd6_defrouter_flush_all(void)2566 nd6_defrouter_flush_all(void)
2567 {
2568 	struct nd_defrouter *dr;
2569 	struct nd6_drhead drq;
2570 
2571 	TAILQ_INIT(&drq);
2572 
2573 	ND6_WLOCK();
2574 	while ((dr = TAILQ_FIRST(&V_nd6_defrouter)) != NULL)
2575 		defrouter_unlink(dr, &drq);
2576 	ND6_WUNLOCK();
2577 
2578 	while ((dr = TAILQ_FIRST(&drq)) != NULL) {
2579 		TAILQ_REMOVE(&drq, dr, dr_entry);
2580 		defrouter_del(dr);
2581 	}
2582 }
2583 
2584 void
nd6_defrouter_init(void)2585 nd6_defrouter_init(void)
2586 {
2587 
2588 	TAILQ_INIT(&V_nd6_defrouter);
2589 }
2590 
2591 static int
nd6_sysctl_drlist(SYSCTL_HANDLER_ARGS)2592 nd6_sysctl_drlist(SYSCTL_HANDLER_ARGS)
2593 {
2594 	struct in6_defrouter d;
2595 	struct nd_defrouter *dr;
2596 	int error;
2597 
2598 	if (req->newptr != NULL)
2599 		return (EPERM);
2600 
2601 	error = sysctl_wire_old_buffer(req, 0);
2602 	if (error != 0)
2603 		return (error);
2604 
2605 	bzero(&d, sizeof(d));
2606 	d.rtaddr.sin6_family = AF_INET6;
2607 	d.rtaddr.sin6_len = sizeof(d.rtaddr);
2608 
2609 	ND6_RLOCK();
2610 	TAILQ_FOREACH(dr, &V_nd6_defrouter, dr_entry) {
2611 		d.rtaddr.sin6_addr = dr->rtaddr;
2612 		error = sa6_recoverscope(&d.rtaddr);
2613 		if (error != 0)
2614 			break;
2615 		d.flags = dr->raflags;
2616 		d.rtlifetime = dr->rtlifetime;
2617 		d.expire = dr->expire + (time_second - time_uptime);
2618 		d.if_index = dr->ifp->if_index;
2619 		error = SYSCTL_OUT(req, &d, sizeof(d));
2620 		if (error != 0)
2621 			break;
2622 	}
2623 	ND6_RUNLOCK();
2624 	return (error);
2625 }
2626 SYSCTL_PROC(_net_inet6_icmp6, ICMPV6CTL_ND6_DRLIST, nd6_drlist,
2627 	CTLTYPE_OPAQUE | CTLFLAG_RD | CTLFLAG_MPSAFE,
2628 	NULL, 0, nd6_sysctl_drlist, "S,in6_defrouter",
2629 	"NDP default router list");
2630