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