Home | History | Annotate | Line # | Download | only in netinet6
nd6_rtr.c revision 1.76
      1 /*	$NetBSD: nd6_rtr.c,v 1.76 2008/10/24 21:30:34 dyoung 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.76 2008/10/24 21:30:34 dyoung 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 <netinet6/in6_ifattach.h>
     57 #include <netinet/ip6.h>
     58 #include <netinet6/ip6_var.h>
     59 #include <netinet6/nd6.h>
     60 #include <netinet/icmp6.h>
     61 #include <netinet6/icmp6_private.h>
     62 #include <netinet6/scope6_var.h>
     63 
     64 #include <net/net_osdep.h>
     65 
     66 static int rtpref(struct nd_defrouter *);
     67 static struct nd_defrouter *defrtrlist_update(struct nd_defrouter *);
     68 static int prelist_update(struct nd_prefixctl *, struct nd_defrouter *,
     69     struct mbuf *, int);
     70 static struct in6_ifaddr *in6_ifadd(struct nd_prefixctl *, int);
     71 static struct nd_pfxrouter *pfxrtr_lookup(struct nd_prefix *,
     72 	struct nd_defrouter *);
     73 static void pfxrtr_add(struct nd_prefix *, struct nd_defrouter *);
     74 static void pfxrtr_del(struct nd_pfxrouter *);
     75 static struct nd_pfxrouter *find_pfxlist_reachable_router
     76 	(struct nd_prefix *);
     77 static void defrouter_delreq(struct nd_defrouter *);
     78 static void nd6_rtmsg(int, struct rtentry *);
     79 
     80 static int in6_init_prefix_ltimes(struct nd_prefix *);
     81 static void in6_init_address_ltimes(struct nd_prefix *ndpr,
     82 	struct in6_addrlifetime *lt6);
     83 
     84 static int rt6_deleteroute(struct rtentry *, void *);
     85 
     86 extern int nd6_recalc_reachtm_interval;
     87 
     88 static struct ifnet *nd6_defifp;
     89 int nd6_defifindex;
     90 
     91 int ip6_use_tempaddr = 0;
     92 
     93 int ip6_desync_factor;
     94 u_int32_t ip6_temp_preferred_lifetime = DEF_TEMP_PREFERRED_LIFETIME;
     95 u_int32_t ip6_temp_valid_lifetime = DEF_TEMP_VALID_LIFETIME;
     96 int ip6_temp_regen_advance = TEMPADDR_REGEN_ADVANCE;
     97 
     98 /* RTPREF_MEDIUM has to be 0! */
     99 #define RTPREF_HIGH	1
    100 #define RTPREF_MEDIUM	0
    101 #define RTPREF_LOW	(-1)
    102 #define RTPREF_RESERVED	(-2)
    103 #define RTPREF_INVALID	(-3)	/* internal */
    104 
    105 /*
    106  * Receive Router Solicitation Message - just for routers.
    107  * Router solicitation/advertisement is mostly managed by userland program
    108  * (rtadvd) so here we have no function like nd6_ra_output().
    109  *
    110  * Based on RFC 2461
    111  */
    112 void
    113 nd6_rs_input(struct mbuf *m, int off, int icmp6len)
    114 {
    115 	struct ifnet *ifp = m->m_pkthdr.rcvif;
    116 	struct ip6_hdr *ip6 = mtod(m, struct ip6_hdr *);
    117 	struct nd_router_solicit *nd_rs;
    118 	struct in6_addr saddr6 = ip6->ip6_src;
    119 	char *lladdr = NULL;
    120 	int lladdrlen = 0;
    121 	union nd_opts ndopts;
    122 
    123 	/* If I'm not a router, ignore it. */
    124 	if (ip6_accept_rtadv != 0 || !ip6_forwarding)
    125 		goto freeit;
    126 
    127 	/* Sanity checks */
    128 	if (ip6->ip6_hlim != 255) {
    129 		nd6log((LOG_ERR,
    130 		    "nd6_rs_input: invalid hlim (%d) from %s to %s on %s\n",
    131 		    ip6->ip6_hlim, ip6_sprintf(&ip6->ip6_src),
    132 		    ip6_sprintf(&ip6->ip6_dst), if_name(ifp)));
    133 		goto bad;
    134 	}
    135 
    136 	/*
    137 	 * Don't update the neighbor cache, if src = ::.
    138 	 * This indicates that the src has no IP address assigned yet.
    139 	 */
    140 	if (IN6_IS_ADDR_UNSPECIFIED(&saddr6))
    141 		goto freeit;
    142 
    143 	IP6_EXTHDR_GET(nd_rs, struct nd_router_solicit *, m, off, icmp6len);
    144 	if (nd_rs == NULL) {
    145 		ICMP6_STATINC(ICMP6_STAT_TOOSHORT);
    146 		return;
    147 	}
    148 
    149 	icmp6len -= sizeof(*nd_rs);
    150 	nd6_option_init(nd_rs + 1, icmp6len, &ndopts);
    151 	if (nd6_options(&ndopts) < 0) {
    152 		nd6log((LOG_INFO,
    153 		    "nd6_rs_input: invalid ND option, ignored\n"));
    154 		/* nd6_options have incremented stats */
    155 		goto freeit;
    156 	}
    157 
    158 	if (ndopts.nd_opts_src_lladdr) {
    159 		lladdr = (char *)(ndopts.nd_opts_src_lladdr + 1);
    160 		lladdrlen = ndopts.nd_opts_src_lladdr->nd_opt_len << 3;
    161 	}
    162 
    163 	if (lladdr && ((ifp->if_addrlen + 2 + 7) & ~7) != lladdrlen) {
    164 		nd6log((LOG_INFO,
    165 		    "nd6_rs_input: lladdrlen mismatch for %s "
    166 		    "(if %d, RS packet %d)\n",
    167 		    ip6_sprintf(&saddr6), ifp->if_addrlen, lladdrlen - 2));
    168 		goto bad;
    169 	}
    170 
    171 	nd6_cache_lladdr(ifp, &saddr6, lladdr, lladdrlen, ND_ROUTER_SOLICIT, 0);
    172 
    173  freeit:
    174 	m_freem(m);
    175 	return;
    176 
    177  bad:
    178 	ICMP6_STATINC(ICMP6_STAT_BADRS);
    179 	m_freem(m);
    180 }
    181 
    182 /*
    183  * Receive Router Advertisement Message.
    184  *
    185  * Based on RFC 2461
    186  * TODO: on-link bit on prefix information
    187  * TODO: ND_RA_FLAG_{OTHER,MANAGED} processing
    188  */
    189 void
    190 nd6_ra_input(struct mbuf *m, int off, int icmp6len)
    191 {
    192 	struct ifnet *ifp = m->m_pkthdr.rcvif;
    193 	struct nd_ifinfo *ndi = ND_IFINFO(ifp);
    194 	struct ip6_hdr *ip6 = mtod(m, struct ip6_hdr *);
    195 	struct nd_router_advert *nd_ra;
    196 	struct in6_addr saddr6 = ip6->ip6_src;
    197 #if 0
    198 	struct in6_addr daddr6 = ip6->ip6_dst;
    199 	int flags; /* = nd_ra->nd_ra_flags_reserved; */
    200 	int is_managed = ((flags & ND_RA_FLAG_MANAGED) != 0);
    201 	int is_other = ((flags & ND_RA_FLAG_OTHER) != 0);
    202 #endif
    203 	int mcast = 0;
    204 	union nd_opts ndopts;
    205 	struct nd_defrouter *dr;
    206 
    207 	/*
    208 	 * We only accept RAs only when
    209 	 * the system-wide variable allows the acceptance, and
    210 	 * per-interface variable allows RAs on the receiving interface.
    211 	 */
    212 	if (ip6_accept_rtadv == 0)
    213 		goto freeit;
    214 	if (!(ndi->flags & ND6_IFF_ACCEPT_RTADV))
    215 		goto freeit;
    216 
    217 	if (ip6->ip6_hlim != 255) {
    218 		nd6log((LOG_ERR,
    219 		    "nd6_ra_input: invalid hlim (%d) from %s to %s on %s\n",
    220 		    ip6->ip6_hlim, ip6_sprintf(&ip6->ip6_src),
    221 		    ip6_sprintf(&ip6->ip6_dst), if_name(ifp)));
    222 		goto bad;
    223 	}
    224 
    225 	if (!IN6_IS_ADDR_LINKLOCAL(&saddr6)) {
    226 		nd6log((LOG_ERR,
    227 		    "nd6_ra_input: src %s is not link-local\n",
    228 		    ip6_sprintf(&saddr6)));
    229 		goto bad;
    230 	}
    231 
    232 	IP6_EXTHDR_GET(nd_ra, struct nd_router_advert *, m, off, icmp6len);
    233 	if (nd_ra == NULL) {
    234 		ICMP6_STATINC(ICMP6_STAT_TOOSHORT);
    235 		return;
    236 	}
    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 drtr;
    249 	u_int32_t advreachable = nd_ra->nd_ra_reachable;
    250 
    251 	/* remember if this is a multicasted advertisement */
    252 	if (IN6_IS_ADDR_MULTICAST(&ip6->ip6_dst))
    253 		mcast = 1;
    254 
    255 	memset(&drtr, 0, sizeof(drtr));
    256 	drtr.rtaddr = saddr6;
    257 	drtr.flags  = nd_ra->nd_ra_flags_reserved;
    258 	drtr.rtlifetime = ntohs(nd_ra->nd_ra_router_lifetime);
    259 	drtr.expire = time_second + drtr.rtlifetime;
    260 	drtr.ifp = ifp;
    261 	/* unspecified or not? (RFC 2461 6.3.4) */
    262 	if (advreachable) {
    263 		NTOHL(advreachable);
    264 		if (advreachable <= MAX_REACHABLE_TIME &&
    265 		    ndi->basereachable != advreachable) {
    266 			ndi->basereachable = advreachable;
    267 			ndi->reachable = ND_COMPUTE_RTIME(ndi->basereachable);
    268 			ndi->recalctm = nd6_recalc_reachtm_interval; /* reset */
    269 		}
    270 	}
    271 	if (nd_ra->nd_ra_retransmit)
    272 		ndi->retrans = ntohl(nd_ra->nd_ra_retransmit);
    273 	if (nd_ra->nd_ra_curhoplimit)
    274 		ndi->chlim = nd_ra->nd_ra_curhoplimit;
    275 	dr = defrtrlist_update(&drtr);
    276     }
    277 
    278 	/*
    279 	 * prefix
    280 	 */
    281 	if (ndopts.nd_opts_pi) {
    282 		struct nd_opt_hdr *pt;
    283 		struct nd_opt_prefix_info *pi = NULL;
    284 		struct nd_prefixctl pr;
    285 
    286 		for (pt = (struct nd_opt_hdr *)ndopts.nd_opts_pi;
    287 		     pt <= (struct nd_opt_hdr *)ndopts.nd_opts_pi_end;
    288 		     pt = (struct nd_opt_hdr *)((char *)pt +
    289 						(pt->nd_opt_len << 3))) {
    290 			if (pt->nd_opt_type != ND_OPT_PREFIX_INFORMATION)
    291 				continue;
    292 			pi = (struct nd_opt_prefix_info *)pt;
    293 
    294 			if (pi->nd_opt_pi_len != 4) {
    295 				nd6log((LOG_INFO,
    296 				    "nd6_ra_input: invalid option "
    297 				    "len %d for prefix information option, "
    298 				    "ignored\n", pi->nd_opt_pi_len));
    299 				continue;
    300 			}
    301 
    302 			if (128 < pi->nd_opt_pi_prefix_len) {
    303 				nd6log((LOG_INFO,
    304 				    "nd6_ra_input: invalid prefix "
    305 				    "len %d for prefix information option, "
    306 				    "ignored\n", pi->nd_opt_pi_prefix_len));
    307 				continue;
    308 			}
    309 
    310 			if (IN6_IS_ADDR_MULTICAST(&pi->nd_opt_pi_prefix)
    311 			 || IN6_IS_ADDR_LINKLOCAL(&pi->nd_opt_pi_prefix)) {
    312 				nd6log((LOG_INFO,
    313 				    "nd6_ra_input: invalid prefix "
    314 				    "%s, ignored\n",
    315 				    ip6_sprintf(&pi->nd_opt_pi_prefix)));
    316 				continue;
    317 			}
    318 
    319 			bzero(&pr, sizeof(pr));
    320 			sockaddr_in6_init(&pr.ndpr_prefix,
    321 			    &pi->nd_opt_pi_prefix, 0, 0, 0);
    322 			pr.ndpr_ifp = (struct ifnet *)m->m_pkthdr.rcvif;
    323 
    324 			pr.ndpr_raf_onlink = (pi->nd_opt_pi_flags_reserved &
    325 			    ND_OPT_PI_FLAG_ONLINK) ? 1 : 0;
    326 			pr.ndpr_raf_auto = (pi->nd_opt_pi_flags_reserved &
    327 			    ND_OPT_PI_FLAG_AUTO) ? 1 : 0;
    328 			pr.ndpr_plen = pi->nd_opt_pi_prefix_len;
    329 			pr.ndpr_vltime = ntohl(pi->nd_opt_pi_valid_time);
    330 			pr.ndpr_pltime = ntohl(pi->nd_opt_pi_preferred_time);
    331 
    332 			(void)prelist_update(&pr, dr, m, mcast);
    333 		}
    334 	}
    335 
    336 	/*
    337 	 * MTU
    338 	 */
    339 	if (ndopts.nd_opts_mtu && ndopts.nd_opts_mtu->nd_opt_mtu_len == 1) {
    340 		u_long mtu;
    341 		u_long maxmtu;
    342 
    343 		mtu = ntohl(ndopts.nd_opts_mtu->nd_opt_mtu_mtu);
    344 
    345 		/* lower bound */
    346 		if (mtu < IPV6_MMTU) {
    347 			nd6log((LOG_INFO, "nd6_ra_input: bogus mtu option "
    348 			    "mtu=%lu sent from %s, ignoring\n",
    349 			    mtu, ip6_sprintf(&ip6->ip6_src)));
    350 			goto skip;
    351 		}
    352 
    353 		/* upper bound */
    354 		maxmtu = (ndi->maxmtu && ndi->maxmtu < ifp->if_mtu)
    355 		    ? ndi->maxmtu : ifp->if_mtu;
    356 		if (mtu <= maxmtu) {
    357 			int change = (ndi->linkmtu != mtu);
    358 
    359 			ndi->linkmtu = mtu;
    360 			if (change) /* in6_maxmtu may change */
    361 				in6_setmaxmtu();
    362 		} else {
    363 			nd6log((LOG_INFO, "nd6_ra_input: bogus mtu "
    364 			    "mtu=%lu sent from %s; "
    365 			    "exceeds maxmtu %lu, ignoring\n",
    366 			    mtu, ip6_sprintf(&ip6->ip6_src), maxmtu));
    367 		}
    368 	}
    369 
    370  skip:
    371 
    372 	/*
    373 	 * Source link layer address
    374 	 */
    375     {
    376 	char *lladdr = NULL;
    377 	int lladdrlen = 0;
    378 
    379 	if (ndopts.nd_opts_src_lladdr) {
    380 		lladdr = (char *)(ndopts.nd_opts_src_lladdr + 1);
    381 		lladdrlen = ndopts.nd_opts_src_lladdr->nd_opt_len << 3;
    382 	}
    383 
    384 	if (lladdr && ((ifp->if_addrlen + 2 + 7) & ~7) != lladdrlen) {
    385 		nd6log((LOG_INFO,
    386 		    "nd6_ra_input: lladdrlen mismatch for %s "
    387 		    "(if %d, RA packet %d)\n", ip6_sprintf(&saddr6),
    388 		    ifp->if_addrlen, lladdrlen - 2));
    389 		goto bad;
    390 	}
    391 
    392 	nd6_cache_lladdr(ifp, &saddr6, lladdr, lladdrlen, ND_ROUTER_ADVERT, 0);
    393 
    394 	/*
    395 	 * Installing a link-layer address might change the state of the
    396 	 * router's neighbor cache, which might also affect our on-link
    397 	 * detection of adveritsed prefixes.
    398 	 */
    399 	pfxlist_onlink_check();
    400     }
    401 
    402  freeit:
    403 	m_freem(m);
    404 	return;
    405 
    406  bad:
    407 	ICMP6_STATINC(ICMP6_STAT_BADRA);
    408 	m_freem(m);
    409 }
    410 
    411 /*
    412  * default router list processing sub routines
    413  */
    414 
    415 /* tell the change to user processes watching the routing socket. */
    416 static void
    417 nd6_rtmsg(int cmd, struct rtentry *rt)
    418 {
    419 	struct rt_addrinfo info;
    420 
    421 	bzero((void *)&info, sizeof(info));
    422 	info.rti_info[RTAX_DST] = rt_getkey(rt);
    423 	info.rti_info[RTAX_GATEWAY] = rt->rt_gateway;
    424 	info.rti_info[RTAX_NETMASK] = rt_mask(rt);
    425 	if (rt->rt_ifp) {
    426 		info.rti_info[RTAX_IFP] = rt->rt_ifp->if_dl->ifa_addr;
    427 		info.rti_info[RTAX_IFA] = rt->rt_ifa->ifa_addr;
    428 	}
    429 
    430 	rt_missmsg(cmd, &info, rt->rt_flags, 0);
    431 }
    432 
    433 void
    434 defrouter_addreq(struct nd_defrouter *new)
    435 {
    436 	union {
    437 		struct sockaddr_in6 sin6;
    438 		struct sockaddr sa;
    439 	} def, mask, gate;
    440 	struct rtentry *newrt = NULL;
    441 	int s;
    442 	int error;
    443 
    444 	memset(&def, 0, sizeof(def));
    445 	memset(&mask, 0, sizeof(mask));
    446 	memset(&gate, 0,sizeof(gate)); /* for safety */
    447 
    448 	def.sin6.sin6_len = mask.sin6.sin6_len = gate.sin6.sin6_len =
    449 	    sizeof(struct sockaddr_in6);
    450 	def.sin6.sin6_family = mask.sin6.sin6_family = gate.sin6.sin6_family = AF_INET6;
    451 	gate.sin6.sin6_addr = new->rtaddr;
    452 #ifndef SCOPEDROUTING
    453 	gate.sin6.sin6_scope_id = 0;	/* XXX */
    454 #endif
    455 
    456 	s = splsoftnet();
    457 	error = rtrequest(RTM_ADD, &def.sa, &gate.sa, &mask.sa,
    458 	    RTF_GATEWAY, &newrt);
    459 	if (newrt) {
    460 		nd6_rtmsg(RTM_ADD, newrt); /* tell user process */
    461 		newrt->rt_refcnt--;
    462 	}
    463 	if (error == 0)
    464 		new->installed = 1;
    465 	splx(s);
    466 	return;
    467 }
    468 
    469 struct nd_defrouter *
    470 defrouter_lookup(const struct in6_addr *addr, struct ifnet *ifp)
    471 {
    472 	struct nd_defrouter *dr;
    473 
    474 	TAILQ_FOREACH(dr, &nd_defrouter, dr_entry) {
    475 		if (dr->ifp == ifp && IN6_ARE_ADDR_EQUAL(addr, &dr->rtaddr))
    476 			break;
    477 	}
    478 
    479 	return dr;		/* search failed */
    480 }
    481 
    482 void
    483 defrtrlist_del(struct nd_defrouter *dr)
    484 {
    485 	struct nd_defrouter *deldr = NULL;
    486 	struct nd_prefix *pr;
    487 
    488 	/*
    489 	 * Flush all the routing table entries that use the router
    490 	 * as a next hop.
    491 	 */
    492 	if (!ip6_forwarding && ip6_accept_rtadv) /* XXX: better condition? */
    493 		rt6_flush(&dr->rtaddr, dr->ifp);
    494 
    495 	if (dr->installed) {
    496 		deldr = dr;
    497 		defrouter_delreq(dr);
    498 	}
    499 	TAILQ_REMOVE(&nd_defrouter, dr, dr_entry);
    500 
    501 	/*
    502 	 * Also delete all the pointers to the router in each prefix lists.
    503 	 */
    504 	LIST_FOREACH(pr, &nd_prefix, ndpr_entry) {
    505 		struct nd_pfxrouter *pfxrtr;
    506 		if ((pfxrtr = pfxrtr_lookup(pr, dr)) != NULL)
    507 			pfxrtr_del(pfxrtr);
    508 	}
    509 	pfxlist_onlink_check();
    510 
    511 	/*
    512 	 * If the router is the primary one, choose a new one.
    513 	 * Note that defrouter_select() will remove the current gateway
    514 	 * from the routing table.
    515 	 */
    516 	if (deldr)
    517 		defrouter_select();
    518 
    519 	free(dr, M_IP6NDP);
    520 }
    521 
    522 /*
    523  * Remove the default route for a given router.
    524  * This is just a subroutine function for defrouter_select(), and should
    525  * not be called from anywhere else.
    526  */
    527 static void
    528 defrouter_delreq(struct nd_defrouter *dr)
    529 {
    530 	union {
    531 		struct sockaddr_in6 sin6;
    532 		struct sockaddr sa;
    533 	} def, mask, gw;
    534 	struct rtentry *oldrt = NULL;
    535 
    536 #ifdef DIAGNOSTIC
    537 	if (dr == NULL)
    538 		panic("dr == NULL in defrouter_delreq");
    539 #endif
    540 
    541 	memset(&def, 0, sizeof(def));
    542 	memset(&mask, 0, sizeof(mask));
    543 	memset(&gw, 0, sizeof(gw));	/* for safety */
    544 
    545 	def.sin6.sin6_len = mask.sin6.sin6_len = gw.sin6.sin6_len =
    546 	    sizeof(struct sockaddr_in6);
    547 	def.sin6.sin6_family = mask.sin6.sin6_family = gw.sin6.sin6_family = AF_INET6;
    548 	gw.sin6.sin6_addr = dr->rtaddr;
    549 #ifndef SCOPEDROUTING
    550 	gw.sin6.sin6_scope_id = 0;	/* XXX */
    551 #endif
    552 
    553 	rtrequest(RTM_DELETE, &def.sa, &gw.sa, &mask.sa, RTF_GATEWAY, &oldrt);
    554 	if (oldrt) {
    555 		nd6_rtmsg(RTM_DELETE, oldrt);
    556 		if (oldrt->rt_refcnt <= 0) {
    557 			/*
    558 			 * XXX: borrowed from the RTM_DELETE case of
    559 			 * rtrequest().
    560 			 */
    561 			oldrt->rt_refcnt++;
    562 			rtfree(oldrt);
    563 		}
    564 	}
    565 
    566 	dr->installed = 0;
    567 }
    568 
    569 /*
    570  * remove all default routes from default router list
    571  */
    572 void
    573 defrouter_reset(void)
    574 {
    575 	struct nd_defrouter *dr;
    576 
    577 	for (dr = TAILQ_FIRST(&nd_defrouter); dr;
    578 	     dr = TAILQ_NEXT(dr, dr_entry))
    579 		defrouter_delreq(dr);
    580 
    581 	/*
    582 	 * XXX should we also nuke any default routers in the kernel, by
    583 	 * going through them by rtalloc1()?
    584 	 */
    585 }
    586 
    587 /*
    588  * Default Router Selection according to Section 6.3.6 of RFC 2461 and
    589  * draft-ietf-ipngwg-router-selection:
    590  * 1) Routers that are reachable or probably reachable should be preferred.
    591  *    If we have more than one (probably) reachable router, prefer ones
    592  *    with the highest router preference.
    593  * 2) When no routers on the list are known to be reachable or
    594  *    probably reachable, routers SHOULD be selected in a round-robin
    595  *    fashion, regardless of router preference values.
    596  * 3) If the Default Router List is empty, assume that all
    597  *    destinations are on-link.
    598  *
    599  * We assume nd_defrouter is sorted by router preference value.
    600  * Since the code below covers both with and without router preference cases,
    601  * we do not need to classify the cases by ifdef.
    602  *
    603  * At this moment, we do not try to install more than one default router,
    604  * even when the multipath routing is available, because we're not sure about
    605  * the benefits for stub hosts comparing to the risk of making the code
    606  * complicated and the possibility of introducing bugs.
    607  */
    608 void
    609 defrouter_select(void)
    610 {
    611 	int s = splsoftnet();
    612 	struct nd_defrouter *dr, *selected_dr = NULL, *installed_dr = NULL;
    613 	struct rtentry *rt = NULL;
    614 	struct llinfo_nd6 *ln = NULL;
    615 
    616 	/*
    617 	 * This function should be called only when acting as an autoconfigured
    618 	 * host.  Although the remaining part of this function is not effective
    619 	 * if the node is not an autoconfigured host, we explicitly exclude
    620 	 * such cases here for safety.
    621 	 */
    622 	if (ip6_forwarding || !ip6_accept_rtadv) {
    623 		nd6log((LOG_WARNING,
    624 		    "defrouter_select: called unexpectedly (forwarding=%d, "
    625 		    "accept_rtadv=%d)\n", ip6_forwarding, ip6_accept_rtadv));
    626 		splx(s);
    627 		return;
    628 	}
    629 
    630 	/*
    631 	 * Let's handle easy case (3) first:
    632 	 * If default router list is empty, there's nothing to be done.
    633 	 */
    634 	if (!TAILQ_FIRST(&nd_defrouter)) {
    635 		splx(s);
    636 		return;
    637 	}
    638 
    639 	/*
    640 	 * Search for a (probably) reachable router from the list.
    641 	 * We just pick up the first reachable one (if any), assuming that
    642 	 * the ordering rule of the list described in defrtrlist_update().
    643 	 */
    644 	for (dr = TAILQ_FIRST(&nd_defrouter); dr;
    645 	     dr = TAILQ_NEXT(dr, dr_entry)) {
    646 		if (selected_dr == NULL &&
    647 		    (rt = nd6_lookup(&dr->rtaddr, 0, dr->ifp)) != NULL &&
    648 		    (ln = (struct llinfo_nd6 *)rt->rt_llinfo) != NULL &&
    649 		    ND6_IS_LLINFO_PROBREACH(ln)) {
    650 			selected_dr = dr;
    651 		}
    652 
    653 		if (dr->installed && !installed_dr)
    654 			installed_dr = dr;
    655 		else if (dr->installed && installed_dr) {
    656 			/* this should not happen.  warn for diagnosis. */
    657 			log(LOG_ERR, "defrouter_select: more than one router"
    658 			    " is installed\n");
    659 		}
    660 	}
    661 	/*
    662 	 * If none of the default routers was found to be reachable,
    663 	 * round-robin the list regardless of preference.
    664 	 * Otherwise, if we have an installed router, check if the selected
    665 	 * (reachable) router should really be preferred to the installed one.
    666 	 * We only prefer the new router when the old one is not reachable
    667 	 * or when the new one has a really higher preference value.
    668 	 */
    669 	if (selected_dr == NULL) {
    670 		if (installed_dr == NULL || !TAILQ_NEXT(installed_dr, dr_entry))
    671 			selected_dr = TAILQ_FIRST(&nd_defrouter);
    672 		else
    673 			selected_dr = TAILQ_NEXT(installed_dr, dr_entry);
    674 	} else if (installed_dr &&
    675 	    (rt = nd6_lookup(&installed_dr->rtaddr, 0, installed_dr->ifp)) &&
    676 	    (ln = (struct llinfo_nd6 *)rt->rt_llinfo) &&
    677 	    ND6_IS_LLINFO_PROBREACH(ln) &&
    678 	    rtpref(selected_dr) <= rtpref(installed_dr)) {
    679 		selected_dr = installed_dr;
    680 	}
    681 
    682 	/*
    683 	 * If the selected router is different than the installed one,
    684 	 * remove the installed router and install the selected one.
    685 	 * Note that the selected router is never NULL here.
    686 	 */
    687 	if (installed_dr != selected_dr) {
    688 		if (installed_dr)
    689 			defrouter_delreq(installed_dr);
    690 		defrouter_addreq(selected_dr);
    691 	}
    692 
    693 	splx(s);
    694 	return;
    695 }
    696 
    697 /*
    698  * for default router selection
    699  * regards router-preference field as a 2-bit signed integer
    700  */
    701 static int
    702 rtpref(struct nd_defrouter *dr)
    703 {
    704 	switch (dr->flags & ND_RA_FLAG_RTPREF_MASK) {
    705 	case ND_RA_FLAG_RTPREF_HIGH:
    706 		return (RTPREF_HIGH);
    707 	case ND_RA_FLAG_RTPREF_MEDIUM:
    708 	case ND_RA_FLAG_RTPREF_RSV:
    709 		return (RTPREF_MEDIUM);
    710 	case ND_RA_FLAG_RTPREF_LOW:
    711 		return (RTPREF_LOW);
    712 	default:
    713 		/*
    714 		 * This case should never happen.  If it did, it would mean a
    715 		 * serious bug of kernel internal.  We thus always bark here.
    716 		 * Or, can we even panic?
    717 		 */
    718 		log(LOG_ERR, "rtpref: impossible RA flag %x\n", dr->flags);
    719 		return (RTPREF_INVALID);
    720 	}
    721 	/* NOTREACHED */
    722 }
    723 
    724 static struct nd_defrouter *
    725 defrtrlist_update(struct nd_defrouter *new)
    726 {
    727 	struct nd_defrouter *dr, *n;
    728 	int s = splsoftnet();
    729 
    730 	if ((dr = defrouter_lookup(&new->rtaddr, new->ifp)) != NULL) {
    731 		/* entry exists */
    732 		if (new->rtlifetime == 0) {
    733 			defrtrlist_del(dr);
    734 			dr = NULL;
    735 		} else {
    736 			int oldpref = rtpref(dr);
    737 
    738 			/* override */
    739 			dr->flags = new->flags; /* xxx flag check */
    740 			dr->rtlifetime = new->rtlifetime;
    741 			dr->expire = new->expire;
    742 
    743 			/*
    744 			 * If the preference does not change, there's no need
    745 			 * to sort the entries.
    746 			 */
    747 			if (rtpref(new) == oldpref) {
    748 				splx(s);
    749 				return (dr);
    750 			}
    751 
    752 			/*
    753 			 * preferred router may be changed, so relocate
    754 			 * this router.
    755 			 * XXX: calling TAILQ_REMOVE directly is a bad manner.
    756 			 * However, since defrtrlist_del() has many side
    757 			 * effects, we intentionally do so here.
    758 			 * defrouter_select() below will handle routing
    759 			 * changes later.
    760 			 */
    761 			TAILQ_REMOVE(&nd_defrouter, dr, dr_entry);
    762 			n = dr;
    763 			goto insert;
    764 		}
    765 		splx(s);
    766 		return (dr);
    767 	}
    768 
    769 	/* entry does not exist */
    770 	if (new->rtlifetime == 0) {
    771 		splx(s);
    772 		return (NULL);
    773 	}
    774 
    775 	n = (struct nd_defrouter *)malloc(sizeof(*n), M_IP6NDP, M_NOWAIT);
    776 	if (n == NULL) {
    777 		splx(s);
    778 		return (NULL);
    779 	}
    780 	bzero(n, sizeof(*n));
    781 	*n = *new;
    782 
    783 insert:
    784 	/*
    785 	 * Insert the new router in the Default Router List;
    786 	 * The Default Router List should be in the descending order
    787 	 * of router-preferece.  Routers with the same preference are
    788 	 * sorted in the arriving time order.
    789 	 */
    790 
    791 	/* insert at the end of the group */
    792 	for (dr = TAILQ_FIRST(&nd_defrouter); dr;
    793 	     dr = TAILQ_NEXT(dr, dr_entry)) {
    794 		if (rtpref(n) > rtpref(dr))
    795 			break;
    796 	}
    797 	if (dr)
    798 		TAILQ_INSERT_BEFORE(dr, n, dr_entry);
    799 	else
    800 		TAILQ_INSERT_TAIL(&nd_defrouter, n, dr_entry);
    801 
    802 	defrouter_select();
    803 
    804 	splx(s);
    805 
    806 	return (n);
    807 }
    808 
    809 static struct nd_pfxrouter *
    810 pfxrtr_lookup(struct nd_prefix *pr, struct nd_defrouter *dr)
    811 {
    812 	struct nd_pfxrouter *search;
    813 
    814 	LIST_FOREACH(search, &pr->ndpr_advrtrs, pfr_entry) {
    815 		if (search->router == dr)
    816 			break;
    817 	}
    818 
    819 	return (search);
    820 }
    821 
    822 static void
    823 pfxrtr_add(struct nd_prefix *pr, struct nd_defrouter *dr)
    824 {
    825 	struct nd_pfxrouter *new;
    826 
    827 	new = (struct nd_pfxrouter *)malloc(sizeof(*new), M_IP6NDP, M_NOWAIT);
    828 	if (new == NULL)
    829 		return;
    830 	bzero(new, sizeof(*new));
    831 	new->router = dr;
    832 
    833 	LIST_INSERT_HEAD(&pr->ndpr_advrtrs, new, pfr_entry);
    834 
    835 	pfxlist_onlink_check();
    836 }
    837 
    838 static void
    839 pfxrtr_del(struct nd_pfxrouter *pfr)
    840 {
    841 	LIST_REMOVE(pfr, pfr_entry);
    842 	free(pfr, M_IP6NDP);
    843 }
    844 
    845 struct nd_prefix *
    846 nd6_prefix_lookup(struct nd_prefixctl *key)
    847 {
    848 	struct nd_prefix *search;
    849 
    850 	LIST_FOREACH(search, &nd_prefix, ndpr_entry) {
    851 		if (key->ndpr_ifp == search->ndpr_ifp &&
    852 		    key->ndpr_plen == search->ndpr_plen &&
    853 		    in6_are_prefix_equal(&key->ndpr_prefix.sin6_addr,
    854 		    &search->ndpr_prefix.sin6_addr, key->ndpr_plen)) {
    855 			break;
    856 		}
    857 	}
    858 
    859 	return (search);
    860 }
    861 
    862 int
    863 nd6_prelist_add(struct nd_prefixctl *pr, struct nd_defrouter *dr,
    864 	struct nd_prefix **newp)
    865 {
    866 	struct nd_prefix *new = NULL;
    867 	int i, s;
    868 	int error;
    869 
    870 	error = 0;
    871 	new = (struct nd_prefix *)malloc(sizeof(*new), M_IP6NDP, M_NOWAIT);
    872 	if (new == NULL)
    873 		return ENOMEM;
    874 	bzero(new, sizeof(*new));
    875 	new->ndpr_ifp = pr->ndpr_ifp;
    876 	new->ndpr_prefix = pr->ndpr_prefix;
    877 	new->ndpr_plen = pr->ndpr_plen;
    878 	new->ndpr_vltime = pr->ndpr_vltime;
    879 	new->ndpr_pltime = pr->ndpr_pltime;
    880 	new->ndpr_flags = pr->ndpr_flags;
    881 	if ((error = in6_init_prefix_ltimes(new)) != 0) {
    882 		free(new, M_IP6NDP);
    883 		return(error);
    884 	}
    885 	new->ndpr_lastupdate = time_second;
    886 	if (newp != NULL)
    887 		*newp = new;
    888 
    889 	/* initialization */
    890 	LIST_INIT(&new->ndpr_advrtrs);
    891 	in6_prefixlen2mask(&new->ndpr_mask, new->ndpr_plen);
    892 	/* make prefix in the canonical form */
    893 	for (i = 0; i < 4; i++)
    894 		new->ndpr_prefix.sin6_addr.s6_addr32[i] &=
    895 		    new->ndpr_mask.s6_addr32[i];
    896 
    897 	s = splsoftnet();
    898 	/* link ndpr_entry to nd_prefix list */
    899 	LIST_INSERT_HEAD(&nd_prefix, new, ndpr_entry);
    900 	splx(s);
    901 
    902 	/* ND_OPT_PI_FLAG_ONLINK processing */
    903 	if (new->ndpr_raf_onlink) {
    904 		int e;
    905 
    906 		if ((e = nd6_prefix_onlink(new)) != 0) {
    907 			nd6log((LOG_ERR, "nd6_prelist_add: failed to make "
    908 			    "the prefix %s/%d on-link on %s (errno=%d)\n",
    909 			    ip6_sprintf(&pr->ndpr_prefix.sin6_addr),
    910 			    pr->ndpr_plen, if_name(pr->ndpr_ifp), e));
    911 			/* proceed anyway. XXX: is it correct? */
    912 		}
    913 	}
    914 
    915 	if (dr)
    916 		pfxrtr_add(new, dr);
    917 
    918 	return 0;
    919 }
    920 
    921 void
    922 prelist_remove(struct nd_prefix *pr)
    923 {
    924 	struct nd_pfxrouter *pfr, *next;
    925 	int e, s;
    926 
    927 	/* make sure to invalidate the prefix until it is really freed. */
    928 	pr->ndpr_vltime = 0;
    929 	pr->ndpr_pltime = 0;
    930 #if 0
    931 	/*
    932 	 * Though these flags are now meaningless, we'd rather keep the value
    933 	 * not to confuse users when executing "ndp -p".
    934 	 */
    935 	pr->ndpr_raf_onlink = 0;
    936 	pr->ndpr_raf_auto = 0;
    937 #endif
    938 	if ((pr->ndpr_stateflags & NDPRF_ONLINK) != 0 &&
    939 	    (e = nd6_prefix_offlink(pr)) != 0) {
    940 		nd6log((LOG_ERR, "prelist_remove: failed to make %s/%d offlink "
    941 		    "on %s, errno=%d\n",
    942 		    ip6_sprintf(&pr->ndpr_prefix.sin6_addr),
    943 		    pr->ndpr_plen, if_name(pr->ndpr_ifp), e));
    944 		/* what should we do? */
    945 	}
    946 
    947 	if (pr->ndpr_refcnt > 0)
    948 		return;		/* notice here? */
    949 
    950 	s = splsoftnet();
    951 	/* unlink ndpr_entry from nd_prefix list */
    952 	LIST_REMOVE(pr, ndpr_entry);
    953 
    954 	/* free list of routers that adversed the prefix */
    955 	for (pfr = LIST_FIRST(&pr->ndpr_advrtrs); pfr != NULL; pfr = next) {
    956 		next = LIST_NEXT(pfr, pfr_entry);
    957 
    958 		free(pfr, M_IP6NDP);
    959 	}
    960 	splx(s);
    961 
    962 	free(pr, M_IP6NDP);
    963 
    964 	pfxlist_onlink_check();
    965 }
    966 
    967 static int
    968 prelist_update(struct nd_prefixctl *new,
    969 	struct nd_defrouter *dr, /* may be NULL */
    970 	struct mbuf *m,
    971 	int mcast)
    972 {
    973 	struct in6_ifaddr *ia6 = NULL, *ia6_match = NULL;
    974 	struct ifaddr *ifa;
    975 	struct ifnet *ifp = new->ndpr_ifp;
    976 	struct nd_prefix *pr;
    977 	int s = splsoftnet();
    978 	int error = 0;
    979 	int newprefix = 0;
    980 	int auth;
    981 	struct in6_addrlifetime lt6_tmp;
    982 
    983 	auth = 0;
    984 	if (m) {
    985 		/*
    986 		 * Authenticity for NA consists authentication for
    987 		 * both IP header and IP datagrams, doesn't it ?
    988 		 */
    989 #if defined(M_AUTHIPHDR) && defined(M_AUTHIPDGM)
    990 		auth = (m->m_flags & M_AUTHIPHDR
    991 		     && m->m_flags & M_AUTHIPDGM) ? 1 : 0;
    992 #endif
    993 	}
    994 
    995 	if ((pr = nd6_prefix_lookup(new)) != NULL) {
    996 		/*
    997 		 * nd6_prefix_lookup() ensures that pr and new have the same
    998 		 * prefix on a same interface.
    999 		 */
   1000 
   1001 		/*
   1002 		 * Update prefix information.  Note that the on-link (L) bit
   1003 		 * and the autonomous (A) bit should NOT be changed from 1
   1004 		 * to 0.
   1005 		 */
   1006 		if (new->ndpr_raf_onlink == 1)
   1007 			pr->ndpr_raf_onlink = 1;
   1008 		if (new->ndpr_raf_auto == 1)
   1009 			pr->ndpr_raf_auto = 1;
   1010 		if (new->ndpr_raf_onlink) {
   1011 			pr->ndpr_vltime = new->ndpr_vltime;
   1012 			pr->ndpr_pltime = new->ndpr_pltime;
   1013 			(void)in6_init_prefix_ltimes(pr); /* XXX error case? */
   1014 			pr->ndpr_lastupdate = time_second;
   1015 		}
   1016 
   1017 		if (new->ndpr_raf_onlink &&
   1018 		    (pr->ndpr_stateflags & NDPRF_ONLINK) == 0) {
   1019 			int e;
   1020 
   1021 			if ((e = nd6_prefix_onlink(pr)) != 0) {
   1022 				nd6log((LOG_ERR,
   1023 				    "prelist_update: failed to make "
   1024 				    "the prefix %s/%d on-link on %s "
   1025 				    "(errno=%d)\n",
   1026 				    ip6_sprintf(&pr->ndpr_prefix.sin6_addr),
   1027 				    pr->ndpr_plen, if_name(pr->ndpr_ifp), e));
   1028 				/* proceed anyway. XXX: is it correct? */
   1029 			}
   1030 		}
   1031 
   1032 		if (dr && pfxrtr_lookup(pr, dr) == NULL)
   1033 			pfxrtr_add(pr, dr);
   1034 	} else {
   1035 		struct nd_prefix *newpr = NULL;
   1036 
   1037 		newprefix = 1;
   1038 
   1039 		if (new->ndpr_vltime == 0)
   1040 			goto end;
   1041 		if (new->ndpr_raf_onlink == 0 && new->ndpr_raf_auto == 0)
   1042 			goto end;
   1043 
   1044 		error = nd6_prelist_add(new, dr, &newpr);
   1045 		if (error != 0 || newpr == NULL) {
   1046 			nd6log((LOG_NOTICE, "prelist_update: "
   1047 			    "nd6_prelist_add failed for %s/%d on %s "
   1048 			    "errno=%d, returnpr=%p\n",
   1049 			    ip6_sprintf(&new->ndpr_prefix.sin6_addr),
   1050 			    new->ndpr_plen, if_name(new->ndpr_ifp),
   1051 			    error, newpr));
   1052 			goto end; /* we should just give up in this case. */
   1053 		}
   1054 
   1055 		/*
   1056 		 * XXX: from the ND point of view, we can ignore a prefix
   1057 		 * with the on-link bit being zero.  However, we need a
   1058 		 * prefix structure for references from autoconfigured
   1059 		 * addresses.  Thus, we explicitly make sure that the prefix
   1060 		 * itself expires now.
   1061 		 */
   1062 		if (newpr->ndpr_raf_onlink == 0) {
   1063 			newpr->ndpr_vltime = 0;
   1064 			newpr->ndpr_pltime = 0;
   1065 			in6_init_prefix_ltimes(newpr);
   1066 		}
   1067 
   1068 		pr = newpr;
   1069 	}
   1070 
   1071 	/*
   1072 	 * Address autoconfiguration based on Section 5.5.3 of RFC 2462.
   1073 	 * Note that pr must be non NULL at this point.
   1074 	 */
   1075 
   1076 	/* 5.5.3 (a). Ignore the prefix without the A bit set. */
   1077 	if (!new->ndpr_raf_auto)
   1078 		goto end;
   1079 
   1080 	/*
   1081 	 * 5.5.3 (b). the link-local prefix should have been ignored in
   1082 	 * nd6_ra_input.
   1083 	 */
   1084 
   1085 	/* 5.5.3 (c). Consistency check on lifetimes: pltime <= vltime. */
   1086 	if (new->ndpr_pltime > new->ndpr_vltime) {
   1087 		error = EINVAL;	/* XXX: won't be used */
   1088 		goto end;
   1089 	}
   1090 
   1091 	/*
   1092 	 * 5.5.3 (d).  If the prefix advertised is not equal to the prefix of
   1093 	 * an address configured by stateless autoconfiguration already in the
   1094 	 * list of addresses associated with the interface, and the Valid
   1095 	 * Lifetime is not 0, form an address.  We first check if we have
   1096 	 * a matching prefix.
   1097 	 * Note: we apply a clarification in rfc2462bis-02 here.  We only
   1098 	 * consider autoconfigured addresses while RFC2462 simply said
   1099 	 * "address".
   1100 	 */
   1101 	IFADDR_FOREACH(ifa, ifp) {
   1102 		struct in6_ifaddr *ifa6;
   1103 		u_int32_t remaininglifetime;
   1104 
   1105 		if (ifa->ifa_addr->sa_family != AF_INET6)
   1106 			continue;
   1107 
   1108 		ifa6 = (struct in6_ifaddr *)ifa;
   1109 
   1110 		/*
   1111 		 * We only consider autoconfigured addresses as per rfc2462bis.
   1112 		 */
   1113 		if (!(ifa6->ia6_flags & IN6_IFF_AUTOCONF))
   1114 			continue;
   1115 
   1116 		/*
   1117 		 * Spec is not clear here, but I believe we should concentrate
   1118 		 * on unicast (i.e. not anycast) addresses.
   1119 		 * XXX: other ia6_flags? detached or duplicated?
   1120 		 */
   1121 		if ((ifa6->ia6_flags & IN6_IFF_ANYCAST) != 0)
   1122 			continue;
   1123 
   1124 		/*
   1125 		 * Ignore the address if it is not associated with a prefix
   1126 		 * or is associated with a prefix that is different from this
   1127 		 * one.  (pr is never NULL here)
   1128 		 */
   1129 		if (ifa6->ia6_ndpr != pr)
   1130 			continue;
   1131 
   1132 		if (ia6_match == NULL) /* remember the first one */
   1133 			ia6_match = ifa6;
   1134 
   1135 		/*
   1136 		 * An already autoconfigured address matched.  Now that we
   1137 		 * are sure there is at least one matched address, we can
   1138 		 * proceed to 5.5.3. (e): update the lifetimes according to the
   1139 		 * "two hours" rule and the privacy extension.
   1140 		 * We apply some clarifications in rfc2462bis:
   1141 		 * - use remaininglifetime instead of storedlifetime as a
   1142 		 *   variable name
   1143 		 * - remove the dead code in the "two-hour" rule
   1144 		 */
   1145 #define TWOHOUR		(120*60)
   1146 		lt6_tmp = ifa6->ia6_lifetime;
   1147 		if (lt6_tmp.ia6t_vltime == ND6_INFINITE_LIFETIME)
   1148 			remaininglifetime = ND6_INFINITE_LIFETIME;
   1149 		else if (time_second - ifa6->ia6_updatetime >
   1150 			 lt6_tmp.ia6t_vltime) {
   1151 			/*
   1152 			 * The case of "invalid" address.  We should usually
   1153 			 * not see this case.
   1154 			 */
   1155 			remaininglifetime = 0;
   1156 		} else
   1157 			remaininglifetime = lt6_tmp.ia6t_vltime -
   1158 			    (time_second - ifa6->ia6_updatetime);
   1159 
   1160 		/* when not updating, keep the current stored lifetime. */
   1161 		lt6_tmp.ia6t_vltime = remaininglifetime;
   1162 
   1163 		if (TWOHOUR < new->ndpr_vltime ||
   1164 		    remaininglifetime < new->ndpr_vltime) {
   1165 			lt6_tmp.ia6t_vltime = new->ndpr_vltime;
   1166 		} else if (remaininglifetime <= TWOHOUR) {
   1167 			if (auth)
   1168 				lt6_tmp.ia6t_vltime = new->ndpr_vltime;
   1169 		} else {
   1170 			/*
   1171 			 * new->ndpr_vltime <= TWOHOUR &&
   1172 			 * TWOHOUR < remaininglifetime
   1173 			 */
   1174 			lt6_tmp.ia6t_vltime = TWOHOUR;
   1175 		}
   1176 
   1177 		/* The 2 hour rule is not imposed for preferred lifetime. */
   1178 		lt6_tmp.ia6t_pltime = new->ndpr_pltime;
   1179 
   1180 		in6_init_address_ltimes(pr, &lt6_tmp);
   1181 
   1182 		/*
   1183 		 * We need to treat lifetimes for temporary addresses
   1184 		 * differently, according to
   1185 		 * draft-ietf-ipv6-privacy-addrs-v2-01.txt 3.3 (1);
   1186 		 * we only update the lifetimes when they are in the maximum
   1187 		 * intervals.
   1188 		 */
   1189 		if ((ifa6->ia6_flags & IN6_IFF_TEMPORARY) != 0) {
   1190 			u_int32_t maxvltime, maxpltime;
   1191 
   1192 			if (ip6_temp_valid_lifetime >
   1193 			    (u_int32_t)((time_second - ifa6->ia6_createtime) +
   1194 			    ip6_desync_factor)) {
   1195 				maxvltime = ip6_temp_valid_lifetime -
   1196 				    (time_second - ifa6->ia6_createtime) -
   1197 				    ip6_desync_factor;
   1198 			} else
   1199 				maxvltime = 0;
   1200 			if (ip6_temp_preferred_lifetime >
   1201 			    (u_int32_t)((time_second - ifa6->ia6_createtime) +
   1202 			    ip6_desync_factor)) {
   1203 				maxpltime = ip6_temp_preferred_lifetime -
   1204 				    (time_second - ifa6->ia6_createtime) -
   1205 				    ip6_desync_factor;
   1206 			} else
   1207 				maxpltime = 0;
   1208 
   1209 			if (lt6_tmp.ia6t_vltime == ND6_INFINITE_LIFETIME ||
   1210 			    lt6_tmp.ia6t_vltime > maxvltime) {
   1211 				lt6_tmp.ia6t_vltime = maxvltime;
   1212 			}
   1213 			if (lt6_tmp.ia6t_pltime == ND6_INFINITE_LIFETIME ||
   1214 			    lt6_tmp.ia6t_pltime > maxpltime) {
   1215 				lt6_tmp.ia6t_pltime = maxpltime;
   1216 			}
   1217 		}
   1218 
   1219 		ifa6->ia6_lifetime = lt6_tmp;
   1220 		ifa6->ia6_updatetime = time_second;
   1221 	}
   1222 	if (ia6_match == NULL && new->ndpr_vltime) {
   1223 		int ifidlen;
   1224 
   1225 		/*
   1226 		 * 5.5.3 (d) (continued)
   1227 		 * No address matched and the valid lifetime is non-zero.
   1228 		 * Create a new address.
   1229 		 */
   1230 
   1231 		/*
   1232 		 * Prefix Length check:
   1233 		 * If the sum of the prefix length and interface identifier
   1234 		 * length does not equal 128 bits, the Prefix Information
   1235 		 * option MUST be ignored.  The length of the interface
   1236 		 * identifier is defined in a separate link-type specific
   1237 		 * document.
   1238 		 */
   1239 		ifidlen = in6_if2idlen(ifp);
   1240 		if (ifidlen < 0) {
   1241 			/* this should not happen, so we always log it. */
   1242 			log(LOG_ERR, "prelist_update: IFID undefined (%s)\n",
   1243 			    if_name(ifp));
   1244 			goto end;
   1245 		}
   1246 		if (ifidlen + pr->ndpr_plen != 128) {
   1247 			nd6log((LOG_INFO,
   1248 			    "prelist_update: invalid prefixlen "
   1249 			    "%d for %s, ignored\n",
   1250 			    pr->ndpr_plen, if_name(ifp)));
   1251 			goto end;
   1252 		}
   1253 
   1254 		if ((ia6 = in6_ifadd(new, mcast)) != NULL) {
   1255 			/*
   1256 			 * note that we should use pr (not new) for reference.
   1257 			 */
   1258 			pr->ndpr_refcnt++;
   1259 			ia6->ia6_ndpr = pr;
   1260 
   1261 			/*
   1262 			 * draft-ietf-ipngwg-temp-addresses-v2-00 3.3 (2).
   1263 			 * When a new public address is created as described
   1264 			 * in RFC2462, also create a new temporary address.
   1265 			 *
   1266 			 * draft-ietf-ipngwg-temp-addresses-v2-00 3.5.
   1267 			 * When an interface connects to a new link, a new
   1268 			 * randomized interface identifier should be generated
   1269 			 * immediately together with a new set of temporary
   1270 			 * addresses.  Thus, we specifiy 1 as the 2nd arg of
   1271 			 * in6_tmpifadd().
   1272 			 */
   1273 			if (ip6_use_tempaddr) {
   1274 				int e;
   1275 				if ((e = in6_tmpifadd(ia6, 1, 1)) != 0) {
   1276 					nd6log((LOG_NOTICE, "prelist_update: "
   1277 					    "failed to create a temporary "
   1278 					    "address, errno=%d\n",
   1279 					    e));
   1280 				}
   1281 			}
   1282 
   1283 			/*
   1284 			 * A newly added address might affect the status
   1285 			 * of other addresses, so we check and update it.
   1286 			 * XXX: what if address duplication happens?
   1287 			 */
   1288 			pfxlist_onlink_check();
   1289 		} else {
   1290 			/* just set an error. do not bark here. */
   1291 			error = EADDRNOTAVAIL; /* XXX: might be unused. */
   1292 		}
   1293 	}
   1294 
   1295  end:
   1296 	splx(s);
   1297 	return error;
   1298 }
   1299 
   1300 /*
   1301  * A supplement function used in the on-link detection below;
   1302  * detect if a given prefix has a (probably) reachable advertising router.
   1303  * XXX: lengthy function name...
   1304  */
   1305 static struct nd_pfxrouter *
   1306 find_pfxlist_reachable_router(struct nd_prefix *pr)
   1307 {
   1308 	struct nd_pfxrouter *pfxrtr;
   1309 	struct rtentry *rt;
   1310 	struct llinfo_nd6 *ln;
   1311 
   1312 	for (pfxrtr = LIST_FIRST(&pr->ndpr_advrtrs); pfxrtr;
   1313 	     pfxrtr = LIST_NEXT(pfxrtr, pfr_entry)) {
   1314 		if ((rt = nd6_lookup(&pfxrtr->router->rtaddr, 0,
   1315 		    pfxrtr->router->ifp)) &&
   1316 		    (ln = (struct llinfo_nd6 *)rt->rt_llinfo) &&
   1317 		    ND6_IS_LLINFO_PROBREACH(ln))
   1318 			break;	/* found */
   1319 	}
   1320 
   1321 	return (pfxrtr);
   1322 }
   1323 
   1324 /*
   1325  * Check if each prefix in the prefix list has at least one available router
   1326  * that advertised the prefix (a router is "available" if its neighbor cache
   1327  * entry is reachable or probably reachable).
   1328  * If the check fails, the prefix may be off-link, because, for example,
   1329  * we have moved from the network but the lifetime of the prefix has not
   1330  * expired yet.  So we should not use the prefix if there is another prefix
   1331  * that has an available router.
   1332  * But, if there is no prefix that has an available router, we still regards
   1333  * all the prefixes as on-link.  This is because we can't tell if all the
   1334  * routers are simply dead or if we really moved from the network and there
   1335  * is no router around us.
   1336  */
   1337 void
   1338 pfxlist_onlink_check(void)
   1339 {
   1340 	struct nd_prefix *pr;
   1341 	struct in6_ifaddr *ifa;
   1342 	struct nd_defrouter *dr;
   1343 	struct nd_pfxrouter *pfxrtr = NULL;
   1344 
   1345 	/*
   1346 	 * Check if there is a prefix that has a reachable advertising
   1347 	 * router.
   1348 	 */
   1349 	LIST_FOREACH(pr, &nd_prefix, ndpr_entry) {
   1350 		if (pr->ndpr_raf_onlink && find_pfxlist_reachable_router(pr))
   1351 			break;
   1352 	}
   1353 	/*
   1354 	 * If we have no such prefix, check whether we still have a router
   1355 	 * that does not advertise any prefixes.
   1356 	 */
   1357 	if (pr == NULL) {
   1358 		TAILQ_FOREACH(dr, &nd_defrouter, dr_entry) {
   1359 			struct nd_prefix *pr0;
   1360 
   1361 			LIST_FOREACH(pr0, &nd_prefix, ndpr_entry) {
   1362 				if ((pfxrtr = pfxrtr_lookup(pr0, dr)) != NULL)
   1363 					break;
   1364 			}
   1365 			if (pfxrtr)
   1366 				break;
   1367 		}
   1368 	}
   1369 	if (pr != NULL || (TAILQ_FIRST(&nd_defrouter) && !pfxrtr)) {
   1370 		/*
   1371 		 * There is at least one prefix that has a reachable router,
   1372 		 * or at least a router which probably does not advertise
   1373 		 * any prefixes.  The latter would be the case when we move
   1374 		 * to a new link where we have a router that does not provide
   1375 		 * prefixes and we configure an address by hand.
   1376 		 * Detach prefixes which have no reachable advertising
   1377 		 * router, and attach other prefixes.
   1378 		 */
   1379 		LIST_FOREACH(pr, &nd_prefix, ndpr_entry) {
   1380 			/* XXX: a link-local prefix should never be detached */
   1381 			if (IN6_IS_ADDR_LINKLOCAL(&pr->ndpr_prefix.sin6_addr))
   1382 				continue;
   1383 
   1384 			/*
   1385 			 * we aren't interested in prefixes without the L bit
   1386 			 * set.
   1387 			 */
   1388 			if (pr->ndpr_raf_onlink == 0)
   1389 				continue;
   1390 
   1391 			if ((pr->ndpr_stateflags & NDPRF_DETACHED) == 0 &&
   1392 			    find_pfxlist_reachable_router(pr) == NULL)
   1393 				pr->ndpr_stateflags |= NDPRF_DETACHED;
   1394 			if ((pr->ndpr_stateflags & NDPRF_DETACHED) != 0 &&
   1395 			    find_pfxlist_reachable_router(pr) != 0)
   1396 				pr->ndpr_stateflags &= ~NDPRF_DETACHED;
   1397 		}
   1398 	} else {
   1399 		/* there is no prefix that has a reachable router */
   1400 		LIST_FOREACH(pr, &nd_prefix, ndpr_entry) {
   1401 			if (IN6_IS_ADDR_LINKLOCAL(&pr->ndpr_prefix.sin6_addr))
   1402 				continue;
   1403 
   1404 			if (pr->ndpr_raf_onlink == 0)
   1405 				continue;
   1406 
   1407 			if ((pr->ndpr_stateflags & NDPRF_DETACHED) != 0)
   1408 				pr->ndpr_stateflags &= ~NDPRF_DETACHED;
   1409 		}
   1410 	}
   1411 
   1412 	/*
   1413 	 * Remove each interface route associated with a (just) detached
   1414 	 * prefix, and reinstall the interface route for a (just) attached
   1415 	 * prefix.  Note that all attempt of reinstallation does not
   1416 	 * necessarily success, when a same prefix is shared among multiple
   1417 	 * interfaces.  Such cases will be handled in nd6_prefix_onlink,
   1418 	 * so we don't have to care about them.
   1419 	 */
   1420 	LIST_FOREACH(pr, &nd_prefix, ndpr_entry) {
   1421 		int e;
   1422 
   1423 		if (IN6_IS_ADDR_LINKLOCAL(&pr->ndpr_prefix.sin6_addr))
   1424 			continue;
   1425 
   1426 		if (pr->ndpr_raf_onlink == 0)
   1427 			continue;
   1428 
   1429 		if ((pr->ndpr_stateflags & NDPRF_DETACHED) != 0 &&
   1430 		    (pr->ndpr_stateflags & NDPRF_ONLINK) != 0) {
   1431 			if ((e = nd6_prefix_offlink(pr)) != 0) {
   1432 				nd6log((LOG_ERR,
   1433 				    "pfxlist_onlink_check: failed to "
   1434 				    "make %s/%d offlink, errno=%d\n",
   1435 				    ip6_sprintf(&pr->ndpr_prefix.sin6_addr),
   1436 				    pr->ndpr_plen, e));
   1437 			}
   1438 		}
   1439 		if ((pr->ndpr_stateflags & NDPRF_DETACHED) == 0 &&
   1440 		    (pr->ndpr_stateflags & NDPRF_ONLINK) == 0 &&
   1441 		    pr->ndpr_raf_onlink) {
   1442 			if ((e = nd6_prefix_onlink(pr)) != 0) {
   1443 				nd6log((LOG_ERR,
   1444 				    "pfxlist_onlink_check: failed to "
   1445 				    "make %s/%d onlink, errno=%d\n",
   1446 				    ip6_sprintf(&pr->ndpr_prefix.sin6_addr),
   1447 				    pr->ndpr_plen, e));
   1448 			}
   1449 		}
   1450 	}
   1451 
   1452 	/*
   1453 	 * Changes on the prefix status might affect address status as well.
   1454 	 * Make sure that all addresses derived from an attached prefix are
   1455 	 * attached, and that all addresses derived from a detached prefix are
   1456 	 * detached.  Note, however, that a manually configured address should
   1457 	 * always be attached.
   1458 	 * The precise detection logic is same as the one for prefixes.
   1459 	 */
   1460 	for (ifa = in6_ifaddr; ifa; ifa = ifa->ia_next) {
   1461 		if (!(ifa->ia6_flags & IN6_IFF_AUTOCONF))
   1462 			continue;
   1463 
   1464 		if (ifa->ia6_ndpr == NULL) {
   1465 			/*
   1466 			 * This can happen when we first configure the address
   1467 			 * (i.e. the address exists, but the prefix does not).
   1468 			 * XXX: complicated relationships...
   1469 			 */
   1470 			continue;
   1471 		}
   1472 
   1473 		if (find_pfxlist_reachable_router(ifa->ia6_ndpr))
   1474 			break;
   1475 	}
   1476 	if (ifa) {
   1477 		for (ifa = in6_ifaddr; ifa; ifa = ifa->ia_next) {
   1478 			if ((ifa->ia6_flags & IN6_IFF_AUTOCONF) == 0)
   1479 				continue;
   1480 
   1481 			if (ifa->ia6_ndpr == NULL) /* XXX: see above. */
   1482 				continue;
   1483 
   1484 			if (find_pfxlist_reachable_router(ifa->ia6_ndpr)) {
   1485 				if (ifa->ia6_flags & IN6_IFF_DETACHED) {
   1486 					ifa->ia6_flags &= ~IN6_IFF_DETACHED;
   1487 					ifa->ia6_flags |= IN6_IFF_TENTATIVE;
   1488 					nd6_dad_start((struct ifaddr *)ifa,
   1489 					    0);
   1490 				}
   1491 			} else {
   1492 				if ((ifa->ia6_flags & IN6_IFF_DETACHED) == 0) {
   1493 					ifa->ia6_flags |= IN6_IFF_DETACHED;
   1494 				}
   1495 			}
   1496 		}
   1497 	}
   1498 	else {
   1499 		for (ifa = in6_ifaddr; ifa; ifa = ifa->ia_next) {
   1500 			if ((ifa->ia6_flags & IN6_IFF_AUTOCONF) == 0)
   1501 				continue;
   1502 
   1503 			if (ifa->ia6_flags & IN6_IFF_DETACHED) {
   1504 				ifa->ia6_flags &= ~IN6_IFF_DETACHED;
   1505 				ifa->ia6_flags |= IN6_IFF_TENTATIVE;
   1506 				/* Do we need a delay in this case? */
   1507 				nd6_dad_start((struct ifaddr *)ifa, 0);
   1508 			}
   1509 		}
   1510 	}
   1511 }
   1512 
   1513 int
   1514 nd6_prefix_onlink(struct nd_prefix *pr)
   1515 {
   1516 	struct ifaddr *ifa;
   1517 	struct ifnet *ifp = pr->ndpr_ifp;
   1518 	struct sockaddr_in6 mask6;
   1519 	struct nd_prefix *opr;
   1520 	u_long rtflags;
   1521 	int error = 0;
   1522 	struct rtentry *rt = NULL;
   1523 
   1524 	/* sanity check */
   1525 	if ((pr->ndpr_stateflags & NDPRF_ONLINK) != 0) {
   1526 		nd6log((LOG_ERR,
   1527 		    "nd6_prefix_onlink: %s/%d is already on-link\n",
   1528 		    ip6_sprintf(&pr->ndpr_prefix.sin6_addr), pr->ndpr_plen));
   1529 		return (EEXIST);
   1530 	}
   1531 
   1532 	/*
   1533 	 * Add the interface route associated with the prefix.  Before
   1534 	 * installing the route, check if there's the same prefix on another
   1535 	 * interface, and the prefix has already installed the interface route.
   1536 	 * Although such a configuration is expected to be rare, we explicitly
   1537 	 * allow it.
   1538 	 */
   1539 	LIST_FOREACH(opr, &nd_prefix, ndpr_entry) {
   1540 		if (opr == pr)
   1541 			continue;
   1542 
   1543 		if ((opr->ndpr_stateflags & NDPRF_ONLINK) == 0)
   1544 			continue;
   1545 
   1546 		if (opr->ndpr_plen == pr->ndpr_plen &&
   1547 		    in6_are_prefix_equal(&pr->ndpr_prefix.sin6_addr,
   1548 		    &opr->ndpr_prefix.sin6_addr, pr->ndpr_plen))
   1549 			return (0);
   1550 	}
   1551 
   1552 	/*
   1553 	 * We prefer link-local addresses as the associated interface address.
   1554 	 */
   1555 	/* search for a link-local addr */
   1556 	ifa = (struct ifaddr *)in6ifa_ifpforlinklocal(ifp,
   1557 	    IN6_IFF_NOTREADY | IN6_IFF_ANYCAST);
   1558 	if (ifa == NULL) {
   1559 		/* XXX: freebsd does not have ifa_ifwithaf */
   1560 		IFADDR_FOREACH(ifa, ifp) {
   1561 			if (ifa->ifa_addr->sa_family == AF_INET6)
   1562 				break;
   1563 		}
   1564 		/* should we care about ia6_flags? */
   1565 	}
   1566 	if (ifa == NULL) {
   1567 		/*
   1568 		 * This can still happen, when, for example, we receive an RA
   1569 		 * containing a prefix with the L bit set and the A bit clear,
   1570 		 * after removing all IPv6 addresses on the receiving
   1571 		 * interface.  This should, of course, be rare though.
   1572 		 */
   1573 		nd6log((LOG_NOTICE,
   1574 		    "nd6_prefix_onlink: failed to find any ifaddr"
   1575 		    " to add route for a prefix(%s/%d) on %s\n",
   1576 		    ip6_sprintf(&pr->ndpr_prefix.sin6_addr),
   1577 		    pr->ndpr_plen, if_name(ifp)));
   1578 		return (0);
   1579 	}
   1580 
   1581 	/*
   1582 	 * in6_ifinit() sets nd6_rtrequest to ifa_rtrequest for all ifaddrs.
   1583 	 * ifa->ifa_rtrequest = nd6_rtrequest;
   1584 	 */
   1585 	bzero(&mask6, sizeof(mask6));
   1586 	mask6.sin6_len = sizeof(mask6);
   1587 	mask6.sin6_addr = pr->ndpr_mask;
   1588 	/* rtrequest() will probably set RTF_UP, but we're not sure. */
   1589 	rtflags = ifa->ifa_flags | RTF_UP;
   1590 	if (nd6_need_cache(ifp)) {
   1591 		/* explicitly set in case ifa_flags does not set the flag. */
   1592 		rtflags |= RTF_CLONING;
   1593 	} else {
   1594 		/*
   1595 		 * explicitly clear the cloning bit in case ifa_flags sets it.
   1596 		 */
   1597 		rtflags &= ~RTF_CLONING;
   1598 	}
   1599 	error = rtrequest(RTM_ADD, (struct sockaddr *)&pr->ndpr_prefix,
   1600 	    ifa->ifa_addr, (struct sockaddr *)&mask6, rtflags, &rt);
   1601 	if (error == 0) {
   1602 		if (rt != NULL) /* this should be non NULL, though */
   1603 			nd6_rtmsg(RTM_ADD, rt);
   1604 		pr->ndpr_stateflags |= NDPRF_ONLINK;
   1605 	} else {
   1606 		nd6log((LOG_ERR, "nd6_prefix_onlink: failed to add route for a"
   1607 		    " prefix (%s/%d) on %s, gw=%s, mask=%s, flags=%lx "
   1608 		    "errno = %d\n",
   1609 		    ip6_sprintf(&pr->ndpr_prefix.sin6_addr),
   1610 		    pr->ndpr_plen, if_name(ifp),
   1611 		    ip6_sprintf(&((struct sockaddr_in6 *)ifa->ifa_addr)->sin6_addr),
   1612 		    ip6_sprintf(&mask6.sin6_addr), rtflags, error));
   1613 	}
   1614 
   1615 	if (rt != NULL)
   1616 		rt->rt_refcnt--;
   1617 
   1618 	return (error);
   1619 }
   1620 
   1621 int
   1622 nd6_prefix_offlink(struct nd_prefix *pr)
   1623 {
   1624 	int error = 0;
   1625 	struct ifnet *ifp = pr->ndpr_ifp;
   1626 	struct nd_prefix *opr;
   1627 	struct sockaddr_in6 sa6, mask6;
   1628 	struct rtentry *rt = NULL;
   1629 
   1630 	/* sanity check */
   1631 	if ((pr->ndpr_stateflags & NDPRF_ONLINK) == 0) {
   1632 		nd6log((LOG_ERR,
   1633 		    "nd6_prefix_offlink: %s/%d is already off-link\n",
   1634 		    ip6_sprintf(&pr->ndpr_prefix.sin6_addr), pr->ndpr_plen));
   1635 		return (EEXIST);
   1636 	}
   1637 
   1638 	sockaddr_in6_init(&sa6, &pr->ndpr_prefix.sin6_addr, 0, 0, 0);
   1639 	sockaddr_in6_init(&mask6, &pr->ndpr_mask, 0, 0, 0);
   1640 	error = rtrequest(RTM_DELETE, (struct sockaddr *)&sa6, NULL,
   1641 	    (struct sockaddr *)&mask6, 0, &rt);
   1642 	if (error == 0) {
   1643 		pr->ndpr_stateflags &= ~NDPRF_ONLINK;
   1644 
   1645 		/* report the route deletion to the routing socket. */
   1646 		if (rt != NULL)
   1647 			nd6_rtmsg(RTM_DELETE, rt);
   1648 
   1649 		/*
   1650 		 * There might be the same prefix on another interface,
   1651 		 * the prefix which could not be on-link just because we have
   1652 		 * the interface route (see comments in nd6_prefix_onlink).
   1653 		 * If there's one, try to make the prefix on-link on the
   1654 		 * interface.
   1655 		 */
   1656 		LIST_FOREACH(opr, &nd_prefix, ndpr_entry) {
   1657 			if (opr == pr)
   1658 				continue;
   1659 
   1660 			if ((opr->ndpr_stateflags & NDPRF_ONLINK) != 0)
   1661 				continue;
   1662 
   1663 			/*
   1664 			 * KAME specific: detached prefixes should not be
   1665 			 * on-link.
   1666 			 */
   1667 			if ((opr->ndpr_stateflags & NDPRF_DETACHED) != 0)
   1668 				continue;
   1669 
   1670 			if (opr->ndpr_plen == pr->ndpr_plen &&
   1671 			    in6_are_prefix_equal(&pr->ndpr_prefix.sin6_addr,
   1672 			    &opr->ndpr_prefix.sin6_addr, pr->ndpr_plen)) {
   1673 				int e;
   1674 
   1675 				if ((e = nd6_prefix_onlink(opr)) != 0) {
   1676 					nd6log((LOG_ERR,
   1677 					    "nd6_prefix_offlink: failed to "
   1678 					    "recover a prefix %s/%d from %s "
   1679 					    "to %s (errno = %d)\n",
   1680 					    ip6_sprintf(&opr->ndpr_prefix.sin6_addr),
   1681 					    opr->ndpr_plen, if_name(ifp),
   1682 					    if_name(opr->ndpr_ifp), e));
   1683 				}
   1684 			}
   1685 		}
   1686 	} else {
   1687 		/* XXX: can we still set the NDPRF_ONLINK flag? */
   1688 		nd6log((LOG_ERR,
   1689 		    "nd6_prefix_offlink: failed to delete route: "
   1690 		    "%s/%d on %s (errno = %d)\n",
   1691 		    ip6_sprintf(&sa6.sin6_addr), pr->ndpr_plen, if_name(ifp),
   1692 		    error));
   1693 	}
   1694 
   1695 	if (rt != NULL) {
   1696 		if (rt->rt_refcnt <= 0) {
   1697 			/* XXX: we should free the entry ourselves. */
   1698 			rt->rt_refcnt++;
   1699 			rtfree(rt);
   1700 		}
   1701 	}
   1702 
   1703 	return (error);
   1704 }
   1705 
   1706 static struct in6_ifaddr *
   1707 in6_ifadd(struct nd_prefixctl *pr, int mcast)
   1708 {
   1709 	struct ifnet *ifp = pr->ndpr_ifp;
   1710 	struct ifaddr *ifa;
   1711 	struct in6_aliasreq ifra;
   1712 	struct in6_ifaddr *ia, *ib;
   1713 	int error, plen0;
   1714 	struct in6_addr mask;
   1715 	int prefixlen = pr->ndpr_plen;
   1716 	int updateflags;
   1717 
   1718 	in6_prefixlen2mask(&mask, prefixlen);
   1719 
   1720 	/*
   1721 	 * find a link-local address (will be interface ID).
   1722 	 * Is it really mandatory? Theoretically, a global or a site-local
   1723 	 * address can be configured without a link-local address, if we
   1724 	 * have a unique interface identifier...
   1725 	 *
   1726 	 * it is not mandatory to have a link-local address, we can generate
   1727 	 * interface identifier on the fly.  we do this because:
   1728 	 * (1) it should be the easiest way to find interface identifier.
   1729 	 * (2) RFC2462 5.4 suggesting the use of the same interface identifier
   1730 	 * for multiple addresses on a single interface, and possible shortcut
   1731 	 * of DAD.  we omitted DAD for this reason in the past.
   1732 	 * (3) a user can prevent autoconfiguration of global address
   1733 	 * by removing link-local address by hand (this is partly because we
   1734 	 * don't have other way to control the use of IPv6 on an interface.
   1735 	 * this has been our design choice - cf. NRL's "ifconfig auto").
   1736 	 * (4) it is easier to manage when an interface has addresses
   1737 	 * with the same interface identifier, than to have multiple addresses
   1738 	 * with different interface identifiers.
   1739 	 */
   1740 	ifa = (struct ifaddr *)in6ifa_ifpforlinklocal(ifp, 0); /* 0 is OK? */
   1741 	if (ifa)
   1742 		ib = (struct in6_ifaddr *)ifa;
   1743 	else
   1744 		return NULL;
   1745 
   1746 #if 0 /* don't care link local addr state, and always do DAD */
   1747 	/* if link-local address is not eligible, do not autoconfigure. */
   1748 	if (((struct in6_ifaddr *)ifa)->ia6_flags & IN6_IFF_NOTREADY) {
   1749 		printf("in6_ifadd: link-local address not ready\n");
   1750 		return NULL;
   1751 	}
   1752 #endif
   1753 
   1754 	/* prefixlen + ifidlen must be equal to 128 */
   1755 	plen0 = in6_mask2len(&ib->ia_prefixmask.sin6_addr, NULL);
   1756 	if (prefixlen != plen0) {
   1757 		nd6log((LOG_INFO, "in6_ifadd: wrong prefixlen for %s "
   1758 		    "(prefix=%d ifid=%d)\n",
   1759 		    if_name(ifp), prefixlen, 128 - plen0));
   1760 		return NULL;
   1761 	}
   1762 
   1763 	/* make ifaddr */
   1764 
   1765 	memset(&ifra, 0, sizeof(ifra));
   1766 	/*
   1767 	 * in6_update_ifa() does not use ifra_name, but we accurately set it
   1768 	 * for safety.
   1769 	 */
   1770 	strncpy(ifra.ifra_name, if_name(ifp), sizeof(ifra.ifra_name));
   1771 	sockaddr_in6_init(&ifra.ifra_addr, &pr->ndpr_prefix.sin6_addr, 0, 0, 0);
   1772 	/* prefix */
   1773 	ifra.ifra_addr.sin6_addr.s6_addr32[0] &= mask.s6_addr32[0];
   1774 	ifra.ifra_addr.sin6_addr.s6_addr32[1] &= mask.s6_addr32[1];
   1775 	ifra.ifra_addr.sin6_addr.s6_addr32[2] &= mask.s6_addr32[2];
   1776 	ifra.ifra_addr.sin6_addr.s6_addr32[3] &= mask.s6_addr32[3];
   1777 
   1778 	/* interface ID */
   1779 	ifra.ifra_addr.sin6_addr.s6_addr32[0] |=
   1780 	    (ib->ia_addr.sin6_addr.s6_addr32[0] & ~mask.s6_addr32[0]);
   1781 	ifra.ifra_addr.sin6_addr.s6_addr32[1] |=
   1782 	    (ib->ia_addr.sin6_addr.s6_addr32[1] & ~mask.s6_addr32[1]);
   1783 	ifra.ifra_addr.sin6_addr.s6_addr32[2] |=
   1784 	    (ib->ia_addr.sin6_addr.s6_addr32[2] & ~mask.s6_addr32[2]);
   1785 	ifra.ifra_addr.sin6_addr.s6_addr32[3] |=
   1786 	    (ib->ia_addr.sin6_addr.s6_addr32[3] & ~mask.s6_addr32[3]);
   1787 
   1788 	/* new prefix mask. */
   1789 	sockaddr_in6_init(&ifra.ifra_prefixmask, &mask, 0, 0, 0);
   1790 
   1791 	/* lifetimes */
   1792 	ifra.ifra_lifetime.ia6t_vltime = pr->ndpr_vltime;
   1793 	ifra.ifra_lifetime.ia6t_pltime = pr->ndpr_pltime;
   1794 
   1795 	/* XXX: scope zone ID? */
   1796 
   1797 	ifra.ifra_flags |= IN6_IFF_AUTOCONF; /* obey autoconf */
   1798 
   1799 	/*
   1800 	 * Make sure that we do not have this address already.  This should
   1801 	 * usually not happen, but we can still see this case, e.g., if we
   1802 	 * have manually configured the exact address to be configured.
   1803 	 */
   1804 	if (in6ifa_ifpwithaddr(ifp, &ifra.ifra_addr.sin6_addr) != NULL) {
   1805 		/* this should be rare enough to make an explicit log */
   1806 		log(LOG_INFO, "in6_ifadd: %s is already configured\n",
   1807 		    ip6_sprintf(&ifra.ifra_addr.sin6_addr));
   1808 		return (NULL);
   1809 	}
   1810 
   1811 	/*
   1812 	 * Allocate ifaddr structure, link into chain, etc.
   1813 	 * If we are going to create a new address upon receiving a multicasted
   1814 	 * RA, we need to impose a random delay before starting DAD.
   1815 	 * [draft-ietf-ipv6-rfc2462bis-02.txt, Section 5.4.2]
   1816 	 */
   1817 	updateflags = 0;
   1818 	if (mcast)
   1819 		updateflags |= IN6_IFAUPDATE_DADDELAY;
   1820 	if ((error = in6_update_ifa(ifp, &ifra, NULL, updateflags)) != 0) {
   1821 		nd6log((LOG_ERR,
   1822 		    "in6_ifadd: failed to make ifaddr %s on %s (errno=%d)\n",
   1823 		    ip6_sprintf(&ifra.ifra_addr.sin6_addr), if_name(ifp),
   1824 		    error));
   1825 		return (NULL);	/* ifaddr must not have been allocated. */
   1826 	}
   1827 
   1828 	ia = in6ifa_ifpwithaddr(ifp, &ifra.ifra_addr.sin6_addr);
   1829 
   1830 	return (ia);		/* this is always non-NULL */
   1831 }
   1832 
   1833 int
   1834 in6_tmpifadd(
   1835 	const struct in6_ifaddr *ia0, /* corresponding public address */
   1836 	int forcegen,
   1837 	int dad_delay)
   1838 {
   1839 	struct ifnet *ifp = ia0->ia_ifa.ifa_ifp;
   1840 	struct in6_ifaddr *newia, *ia;
   1841 	struct in6_aliasreq ifra;
   1842 	int i, error;
   1843 	int trylimit = 3;	/* XXX: adhoc value */
   1844 	int updateflags;
   1845 	u_int32_t randid[2];
   1846 	u_int32_t vltime0, pltime0;
   1847 
   1848 	memset(&ifra, 0, sizeof(ifra));
   1849 	strncpy(ifra.ifra_name, if_name(ifp), sizeof(ifra.ifra_name));
   1850 	ifra.ifra_addr = ia0->ia_addr;
   1851 	/* copy prefix mask */
   1852 	ifra.ifra_prefixmask = ia0->ia_prefixmask;
   1853 	/* clear the old IFID */
   1854 	for (i = 0; i < 4; i++) {
   1855 		ifra.ifra_addr.sin6_addr.s6_addr32[i] &=
   1856 		    ifra.ifra_prefixmask.sin6_addr.s6_addr32[i];
   1857 	}
   1858 
   1859   again:
   1860 	if (in6_get_tmpifid(ifp, (u_int8_t *)randid,
   1861 	    (const u_int8_t *)&ia0->ia_addr.sin6_addr.s6_addr[8], forcegen)) {
   1862 		nd6log((LOG_NOTICE, "in6_tmpifadd: failed to find a good "
   1863 		    "random IFID\n"));
   1864 		return (EINVAL);
   1865 	}
   1866 	ifra.ifra_addr.sin6_addr.s6_addr32[2] |=
   1867 	    (randid[0] & ~(ifra.ifra_prefixmask.sin6_addr.s6_addr32[2]));
   1868 	ifra.ifra_addr.sin6_addr.s6_addr32[3] |=
   1869 	    (randid[1] & ~(ifra.ifra_prefixmask.sin6_addr.s6_addr32[3]));
   1870 
   1871 	/*
   1872 	 * in6_get_tmpifid() quite likely provided a unique interface ID.
   1873 	 * However, we may still have a chance to see collision, because
   1874 	 * there may be a time lag between generation of the ID and generation
   1875 	 * of the address.  So, we'll do one more sanity check.
   1876 	 */
   1877 	for (ia = in6_ifaddr; ia; ia = ia->ia_next) {
   1878 		if (IN6_ARE_ADDR_EQUAL(&ia->ia_addr.sin6_addr,
   1879 		    &ifra.ifra_addr.sin6_addr)) {
   1880 			if (trylimit-- == 0) {
   1881 				/*
   1882 				 * Give up.  Something strange should have
   1883 				 * happened.
   1884 				 */
   1885 				nd6log((LOG_NOTICE, "in6_tmpifadd: failed to "
   1886 				    "find a unique random IFID\n"));
   1887 				return (EEXIST);
   1888 			}
   1889 			forcegen = 1;
   1890 			goto again;
   1891 		}
   1892 	}
   1893 
   1894 	/*
   1895 	 * The Valid Lifetime is the lower of the Valid Lifetime of the
   1896          * public address or TEMP_VALID_LIFETIME.
   1897 	 * The Preferred Lifetime is the lower of the Preferred Lifetime
   1898          * of the public address or TEMP_PREFERRED_LIFETIME -
   1899          * DESYNC_FACTOR.
   1900 	 */
   1901 	if (ia0->ia6_lifetime.ia6t_vltime != ND6_INFINITE_LIFETIME) {
   1902 		vltime0 = IFA6_IS_INVALID(ia0) ? 0 :
   1903 		    (ia0->ia6_lifetime.ia6t_vltime -
   1904 		    (time_second - ia0->ia6_updatetime));
   1905 		if (vltime0 > ip6_temp_valid_lifetime)
   1906 			vltime0 = ip6_temp_valid_lifetime;
   1907 	} else
   1908 		vltime0 = ip6_temp_valid_lifetime;
   1909 	if (ia0->ia6_lifetime.ia6t_pltime != ND6_INFINITE_LIFETIME) {
   1910 		pltime0 = IFA6_IS_DEPRECATED(ia0) ? 0 :
   1911 		    (ia0->ia6_lifetime.ia6t_pltime -
   1912 		    (time_second - ia0->ia6_updatetime));
   1913 		if (pltime0 > ip6_temp_preferred_lifetime - ip6_desync_factor){
   1914 			pltime0 = ip6_temp_preferred_lifetime -
   1915 			    ip6_desync_factor;
   1916 		}
   1917 	} else
   1918 		pltime0 = ip6_temp_preferred_lifetime - ip6_desync_factor;
   1919 	ifra.ifra_lifetime.ia6t_vltime = vltime0;
   1920 	ifra.ifra_lifetime.ia6t_pltime = pltime0;
   1921 
   1922 	/*
   1923 	 * A temporary address is created only if this calculated Preferred
   1924 	 * Lifetime is greater than REGEN_ADVANCE time units.
   1925 	 */
   1926 	if (ifra.ifra_lifetime.ia6t_pltime <= ip6_temp_regen_advance)
   1927 		return (0);
   1928 
   1929 	/* XXX: scope zone ID? */
   1930 
   1931 	ifra.ifra_flags |= (IN6_IFF_AUTOCONF|IN6_IFF_TEMPORARY);
   1932 
   1933 	/* allocate ifaddr structure, link into chain, etc. */
   1934 	updateflags = 0;
   1935 	if (dad_delay)
   1936 		updateflags |= IN6_IFAUPDATE_DADDELAY;
   1937 	if ((error = in6_update_ifa(ifp, &ifra, NULL, updateflags)) != 0)
   1938 		return (error);
   1939 
   1940 	newia = in6ifa_ifpwithaddr(ifp, &ifra.ifra_addr.sin6_addr);
   1941 	if (newia == NULL) {	/* XXX: can it happen? */
   1942 		nd6log((LOG_ERR,
   1943 		    "in6_tmpifadd: ifa update succeeded, but we got "
   1944 		    "no ifaddr\n"));
   1945 		return (EINVAL); /* XXX */
   1946 	}
   1947 	newia->ia6_ndpr = ia0->ia6_ndpr;
   1948 	newia->ia6_ndpr->ndpr_refcnt++;
   1949 
   1950 	/*
   1951 	 * A newly added address might affect the status of other addresses.
   1952 	 * XXX: when the temporary address is generated with a new public
   1953 	 * address, the onlink check is redundant.  However, it would be safe
   1954 	 * to do the check explicitly everywhere a new address is generated,
   1955 	 * and, in fact, we surely need the check when we create a new
   1956 	 * temporary address due to deprecation of an old temporary address.
   1957 	 */
   1958 	pfxlist_onlink_check();
   1959 
   1960 	return (0);
   1961 }
   1962 
   1963 static int
   1964 in6_init_prefix_ltimes(struct nd_prefix *ndpr)
   1965 {
   1966 
   1967 	/* check if preferred lifetime > valid lifetime.  RFC2462 5.5.3 (c) */
   1968 	if (ndpr->ndpr_pltime > ndpr->ndpr_vltime) {
   1969 		nd6log((LOG_INFO, "in6_init_prefix_ltimes: preferred lifetime"
   1970 		    "(%d) is greater than valid lifetime(%d)\n",
   1971 		    (u_int)ndpr->ndpr_pltime, (u_int)ndpr->ndpr_vltime));
   1972 		return (EINVAL);
   1973 	}
   1974 	if (ndpr->ndpr_pltime == ND6_INFINITE_LIFETIME)
   1975 		ndpr->ndpr_preferred = 0;
   1976 	else
   1977 		ndpr->ndpr_preferred = time_second + ndpr->ndpr_pltime;
   1978 	if (ndpr->ndpr_vltime == ND6_INFINITE_LIFETIME)
   1979 		ndpr->ndpr_expire = 0;
   1980 	else
   1981 		ndpr->ndpr_expire = time_second + ndpr->ndpr_vltime;
   1982 
   1983 	return 0;
   1984 }
   1985 
   1986 static void
   1987 in6_init_address_ltimes(struct nd_prefix *new,
   1988     struct in6_addrlifetime *lt6)
   1989 {
   1990 
   1991 	/* Valid lifetime must not be updated unless explicitly specified. */
   1992 	/* init ia6t_expire */
   1993 	if (lt6->ia6t_vltime == ND6_INFINITE_LIFETIME)
   1994 		lt6->ia6t_expire = 0;
   1995 	else {
   1996 		lt6->ia6t_expire = time_second;
   1997 		lt6->ia6t_expire += lt6->ia6t_vltime;
   1998 	}
   1999 
   2000 	/* init ia6t_preferred */
   2001 	if (lt6->ia6t_pltime == ND6_INFINITE_LIFETIME)
   2002 		lt6->ia6t_preferred = 0;
   2003 	else {
   2004 		lt6->ia6t_preferred = time_second;
   2005 		lt6->ia6t_preferred += lt6->ia6t_pltime;
   2006 	}
   2007 }
   2008 
   2009 /*
   2010  * Delete all the routing table entries that use the specified gateway.
   2011  * XXX: this function causes search through all entries of routing table, so
   2012  * it shouldn't be called when acting as a router.
   2013  */
   2014 void
   2015 rt6_flush(struct in6_addr *gateway, struct ifnet *ifp)
   2016 {
   2017 	int s = splsoftnet();
   2018 
   2019 	/* We'll care only link-local addresses */
   2020 	if (!IN6_IS_ADDR_LINKLOCAL(gateway)) {
   2021 		splx(s);
   2022 		return;
   2023 	}
   2024 
   2025 	rt_walktree(AF_INET6, rt6_deleteroute, (void *)gateway);
   2026 	splx(s);
   2027 }
   2028 
   2029 static int
   2030 rt6_deleteroute(struct rtentry *rt, void *arg)
   2031 {
   2032 #define SIN6(s)	((struct sockaddr_in6 *)s)
   2033 	struct in6_addr *gate = (struct in6_addr *)arg;
   2034 
   2035 	if (rt->rt_gateway == NULL || rt->rt_gateway->sa_family != AF_INET6)
   2036 		return (0);
   2037 
   2038 	if (!IN6_ARE_ADDR_EQUAL(gate, &SIN6(rt->rt_gateway)->sin6_addr))
   2039 		return (0);
   2040 
   2041 	/*
   2042 	 * Do not delete a static route.
   2043 	 * XXX: this seems to be a bit ad-hoc. Should we consider the
   2044 	 * 'cloned' bit instead?
   2045 	 */
   2046 	if ((rt->rt_flags & RTF_STATIC) != 0)
   2047 		return (0);
   2048 
   2049 	/*
   2050 	 * We delete only host route. This means, in particular, we don't
   2051 	 * delete default route.
   2052 	 */
   2053 	if ((rt->rt_flags & RTF_HOST) == 0)
   2054 		return (0);
   2055 
   2056 	return (rtrequest(RTM_DELETE, rt_getkey(rt), rt->rt_gateway,
   2057 	    rt_mask(rt), rt->rt_flags, 0));
   2058 #undef SIN6
   2059 }
   2060 
   2061 int
   2062 nd6_setdefaultiface(int ifindex)
   2063 {
   2064 	int error = 0;
   2065 
   2066 	if (ifindex < 0 || if_indexlim <= ifindex)
   2067 		return (EINVAL);
   2068 	if (ifindex != 0 && !ifindex2ifnet[ifindex])
   2069 		return (EINVAL);
   2070 
   2071 	if (nd6_defifindex != ifindex) {
   2072 		nd6_defifindex = ifindex;
   2073 		if (nd6_defifindex > 0) {
   2074 			nd6_defifp = ifindex2ifnet[nd6_defifindex];
   2075 		} else
   2076 			nd6_defifp = NULL;
   2077 
   2078 		/*
   2079 		 * Our current implementation assumes one-to-one maping between
   2080 		 * interfaces and links, so it would be natural to use the
   2081 		 * default interface as the default link.
   2082 		 */
   2083 		scope6_setdefault(nd6_defifp);
   2084 	}
   2085 
   2086 	return (error);
   2087 }
   2088