xref: /netbsd/sys/netinet6/nd6_rtr.c (revision bf9ec67e)
1 /*	$NetBSD: nd6_rtr.c,v 1.28 2001/12/18 03:04:05 itojun Exp $	*/
2 /*	$KAME: nd6_rtr.c,v 1.95 2001/02/07 08:09:47 itojun Exp $	*/
3 
4 /*
5  * Copyright (C) 1995, 1996, 1997, and 1998 WIDE Project.
6  * All rights reserved.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  * 3. Neither the name of the project nor the names of its contributors
17  *    may be used to endorse or promote products derived from this software
18  *    without specific prior written permission.
19  *
20  * THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND
21  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23  * ARE DISCLAIMED.  IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE
24  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
26  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
29  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
30  * SUCH DAMAGE.
31  */
32 
33 #include <sys/cdefs.h>
34 __KERNEL_RCSID(0, "$NetBSD: nd6_rtr.c,v 1.28 2001/12/18 03:04:05 itojun Exp $");
35 
36 #include <sys/param.h>
37 #include <sys/systm.h>
38 #include <sys/malloc.h>
39 #include <sys/mbuf.h>
40 #include <sys/socket.h>
41 #include <sys/sockio.h>
42 #include <sys/time.h>
43 #include <sys/kernel.h>
44 #include <sys/errno.h>
45 #include <sys/ioctl.h>
46 #include <sys/syslog.h>
47 
48 #include <net/if.h>
49 #include <net/if_types.h>
50 #include <net/if_dl.h>
51 #include <net/route.h>
52 #include <net/radix.h>
53 
54 #include <netinet/in.h>
55 #include <netinet6/in6_var.h>
56 #include <netinet/ip6.h>
57 #include <netinet6/ip6_var.h>
58 #include <netinet6/nd6.h>
59 #include <netinet/icmp6.h>
60 
61 #include <net/net_osdep.h>
62 
63 #define SDL(s)	((struct sockaddr_dl *)s)
64 
65 static struct nd_defrouter *defrtrlist_update __P((struct nd_defrouter *));
66 static int prelist_add __P((struct nd_prefix *, struct nd_defrouter *));
67 static struct nd_prefix *prefix_lookup __P((struct nd_prefix *));
68 static struct in6_ifaddr *in6_ifadd __P((struct ifnet *, struct in6_addr *,
69 			  struct in6_addr *, int));
70 static struct nd_pfxrouter *pfxrtr_lookup __P((struct nd_prefix *,
71 					       struct nd_defrouter *));
72 static void pfxrtr_add __P((struct nd_prefix *, struct nd_defrouter *));
73 static void pfxrtr_del __P((struct nd_pfxrouter *));
74 static struct nd_pfxrouter *find_pfxlist_reachable_router __P((struct nd_prefix *));
75 static void nd6_detach_prefix __P((struct nd_prefix *));
76 static void nd6_attach_prefix __P((struct nd_prefix *));
77 static void defrouter_addifreq __P((struct ifnet *));
78 
79 static void in6_init_address_ltimes __P((struct nd_prefix *ndpr,
80 					 struct in6_addrlifetime *lt6,
81 					 int update_vltime));
82 
83 static int rt6_deleteroute __P((struct radix_node *, void *));
84 
85 extern int nd6_recalc_reachtm_interval;
86 
87 static struct ifnet *nd6_defifp;
88 int nd6_defifindex;
89 
90 /*
91  * Receive Router Solicitation Message - just for routers.
92  * Router solicitation/advertisement is mostly managed by userland program
93  * (rtadvd) so here we have no function like nd6_ra_output().
94  *
95  * Based on RFC 2461
96  */
97 void
98 nd6_rs_input(m, off, icmp6len)
99 	struct	mbuf *m;
100 	int off, icmp6len;
101 {
102 	struct ifnet *ifp = m->m_pkthdr.rcvif;
103 	struct ip6_hdr *ip6 = mtod(m, struct ip6_hdr *);
104 	struct nd_router_solicit *nd_rs;
105 	struct in6_addr saddr6 = ip6->ip6_src;
106 #if 0
107 	struct in6_addr daddr6 = ip6->ip6_dst;
108 #endif
109 	char *lladdr = NULL;
110 	int lladdrlen = 0;
111 #if 0
112 	struct sockaddr_dl *sdl = (struct sockaddr_dl *)NULL;
113 	struct llinfo_nd6 *ln = (struct llinfo_nd6 *)NULL;
114 	struct rtentry *rt = NULL;
115 	int is_newentry;
116 #endif
117 	union nd_opts ndopts;
118 
119 	/* If I'm not a router, ignore it. */
120 	if (ip6_accept_rtadv != 0 || ip6_forwarding != 1)
121 		goto freeit;
122 
123 	/* Sanity checks */
124 	if (ip6->ip6_hlim != 255) {
125 		nd6log((LOG_ERR,
126 		    "nd6_rs_input: invalid hlim (%d) from %s to %s on %s\n",
127 		    ip6->ip6_hlim, ip6_sprintf(&ip6->ip6_src),
128 		    ip6_sprintf(&ip6->ip6_dst), if_name(ifp)));
129 		goto bad;
130 	}
131 
132 	/*
133 	 * Don't update the neighbor cache, if src = ::.
134 	 * This indicates that the src has no IP address assigned yet.
135 	 */
136 	if (IN6_IS_ADDR_UNSPECIFIED(&saddr6))
137 		goto freeit;
138 
139 #ifndef PULLDOWN_TEST
140 	IP6_EXTHDR_CHECK(m, off, icmp6len,);
141 	nd_rs = (struct nd_router_solicit *)((caddr_t)ip6 + off);
142 #else
143 	IP6_EXTHDR_GET(nd_rs, struct nd_router_solicit *, m, off, icmp6len);
144 	if (nd_rs == NULL) {
145 		icmp6stat.icp6s_tooshort++;
146 		return;
147 	}
148 #endif
149 
150 	icmp6len -= sizeof(*nd_rs);
151 	nd6_option_init(nd_rs + 1, icmp6len, &ndopts);
152 	if (nd6_options(&ndopts) < 0) {
153 		nd6log((LOG_INFO,
154 		    "nd6_rs_input: invalid ND option, ignored\n"));
155 		/* nd6_options have incremented stats */
156 		goto freeit;
157 	}
158 
159 	if (ndopts.nd_opts_src_lladdr) {
160 		lladdr = (char *)(ndopts.nd_opts_src_lladdr + 1);
161 		lladdrlen = ndopts.nd_opts_src_lladdr->nd_opt_len << 3;
162 	}
163 
164 	if (lladdr && ((ifp->if_addrlen + 2 + 7) & ~7) != lladdrlen) {
165 		nd6log((LOG_INFO,
166 		    "nd6_rs_input: lladdrlen mismatch for %s "
167 		    "(if %d, RS packet %d)\n",
168 			ip6_sprintf(&saddr6), ifp->if_addrlen, lladdrlen - 2));
169 		goto bad;
170 	}
171 
172 	nd6_cache_lladdr(ifp, &saddr6, lladdr, lladdrlen, ND_ROUTER_SOLICIT, 0);
173 
174  freeit:
175 	m_freem(m);
176 	return;
177 
178  bad:
179 	icmp6stat.icp6s_badrs++;
180 	m_freem(m);
181 }
182 
183 /*
184  * Receive Router Advertisement Message.
185  *
186  * Based on RFC 2461
187  * TODO: on-link bit on prefix information
188  * TODO: ND_RA_FLAG_{OTHER,MANAGED} processing
189  */
190 void
191 nd6_ra_input(m, off, icmp6len)
192 	struct	mbuf *m;
193 	int off, icmp6len;
194 {
195 	struct ifnet *ifp = m->m_pkthdr.rcvif;
196 	struct nd_ifinfo *ndi = &nd_ifinfo[ifp->if_index];
197 	struct ip6_hdr *ip6 = mtod(m, struct ip6_hdr *);
198 	struct nd_router_advert *nd_ra;
199 	struct in6_addr saddr6 = ip6->ip6_src;
200 #if 0
201 	struct in6_addr daddr6 = ip6->ip6_dst;
202 	int flags; /* = nd_ra->nd_ra_flags_reserved; */
203 	int is_managed = ((flags & ND_RA_FLAG_MANAGED) != 0);
204 	int is_other = ((flags & ND_RA_FLAG_OTHER) != 0);
205 #endif
206 	union nd_opts ndopts;
207 	struct nd_defrouter *dr;
208 
209 	if (ip6_accept_rtadv == 0)
210 		goto freeit;
211 
212 	if (ip6->ip6_hlim != 255) {
213 		nd6log((LOG_ERR,
214 		    "nd6_ra_input: invalid hlim (%d) from %s to %s on %s\n",
215 		    ip6->ip6_hlim, ip6_sprintf(&ip6->ip6_src),
216 		    ip6_sprintf(&ip6->ip6_dst), if_name(ifp)));
217 		goto bad;
218 	}
219 
220 	if (!IN6_IS_ADDR_LINKLOCAL(&saddr6)) {
221 		nd6log((LOG_ERR,
222 		    "nd6_ra_input: src %s is not link-local\n",
223 		    ip6_sprintf(&saddr6)));
224 		goto bad;
225 	}
226 
227 #ifndef PULLDOWN_TEST
228 	IP6_EXTHDR_CHECK(m, off, icmp6len,);
229 	nd_ra = (struct nd_router_advert *)((caddr_t)ip6 + off);
230 #else
231 	IP6_EXTHDR_GET(nd_ra, struct nd_router_advert *, m, off, icmp6len);
232 	if (nd_ra == NULL) {
233 		icmp6stat.icp6s_tooshort++;
234 		return;
235 	}
236 #endif
237 
238 	icmp6len -= sizeof(*nd_ra);
239 	nd6_option_init(nd_ra + 1, icmp6len, &ndopts);
240 	if (nd6_options(&ndopts) < 0) {
241 		nd6log((LOG_INFO,
242 		    "nd6_ra_input: invalid ND option, ignored\n"));
243 		/* nd6_options have incremented stats */
244 		goto freeit;
245 	}
246 
247     {
248 	struct nd_defrouter dr0;
249 	u_int32_t advreachable = nd_ra->nd_ra_reachable;
250 	long time_second = time.tv_sec;
251 
252 	Bzero(&dr0, sizeof(dr0));
253 	dr0.rtaddr = saddr6;
254 	dr0.flags  = nd_ra->nd_ra_flags_reserved;
255 	dr0.rtlifetime = ntohs(nd_ra->nd_ra_router_lifetime);
256 	dr0.expire = time_second + dr0.rtlifetime;
257 	dr0.ifp = ifp;
258 	/* unspecified or not? (RFC 2461 6.3.4) */
259 	if (advreachable) {
260 		NTOHL(advreachable);
261 		if (advreachable <= MAX_REACHABLE_TIME &&
262 		    ndi->basereachable != advreachable) {
263 			ndi->basereachable = advreachable;
264 			ndi->reachable = ND_COMPUTE_RTIME(ndi->basereachable);
265 			ndi->recalctm = nd6_recalc_reachtm_interval; /* reset */
266 		}
267 	}
268 	if (nd_ra->nd_ra_retransmit)
269 		ndi->retrans = ntohl(nd_ra->nd_ra_retransmit);
270 	if (nd_ra->nd_ra_curhoplimit)
271 		ndi->chlim = nd_ra->nd_ra_curhoplimit;
272 	dr = defrtrlist_update(&dr0);
273     }
274 
275 	/*
276 	 * prefix
277 	 */
278 	if (ndopts.nd_opts_pi) {
279 		struct nd_opt_hdr *pt;
280 		struct nd_opt_prefix_info *pi;
281 		struct nd_prefix pr;
282 
283 		for (pt = (struct nd_opt_hdr *)ndopts.nd_opts_pi;
284 		     pt <= (struct nd_opt_hdr *)ndopts.nd_opts_pi_end;
285 		     pt = (struct nd_opt_hdr *)((caddr_t)pt +
286 						(pt->nd_opt_len << 3))) {
287 			if (pt->nd_opt_type != ND_OPT_PREFIX_INFORMATION)
288 				continue;
289 			pi = (struct nd_opt_prefix_info *)pt;
290 
291 			if (pi->nd_opt_pi_len != 4) {
292 				nd6log((LOG_INFO,
293 				    "nd6_ra_input: invalid option "
294 				    "len %d for prefix information option, "
295 				    "ignored\n", pi->nd_opt_pi_len));
296 				continue;
297 			}
298 
299 			if (128 < pi->nd_opt_pi_prefix_len) {
300 				nd6log((LOG_INFO,
301 				    "nd6_ra_input: invalid prefix "
302 				    "len %d for prefix information option, "
303 				    "ignored\n", pi->nd_opt_pi_prefix_len));
304 				continue;
305 			}
306 
307 			if (IN6_IS_ADDR_MULTICAST(&pi->nd_opt_pi_prefix)
308 			 || IN6_IS_ADDR_LINKLOCAL(&pi->nd_opt_pi_prefix)) {
309 				nd6log((LOG_INFO,
310 				    "nd6_ra_input: invalid prefix "
311 				    "%s, ignored\n",
312 				    ip6_sprintf(&pi->nd_opt_pi_prefix)));
313 				continue;
314 			}
315 
316 			/* aggregatable unicast address, rfc2374 */
317 			if ((pi->nd_opt_pi_prefix.s6_addr8[0] & 0xe0) == 0x20
318 			 && pi->nd_opt_pi_prefix_len != 64) {
319 				nd6log((LOG_INFO,
320 				    "nd6_ra_input: invalid prefixlen "
321 				    "%d for rfc2374 prefix %s, ignored\n",
322 				    pi->nd_opt_pi_prefix_len,
323 				    ip6_sprintf(&pi->nd_opt_pi_prefix)));
324 				continue;
325 			}
326 
327 			bzero(&pr, sizeof(pr));
328 			pr.ndpr_prefix.sin6_family = AF_INET6;
329 			pr.ndpr_prefix.sin6_len = sizeof(pr.ndpr_prefix);
330 			pr.ndpr_prefix.sin6_addr = pi->nd_opt_pi_prefix;
331 			pr.ndpr_ifp = (struct ifnet *)m->m_pkthdr.rcvif;
332 
333 			pr.ndpr_raf_onlink = (pi->nd_opt_pi_flags_reserved &
334 					      ND_OPT_PI_FLAG_ONLINK) ? 1 : 0;
335 			pr.ndpr_raf_auto = (pi->nd_opt_pi_flags_reserved &
336 					    ND_OPT_PI_FLAG_AUTO) ? 1 : 0;
337 			pr.ndpr_plen = pi->nd_opt_pi_prefix_len;
338 			pr.ndpr_vltime = ntohl(pi->nd_opt_pi_valid_time);
339 			pr.ndpr_pltime =
340 				ntohl(pi->nd_opt_pi_preferred_time);
341 
342 			if (in6_init_prefix_ltimes(&pr))
343 				continue; /* prefix lifetime init failed */
344 
345 			(void)prelist_update(&pr, dr, m);
346 		}
347 	}
348 
349 	/*
350 	 * MTU
351 	 */
352 	if (ndopts.nd_opts_mtu && ndopts.nd_opts_mtu->nd_opt_mtu_len == 1) {
353 		u_int32_t mtu = ntohl(ndopts.nd_opts_mtu->nd_opt_mtu_mtu);
354 
355 		/* lower bound */
356 		if (mtu < IPV6_MMTU) {
357 			nd6log((LOG_INFO, "nd6_ra_input: bogus mtu option "
358 			    "mtu=%d sent from %s, ignoring\n",
359 			    mtu, ip6_sprintf(&ip6->ip6_src)));
360 			goto skip;
361 		}
362 
363 		/* upper bound */
364 		if (ndi->maxmtu) {
365 			if (mtu <= ndi->maxmtu) {
366 				int change = (ndi->linkmtu != mtu);
367 
368 				ndi->linkmtu = mtu;
369 				if (change) /* in6_maxmtu may change */
370 					in6_setmaxmtu();
371 			} else {
372 				nd6log((LOG_INFO, "nd6_ra_input: bogus mtu "
373 				    "mtu=%d sent from %s; "
374 				    "exceeds maxmtu %d, ignoring\n",
375 				    mtu, ip6_sprintf(&ip6->ip6_src),
376 				    ndi->maxmtu));
377 			}
378 		} else {
379 			nd6log((LOG_INFO, "nd6_ra_input: mtu option "
380 			    "mtu=%d sent from %s; maxmtu unknown, "
381 			    "ignoring\n",
382 			    mtu, ip6_sprintf(&ip6->ip6_src)));
383 		}
384 	}
385 
386  skip:
387 
388 	/*
389 	 * Source link layer address
390 	 */
391     {
392 	char *lladdr = NULL;
393 	int lladdrlen = 0;
394 
395 	if (ndopts.nd_opts_src_lladdr) {
396 		lladdr = (char *)(ndopts.nd_opts_src_lladdr + 1);
397 		lladdrlen = ndopts.nd_opts_src_lladdr->nd_opt_len << 3;
398 	}
399 
400 	if (lladdr && ((ifp->if_addrlen + 2 + 7) & ~7) != lladdrlen) {
401 		nd6log((LOG_INFO,
402 		    "nd6_ra_input: lladdrlen mismatch for %s "
403 		    "(if %d, RA packet %d)\n",
404 			ip6_sprintf(&saddr6), ifp->if_addrlen, lladdrlen - 2));
405 		goto bad;
406 	}
407 
408 	nd6_cache_lladdr(ifp, &saddr6, lladdr, lladdrlen, ND_ROUTER_ADVERT, 0);
409 
410 	/*
411 	 * Installing a link-layer address might change the state of the
412 	 * router's neighbor cache, which might also affect our on-link
413 	 * detection of adveritsed prefixes.
414 	 */
415 	pfxlist_onlink_check();
416     }
417 
418  freeit:
419 	m_freem(m);
420 	return;
421 
422  bad:
423 	icmp6stat.icp6s_badra++;
424 	m_freem(m);
425 }
426 
427 /*
428  * default router list proccessing sub routines
429  */
430 void
431 defrouter_addreq(new)
432 	struct nd_defrouter *new;
433 {
434 	struct sockaddr_in6 def, mask, gate;
435 	int s;
436 
437 	Bzero(&def, sizeof(def));
438 	Bzero(&mask, sizeof(mask));
439 	Bzero(&gate, sizeof(gate));
440 
441 	def.sin6_len = mask.sin6_len = gate.sin6_len
442 		= sizeof(struct sockaddr_in6);
443 	def.sin6_family = mask.sin6_family = gate.sin6_family = AF_INET6;
444 	gate.sin6_addr = new->rtaddr;
445 
446 	s = splsoftnet();
447 	(void)rtrequest(RTM_ADD, (struct sockaddr *)&def,
448 		(struct sockaddr *)&gate, (struct sockaddr *)&mask,
449 		RTF_GATEWAY, NULL);
450 	splx(s);
451 	return;
452 }
453 
454 /* Add a route to a given interface as default */
455 static void
456 defrouter_addifreq(ifp)
457 	struct ifnet *ifp;
458 {
459 	struct sockaddr_in6 def, mask;
460 	struct ifaddr *ifa;
461 	int error, flags;
462 
463 	bzero(&def, sizeof(def));
464 	bzero(&mask, sizeof(mask));
465 
466 	def.sin6_len = mask.sin6_len = sizeof(struct sockaddr_in6);
467 	def.sin6_family = mask.sin6_family = AF_INET6;
468 
469 	/*
470 	 * Search for an ifaddr beloging to the specified interface.
471 	 * XXX: An IPv6 address are required to be assigned on the interface.
472 	 */
473 	if ((ifa = ifaof_ifpforaddr((struct sockaddr *)&def, ifp)) == NULL) {
474 		nd6log((LOG_ERR,	/* better error? */
475 		    "defrouter_addifreq: failed to find an ifaddr "
476 		    "to install a route to interface %s\n",
477 		    if_name(ifp)));
478 		return;
479 	}
480 
481 	flags = ifa->ifa_flags;
482 	if ((ifp->if_flags & IFF_POINTOPOINT) != 0)
483 		flags &= ~RTF_CLONING;
484 	error = rtrequest(RTM_ADD, (struct sockaddr *)&def, ifa->ifa_addr,
485 			  (struct sockaddr *)&mask, flags, NULL);
486 	if (error != 0) {
487 		nd6log((LOG_ERR,
488 		    "defrouter_addifreq: failed to install a route to "
489 		    "interface %s (errno = %d)\n",
490 		    if_name(ifp), error));
491 	}
492 }
493 
494 struct nd_defrouter *
495 defrouter_lookup(addr, ifp)
496 	struct in6_addr *addr;
497 	struct ifnet *ifp;
498 {
499 	struct nd_defrouter *dr;
500 
501 	for (dr = TAILQ_FIRST(&nd_defrouter); dr;
502 	     dr = TAILQ_NEXT(dr, dr_entry)) {
503 		if (dr->ifp == ifp && IN6_ARE_ADDR_EQUAL(addr, &dr->rtaddr))
504 			return(dr);
505 	}
506 
507 	return(NULL);		/* search failed */
508 }
509 
510 void
511 defrouter_delreq(dr, dofree)
512 	struct nd_defrouter *dr;
513 	int dofree;
514 {
515 	struct sockaddr_in6 def, mask, gate;
516 
517 	Bzero(&def, sizeof(def));
518 	Bzero(&mask, sizeof(mask));
519 	Bzero(&gate, sizeof(gate));
520 
521 	def.sin6_len = mask.sin6_len = gate.sin6_len
522 		= sizeof(struct sockaddr_in6);
523 	def.sin6_family = mask.sin6_family = gate.sin6_family = AF_INET6;
524 	gate.sin6_addr = dr->rtaddr;
525 
526 	rtrequest(RTM_DELETE, (struct sockaddr *)&def,
527 		  (struct sockaddr *)&gate,
528 		  (struct sockaddr *)&mask,
529 		  RTF_GATEWAY, (struct rtentry **)0);
530 
531 	if (dofree)		/* XXX: necessary? */
532 		free(dr, M_IP6NDP);
533 }
534 
535 void
536 defrtrlist_del(dr)
537 	struct nd_defrouter *dr;
538 {
539 	struct nd_defrouter *deldr = NULL;
540 	struct nd_prefix *pr;
541 
542 	/*
543 	 * Flush all the routing table entries that use the router
544 	 * as a next hop.
545 	 */
546 	if (!ip6_forwarding && ip6_accept_rtadv) {
547 		/* above is a good condition? */
548 		rt6_flush(&dr->rtaddr, dr->ifp);
549 	}
550 
551 	if (dr == TAILQ_FIRST(&nd_defrouter))
552 		deldr = dr;	/* The router is primary. */
553 
554 	TAILQ_REMOVE(&nd_defrouter, dr, dr_entry);
555 
556 	/*
557 	 * Also delete all the pointers to the router in each prefix lists.
558 	 */
559 	for (pr = nd_prefix.lh_first; pr; pr = pr->ndpr_next) {
560 		struct nd_pfxrouter *pfxrtr;
561 		if ((pfxrtr = pfxrtr_lookup(pr, dr)) != NULL)
562 			pfxrtr_del(pfxrtr);
563 	}
564 	pfxlist_onlink_check();
565 
566 	/*
567 	 * If the router is the primary one, choose a new one.
568 	 * Note that defrouter_select() will remove the current gateway
569 	 * from the routing table.
570 	 */
571 	if (deldr)
572 		defrouter_select();
573 
574 	free(dr, M_IP6NDP);
575 }
576 
577 /*
578  * Default Router Selection according to Section 6.3.6 of RFC 2461:
579  * 1) Routers that are reachable or probably reachable should be
580  *    preferred.
581  * 2) When no routers on the list are known to be reachable or
582  *    probably reachable, routers SHOULD be selected in a round-robin
583  *    fashion.
584  * 3) If the Default Router List is empty, assume that all
585  *    destinations are on-link.
586  */
587 void
588 defrouter_select()
589 {
590 	int s = splsoftnet();
591 	struct nd_defrouter *dr, anydr;
592 	struct rtentry *rt = NULL;
593 	struct llinfo_nd6 *ln = NULL;
594 
595 	/*
596 	 * Search for a (probably) reachable router from the list.
597 	 */
598 	for (dr = TAILQ_FIRST(&nd_defrouter); dr;
599 	     dr = TAILQ_NEXT(dr, dr_entry)) {
600 		if ((rt = nd6_lookup(&dr->rtaddr, 0, dr->ifp)) &&
601 		    (ln = (struct llinfo_nd6 *)rt->rt_llinfo) &&
602 		    ND6_IS_LLINFO_PROBREACH(ln)) {
603 			/* Got it, and move it to the head */
604 			TAILQ_REMOVE(&nd_defrouter, dr, dr_entry);
605 			TAILQ_INSERT_HEAD(&nd_defrouter, dr, dr_entry);
606 			break;
607 		}
608 	}
609 
610 	if ((dr = TAILQ_FIRST(&nd_defrouter))) {
611 		/*
612 		 * De-install the previous default gateway and install
613 		 * a new one.
614 		 * Note that if there is no reachable router in the list,
615 		 * the head entry will be used anyway.
616 		 * XXX: do we have to check the current routing table entry?
617 		 */
618 		bzero(&anydr, sizeof(anydr));
619 		defrouter_delreq(&anydr, 0);
620 		defrouter_addreq(dr);
621 	}
622 	else {
623 		/*
624 		 * The Default Router List is empty, so install the default
625 		 * route to an inteface.
626 		 * XXX: The specification does not say this mechanism should
627 		 * be restricted to hosts, but this would be not useful
628 		 * (even harmful) for routers.
629 		 */
630 		if (!ip6_forwarding) {
631 			/*
632 			 * De-install the current default route
633 			 * in advance.
634 			 */
635 			bzero(&anydr, sizeof(anydr));
636 			defrouter_delreq(&anydr, 0);
637 			if (nd6_defifp) {
638 				/*
639 				 * Install a route to the default interface
640 				 * as default route.
641 				 * XXX: we enable this for host only, because
642 				 * this may override a default route installed
643 				 * a user process (e.g. routing daemon) in a
644 				 * router case.
645 				 */
646 				defrouter_addifreq(nd6_defifp);
647 			} else {
648 				nd6log((LOG_INFO, "defrouter_select: "
649 				    "there's no default router and no default"
650 				    " interface\n"));
651 			}
652 		}
653 	}
654 
655 	splx(s);
656 	return;
657 }
658 
659 static struct nd_defrouter *
660 defrtrlist_update(new)
661 	struct nd_defrouter *new;
662 {
663 	struct nd_defrouter *dr, *n;
664 	int s = splsoftnet();
665 
666 	if ((dr = defrouter_lookup(&new->rtaddr, new->ifp)) != NULL) {
667 		/* entry exists */
668 		if (new->rtlifetime == 0) {
669 			defrtrlist_del(dr);
670 			dr = NULL;
671 		} else {
672 			/* override */
673 			dr->flags = new->flags; /* xxx flag check */
674 			dr->rtlifetime = new->rtlifetime;
675 			dr->expire = new->expire;
676 		}
677 		splx(s);
678 		return(dr);
679 	}
680 
681 	/* entry does not exist */
682 	if (new->rtlifetime == 0) {
683 		splx(s);
684 		return(NULL);
685 	}
686 
687 	n = (struct nd_defrouter *)malloc(sizeof(*n), M_IP6NDP, M_NOWAIT);
688 	if (n == NULL) {
689 		splx(s);
690 		return(NULL);
691 	}
692 	bzero(n, sizeof(*n));
693 	*n = *new;
694 
695 	/*
696 	 * Insert the new router at the end of the Default Router List.
697 	 * If there is no other router, install it anyway. Otherwise,
698 	 * just continue to use the current default router.
699 	 */
700 	TAILQ_INSERT_TAIL(&nd_defrouter, n, dr_entry);
701 	if (TAILQ_FIRST(&nd_defrouter) == n)
702 		defrouter_select();
703 	splx(s);
704 
705 	return(n);
706 }
707 
708 static struct nd_pfxrouter *
709 pfxrtr_lookup(pr, dr)
710 	struct nd_prefix *pr;
711 	struct nd_defrouter *dr;
712 {
713 	struct nd_pfxrouter *search;
714 
715 	for (search = pr->ndpr_advrtrs.lh_first; search; search = search->pfr_next) {
716 		if (search->router == dr)
717 			break;
718 	}
719 
720 	return(search);
721 }
722 
723 static void
724 pfxrtr_add(pr, dr)
725 	struct nd_prefix *pr;
726 	struct nd_defrouter *dr;
727 {
728 	struct nd_pfxrouter *new;
729 
730 	new = (struct nd_pfxrouter *)malloc(sizeof(*new), M_IP6NDP, M_NOWAIT);
731 	if (new == NULL)
732 		return;
733 	bzero(new, sizeof(*new));
734 	new->router = dr;
735 
736 	LIST_INSERT_HEAD(&pr->ndpr_advrtrs, new, pfr_entry);
737 
738 	pfxlist_onlink_check();
739 }
740 
741 static void
742 pfxrtr_del(pfr)
743 	struct nd_pfxrouter *pfr;
744 {
745 	LIST_REMOVE(pfr, pfr_entry);
746 	free(pfr, M_IP6NDP);
747 }
748 
749 static struct nd_prefix *
750 prefix_lookup(pr)
751 	struct nd_prefix *pr;
752 {
753 	struct nd_prefix *search;
754 
755 	for (search = nd_prefix.lh_first; search; search = search->ndpr_next) {
756 		if (pr->ndpr_ifp == search->ndpr_ifp &&
757 		    pr->ndpr_plen == search->ndpr_plen &&
758 		    in6_are_prefix_equal(&pr->ndpr_prefix.sin6_addr,
759 					 &search->ndpr_prefix.sin6_addr,
760 					 pr->ndpr_plen)
761 		    ) {
762 			break;
763 		}
764 	}
765 
766 	return(search);
767 }
768 
769 static int
770 prelist_add(pr, dr)
771 	struct nd_prefix *pr;
772 	struct nd_defrouter *dr;
773 {
774 	struct nd_prefix *new;
775 	int i, s;
776 
777 	new = (struct nd_prefix *)malloc(sizeof(*new), M_IP6NDP, M_NOWAIT);
778 	if (new == NULL)
779 		return ENOMEM;
780 	bzero(new, sizeof(*new));
781 	*new = *pr;
782 
783 	/* initilization */
784 	new->ndpr_statef_onlink = pr->ndpr_statef_onlink;
785 	LIST_INIT(&new->ndpr_advrtrs);
786 	in6_prefixlen2mask(&new->ndpr_mask, new->ndpr_plen);
787 	/* make prefix in the canonical form */
788 	for (i = 0; i < 4; i++)
789 		new->ndpr_prefix.sin6_addr.s6_addr32[i] &=
790 			new->ndpr_mask.s6_addr32[i];
791 
792 	/* xxx ND_OPT_PI_FLAG_ONLINK processing */
793 
794 	s = splsoftnet();
795 	/* link ndpr_entry to nd_prefix list */
796 	LIST_INSERT_HEAD(&nd_prefix, new, ndpr_entry);
797 	splx(s);
798 
799 	if (dr)
800 		pfxrtr_add(new, dr);
801 
802 	return 0;
803 }
804 
805 void
806 prelist_remove(pr)
807 	struct nd_prefix *pr;
808 {
809 	struct nd_pfxrouter *pfr, *next;
810 	int s;
811 
812 	s = splsoftnet();
813 	/* unlink ndpr_entry from nd_prefix list */
814 	LIST_REMOVE(pr, ndpr_entry);
815 
816 	/* free list of routers that adversed the prefix */
817 	for (pfr = pr->ndpr_advrtrs.lh_first; pfr; pfr = next) {
818 		next = pfr->pfr_next;
819 
820 		free(pfr, M_IP6NDP);
821 	}
822 	splx(s);
823 
824 	free(pr, M_IP6NDP);
825 
826 	pfxlist_onlink_check();
827 }
828 
829 /*
830  * NOTE: We set address lifetime to keep
831  *	address lifetime <= prefix lifetime
832  * invariant.  This is to simplify on-link determination code.
833  * If onlink determination is udated, this routine may have to be updated too.
834  */
835 int
836 prelist_update(new, dr, m)
837 	struct nd_prefix *new;
838 	struct nd_defrouter *dr; /* may be NULL */
839 	struct mbuf *m;
840 {
841 	struct in6_ifaddr *ia6 = NULL;
842 	struct nd_prefix *pr;
843 	int s = splsoftnet();
844 	int error = 0;
845 	int auth;
846 	struct in6_addrlifetime *lt6;
847 
848 	auth = 0;
849 	if (m) {
850 		/*
851 		 * Authenticity for NA consists authentication for
852 		 * both IP header and IP datagrams, doesn't it ?
853 		 */
854 #if defined(M_AUTHIPHDR) && defined(M_AUTHIPDGM)
855 		auth = (m->m_flags & M_AUTHIPHDR
856 		     && m->m_flags & M_AUTHIPDGM) ? 1 : 0;
857 #endif
858 	}
859 
860 	if ((pr = prefix_lookup(new)) != NULL) {
861 		if (pr->ndpr_ifp != new->ndpr_ifp) {
862 			error = EADDRNOTAVAIL;
863 			goto end;
864 		}
865 		/* update prefix information */
866 		pr->ndpr_flags = new->ndpr_flags;
867 		pr->ndpr_vltime = new->ndpr_vltime;
868 		pr->ndpr_pltime = new->ndpr_pltime;
869 		pr->ndpr_preferred = new->ndpr_preferred;
870 		pr->ndpr_expire = new->ndpr_expire;
871 
872 		/*
873 		 * RFC 2462 5.5.3 (d) or (e)
874 		 * We got a prefix which we have seen in the past.
875 		 */
876 		if (!new->ndpr_raf_auto)
877 			goto noautoconf1;
878 
879 		if (IN6_IS_ADDR_UNSPECIFIED(&pr->ndpr_addr))
880 			ia6 = NULL;
881 		else
882 			ia6 = in6ifa_ifpwithaddr(pr->ndpr_ifp, &pr->ndpr_addr);
883 
884 		if (ia6 == NULL) {
885 			/*
886 			 * Special case:
887 			 * (1) We have seen the prefix advertised before, but
888 			 * we have never performed autoconfig for this prefix.
889 			 * This is because Autonomous bit was 0 previously, or
890 			 * autoconfig failed due to some other reasons.
891 			 * (2) We have seen the prefix advertised before and
892 			 * we have performed autoconfig in the past, but
893 			 * we seem to have no interface address right now.
894 			 * This is because the interface address have expired.
895 			 *
896 			 * This prefix is fresh, with respect to autoconfig
897 			 * process.
898 			 *
899 			 * Add an address based on RFC 2462 5.5.3 (d).
900 			 */
901 			ia6 = in6_ifadd(pr->ndpr_ifp,
902 				&pr->ndpr_prefix.sin6_addr, &pr->ndpr_addr,
903 				new->ndpr_plen);
904 			if (!ia6) {
905 				error = EADDRNOTAVAIL;
906 				nd6log((LOG_ERR,
907 				    "prelist_update: failed to add a "
908 				    "new address\n"));
909 				goto noautoconf1;
910 			}
911 
912 			lt6 = &ia6->ia6_lifetime;
913 
914 			/* address lifetime <= prefix lifetime */
915 			lt6->ia6t_vltime = new->ndpr_vltime;
916 			lt6->ia6t_pltime = new->ndpr_pltime;
917 			in6_init_address_ltimes(new, lt6, 1);
918 		} else {
919 #define TWOHOUR		(120*60)
920 			/*
921 			 * We have seen the prefix before, and we have added
922 			 * interface address in the past.  We still have
923 			 * the interface address assigned.
924 			 *
925 			 * update address lifetime based on RFC 2462
926 			 * 5.5.3 (e).
927 			 */
928 			int update = 0;
929 
930 			lt6 = &ia6->ia6_lifetime;
931 
932 #if 0	/* RFC 2462 5.5.3 (e) */
933 			lt6->ia6t_pltime = new->ndpr_pltime;
934 			if (TWOHOUR < new->ndpr_vltime
935 			 || lt6pr->nd < new->ndpr_vltime) {
936 				lt6->ia6t_vltime = new->ndpr_vltime;
937 				update++;
938 			} else if (auth
939 				&& lt6->ia6t_vltime <= TWOHOUR0
940 				&& new->ndpr_vltime <= lt6->ia6t_vltime) {
941 				lt6->ia6t_vltime = new->ndpr_vltime;
942 				update++;
943 			} else {
944 				lt6->ia6t_vltime = TWOHOUR;
945 				update++;
946 			}
947 
948 			/* 2 hour rule is not imposed for pref lifetime */
949 			new->ndpr_apltime = new->ndpr_pltime;
950 			lt6->ia6t_pltime = new->ndpr_pltime;
951 #else	/* update from Jim Bound, (ipng 6712) */
952 			if (TWOHOUR < new->ndpr_vltime
953 			 || lt6->ia6t_vltime < new->ndpr_vltime) {
954 				lt6->ia6t_vltime = new->ndpr_vltime;
955 				update++;
956 			} else if (auth) {
957 				lt6->ia6t_vltime = new->ndpr_vltime;
958 				update++;
959 			}
960 
961 			/* jim bound rule is not imposed for pref lifetime */
962 			lt6->ia6t_pltime = new->ndpr_pltime;
963 #endif
964 			in6_init_address_ltimes(new, lt6, update);
965 		}
966 
967  noautoconf1:
968 
969 #if 0
970 		/* address lifetime expire processing, RFC 2462 5.5.4. */
971 		if (pr->ndpr_preferred && pr->ndpr_preferred < time_second) {
972 			struct in6_ifaddr *ia6;
973 
974 			ia6 = in6ifa_ifpwithaddr(pr->ndpr_ifp, &pr->ndpr_addr);
975 			if (ia6)
976 				ia6->ia6_flags &= ~IN6_IFF_DEPRECATED;
977 		}
978 #endif
979 
980 		if (dr && pfxrtr_lookup(pr, dr) == NULL)
981 			pfxrtr_add(pr, dr);
982 	} else {
983 		int error_tmp;
984 
985 		if (new->ndpr_vltime == 0) goto end;
986 
987 		bzero(&new->ndpr_addr, sizeof(struct in6_addr));
988 
989 		/*
990 		 * RFC 2462 5.5.3 (d)
991 		 * We got a fresh prefix.  Perform some sanity checks
992 		 * and add an interface address by appending interface ID
993 		 * to the advertised prefix.
994 		 */
995 		if (!new->ndpr_raf_auto)
996 			goto noautoconf2;
997 
998 		ia6 = in6_ifadd(new->ndpr_ifp, &new->ndpr_prefix.sin6_addr,
999 			  &new->ndpr_addr, new->ndpr_plen);
1000 		if (!ia6) {
1001 			error = EADDRNOTAVAIL;
1002 			nd6log((LOG_ERR, "prelist_update: "
1003 				"failed to add a new address\n"));
1004 			goto noautoconf2;
1005 		}
1006 		/* set onlink bit if an interface route is configured */
1007 		new->ndpr_statef_onlink = (ia6->ia_flags & IFA_ROUTE) ? 1 : 0;
1008 
1009 		lt6 = &ia6->ia6_lifetime;
1010 
1011 		/* address lifetime <= prefix lifetime */
1012 		lt6->ia6t_vltime = new->ndpr_vltime;
1013 		lt6->ia6t_pltime = new->ndpr_pltime;
1014 		in6_init_address_ltimes(new, lt6, 1);
1015 
1016  noautoconf2:
1017 		error_tmp = prelist_add(new, dr);
1018 		error = error_tmp ? error_tmp : error;
1019 	}
1020 
1021  end:
1022 	splx(s);
1023 	return error;
1024 }
1025 
1026 /*
1027  * A supplement function used in the on-link detection below;
1028  * detect if a given prefix has a (probably) reachable advertising router.
1029  * XXX: lengthy function name...
1030  */
1031 static struct nd_pfxrouter *
1032 find_pfxlist_reachable_router(pr)
1033 	struct nd_prefix *pr;
1034 {
1035 	struct nd_pfxrouter *pfxrtr;
1036 	struct rtentry *rt;
1037 	struct llinfo_nd6 *ln;
1038 
1039 	for (pfxrtr = LIST_FIRST(&pr->ndpr_advrtrs); pfxrtr;
1040 	     pfxrtr = LIST_NEXT(pfxrtr, pfr_entry)) {
1041 		if ((rt = nd6_lookup(&pfxrtr->router->rtaddr, 0,
1042 				     pfxrtr->router->ifp)) &&
1043 		    (ln = (struct llinfo_nd6 *)rt->rt_llinfo) &&
1044 		    ND6_IS_LLINFO_PROBREACH(ln))
1045 			break;	/* found */
1046 	}
1047 
1048 	return(pfxrtr);
1049 
1050 }
1051 
1052 /*
1053  * Check if each prefix in the prefix list has at least one available router
1054  * that advertised the prefix (a router is "available" if its neighbor cache
1055  * entry is reachable or probably reachable).
1056  * If the check fails, the prefix may be off-link, because, for example,
1057  * we have moved from the network but the lifetime of the prefix has not
1058  * expired yet.  So we should not use the prefix if there is another prefix
1059  * that has an available router.
1060  * But, if there is no prefix that has an available router, we still regards
1061  * all the prefixes as on-link.  This is because we can't tell if all the
1062  * routers are simply dead or if we really moved from the network and there
1063  * is no router around us.
1064  */
1065 void
1066 pfxlist_onlink_check()
1067 {
1068 	struct nd_prefix *pr;
1069 
1070 	/*
1071 	 * Check if there is a prefix that has a reachable advertising
1072 	 * router.
1073 	 */
1074 	for (pr = nd_prefix.lh_first; pr; pr = pr->ndpr_next) {
1075 		if (find_pfxlist_reachable_router(pr))
1076 			break;
1077 	}
1078 
1079 	if (pr) {
1080 		/*
1081 		 * There is at least one prefix that has a reachable router.
1082 		 * First, detach prefixes which has no reachable advertising
1083 		 * router and then attach other prefixes.
1084 		 * The order is important since an attached prefix and a
1085 		 * detached prefix may have a same interface route.
1086 		 */
1087 		for (pr = nd_prefix.lh_first; pr; pr = pr->ndpr_next) {
1088 			if (find_pfxlist_reachable_router(pr) == NULL &&
1089 			    pr->ndpr_statef_onlink) {
1090 				pr->ndpr_statef_onlink = 0;
1091 				nd6_detach_prefix(pr);
1092 			}
1093 		}
1094 		for (pr = nd_prefix.lh_first; pr; pr = pr->ndpr_next) {
1095 			if (find_pfxlist_reachable_router(pr) &&
1096 			    pr->ndpr_statef_onlink == 0)
1097 				nd6_attach_prefix(pr);
1098 		}
1099 	}
1100 	else {
1101 		/* there is no prefix that has a reachable router */
1102 		for (pr = nd_prefix.lh_first; pr; pr = pr->ndpr_next)
1103 			if (pr->ndpr_statef_onlink == 0)
1104 				nd6_attach_prefix(pr);
1105 	}
1106 }
1107 
1108 static void
1109 nd6_detach_prefix(pr)
1110 	struct nd_prefix *pr;
1111 {
1112 	struct in6_ifaddr *ia6;
1113 	struct sockaddr_in6 sa6, mask6;
1114 
1115 	/*
1116 	 * Delete the interface route associated with the prefix.
1117 	 */
1118 	bzero(&sa6, sizeof(sa6));
1119 	sa6.sin6_family = AF_INET6;
1120 	sa6.sin6_len = sizeof(sa6);
1121 	bcopy(&pr->ndpr_prefix.sin6_addr, &sa6.sin6_addr,
1122 	      sizeof(struct in6_addr));
1123 	bzero(&mask6, sizeof(mask6));
1124 	mask6.sin6_family = AF_INET6;
1125 	mask6.sin6_len = sizeof(sa6);
1126 	bcopy(&pr->ndpr_mask, &mask6.sin6_addr, sizeof(struct in6_addr));
1127 	{
1128 		int e;
1129 
1130 		e = rtrequest(RTM_DELETE, (struct sockaddr *)&sa6, NULL,
1131 			      (struct sockaddr *)&mask6, 0, NULL);
1132 		if (e) {
1133 			nd6log((LOG_ERR,
1134 			    "nd6_detach_prefix: failed to delete route: "
1135 			    "%s/%d (errno = %d)\n",
1136 			    ip6_sprintf(&sa6.sin6_addr),
1137 			    pr->ndpr_plen,
1138 			    e));
1139 		}
1140 	}
1141 
1142 	/*
1143 	 * Mark the address derived from the prefix detached so that
1144 	 * it won't be used as a source address for a new connection.
1145 	 */
1146 	if (IN6_IS_ADDR_UNSPECIFIED(&pr->ndpr_addr))
1147 		ia6 = NULL;
1148 	else
1149 		ia6 = in6ifa_ifpwithaddr(pr->ndpr_ifp, &pr->ndpr_addr);
1150 	if (ia6)
1151 		ia6->ia6_flags |= IN6_IFF_DETACHED;
1152 }
1153 
1154 static void
1155 nd6_attach_prefix(pr)
1156 	struct nd_prefix *pr;
1157 {
1158 	struct ifaddr *ifa;
1159 	struct in6_ifaddr *ia6;
1160 
1161 	/*
1162 	 * Add the interface route associated with the prefix(if necessary)
1163 	 * Should we consider if the L bit is set in pr->ndpr_flags?
1164 	 */
1165 	ifa = ifaof_ifpforaddr((struct sockaddr *)&pr->ndpr_prefix,
1166 			       pr->ndpr_ifp);
1167 	if (ifa == NULL) {
1168 		nd6log((LOG_ERR,
1169 		    "nd6_attach_prefix: failed to find any ifaddr"
1170 		    " to add route for a prefix(%s/%d)\n",
1171 		    ip6_sprintf(&pr->ndpr_addr), pr->ndpr_plen));
1172 	}
1173 	else {
1174 		int e;
1175 		struct sockaddr_in6 mask6;
1176 
1177 		bzero(&mask6, sizeof(mask6));
1178 		mask6.sin6_family = AF_INET6;
1179 		mask6.sin6_len = sizeof(mask6);
1180 		mask6.sin6_addr = pr->ndpr_mask;
1181 		e = rtrequest(RTM_ADD, (struct sockaddr *)&pr->ndpr_prefix,
1182 			      ifa->ifa_addr, (struct sockaddr *)&mask6,
1183 			      ifa->ifa_flags, NULL);
1184 		if (e == 0)
1185 			pr->ndpr_statef_onlink = 1;
1186 		else {
1187 			nd6log((LOG_DEBUG,
1188 			    "nd6_attach_prefix: failed to add route for"
1189 			    " a prefix(%s/%d), errno = %d\n",
1190 			    ip6_sprintf(&pr->ndpr_addr), pr->ndpr_plen, e));
1191 		}
1192 	}
1193 
1194 	/*
1195 	 * Now the address derived from the prefix can be used as a source
1196 	 * for a new connection, so clear the detached flag.
1197 	 */
1198 	if (IN6_IS_ADDR_UNSPECIFIED(&pr->ndpr_addr))
1199 		ia6 = NULL;
1200 	else
1201 		ia6 = in6ifa_ifpwithaddr(pr->ndpr_ifp, &pr->ndpr_addr);
1202 	if (ia6) {
1203 		ia6->ia6_flags &= ~IN6_IFF_DETACHED;
1204 		if (pr->ndpr_statef_onlink)
1205 			ia6->ia_flags |= IFA_ROUTE;
1206 	}
1207 }
1208 
1209 static struct in6_ifaddr *
1210 in6_ifadd(ifp, in6, addr, prefixlen)
1211 	struct ifnet *ifp;
1212 	struct in6_addr *in6;
1213 	struct in6_addr *addr;
1214 	int prefixlen;	/* prefix len of the new prefix in "in6" */
1215 {
1216 	struct ifaddr *ifa;
1217 	struct in6_ifaddr *ia, *ib, *oia;
1218 	int s, error;
1219 	struct in6_addr mask;
1220 
1221 	in6_len2mask(&mask, prefixlen);
1222 
1223 	/* find link-local address (will be interface ID) */
1224 	ifa = (struct ifaddr *)in6ifa_ifpforlinklocal(ifp, 0);/* 0 is OK? */
1225 	if (ifa)
1226 		ib = (struct in6_ifaddr *)ifa;
1227 	else
1228 		return NULL;
1229 
1230 #if 0 /* don't care link local addr state, and always do DAD */
1231 	/* if link-local address is not eligible, do not autoconfigure. */
1232 	if (((struct in6_ifaddr *)ifa)->ia6_flags & IN6_IFF_NOTREADY) {
1233 		printf("in6_ifadd: link-local address not ready\n");
1234 		return NULL;
1235 	}
1236 #endif
1237 
1238 	/* prefixlen + ifidlen must be equal to 128 */
1239 	if (prefixlen != in6_mask2len(&ib->ia_prefixmask.sin6_addr)) {
1240 		nd6log((LOG_ERR, "in6_ifadd: wrong prefixlen for %s"
1241 			"(prefix=%d ifid=%d)\n", if_name(ifp),
1242 			prefixlen,
1243 			128 - in6_mask2len(&ib->ia_prefixmask.sin6_addr)));
1244 		return NULL;
1245 	}
1246 
1247 	/* make ifaddr */
1248 	ia = (struct in6_ifaddr *)malloc(sizeof(*ia), M_IFADDR, M_DONTWAIT);
1249 	if (ia == NULL) {
1250 		printf("ENOBUFS in in6_ifadd %d\n", __LINE__);
1251 		return NULL;
1252 	}
1253 
1254 	bzero((caddr_t)ia, sizeof(*ia));
1255 	ia->ia_ifa.ifa_addr = (struct sockaddr *)&ia->ia_addr;
1256 	if (ifp->if_flags & IFF_POINTOPOINT)
1257 		ia->ia_ifa.ifa_dstaddr = (struct sockaddr *)&ia->ia_dstaddr;
1258 	else
1259 		ia->ia_ifa.ifa_dstaddr = NULL;
1260 	ia->ia_ifa.ifa_netmask = (struct sockaddr *)&ia->ia_prefixmask;
1261 	ia->ia_ifp = ifp;
1262 
1263 	/* link to in6_ifaddr */
1264 	if ((oia = in6_ifaddr) != NULL) {
1265 		for( ; oia->ia_next; oia = oia->ia_next)
1266 			continue;
1267 		oia->ia_next = ia;
1268 	} else {
1269 		/*
1270 		 * This should be impossible, since we have at least one
1271 		 * link-local address (see the beginning of this function).
1272 		 * XXX: should we rather panic here?
1273 		 */
1274 		printf("in6_ifadd: in6_ifaddr is NULL (impossible!)\n");
1275 		in6_ifaddr = ia;
1276 	}
1277 	/* gain a refcnt for the link from in6_ifaddr */
1278 	IFAREF((struct ifaddr *)ia);
1279 
1280 	/* link to if_addrlist */
1281 	TAILQ_INSERT_TAIL(&ifp->if_addrlist, (struct ifaddr *)ia, ifa_list);
1282 	/* gain another refcnt for the link from if_addrlist */
1283 	IFAREF((struct ifaddr *)ia);
1284 
1285 	/* new address */
1286 	ia->ia_addr.sin6_len = sizeof(struct sockaddr_in6);
1287 	ia->ia_addr.sin6_family = AF_INET6;
1288 	/* prefix */
1289 	bcopy(in6, &ia->ia_addr.sin6_addr, sizeof(ia->ia_addr.sin6_addr));
1290 	ia->ia_addr.sin6_addr.s6_addr32[0] &= mask.s6_addr32[0];
1291 	ia->ia_addr.sin6_addr.s6_addr32[1] &= mask.s6_addr32[1];
1292 	ia->ia_addr.sin6_addr.s6_addr32[2] &= mask.s6_addr32[2];
1293 	ia->ia_addr.sin6_addr.s6_addr32[3] &= mask.s6_addr32[3];
1294 	/* interface ID */
1295 	ia->ia_addr.sin6_addr.s6_addr32[0]
1296 		|= (ib->ia_addr.sin6_addr.s6_addr32[0] & ~mask.s6_addr32[0]);
1297 	ia->ia_addr.sin6_addr.s6_addr32[1]
1298 		|= (ib->ia_addr.sin6_addr.s6_addr32[1] & ~mask.s6_addr32[1]);
1299 	ia->ia_addr.sin6_addr.s6_addr32[2]
1300 		|= (ib->ia_addr.sin6_addr.s6_addr32[2] & ~mask.s6_addr32[2]);
1301 	ia->ia_addr.sin6_addr.s6_addr32[3]
1302 		|= (ib->ia_addr.sin6_addr.s6_addr32[3] & ~mask.s6_addr32[3]);
1303 
1304 	/* new prefix */
1305 	ia->ia_prefixmask.sin6_len = sizeof(struct sockaddr_in6);
1306 	ia->ia_prefixmask.sin6_family = AF_INET6;
1307 	bcopy(&mask, &ia->ia_prefixmask.sin6_addr,
1308 		sizeof(ia->ia_prefixmask.sin6_addr));
1309 
1310 	/* same routine */
1311 	ia->ia_ifa.ifa_rtrequest =
1312 		(ifp->if_type == IFT_PPP) ? nd6_p2p_rtrequest : nd6_rtrequest;
1313 	ia->ia_ifa.ifa_flags |= RTF_CLONING;
1314 	ia->ia_ifa.ifa_metric = ifp->if_metric;
1315 
1316 	/* add interface route */
1317 	if ((error = rtinit(&(ia->ia_ifa), (int)RTM_ADD, RTF_UP|RTF_CLONING))) {
1318 		nd6log((LOG_NOTICE,
1319 		    "in6_ifadd: failed to add an interface route "
1320 		    "for %s/%d on %s, errno = %d\n",
1321 		    ip6_sprintf(&ia->ia_addr.sin6_addr), prefixlen,
1322 		    if_name(ifp), error));
1323 	}
1324 	else
1325 		ia->ia_flags |= IFA_ROUTE;
1326 
1327 	*addr = ia->ia_addr.sin6_addr;
1328 
1329 	if (ifp->if_flags & IFF_MULTICAST) {
1330 		int error;	/* not used */
1331 		struct in6_addr sol6;
1332 
1333 		/* Restore saved multicast addresses(if any). */
1334 		in6_restoremkludge(ia, ifp);
1335 
1336 		/* join solicited node multicast address */
1337 		bzero(&sol6, sizeof(sol6));
1338 		sol6.s6_addr16[0] = htons(0xff02);
1339 		sol6.s6_addr16[1] = htons(ifp->if_index);
1340 		sol6.s6_addr32[1] = 0;
1341 		sol6.s6_addr32[2] = htonl(1);
1342 		sol6.s6_addr32[3] = ia->ia_addr.sin6_addr.s6_addr32[3];
1343 		sol6.s6_addr8[12] = 0xff;
1344 		if (!in6_addmulti(&sol6, ifp, &error)) {
1345 			nd6log((LOG_ERR, "%s: failed to join %s (errno=%d)\n",
1346 			    if_name(ifp), ip6_sprintf(&sol6), error));
1347 		}
1348 	}
1349 
1350 	ia->ia6_flags |= IN6_IFF_TENTATIVE;
1351 
1352 	/*
1353 	 * To make the interface up. Only AF_INET6 in ia is used...
1354 	 */
1355 	s = splnet();
1356 	if (ifp->if_ioctl && (*ifp->if_ioctl)(ifp, SIOCSIFADDR, (caddr_t)ia)) {
1357 		splx(s);
1358 		return NULL;
1359 	}
1360 	splx(s);
1361 
1362 	/* Perform DAD, if needed. */
1363 	nd6_dad_start((struct ifaddr *)ia, NULL);
1364 
1365 	return ia;
1366 }
1367 
1368 int
1369 in6_ifdel(ifp, in6)
1370 	struct ifnet *ifp;
1371 	struct in6_addr *in6;
1372 {
1373 	struct in6_ifaddr *ia = (struct in6_ifaddr *)NULL;
1374 	struct in6_ifaddr *oia = (struct in6_ifaddr *)NULL;
1375 
1376 	if (!ifp)
1377 		return -1;
1378 
1379 	ia = in6ifa_ifpwithaddr(ifp, in6);
1380 	if (!ia)
1381 		return -1;
1382 
1383 	if (ifp->if_flags & IFF_MULTICAST) {
1384 		/*
1385 		 * delete solicited multicast addr for deleting host id
1386 		 */
1387 		struct in6_multi *in6m;
1388 		struct in6_addr llsol;
1389 		bzero(&llsol, sizeof(struct in6_addr));
1390 		llsol.s6_addr16[0] = htons(0xff02);
1391 		llsol.s6_addr16[1] = htons(ifp->if_index);
1392 		llsol.s6_addr32[1] = 0;
1393 		llsol.s6_addr32[2] = htonl(1);
1394 		llsol.s6_addr32[3] =
1395 				ia->ia_addr.sin6_addr.s6_addr32[3];
1396 		llsol.s6_addr8[12] = 0xff;
1397 
1398 		IN6_LOOKUP_MULTI(llsol, ifp, in6m);
1399 		if (in6m)
1400 			in6_delmulti(in6m);
1401 	}
1402 
1403 	if (ia->ia_flags & IFA_ROUTE) {
1404 		rtinit(&(ia->ia_ifa), (int)RTM_DELETE, 0);
1405 		ia->ia_flags &= ~IFA_ROUTE;
1406 	}
1407 
1408 	TAILQ_REMOVE(&ifp->if_addrlist, (struct ifaddr *)ia, ifa_list);
1409 	IFAFREE(&ia->ia_ifa);
1410 
1411 	/* lladdr is never deleted */
1412 	oia = ia;
1413 	if (oia == (ia = in6_ifaddr))
1414 		in6_ifaddr = ia->ia_next;
1415 	else {
1416 		while (ia->ia_next && (ia->ia_next != oia))
1417 			ia = ia->ia_next;
1418 		if (ia->ia_next)
1419 			ia->ia_next = oia->ia_next;
1420 		else
1421 			return -1;
1422 	}
1423 
1424 	in6_savemkludge(oia);
1425 	IFAFREE((&oia->ia_ifa));
1426 /* xxx
1427 	rtrequest(RTM_DELETE,
1428 		  (struct sockaddr *)&ia->ia_addr,
1429 		  (struct sockaddr *)0
1430 		  (struct sockaddr *)&ia->ia_prefixmask,
1431 		  RTF_UP|RTF_CLONING,
1432 		  (struct rtentry **)0);
1433 */
1434 	return 0;
1435 }
1436 
1437 int
1438 in6_init_prefix_ltimes(struct nd_prefix *ndpr)
1439 {
1440 	long time_second = time.tv_sec;
1441 
1442 	/* check if preferred lifetime > valid lifetime.  RFC2462 5.5.3 (c) */
1443 	if (ndpr->ndpr_pltime > ndpr->ndpr_vltime) {
1444 		nd6log((LOG_INFO, "in6_init_prefix_ltimes: preferred lifetime"
1445 		    "(%d) is greater than valid lifetime(%d)\n",
1446 		    (u_int)ndpr->ndpr_pltime, (u_int)ndpr->ndpr_vltime));
1447 		return (EINVAL);
1448 	}
1449 	if (ndpr->ndpr_pltime == ND6_INFINITE_LIFETIME)
1450 		ndpr->ndpr_preferred = 0;
1451 	else
1452 		ndpr->ndpr_preferred = time_second + ndpr->ndpr_pltime;
1453 	if (ndpr->ndpr_vltime == ND6_INFINITE_LIFETIME)
1454 		ndpr->ndpr_expire = 0;
1455 	else
1456 		ndpr->ndpr_expire = time_second + ndpr->ndpr_vltime;
1457 
1458 	return 0;
1459 }
1460 
1461 static void
1462 in6_init_address_ltimes(struct nd_prefix *new,
1463 			struct in6_addrlifetime *lt6,
1464 			int update_vltime)
1465 {
1466 	long time_second = time.tv_sec;
1467 
1468 	/* Valid lifetime must not be updated unless explicitly specified. */
1469 	if (update_vltime) {
1470 		/* init ia6t_expire */
1471 		if (lt6->ia6t_vltime == ND6_INFINITE_LIFETIME)
1472 			lt6->ia6t_expire = 0;
1473 		else {
1474 			lt6->ia6t_expire = time_second;
1475 			lt6->ia6t_expire += lt6->ia6t_vltime;
1476 		}
1477 		/* Ensure addr lifetime <= prefix lifetime. */
1478 		if (new->ndpr_expire && lt6->ia6t_expire &&
1479 		    new->ndpr_expire < lt6->ia6t_expire)
1480 			lt6->ia6t_expire = new->ndpr_expire;
1481 	}
1482 
1483 	/* init ia6t_preferred */
1484 	if (lt6->ia6t_pltime == ND6_INFINITE_LIFETIME)
1485 		lt6->ia6t_preferred = 0;
1486 	else {
1487 		lt6->ia6t_preferred = time_second;
1488 		lt6->ia6t_preferred += lt6->ia6t_pltime;
1489 	}
1490 	 /* Ensure addr lifetime <= prefix lifetime. */
1491 	if (new->ndpr_preferred && lt6->ia6t_preferred
1492 	    && new->ndpr_preferred < lt6->ia6t_preferred)
1493 		lt6->ia6t_preferred = new->ndpr_preferred;
1494 }
1495 
1496 /*
1497  * Delete all the routing table entries that use the specified gateway.
1498  * XXX: this function causes search through all entries of routing table, so
1499  * it shouldn't be called when acting as a router.
1500  */
1501 void
1502 rt6_flush(gateway, ifp)
1503 	struct in6_addr *gateway;
1504 	struct ifnet *ifp;
1505 {
1506 	struct radix_node_head *rnh = rt_tables[AF_INET6];
1507 	int s = splsoftnet();
1508 
1509 	/* We'll care only link-local addresses */
1510 	if (!IN6_IS_ADDR_LINKLOCAL(gateway)) {
1511 		splx(s);
1512 		return;
1513 	}
1514 	/* XXX: hack for KAME's link-local address kludge */
1515 	gateway->s6_addr16[1] = htons(ifp->if_index);
1516 
1517 	rnh->rnh_walktree(rnh, rt6_deleteroute, (void *)gateway);
1518 	splx(s);
1519 }
1520 
1521 static int
1522 rt6_deleteroute(rn, arg)
1523 	struct radix_node *rn;
1524 	void *arg;
1525 {
1526 #define SIN6(s)	((struct sockaddr_in6 *)s)
1527 	struct rtentry *rt = (struct rtentry *)rn;
1528 	struct in6_addr *gate = (struct in6_addr *)arg;
1529 
1530 	if (rt->rt_gateway == NULL || rt->rt_gateway->sa_family != AF_INET6)
1531 		return(0);
1532 
1533 	if (!IN6_ARE_ADDR_EQUAL(gate, &SIN6(rt->rt_gateway)->sin6_addr))
1534 		return(0);
1535 
1536 	/*
1537 	 * Do not delete a static route.
1538 	 * XXX: this seems to be a bit ad-hoc. Should we consider the
1539 	 * 'cloned' bit instead?
1540 	 */
1541 	if ((rt->rt_flags & RTF_STATIC) != 0)
1542 		return(0);
1543 
1544 	/*
1545 	 * We delete only host route. This means, in particular, we don't
1546 	 * delete default route.
1547 	 */
1548 	if ((rt->rt_flags & RTF_HOST) == 0)
1549 		return(0);
1550 
1551 	return(rtrequest(RTM_DELETE, rt_key(rt),
1552 			 rt->rt_gateway, rt_mask(rt), rt->rt_flags, 0));
1553 #undef SIN6
1554 }
1555 
1556 int
1557 nd6_setdefaultiface(ifindex)
1558 	int ifindex;
1559 {
1560 	int error = 0;
1561 
1562 	if (ifindex < 0 || if_index < ifindex)
1563 		return(EINVAL);
1564 
1565 	if (nd6_defifindex != ifindex) {
1566 		nd6_defifindex = ifindex;
1567 		if (nd6_defifindex > 0) {
1568 			nd6_defifp = ifindex2ifnet[nd6_defifindex];
1569 		} else
1570 			nd6_defifp = NULL;
1571 
1572 		/*
1573 		 * If the Default Router List is empty, install a route
1574 		 * to the specified interface as default or remove the default
1575 		 * route when the default interface becomes canceled.
1576 		 * The check for the queue is actually redundant, but
1577 		 * we do this here to avoid re-install the default route
1578 		 * if the list is NOT empty.
1579 		 */
1580 		if (TAILQ_FIRST(&nd_defrouter) == NULL)
1581 			defrouter_select();
1582 	}
1583 
1584 	return(error);
1585 }
1586