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