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