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