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