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