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