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